document.lib.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. <?php
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2008 Dokeos SPRL
  6. Copyright (c) 2003 Ghent University (UGent)
  7. Copyright (c) Roan Embrechts, Vrije Universiteit Brussel
  8. For a full list of contributors, see "credits.txt".
  9. The full license can be read in "license.txt".
  10. This program is free software; you can redistribute it and/or
  11. modify it under the terms of the GNU General Public License
  12. as published by the Free Software Foundation; either version 2
  13. of the License, or (at your option) any later version.
  14. See the GNU General Public License for more details.
  15. Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
  16. Mail: info@dokeos.com
  17. ==============================================================================
  18. */
  19. /**
  20. ==============================================================================
  21. * This is the document library for Dokeos.
  22. * It is / will be used to provide a service layer to all document-using tools.
  23. * and eliminate code duplication fro group documents, scorm documents, main documents.
  24. * Include/require it in your code to use its functionality.
  25. *
  26. * @version 1.1, January 2005
  27. * @package dokeos.library
  28. ==============================================================================
  29. */
  30. /*
  31. ==============================================================================
  32. DOCUMENTATION
  33. use the functions like this: DocumentManager::get_course_quota()
  34. ==============================================================================
  35. */
  36. /*
  37. ==============================================================================
  38. CONSTANTS
  39. ==============================================================================
  40. */
  41. define("DISK_QUOTA_FIELD", "disk_quota"); //name of the database field
  42. /** default quota for the course documents folder */
  43. define("DEFAULT_DOCUMENT_QUOTA", get_setting('default_document_quotum'));
  44. /*
  45. ==============================================================================
  46. VARIABLES
  47. ==============================================================================
  48. */
  49. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  50. $baseServDir = api_get_path(SYS_PATH);
  51. $baseServUrl = $_configuration['url_append']."/";
  52. $baseWorkDir = $sys_course_path.(!empty($courseDir)?$courseDir:'');
  53. /*
  54. ==============================================================================
  55. DocumentManager CLASS
  56. the class and its functions
  57. ==============================================================================
  58. */
  59. /**
  60. * @package dokeos.library
  61. */
  62. class DocumentManager {
  63. private function __construct() {
  64. }
  65. /**
  66. * @return the document folder quuta of the current course, in bytes
  67. * @todo eliminate globals
  68. */
  69. public static function get_course_quota () {
  70. global $_course, $maxFilledSpace;
  71. $course_code = Database::escape_string($_course['sysCode']);
  72. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  73. $sql_query = "SELECT ".DISK_QUOTA_FIELD." FROM $course_table WHERE code = '$course_code'";
  74. $sql_result = api_sql_query($sql_query, __FILE__, __LINE__);
  75. $result = Database::fetch_array($sql_result);
  76. $course_quota = $result[DISK_QUOTA_FIELD];
  77. if ($course_quota == NULL)
  78. {
  79. //course table entry for quota was null
  80. //use default value
  81. $course_quota = DEFAULT_DOCUMENT_QUOTA;
  82. }
  83. return $course_quota;
  84. }
  85. /**
  86. * Get the content type of a file by checking the extension
  87. * We could use mime_content_type() with php-versions > 4.3,
  88. * but this doesn't work as it should on Windows installations
  89. *
  90. * @param string $filename or boolean TRUE to return complete array
  91. * @author ? first version
  92. * @author Bert Vanderkimpen
  93. *
  94. */
  95. public static function file_get_mime_type ($filename) {
  96. //all mime types in an array (from 1.6, this is the authorative source)
  97. //please keep this alphabetical if you add something to this list!!!
  98. $mime_types=array(
  99. "ai" => "application/postscript",
  100. "aif" => "audio/x-aiff",
  101. "aifc" => "audio/x-aiff",
  102. "aiff" => "audio/x-aiff",
  103. "asf" => "video/x-ms-asf",
  104. "asc" => "text/plain",
  105. "au" => "audio/basic",
  106. "avi" => "video/x-msvideo",
  107. "bcpio" => "application/x-bcpio",
  108. "bin" => "application/octet-stream",
  109. "bmp" => "image/bmp",
  110. "cdf" => "application/x-netcdf",
  111. "class" => "application/octet-stream",
  112. "cpio" => "application/x-cpio",
  113. "cpt" => "application/mac-compactpro",
  114. "csh" => "application/x-csh",
  115. "css" => "text/css",
  116. "dcr" => "application/x-director",
  117. "dir" => "application/x-director",
  118. "djv" => "image/vnd.djvu",
  119. "djvu" => "image/vnd.djvu",
  120. "dll" => "application/octet-stream",
  121. "dmg" => "application/x-diskcopy",
  122. "dms" => "application/octet-stream",
  123. "doc" => "application/msword",
  124. "dvi" => "application/x-dvi",
  125. "dwg" => "application/vnd.dwg",
  126. "dxf" => "application/vnd.dxf",
  127. "dxr" => "application/x-director",
  128. "eps" => "application/postscript",
  129. "etx" => "text/x-setext",
  130. "exe" => "application/octet-stream",
  131. "ez" => "application/andrew-inset",
  132. "gif" => "image/gif",
  133. "gtar" => "application/x-gtar",
  134. "gz" => "application/x-gzip",
  135. "hdf" => "application/x-hdf",
  136. "hqx" => "application/mac-binhex40",
  137. "htm" => "text/html",
  138. "html" => "text/html",
  139. "ice" => "x-conference-xcooltalk",
  140. "ief" => "image/ief",
  141. "iges" => "model/iges",
  142. "igs" => "model/iges",
  143. "jar" => "application/java-archiver",
  144. "jpe" => "image/jpeg",
  145. "jpeg" => "image/jpeg",
  146. "jpg" => "image/jpeg",
  147. "js" => "application/x-javascript",
  148. "kar" => "audio/midi",
  149. "latex" => "application/x-latex",
  150. "lha" => "application/octet-stream",
  151. "lzh" => "application/octet-stream",
  152. "m1a" => "audio/mpeg",
  153. "m2a" => "audio/mpeg",
  154. "m3u" => "audio/x-mpegurl",
  155. "man" => "application/x-troff-man",
  156. "me" => "application/x-troff-me",
  157. "mesh" => "model/mesh",
  158. "mid" => "audio/midi",
  159. "midi" => "audio/midi",
  160. "mov" => "video/quicktime",
  161. "movie" => "video/x-sgi-movie",
  162. "mp2" => "audio/mpeg",
  163. "mp3" => "audio/mpeg",
  164. "mp4" => "video/mpeg4-generic",
  165. "mpa" => "audio/mpeg",
  166. "mpe" => "video/mpeg",
  167. "mpeg" => "video/mpeg",
  168. "mpg" => "video/mpeg",
  169. "mpga" => "audio/mpeg",
  170. "ms" => "application/x-troff-ms",
  171. "msh" => "model/mesh",
  172. "mxu" => "video/vnd.mpegurl",
  173. "nc" => "application/x-netcdf",
  174. "oda" => "application/oda",
  175. "pbm" => "image/x-portable-bitmap",
  176. "pct" => "image/pict",
  177. "pdb" => "chemical/x-pdb",
  178. "pdf" => "application/pdf",
  179. "pgm" => "image/x-portable-graymap",
  180. "pgn" => "application/x-chess-pgn",
  181. "pict" => "image/pict",
  182. "png" => "image/png",
  183. "pnm" => "image/x-portable-anymap",
  184. "ppm" => "image/x-portable-pixmap",
  185. "ppt" => "application/vnd.ms-powerpoint",
  186. "pps" => "application/vnd.ms-powerpoint",
  187. "ps" => "application/postscript",
  188. "qt" => "video/quicktime",
  189. "ra" => "audio/x-realaudio",
  190. "ram" => "audio/x-pn-realaudio",
  191. "rar" => "image/x-rar-compressed",
  192. "ras" => "image/x-cmu-raster",
  193. "rgb" => "image/x-rgb",
  194. "rm" => "audio/x-pn-realaudio",
  195. "roff" => "application/x-troff",
  196. "rpm" => "audio/x-pn-realaudio-plugin",
  197. "rtf" => "text/rtf",
  198. "rtx" => "text/richtext",
  199. "sgm" => "text/sgml",
  200. "sgml" => "text/sgml",
  201. "sh" => "application/x-sh",
  202. "shar" => "application/x-shar",
  203. "silo" => "model/mesh",
  204. "sib" => "application/X-Sibelius-Score",
  205. "sit" => "application/x-stuffit",
  206. "skd" => "application/x-koan",
  207. "skm" => "application/x-koan",
  208. "skp" => "application/x-koan",
  209. "skt" => "application/x-koan",
  210. "smi" => "application/smil",
  211. "smil" => "application/smil",
  212. "snd" => "audio/basic",
  213. "so" => "application/octet-stream",
  214. "spl" => "application/x-futuresplash",
  215. "src" => "application/x-wais-source",
  216. "sv4cpio" => "application/x-sv4cpio",
  217. "sv4crc" => "application/x-sv4crc",
  218. "svf" => "application/vnd.svf",
  219. "swf" => "application/x-shockwave-flash",
  220. "sxc" => "application/vnd.sun.xml.calc",
  221. "sxi" => "application/vnd.sun.xml.impress",
  222. "sxw" => "application/vnd.sun.xml.writer",
  223. "t" => "application/x-troff",
  224. "tar" => "application/x-tar",
  225. "tcl" => "application/x-tcl",
  226. "tex" => "application/x-tex",
  227. "texi" => "application/x-texinfo",
  228. "texinfo" => "application/x-texinfo",
  229. "tga" => "image/x-targa",
  230. "tif" => "image/tif",
  231. "tiff" => "image/tiff",
  232. "tr" => "application/x-troff",
  233. "tsv" => "text/tab-seperated-values",
  234. "txt" => "text/plain",
  235. "ustar" => "application/x-ustar",
  236. "vcd" => "application/x-cdlink",
  237. "vrml" => "model/vrml",
  238. "wav" => "audio/x-wav",
  239. "wbmp" => "image/vnd.wap.wbmp",
  240. "wbxml" => "application/vnd.wap.wbxml",
  241. "wml" => "text/vnd.wap.wml",
  242. "wmlc" => "application/vnd.wap.wmlc",
  243. "wmls" => "text/vnd.wap.wmlscript",
  244. "wmlsc" => "application/vnd.wap.wmlscriptc",
  245. "wma" => "video/x-ms-wma",
  246. "wmv" => "audio/x-ms-wmv",
  247. "wrl" => "model/vrml",
  248. "xbm" => "image/x-xbitmap",
  249. "xht" => "application/xhtml+xml",
  250. "xhtml" => "application/xhtml+xml",
  251. "xls" => "application/vnd.ms-excel",
  252. "xml" => "text/xml",
  253. "xpm" => "image/x-xpixmap",
  254. "xsl" => "text/xml",
  255. "xwd" => "image/x-windowdump",
  256. "xyz" => "chemical/x-xyz",
  257. "zip" => "application/zip"
  258. );
  259. if ($filename === TRUE)
  260. {
  261. return $mime_types;
  262. }
  263. //get the extension of the file
  264. $extension = explode('.', $filename);
  265. //$filename will be an array if a . was found
  266. if (is_array($extension))
  267. {
  268. $extension = (strtolower($extension[sizeof($extension) - 1]));
  269. }
  270. //file without extension
  271. else
  272. {
  273. $extension = 'empty';
  274. }
  275. //if the extension is found, return the content type
  276. if (isset ($mime_types[$extension]))
  277. return $mime_types[$extension];
  278. //else return octet-stream
  279. return "application/octet-stream";
  280. }
  281. /**
  282. * @return true if the user is allowed to see the document, false otherwise
  283. * @author Sergio A Kessler, first version
  284. * @author Roan Embrechts, bugfix
  285. * @todo ??not only check if a file is visible, but also check if the user is allowed to see the file??
  286. */
  287. public static function file_visible_to_user ($this_course, $doc_url) {
  288. if (api_is_allowed_to_edit())
  289. {
  290. return true;
  291. }
  292. else
  293. {
  294. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  295. $tbl_item_property = $this_course.'item_property';
  296. $doc_url = Database::escape_string($doc_url);
  297. //$doc_url = addslashes($doc_url);
  298. $query = "SELECT 1 FROM $tbl_document AS docs,$tbl_item_property AS props
  299. WHERE props.tool = 'document' AND docs.id=props.ref AND props.visibility <> '1' AND docs.path = '$doc_url'";
  300. //echo $query;
  301. $result = api_sql_query($query, __FILE__, __LINE__);
  302. return (Database::num_rows($result) == 0);
  303. }
  304. }
  305. /**
  306. * This function streams a file to the client
  307. *
  308. * @param string $full_file_name
  309. * @param boolean $forced
  310. * @param string $name
  311. * @return false if file doesn't exist, true if stream succeeded
  312. */
  313. public static function file_send_for_download ($full_file_name, $forced = false, $name = '') {
  314. if (!is_file($full_file_name))
  315. {
  316. return false;
  317. }
  318. $filename = ($name == '') ? basename($full_file_name) : $name;
  319. $len = filesize($full_file_name);
  320. if ($forced)
  321. {
  322. //force the browser to save the file instead of opening it
  323. header('Content-type: application/octet-stream');
  324. //header('Content-Type: application/force-download');
  325. header('Content-length: '.$len);
  326. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT']))
  327. {
  328. header('Content-Disposition: filename= '.$filename);
  329. }
  330. else
  331. {
  332. header('Content-Disposition: attachment; filename= '.$filename);
  333. }
  334. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  335. {
  336. header('Pragma: ');
  337. header('Cache-Control: ');
  338. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  339. }
  340. header('Content-Description: '.$filename);
  341. header('Content-transfer-encoding: binary');
  342. $fp = fopen($full_file_name, 'r');
  343. fpassthru($fp);
  344. return true;
  345. }
  346. else
  347. {
  348. //no forced download, just let the browser decide what to do according to the mimetype
  349. $content_type = self::file_get_mime_type($filename);
  350. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  351. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  352. // Commented to avoid double caching declaration when playing with IE and HTTPS
  353. //header('Cache-Control: no-cache, must-revalidate');
  354. //header('Pragma: no-cache');
  355. header('Content-type: '.$content_type);
  356. header('Content-Length: '.$len);
  357. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  358. if (strpos($user_agent, 'msie'))
  359. {
  360. header('Content-Disposition: ; filename= '.$filename);
  361. }
  362. else
  363. {
  364. header('Content-Disposition: inline; filename= '.$filename);
  365. }
  366. readfile($full_file_name);
  367. return true;
  368. }
  369. }
  370. /**
  371. * This function streams a string to the client for download.
  372. * You have to ensure that the calling script then stops processing (exit();)
  373. * otherwise it may cause subsequent use of the page to want to download
  374. * other pages in php rather than interpreting them.
  375. *
  376. * @param string The string contents
  377. * @param boolean Whether "save" mode is forced (or opening directly authorized)
  378. * @param string The name of the file in the end (including extension)
  379. * @return false if file doesn't exist, true if stream succeeded
  380. */
  381. public static function string_send_for_download ($full_string, $forced = false, $name = '') {
  382. $filename = $name;
  383. $len = strlen($full_string);
  384. if ($forced)
  385. {
  386. //force the browser to save the file instead of opening it
  387. header('Content-type: application/octet-stream');
  388. //header('Content-Type: application/force-download');
  389. header('Content-length: '.$len);
  390. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT']))
  391. {
  392. header('Content-Disposition: filename= '.$filename);
  393. }
  394. else
  395. {
  396. header('Content-Disposition: attachment; filename= '.$filename);
  397. }
  398. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  399. {
  400. header('Pragma: ');
  401. header('Cache-Control: ');
  402. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  403. }
  404. header('Content-Description: '.$filename);
  405. header('Content-transfer-encoding: binary');
  406. //$fp = fopen($full_string, 'r');
  407. //fpassthru($fp);
  408. echo $full_string;
  409. return true;
  410. //You have to ensure that the calling script then stops processing (exit();)
  411. //otherwise it may cause subsequent use of the page to want to download
  412. //other pages in php rather than interpreting them.
  413. }
  414. else
  415. {
  416. //no forced download, just let the browser decide what to do according to the mimetype
  417. $content_type = self::file_get_mime_type($filename);
  418. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  419. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  420. header('Cache-Control: no-cache, must-revalidate');
  421. header('Pragma: no-cache');
  422. header('Content-type: '.$content_type);
  423. header('Content-Length: '.$len);
  424. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  425. if (strpos($user_agent, 'msie'))
  426. {
  427. header('Content-Disposition: ; filename= '.$filename);
  428. }
  429. else
  430. {
  431. header('Content-Disposition: inline; filename= '.$filename);
  432. }
  433. echo($full_string);
  434. //You have to ensure that the calling script then stops processing (exit();)
  435. //otherwise it may cause subsequent use of the page to want to download
  436. //other pages in php rather than interpreting them.
  437. return true;
  438. }
  439. }
  440. /**
  441. * Fetches all document data for the given user/group
  442. *
  443. * @param array $_course
  444. * @param string $path
  445. * @param int $to_group_id
  446. * @param int $to_user_id
  447. * @param boolean $can_see_invisible
  448. * @return array with all document data
  449. */
  450. public static function get_all_document_data ($_course, $path = '/', $to_group_id = 0, $to_user_id = NULL, $can_see_invisible = false) {
  451. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  452. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  453. //if to_user_id = NULL -> change query (IS NULL)
  454. //$to_user_id = (is_null($to_user_id))?'IS NULL':'= '.$to_user_id;
  455. if (!is_null($to_user_id))
  456. {
  457. $to_field = 'last.to_user_id';
  458. $to_value = $to_user_id;
  459. }
  460. else
  461. {
  462. $to_field = 'last.to_group_id';
  463. $to_value = $to_group_id;
  464. }
  465. //escape underscores in the path so they don't act as a wildcard
  466. $path = Database::escape_string(str_replace('_', '\_', $path));
  467. $to_user_id = Database::escape_string($to_user_id);
  468. $to_value = Database::escape_string($to_value);
  469. //if they can't see invisible files, they can only see files with visibility 1
  470. $visibility_bit = ' = 1';
  471. //if they can see invisible files, only deleted files (visibility 2) are filtered out
  472. if ($can_see_invisible)
  473. {
  474. $visibility_bit = ' <> 2';
  475. }
  476. //the given path will not end with a slash, unless it's the root '/'
  477. //so no root -> add slash
  478. $added_slash = ($path == '/') ? '' : '/';
  479. $sql = "SELECT *
  480. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  481. WHERE docs.id = last.ref
  482. AND docs.path LIKE '".$path.$added_slash."%'
  483. AND docs.path NOT LIKE '".$path.$added_slash."%/%'
  484. AND last.tool = '".TOOL_DOCUMENT."'
  485. AND ".$to_field." = ".$to_value."
  486. AND last.visibility".$visibility_bit;
  487. //echo $sql;
  488. $result = api_sql_query($sql);
  489. if ($result && Database::num_rows($result) != 0)
  490. {
  491. while ($row = Database::fetch_array($result,'ASSOC'))
  492. //while ($row = Database::fetch_array($result,MYSQL_NUM))
  493. {
  494. if($row['filetype']=='file' && pathinfo($row['path'],PATHINFO_EXTENSION)=='html'){
  495. //Templates management
  496. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  497. $sql_is_template = "SELECT id FROM $table_template
  498. WHERE course_code='".$_course['id']."'
  499. AND user_id='".api_get_user_id()."'
  500. AND ref_doc='".$row['id']."'";
  501. $template_result = api_sql_query($sql_is_template);
  502. if(Database::num_rows($template_result)>0){
  503. $row['is_template'] = 1;
  504. }
  505. else{
  506. $row['is_template'] = 0;
  507. }
  508. }
  509. $document_data[$row['id']] = $row;
  510. //$document_data[] = $row;
  511. }
  512. return $document_data;
  513. }
  514. else
  515. {
  516. //display_error("Error getting document info from database (".mysql_error().")!");
  517. return false;
  518. }
  519. }
  520. /**
  521. * Gets the paths of all folders in a course
  522. * can show all folders (exept for the deleted ones) or only visible ones
  523. * @param array $_course
  524. * @param boolean $can_see_invisible
  525. * @param int $to_group_id
  526. * @return array with paths
  527. */
  528. public static function get_all_document_folders ($_course, $to_group_id = '0', $can_see_invisible = false) {
  529. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  530. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  531. if(empty($doc_url)){
  532. $to_group_id = '0';
  533. } else {
  534. $to_group_id = Database::escape_string($to_group_id);
  535. }
  536. if ($can_see_invisible)
  537. {
  538. $sql = "SELECT path
  539. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  540. WHERE docs.id = last.ref
  541. AND docs.filetype = 'folder'
  542. AND last.tool = '".TOOL_DOCUMENT."'
  543. AND last.to_group_id = ".$to_group_id."
  544. AND last.visibility <> 2";
  545. $result = api_sql_query($sql, __FILE__, __LINE__);
  546. if ($result && Database::num_rows($result) != 0)
  547. {
  548. while ($row = Database::fetch_array($result,'ASSOC'))
  549. {
  550. $document_folders[] = $row['path'];
  551. }
  552. //sort($document_folders);
  553. natsort($document_folders);
  554. //return results
  555. return $document_folders;
  556. }
  557. else
  558. {
  559. return false;
  560. }
  561. }
  562. //no invisible folders
  563. else
  564. {
  565. //get visible folders
  566. $visible_sql = "SELECT path
  567. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  568. WHERE docs.id = last.ref
  569. AND docs.filetype = 'folder'
  570. AND last.tool = '".TOOL_DOCUMENT."'
  571. AND last.to_group_id = ".$to_group_id."
  572. AND last.visibility = 1";
  573. $visibleresult = api_sql_query($visible_sql, __FILE__, __LINE__);
  574. while ($all_visible_folders = Database::fetch_array($visibleresult,'ASSOC'))
  575. {
  576. $visiblefolders[] = $all_visible_folders['path'];
  577. //echo "visible folders: ".$all_visible_folders['path']."<br>";
  578. }
  579. //get invisible folders
  580. $invisible_sql = "SELECT path
  581. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  582. WHERE docs.id = last.ref
  583. AND docs.filetype = 'folder'
  584. AND last.tool = '".TOOL_DOCUMENT."'
  585. AND last.to_group_id = ".$to_group_id."
  586. AND last.visibility = 0";
  587. $invisibleresult = api_sql_query($invisible_sql, __FILE__, __LINE__);
  588. while ($invisible_folders = Database::fetch_array($invisibleresult,'ASSOC'))
  589. {
  590. //get visible folders in the invisible ones -> they are invisible too
  591. //echo "invisible folders: ".$invisible_folders['path']."<br>";
  592. $folder_in_invisible_sql = "SELECT path
  593. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  594. WHERE docs.id = last.ref
  595. AND docs.path LIKE '".Database::escape_string($invisible_folders['path'])."/%'
  596. AND docs.filetype = 'folder'
  597. AND last.tool = '".TOOL_DOCUMENT."'
  598. AND last.to_group_id = ".$to_group_id."
  599. AND last.visibility = 1";
  600. $folder_in_invisible_result = api_sql_query($folder_in_invisible_sql, __FILE__, __LINE__);
  601. while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result,'ASSOC'))
  602. {
  603. $invisiblefolders[] = $folders_in_invisible_folder['path'];
  604. //echo "<br>folders in invisible folders: ".$folders_in_invisible_folder['path']."<br><br><br>";
  605. }
  606. }
  607. //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
  608. if (is_array($visiblefolders) && is_array($invisiblefolders))
  609. {
  610. $document_folders = array_diff($visiblefolders, $invisiblefolders);
  611. //sort($document_folders);
  612. natsort($document_folders);
  613. return $document_folders;
  614. }
  615. //only visible folders found
  616. elseif (is_array($visiblefolders))
  617. {
  618. //sort($visiblefolders);
  619. natsort($visiblefolders);
  620. return $visiblefolders;
  621. }
  622. //no visible folders found
  623. else
  624. {
  625. return false;
  626. }
  627. }
  628. }
  629. /**
  630. * This check if a document has the readonly property checked, then see if the user
  631. * is the owner of this file, if all this is true then return true.
  632. *
  633. * @param array $_course
  634. * @param int $user_id id of the current user
  635. * @param string $file path stored in the database
  636. * @param int $document_id in case you dont have the file path ,insert the id of the file here and leave $file in blank ''
  637. * @return boolean true/false
  638. **/
  639. public static function check_readonly ($_course,$user_id,$file,$document_id='',$to_delete=false) {
  640. if(!(!empty($document_id) && is_numeric($document_id)))
  641. {
  642. $document_id = self::get_document_id($_course, $file);
  643. }
  644. $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  645. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  646. if ($to_delete)
  647. {
  648. if (self::is_folder($_course, $document_id))
  649. {
  650. if (!empty($file))
  651. {
  652. $path = Database::escape_string($file);
  653. $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM ".$TABLE_DOCUMENT." td , $TABLE_PROPERTY tp
  654. WHERE tp.ref= td.id and (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
  655. //get all id's of documents that are deleted
  656. $what_to_check_result = api_sql_query($what_to_check_sql, __FILE__, __LINE__);
  657. if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0)
  658. {
  659. // file with readonly set to 1 exist?
  660. $readonly_set=false;
  661. while ($row = Database::fetch_array($what_to_check_result))
  662. {
  663. //query to delete from item_property table
  664. //echo $row['id']; echo "<br>";
  665. if ($row['readonly']==1)
  666. {
  667. if (!($row['insert_user_id'] == $user_id))
  668. {
  669. $readonly_set=true;
  670. break;
  671. }
  672. }
  673. }
  674. if ($readonly_set)
  675. {
  676. return true;
  677. }
  678. }
  679. }
  680. return false;
  681. }
  682. }
  683. if (!empty($document_id))
  684. {
  685. $sql= 'SELECT a.insert_user_id, b.readonly FROM '.$TABLE_PROPERTY.' a,'.$TABLE_DOCUMENT.' b
  686. WHERE a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
  687. $resultans = api_sql_query($sql, __FILE__, __LINE__);
  688. $doc_details = Database ::fetch_array($resultans,'ASSOC');
  689. if($doc_details['readonly']==1)
  690. {
  691. if ( $doc_details['insert_user_id'] == $user_id || api_is_platform_admin() )
  692. {
  693. return false;
  694. }
  695. else
  696. {
  697. return true;
  698. }
  699. }
  700. }
  701. return false;
  702. }
  703. /**
  704. * This check if a document is a folder or not
  705. * @param array $_course
  706. * @param int $document_id of the item
  707. * @return boolean true/false
  708. **/
  709. public static function is_folder ($_course, $document_id) {
  710. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  711. //if (!empty($document_id))
  712. $document_id = Database::escape_string($document_id);
  713. $resultans = api_sql_query('SELECT filetype FROM '.$TABLE_DOCUMENT.' WHERE id='.$document_id.'', __FILE__, __LINE__);
  714. $result= Database::fetch_array($resultans,'ASSOC');
  715. if ($result['filetype']=='folder') {
  716. return true;
  717. } else {
  718. return false;
  719. }
  720. }
  721. /**
  722. * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
  723. * Files/folders that are inside a deleted folder get visibility 2
  724. *
  725. * @param array $_course
  726. * @param string $path, path stored in the database
  727. * @param string ,$base_work_dir, path to the documents folder
  728. * @return boolean true/false
  729. * @todo now only files/folders in a folder get visibility 2, we should rename them too.
  730. */
  731. public static function delete_document ($_course, $path, $base_work_dir) {
  732. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  733. $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  734. //first, delete the actual document...
  735. $document_id = self :: get_document_id($_course, $path);
  736. $new_path = $path.'_DELETED_'.$document_id;
  737. if ($document_id)
  738. {
  739. if (get_setting('permanently_remove_deleted_files') == 'true') //deleted files are *really* deleted
  740. {
  741. $what_to_delete_sql = "SELECT id FROM ".$TABLE_DOCUMENT." WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  742. //get all id's of documents that are deleted
  743. $what_to_delete_result = api_sql_query($what_to_delete_sql, __FILE__, __LINE__);
  744. if ($what_to_delete_result && Database::num_rows($what_to_delete_result) != 0)
  745. {
  746. //needed to deleted medadata
  747. require_once (api_get_path(SYS_CODE_PATH).'metadata/md_funcs.php');
  748. require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
  749. $mdStore = new mdstore(TRUE);
  750. //delete all item_property entries
  751. while ($row = Database::fetch_array($what_to_delete_result))
  752. {
  753. //query to delete from item_property table
  754. //avoid wrong behavior
  755. //$remove_from_item_property_sql = "DELETE FROM ".$TABLE_ITEMPROPERTY." WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  756. api_item_property_update($_course, TOOL_DOCUMENT, $row['id'], 'delete', api_get_user_id());
  757. //query to delete from document table
  758. $remove_from_document_sql = "DELETE FROM ".$TABLE_DOCUMENT." WHERE id = ".$row['id']."";
  759. self::unset_document_as_template($row['id'],$_course, api_get_user_id());
  760. //echo($remove_from_item_property_sql.'<br>');
  761. //api_sql_query($remove_from_item_property_sql, __FILE__, __LINE__);
  762. //echo($remove_from_document_sql.'<br>');
  763. api_sql_query($remove_from_document_sql, __FILE__, __LINE__);
  764. //delete metadata
  765. $eid = 'Document'.'.'.$row['id'];
  766. $mdStore->mds_delete($eid);
  767. $mdStore->mds_delete_offspring($eid);
  768. }
  769. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  770. //delete documents, do it like this so metadata get's deleted too
  771. //update_db_info('delete', $path);
  772. //throw it away
  773. my_delete($base_work_dir.$path);
  774. return true;
  775. }
  776. else
  777. {
  778. return false;
  779. }
  780. }
  781. else //set visibility to 2 and rename file/folder to qsdqsd_DELETED_#id
  782. {
  783. if (api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'delete', api_get_user_id()))
  784. {
  785. //echo('item_property_update OK');
  786. if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path) )
  787. {
  788. if(rename($base_work_dir.$path, $base_work_dir.$new_path))
  789. {
  790. self::unset_document_as_template($document_id, api_get_course_id(), api_get_user_id());
  791. $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE id='".$document_id."'";
  792. if (api_sql_query($sql, __FILE__, __LINE__))
  793. {
  794. //if it is a folder it can contain files
  795. $sql = "SELECT id,path FROM ".$TABLE_DOCUMENT." WHERE path LIKE BINARY '".$path."/%'";
  796. $result = api_sql_query($sql, __FILE__, __LINE__);
  797. if ($result && Database::num_rows($result) > 0)
  798. {
  799. while ($deleted_items = Database::fetch_array($result,'ASSOC'))
  800. {
  801. //echo('to delete also: id '.$deleted_items['id']);
  802. api_item_property_update($_course, TOOL_DOCUMENT, $deleted_items['id'], 'delete', api_get_user_id());
  803. //Change path of subfolders and documents in database
  804. $old_item_path = $deleted_items['path'];
  805. $new_item_path = $new_path.substr($old_item_path, strlen($path));
  806. /*/
  807. * trying to fix this bug FS#2681
  808. echo $base_work_dir.$old_item_path;
  809. echo "<br>";
  810. echo $base_work_dir.$new_item_path;
  811. echo "<br>";echo "<br>";
  812. rename($base_work_dir.$old_item_path, $base_work_dir.$new_item_path);
  813. */
  814. self::unset_document_as_template($deleted_items['id'], api_get_course_id(), api_get_user_id());
  815. $sql = "UPDATE $TABLE_DOCUMENT set path = '".$new_item_path."' WHERE id = ".$deleted_items['id'];
  816. api_sql_query($sql, __FILE__, __LINE__);
  817. }
  818. }
  819. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  820. return true;
  821. }
  822. }
  823. else
  824. {
  825. //Couldn't rename - file permissions problem?
  826. error_log(__FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',0);
  827. }
  828. }
  829. else
  830. { //echo $base_work_dir.$path;
  831. //The file or directory isn't there anymore (on the filesystem)
  832. // This means it has been removed externally. To prevent a
  833. // blocking error from happening, we drop the related items from the
  834. // item_property and the document table.
  835. error_log(__FILE__.' '.__LINE__.': System inconsistency detected. The file or directory '.$base_work_dir.$path.' seems to have been removed from the filesystem independently from the web platform. To restore consistency, the elements using the same path will be removed from the database',0);
  836. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  837. $res = Database::query($sql,__FILE__,__LINE__);
  838. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  839. while ( $row = Database::fetch_array($res) )
  840. {
  841. $sqlipd = "DELETE FROM $TABLE_ITEMPROPERTY WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  842. $resipd = Database::query($sqlipd,__FILE__,__LINE__);
  843. self::unset_document_as_template($row['id'],api_get_course_id(), api_get_user_id());
  844. $sqldd = "DELETE FROM $TABLE_DOCUMENT WHERE id = ".$row['id'];
  845. $resdd = Database::query($sqldd,__FILE__,__LINE__);
  846. }
  847. }
  848. }
  849. }
  850. }
  851. return false;
  852. }
  853. /**
  854. * Removes documents from search engine database
  855. *
  856. * @param string $course_id Course code
  857. * @param int $document_id Document id to delete
  858. */
  859. public static function delete_document_from_search_engine ($course_id, $document_id) {
  860. // remove from search engine if enabled
  861. if (api_get_setting('search_enabled') == 'true') {
  862. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  863. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  864. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  865. $res = api_sql_query($sql, __FILE__, __LINE__);
  866. if (Database::num_rows($res) > 0) {
  867. $row2 = Database::fetch_array($res);
  868. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  869. $di = new DokeosIndexer();
  870. $di->remove_document((int)$row2['search_did']);
  871. }
  872. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  873. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  874. api_sql_query($sql, __FILE__, __LINE__);
  875. // remove terms from db
  876. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  877. delete_all_values_for_item($course_id, TOOL_DOCUMENT, $document_id);
  878. }
  879. }
  880. /**
  881. * Gets the id of a document with a given path
  882. *
  883. * @param array $_course
  884. * @param string $path
  885. * @return int id of document / false if no doc found
  886. */
  887. public static function get_document_id ($_course, $path) {
  888. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  889. $path = Database::escape_string($path);
  890. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path LIKE BINARY '$path'";
  891. $result = api_sql_query($sql, __FILE__, __LINE__);
  892. if ($result && Database::num_rows($result) == 1) {
  893. $row = Database::fetch_array($result);
  894. return $row[0];
  895. } else {
  896. return false;
  897. }
  898. }
  899. /**
  900. * Allow to set a specific document as a new template for FCKEditor for a particular user in a particular course
  901. *
  902. * @param string $title
  903. * @param string $description
  904. * @param int $document_id_for_template the document id
  905. * @param string $couse_code
  906. * @param int $user_id
  907. */
  908. public static function set_document_as_template ($title, $description, $document_id_for_template, $couse_code, $user_id, $image) {
  909. // Database table definition
  910. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  911. // creating the sql statement
  912. $sql = "INSERT INTO ".$table_template."
  913. (title, description, course_code, user_id, ref_doc, image)
  914. VALUES (
  915. '".Database::escape_string($title)."',
  916. '".Database::escape_string($description)."',
  917. '".Database::escape_string($couse_code)."',
  918. '".Database::escape_string($user_id)."',
  919. '".Database::escape_string($document_id_for_template)."',
  920. '".Database::escape_string($image)."')";
  921. api_sql_query($sql);
  922. return true;
  923. }
  924. /**
  925. * Unset a document as template
  926. *
  927. * @param int $document_id
  928. * @param string $couse_code
  929. * @param int $user_id
  930. */
  931. public static function unset_document_as_template ($document_id, $course_code, $user_id) {
  932. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  933. $course_code = Database::escape_string($course_code);
  934. $user_id = Database::escape_string($user_id);
  935. $document_id = Database::escape_string($document_id);
  936. $sql = 'SELECT id FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  937. $result = api_sql_query($sql);
  938. $template_id = Database::result($result,0,0);
  939. include_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
  940. my_delete(api_get_path(SYS_CODE_PATH).'upload/template_thumbnails/'.$template_id.'.jpg');
  941. $sql = 'DELETE FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  942. api_sql_query($sql);
  943. }
  944. /**
  945. * return true if the documentpath have visibility=1 as item_property
  946. *
  947. * @param string $document_path the relative complete path of the document
  948. * @param array $course the _course array info of the document's course
  949. */
  950. public static function is_visible ($doc_path, $course) {
  951. $docTable = Database::get_course_table(TABLE_DOCUMENT, $course['dbName']);
  952. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);
  953. //note the extra / at the end of doc_path to match every path in the
  954. // document table that is part of the document path
  955. $doc_path = Database::escape_string($doc_path);
  956. $sql = "SELECT path FROM $docTable d, $propTable ip " .
  957. "where d.id=ip.ref AND ip.tool='".TOOL_DOCUMENT."' AND d.filetype='file' AND visibility=0 AND ".
  958. "locate(concat(path,'/'),'".$doc_path."/')=1";
  959. $result = api_sql_query($sql,__FILE__,__LINE__);
  960. if (Database::num_rows($result) > 0){
  961. $row = Database::fetch_array($result);
  962. //echo "$row[0] not visible";
  963. return false;
  964. }
  965. //improved protection of documents viewable directly through the url: incorporates the same protections of the course at the url of documents: access allowed for the whole world Open, access allowed for users registered on the platform Private access, document accessible only to course members (see the Users list), Completely closed; the document is only accessible to the course admin and teaching assistants.
  966. if ($_SESSION ['is_allowed_in_course'] || api_is_platform_admin())
  967. {
  968. return true; // ok, document is visible
  969. }
  970. else
  971. {
  972. return false;
  973. }
  974. }
  975. }
  976. //end class DocumentManager
  977. ?>