md_funcs.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php /* <!-- Dokeos metadata/md_funcs.php -->
  2. <!-- 2006/12/15 -->
  3. <!-- Copyright (C) 2006 rene.haentjens@UGent.be - see note at end of text -->
  4. */
  5. /**
  6. ==============================================================================
  7. * Dokeos Metadata: common functions and mdstore class
  8. *
  9. * This script requires xmd.lib.php and xht.lib.php (Dokeos inc/lib).
  10. *
  11. * Note on the funny characters used in mds_update_xml_and_mdt:
  12. *
  13. * ! and ~ and , are handled by xmd_update, see xmd.lib.php
  14. * ~~ !! ; and = are handled here; note that = excludes newlines in value
  15. *
  16. * path!elem create new element (not for attributes!)
  17. * path=value assign new value to existing element or value to attribute
  18. * path~ delete element (you cannot delete an attribute)
  19. * ~~ delete the whole xmldoc and the DB entry
  20. * !! this (xml) document contains the course keywords
  21. *
  22. * path1,path2,...;subpath=value for all elements in path1, path2, ...
  23. * assign value to subpath (see also xmd_update_many)
  24. *
  25. * @package dokeos.metadata
  26. ==============================================================================
  27. */
  28. // FETCH GET/POST-DATA; GENERAL FUNCTIONS ------------------------------------->
  29. if (isset($getpostvars) && is_array($getpostvars))
  30. foreach ($getpostvars as $gpvar)
  31. if (is_string($gpvar) && (isset($_POST[$gpvar]) || isset($_GET[$gpvar])))
  32. {
  33. $val = isset($_POST[$gpvar]) ? $_POST[$gpvar] : $_GET[$gpvar];
  34. $GLOBALS[$gpvar] = get_magic_quotes_gpc() ? stripslashes($val) : $val;
  35. }
  36. function fgc($filename)
  37. {
  38. $fp = fopen($filename, 'rb'); $buffer = fread($fp, filesize($filename));
  39. fclose($fp); return $buffer; // file_get_contents: PHP >= 4.3.0
  40. }
  41. function give_up($msg)
  42. {
  43. global $charset;
  44. echo '<p align="center">MetaData:<br /><b>? ',
  45. htmlspecialchars($msg, ENT_QUOTES, $charset), '</b></p>'; exit;
  46. }
  47. function getpar($name, $description, $default = '')
  48. {
  49. $value = isset($_GET[$value = api_strtolower($name)]) ? $_GET[$value] : '';
  50. $value = get_magic_quotes_gpc() ? stripslashes($value) : $value;
  51. if (!$value) $value = $default;
  52. if ($value == '') give_up('URL parameter ' . api_strtoupper($name) . ' - ' .
  53. $description . ' - is required');
  54. define(api_strtoupper($name), $value);
  55. }
  56. function get_course_path()
  57. {
  58. return api_get_path(SYS_COURSE_PATH);
  59. }
  60. function get_course_web()
  61. {
  62. return api_get_path(WEB_COURSE_PATH);
  63. }
  64. function define_htt($htt_file, $urlp, $course_path)
  65. {
  66. global $charset;
  67. ($htt_file_contents = @fgc($htt_file))
  68. or give_up('Templates file "' . $htt_file . '" is missing...');
  69. $xhtDoc = new xhtdoc($htt_file_contents);
  70. if ($xhtDoc->htt_error)
  71. give_up('Templates file "' . $htt_file . '": ' . $xhtDoc->htt_error);
  72. $xhtDoc->xht_param['self'] = api_get_self() . $urlp;
  73. $xhtDoc->xht_param['dateTime'] = date('Y-m-d');
  74. $ckw = $course_path . '/CourseKwds.js';
  75. define('KEYWORDS_CACHE', get_course_path() . $ckw);
  76. if (file_exists(KEYWORDS_CACHE)) $kcdt =
  77. htmlspecialchars(date('Y/m/d H:i:s', filemtime(KEYWORDS_CACHE)), ENT_QUOTES, $charset);
  78. $xhtDoc->xht_param['keywordscache'] = $kcdt ?
  79. '<script type="text/javascript" src="' . get_course_web() . $ckw . '"></script>' .
  80. '<br /><small><i>(CourseKwds cache: ' . $kcdt . ')</i></small>' : '';
  81. return $xhtDoc;
  82. }
  83. function make_uri()
  84. {
  85. $regs = array(); // for use with ereg()
  86. $uri = strtr(ereg_replace(
  87. "[^0-9A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\xFF\*\(\('!_.-]", "_",
  88. api_get_setting('siteName')), "\\", "_"); // allow letdigs, and _-.()'!*
  89. if (($p = strpos($uri, '.')) !== FALSE)
  90. $uri = substr($uri, 0, $p);
  91. if (ereg('^([^/]+//)?([^/\?]+)[/\?]',api_get_path(WEB_PATH).'/',$regs))
  92. if (ereg('([^\.]+)(\.ca)?(\.[^\.]+)?', strrev($regs[2]), $regs))
  93. $uri = str_replace('.', '-',
  94. strrev($regs[1].$regs[2].$regs[3])) . ':' . $uri;
  95. $uri = 'urn:' . strtolower($uri);
  96. while (substr($uri, -1)=='.') $uri = substr($uri,0,-1);
  97. return $uri;
  98. }
  99. // IEEE LOM: DEFAULT XML AND DUBLIN CORE MAPPING ------------------------------>
  100. $ieee_xml = <<<EOD
  101. <!-- {-XML-} -->
  102. <item>
  103. <metadata>
  104. <lom xmlns="http://ltsc.ieee.org/xsd/LOM">
  105. <general>
  106. <identifier><catalog>{-H {-P siteUri-}-}.</catalog><entry>{-H {-P entry-}-}</entry></identifier>
  107. <title><string language="{-H {-P mdlang-}-}">{-H {-P title-}-}</string></title>
  108. <language>{-H {-P lang-}-}</language>
  109. <description><string language="{-H {-P mdlang-}-}">{-H {-P description-}-}</string></description>
  110. <coverage><string language="{-H {-P mdlang-}-}">{-H {-P coverage-}-}</string></coverage>
  111. </general>
  112. <lifeCycle>
  113. <version><string language="xx">0.5</string></version>
  114. <status><source>LOMv1.0</source><value>draft</value></status>
  115. <contribute>
  116. <role><source>LOMv1.0</source><value>author</value></role>
  117. <entity>{-H {-P author-}-}</entity>
  118. <date><dateTime>{-H {-P dateTime-}-}</dateTime></date>
  119. </contribute>
  120. </lifeCycle>
  121. <metaMetadata>
  122. <metadataSchema>ADLv1.3</metadataSchema>
  123. </metaMetadata>
  124. <technical>
  125. <format>{-H {-P format-}-}</format>
  126. <size>{-H {-P size-}-}</size>
  127. <location>{-H {-P location-}-}</location>
  128. </technical>
  129. <educational>
  130. <learningResourceType><source>LOMv1.0</source><value>narrative text</value></learningResourceType>
  131. </educational>
  132. <rights>
  133. <cost><source>LOMv1.0</source><value>yes</value></cost>
  134. <copyrightAndOtherRestrictions><source>LOMv1.0</source><value>yes</value></copyrightAndOtherRestrictions>
  135. <description><string language="{-H {-P mdlang-}-}">{-L MdCopyright-}</string></description>
  136. </rights>
  137. <classification>
  138. <purpose><source>LOMv1.0</source><value>educational objective</value></purpose>
  139. </classification>
  140. </lom>
  141. </metadata>
  142. </item>
  143. <!-- {--} -->
  144. EOD;
  145. $ieee_dcmap_e = array(
  146. 'Identifier'=> 'metadata/lom/general/identifier[1]',
  147. 'Title'=> 'metadata/lom/general/title[1]',
  148. 'Language'=> 'metadata/lom/general/language[1]',
  149. 'Description'=> 'metadata/lom/general/description[1]',
  150. 'Coverage'=> 'metadata/lom/general/coverage[1]',
  151. 'Type'=> 'metadata/lom/educational/learningResourceType[1]',
  152. 'Date'=> 'metadata/lom/lifeCycle/contribute[1]/date',
  153. 'Creator'=> 'metadata/lom/lifeCycle/contribute[1]/entity',
  154. 'Format'=> 'metadata/lom/technical/format[1]',
  155. 'Rights'=> 'metadata/lom/rights/description[1]');
  156. // maps Dublin Core elements to xmd paths for elements (not yet complete)
  157. $ieee_dcmap_v = array(
  158. 'Identifier'=> 'metadata/lom/general/identifier[1]/entry',
  159. 'Title'=> 'metadata/lom/general/title[1]/string',
  160. 'Language'=> 'metadata/lom/general/language[1]',
  161. 'Description'=> 'metadata/lom/general/description[1]/string',
  162. 'Coverage'=> 'metadata/lom/general/coverage[1]/string',
  163. 'Type'=> 'metadata/lom/educational/learningResourceType[1]/value',
  164. 'Date'=> 'metadata/lom/lifeCycle/contribute[1]/date/dateTime',
  165. 'Creator'=> 'metadata/lom/lifeCycle/contribute[1]/entity',
  166. 'Format'=> 'metadata/lom/technical/format[1]',
  167. 'Rights'=> 'metadata/lom/rights/description[1]/string');
  168. // maps Dublin Core elements to xmd paths for values (not yet complete)
  169. // KEYWORD TREE --------------------------------------------------------------->
  170. function define_kwds($mdo)
  171. {
  172. if (!($newtext = trim(@fgc(get_course_path() . $mdo->mdo_course['path'] .
  173. '/document' . $mdo->mdo_path ))))
  174. {
  175. unlink(KEYWORDS_CACHE); return;
  176. }
  177. // templates to define the tree as JScript object
  178. $xhtDocKw = new xhtdoc(<<<EOD
  179. <!-- {-KWTREE_OBJECT-} -->
  180. KWTREE_OBJECT = {n:"", ti:"{-X @title-}"
  181. , c:[{-R * C DOWN_THE_KWTREE-}]};
  182. document.write(traverseKwObj(KWTREE_OBJECT, '', 0)); KWDS_ARRAY.sort();
  183. <!-- {-DOWN_THE_KWTREE-} -->
  184. {-T number > 1 , -}{n:"{-V @.-}"{-D cm {-X @comment-}-}{-T cm != empty , cm:"{-P cm-}"-}{-D pt {-X @postit-}-}{-T pt != empty , pt:"{-P pt-}"-}{-R * P empty-}{-T number >= 1
  185. , c:[-}{-T number >= 1 R * C DOWN_THE_KWTREE-}{-R * P empty-}{-T number >= 1 ]-}}
  186. <!-- {--} -->
  187. EOD
  188. ); // traverseKwObj (md_script) generates clickable tree and populates KWDS_ARRAY
  189. if ($xhtDocKw->htt_error)
  190. give_up('KwdTree template (metadata/md_funcs): ' . $xhtDocKw->htt_error);
  191. $xhtDocKw->xht_xmldoc = new xmddoc(explode("\n", $newtext));
  192. if ($xhtDocKw->xht_xmldoc->error)
  193. give_up('CourseKwds (metadata/md_funcs): XML error: ' .
  194. $xhtDocKw->xht_xmldoc->error);
  195. if (count($xhtDocKw->xht_xmldoc->children[0]) < 2)
  196. {
  197. unlink(KEYWORDS_CACHE); return;
  198. }
  199. $fileHandler = @fopen(KEYWORDS_CACHE, 'w');
  200. @fwrite($fileHandler, $xhtDocKw->xht_fill_template('KWTREE_OBJECT'));
  201. @fclose($fileHandler);
  202. }
  203. // METADATA STORE ------------------------------------------------------------->
  204. class mdstore
  205. {
  206. var $mds_something;
  207. function mds_get($eid, $column = 'mdxmltext', $must_exist = '') // none: FALSE
  208. {
  209. if (($mdt = Database::fetch_array($this->_query("SELECT " . $column .
  210. " FROM " . MDS_TABLE . " WHERE ", $eid)))) return $mdt[$column];
  211. if ($must_exist) give_up($must_exist . $this->_coldat('eid', $eid));
  212. return FALSE;
  213. }
  214. function mds_get_dc_elements($mdo) // no record: FALSE
  215. {
  216. if (!($mdt = $this->mds_get($mdo->mdo_eid))) return FALSE;
  217. $xmlDoc = new xmddoc(explode("\n", $mdt)); if ($xmlDoc->error) return FALSE;
  218. $result = array();
  219. foreach ($mdo->mdo_dcmap_v as $dce => $xp)
  220. {
  221. $result[$dce] = $xmlDoc->xmd_value($xp);
  222. }
  223. return $result;
  224. }
  225. function mds_get_many($columns, $where_clause)
  226. {
  227. $cols = '';
  228. foreach (explode(',', $columns) as $col) $cols .= "," . trim($col);
  229. if (!$cols) return;
  230. return $this->_query("SELECT " . api_substr($cols, 1) .
  231. " FROM " . MDS_TABLE . " WHERE ". $where_clause);
  232. }
  233. function mds_put($eid, $data, $column = 'mdxmltext', $exists = TRUE)
  234. {
  235. if ($exists === TRUE)
  236. return $this->_query("UPDATE " . MDS_TABLE . " SET " .
  237. $this->_coldat($column, $data) . " WHERE ", $eid);
  238. elseif ($exists === FALSE)
  239. return $this->_query("INSERT INTO " . MDS_TABLE . " SET " .
  240. $this->_coldat($column, $data) . ", ", $eid);
  241. else // user doesn't know, check first whether the record exists
  242. return $this->mds_put($eid, $data, $column,
  243. !($this->mds_get($eid) === FALSE));
  244. }
  245. function mds_put_dc_elements($mdo, $dcelem)
  246. {
  247. if (($mdt = $this->mds_get($mdo->mdo_eid)) === FALSE)
  248. {
  249. $mdt = $mdo->mdo_generate_default_xml_metadata(); $exists = FALSE;
  250. }
  251. else $exists = TRUE;
  252. $xmlDoc = new xmddoc(explode("\n", $mdt)); if ($xmlDoc->error) return FALSE;
  253. foreach ($dcelem as $dce => $value)
  254. {
  255. $xmlDoc->xmd_update($mdo->mdo_dcmap_v[$dce], (string) $value);
  256. }
  257. $this->mds_put($mdo->mdo_eid, '', 'md5', $exists);
  258. return $this->mds_put($mdo->mdo_eid, $xmlDoc->xmd_xml());
  259. }
  260. function mds_append($eid, $moredata, $column = 'indexabletext')
  261. {
  262. if (($olddata = $this->mds_get($eid, $column)) === FALSE) return FALSE;
  263. $this->mds_put($eid, $olddata . $moredata, $column); return $olddata;
  264. }
  265. function mds_delete($eid)
  266. {
  267. return $this->_query("DELETE FROM " . MDS_TABLE . " WHERE ", $eid);
  268. }
  269. function mds_delete_offspring($eid, $sep = '.')
  270. {
  271. return $this->_query("DELETE FROM " . MDS_TABLE . " WHERE ", $eid, $sep);
  272. }
  273. function mds_delete_many($idarray)
  274. {
  275. if (!is_array($idarray) || count($idarray) == 0) return FALSE;
  276. return $this->_query("DELETE FROM " . MDS_TABLE . " WHERE eid IN ('" .
  277. implode("','", array_map('addslashes', $idarray)) . "')");
  278. }
  279. function mds_update_xml_and_mdt($mdo, &$xmlDoc, $mda, $eid, &$traceinfo,
  280. $exists = TRUE) // note: $xmlDoc and $traceinfo passed by reference
  281. {
  282. foreach (explode("\n",
  283. str_replace("\r", "\n", str_replace("\r\n", "\n", $mda))) as $update)
  284. {
  285. if (!$update) continue;
  286. if (($nameLth = strpos($update, '='))) // e.g. 'gen/tit/str=new'
  287. {
  288. if (($text = api_substr($update, $nameLth + 1)) === FALSE) $text = '';
  289. if (!($path = trim(api_substr($update, 0, $nameLth)))) continue;
  290. if (($sc = api_strpos($path, ';'))) // e.g. 'gen/tit,gen/des;str@lang'
  291. $xmlDoc->xmd_update_many(api_substr($path, 0, $sc),
  292. api_substr($path, $sc + 1), $text);
  293. else
  294. $xmlDoc->xmd_update($path, $text);
  295. }
  296. elseif ($nameLth === FALSE) // e.g. 'gen/tit/str[-1]~'
  297. {
  298. if ($update == '~~')
  299. {
  300. $update = 'DELETE ' . $eid;
  301. if ($exists === FALSE) $update = '';
  302. else $this->mds_delete($eid);
  303. $mda = ''; $exists = TRUE;
  304. foreach ($xmlDoc->children[0] as $key => $child)
  305. unset($xmlDoc->children[0][$key]);
  306. }
  307. elseif ($update == '!!')
  308. {
  309. define_kwds($mdo);
  310. $update = ''; $mda = ''; $exists = TRUE;
  311. }
  312. else
  313. {
  314. $x = $xmlDoc->xmd_update(trim($update), '');
  315. }
  316. }
  317. if ($update) $traceinfo .= $update . '- ';
  318. }
  319. $mdt = $xmlDoc->xmd_xml();
  320. if ($exists === FALSE)
  321. {
  322. $this->mds_put($eid, $mdt, 'mdxmltext', FALSE);
  323. $traceinfo .= 'INSERT ' . $eid . '- ';
  324. }
  325. elseif($mda)
  326. {
  327. $this->mds_put($eid, $mdt, 'mdxmltext');
  328. $traceinfo .= 'UPDATE ' . $eid . '- ';
  329. }
  330. return $mdt;
  331. }
  332. function mdstore($allow_create)
  333. {
  334. global $_course; if (!isset($_course)) return;
  335. define('MDS_TABLE', Database::get_course_table(TABLE_METADATA));
  336. $this->_query("CREATE TABLE IF NOT EXISTS " . MDS_TABLE . " ( " .
  337. "eid varchar(250) NOT NULL," . // entry-id, e.g. doc.1
  338. "mdxmltext text default ''," . // MD-text, XML-formatted
  339. "md5 char(32) default ''," . // hash-validator
  340. "htmlcache1 text default ''," . // cached HTML, part 1
  341. "htmlcache2 text default ''," . // cached HTML, part 2
  342. "indexabletext text default ''," . // indexable for search
  343. "PRIMARY KEY (eid) )");
  344. }
  345. function _coldatstart($column, $data)
  346. {
  347. return $column . " LIKE '" . addslashes($data) . "%'";
  348. }
  349. function _coldat($column, $data)
  350. {
  351. return $column . "='" . addslashes($data) . "'";
  352. }
  353. function _query($sql, $eid = '', $sep = '')
  354. {
  355. if ($eid) $sql .= $sep ? $this->_coldatstart('eid', $eid . $sep) :
  356. $this->_coldat('eid', $eid);
  357. return Database::query($sql);
  358. }
  359. }
  360. /*
  361. <!--
  362. This program is free software; you can redistribute it and/or
  363. modify it under the terms of the GNU General Public License
  364. as published by the Free Software Foundation; either version 2
  365. of the License, or (at your option) any later version.
  366. This program is distributed in the hope that it will be useful,
  367. but WITHOUT ANY WARRANTY; without even the implied warranty of
  368. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  369. GNU General Public License for more details.
  370. -->
  371. */
  372. ?>