document.lib.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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. {
  64. /**
  65. * @return the document folder quuta of the current course, in bytes
  66. * @todo eliminate globals
  67. */
  68. function get_course_quota()
  69. {
  70. global $_course, $maxFilledSpace;
  71. $course_code = $_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. function file_get_mime_type($filename)
  96. {
  97. //all mime types in an array (from 1.6, this is the authorative source)
  98. //please keep this alphabetical if you add something to this list!!!
  99. $mime_types=array(
  100. "ai" => "application/postscript",
  101. "aif" => "audio/x-aiff",
  102. "aifc" => "audio/x-aiff",
  103. "aiff" => "audio/x-aiff",
  104. "asf" => "video/x-ms-asf",
  105. "asc" => "text/plain",
  106. "au" => "audio/basic",
  107. "avi" => "video/x-msvideo",
  108. "bcpio" => "application/x-bcpio",
  109. "bin" => "application/octet-stream",
  110. "bmp" => "image/bmp",
  111. "cdf" => "application/x-netcdf",
  112. "class" => "application/octet-stream",
  113. "cpio" => "application/x-cpio",
  114. "cpt" => "application/mac-compactpro",
  115. "csh" => "application/x-csh",
  116. "css" => "text/css",
  117. "dcr" => "application/x-director",
  118. "dir" => "application/x-director",
  119. "djv" => "image/vnd.djvu",
  120. "djvu" => "image/vnd.djvu",
  121. "dll" => "application/octet-stream",
  122. "dmg" => "application/x-diskcopy",
  123. "dms" => "application/octet-stream",
  124. "doc" => "application/msword",
  125. "dvi" => "application/x-dvi",
  126. "dwg" => "application/vnd.dwg",
  127. "dxf" => "application/vnd.dxf",
  128. "dxr" => "application/x-director",
  129. "eps" => "application/postscript",
  130. "etx" => "text/x-setext",
  131. "exe" => "application/octet-stream",
  132. "ez" => "application/andrew-inset",
  133. "gif" => "image/gif",
  134. "gtar" => "application/x-gtar",
  135. "gz" => "application/x-gzip",
  136. "hdf" => "application/x-hdf",
  137. "hqx" => "application/mac-binhex40",
  138. "htm" => "text/html",
  139. "html" => "text/html",
  140. "ice" => "x-conference-xcooltalk",
  141. "ief" => "image/ief",
  142. "iges" => "model/iges",
  143. "igs" => "model/iges",
  144. "jar" => "application/java-archiver",
  145. "jpe" => "image/jpeg",
  146. "jpeg" => "image/jpeg",
  147. "jpg" => "image/jpeg",
  148. "js" => "application/x-javascript",
  149. "kar" => "audio/midi",
  150. "latex" => "application/x-latex",
  151. "lha" => "application/octet-stream",
  152. "lzh" => "application/octet-stream",
  153. "m1a" => "audio/mpeg",
  154. "m2a" => "audio/mpeg",
  155. "m3u" => "audio/x-mpegurl",
  156. "man" => "application/x-troff-man",
  157. "me" => "application/x-troff-me",
  158. "mesh" => "model/mesh",
  159. "mid" => "audio/midi",
  160. "midi" => "audio/midi",
  161. "mov" => "video/quicktime",
  162. "movie" => "video/x-sgi-movie",
  163. "mp2" => "audio/mpeg",
  164. "mp3" => "audio/mpeg",
  165. "mp4" => "video/mpeg4-generic",
  166. "mpa" => "audio/mpeg",
  167. "mpe" => "video/mpeg",
  168. "mpeg" => "video/mpeg",
  169. "mpg" => "video/mpeg",
  170. "mpga" => "audio/mpeg",
  171. "ms" => "application/x-troff-ms",
  172. "msh" => "model/mesh",
  173. "mxu" => "video/vnd.mpegurl",
  174. "nc" => "application/x-netcdf",
  175. "oda" => "application/oda",
  176. "pbm" => "image/x-portable-bitmap",
  177. "pct" => "image/pict",
  178. "pdb" => "chemical/x-pdb",
  179. "pdf" => "application/pdf",
  180. "pgm" => "image/x-portable-graymap",
  181. "pgn" => "application/x-chess-pgn",
  182. "pict" => "image/pict",
  183. "png" => "image/png",
  184. "pnm" => "image/x-portable-anymap",
  185. "ppm" => "image/x-portable-pixmap",
  186. "ppt" => "application/vnd.ms-powerpoint",
  187. "pps" => "application/vnd.ms-powerpoint",
  188. "ps" => "application/postscript",
  189. "qt" => "video/quicktime",
  190. "ra" => "audio/x-realaudio",
  191. "ram" => "audio/x-pn-realaudio",
  192. "rar" => "image/x-rar-compressed",
  193. "ras" => "image/x-cmu-raster",
  194. "rgb" => "image/x-rgb",
  195. "rm" => "audio/x-pn-realaudio",
  196. "roff" => "application/x-troff",
  197. "rpm" => "audio/x-pn-realaudio-plugin",
  198. "rtf" => "text/rtf",
  199. "rtx" => "text/richtext",
  200. "sgm" => "text/sgml",
  201. "sgml" => "text/sgml",
  202. "sh" => "application/x-sh",
  203. "shar" => "application/x-shar",
  204. "silo" => "model/mesh",
  205. "sib" => "application/X-Sibelius-Score",
  206. "sit" => "application/x-stuffit",
  207. "skd" => "application/x-koan",
  208. "skm" => "application/x-koan",
  209. "skp" => "application/x-koan",
  210. "skt" => "application/x-koan",
  211. "smi" => "application/smil",
  212. "smil" => "application/smil",
  213. "snd" => "audio/basic",
  214. "so" => "application/octet-stream",
  215. "spl" => "application/x-futuresplash",
  216. "src" => "application/x-wais-source",
  217. "sv4cpio" => "application/x-sv4cpio",
  218. "sv4crc" => "application/x-sv4crc",
  219. "svf" => "application/vnd.svf",
  220. "swf" => "application/x-shockwave-flash",
  221. "sxc" => "application/vnd.sun.xml.calc",
  222. "sxi" => "application/vnd.sun.xml.impress",
  223. "sxw" => "application/vnd.sun.xml.writer",
  224. "t" => "application/x-troff",
  225. "tar" => "application/x-tar",
  226. "tcl" => "application/x-tcl",
  227. "tex" => "application/x-tex",
  228. "texi" => "application/x-texinfo",
  229. "texinfo" => "application/x-texinfo",
  230. "tga" => "image/x-targa",
  231. "tif" => "image/tif",
  232. "tiff" => "image/tiff",
  233. "tr" => "application/x-troff",
  234. "tsv" => "text/tab-seperated-values",
  235. "txt" => "text/plain",
  236. "ustar" => "application/x-ustar",
  237. "vcd" => "application/x-cdlink",
  238. "vrml" => "model/vrml",
  239. "wav" => "audio/x-wav",
  240. "wbmp" => "image/vnd.wap.wbmp",
  241. "wbxml" => "application/vnd.wap.wbxml",
  242. "wml" => "text/vnd.wap.wml",
  243. "wmlc" => "application/vnd.wap.wmlc",
  244. "wmls" => "text/vnd.wap.wmlscript",
  245. "wmlsc" => "application/vnd.wap.wmlscriptc",
  246. "wma" => "video/x-ms-wma",
  247. "wmv" => "audio/x-ms-wmv",
  248. "wrl" => "model/vrml",
  249. "xbm" => "image/x-xbitmap",
  250. "xht" => "application/xhtml+xml",
  251. "xhtml" => "application/xhtml+xml",
  252. "xls" => "application/vnd.ms-excel",
  253. "xml" => "text/xml",
  254. "xpm" => "image/x-xpixmap",
  255. "xsl" => "text/xml",
  256. "xwd" => "image/x-windowdump",
  257. "xyz" => "chemical/x-xyz",
  258. "zip" => "application/zip"
  259. );
  260. if ($filename === TRUE)
  261. {
  262. return $mime_types;
  263. }
  264. //get the extension of the file
  265. $extension = explode('.', $filename);
  266. //$filename will be an array if a . was found
  267. if (is_array($extension))
  268. {
  269. $extension = (strtolower($extension[sizeof($extension) - 1]));
  270. }
  271. //file without extension
  272. else
  273. {
  274. $extension = 'empty';
  275. }
  276. //if the extension is found, return the content type
  277. if (isset ($mime_types[$extension]))
  278. return $mime_types[$extension];
  279. //else return octet-stream
  280. return "application/octet-stream";
  281. }
  282. /**
  283. * @return true if the user is allowed to see the document, false otherwise
  284. * @author Sergio A Kessler, first version
  285. * @author Roan Embrechts, bugfix
  286. * @todo ??not only check if a file is visible, but also check if the user is allowed to see the file??
  287. */
  288. function file_visible_to_user($this_course, $doc_url)
  289. {
  290. if (api_is_allowed_to_edit())
  291. {
  292. return true;
  293. }
  294. else
  295. {
  296. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  297. $tbl_item_property = $this_course.'item_property';
  298. //$doc_url = addslashes($doc_url);
  299. $query = "SELECT 1 FROM `$tbl_document` AS docs,`$tbl_item_property` AS props 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. function file_send_for_download($full_file_name, $forced = false, $name = '')
  314. {
  315. if (!is_file($full_file_name))
  316. {
  317. return false;
  318. }
  319. $filename = ($name == '') ? basename($full_file_name) : $name;
  320. $len = filesize($full_file_name);
  321. if ($forced)
  322. {
  323. //force the browser to save the file instead of opening it
  324. header('Content-type: application/octet-stream');
  325. //header('Content-Type: application/force-download');
  326. header('Content-length: '.$len);
  327. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT']))
  328. {
  329. header('Content-Disposition: filename= '.$filename);
  330. }
  331. else
  332. {
  333. header('Content-Disposition: attachment; filename= '.$filename);
  334. }
  335. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  336. {
  337. header('Pragma: ');
  338. header('Cache-Control: ');
  339. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  340. }
  341. header('Content-Description: '.$filename);
  342. header('Content-transfer-encoding: binary');
  343. $fp = fopen($full_file_name, 'r');
  344. fpassthru($fp);
  345. return true;
  346. }
  347. else
  348. {
  349. //no forced download, just let the browser decide what to do according to the mimetype
  350. $content_type = DocumentManager::file_get_mime_type($filename);
  351. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  352. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  353. // Commented to avoid double caching declaration when playing with IE and HTTPS
  354. //header('Cache-Control: no-cache, must-revalidate');
  355. //header('Pragma: no-cache');
  356. header('Content-type: '.$content_type);
  357. header('Content-Length: '.$len);
  358. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  359. if (strpos($user_agent, 'msie'))
  360. {
  361. header('Content-Disposition: ; filename= '.$filename);
  362. }
  363. else
  364. {
  365. header('Content-Disposition: inline; filename= '.$filename);
  366. }
  367. readfile($full_file_name);
  368. return true;
  369. }
  370. }
  371. /**
  372. * This function streams a string to the client for download.
  373. * You have to ensure that the calling script then stops processing (exit();)
  374. * otherwise it may cause subsequent use of the page to want to download
  375. * other pages in php rather than interpreting them.
  376. *
  377. * @param string The string contents
  378. * @param boolean Whether "save" mode is forced (or opening directly authorized)
  379. * @param string The name of the file in the end (including extension)
  380. * @return false if file doesn't exist, true if stream succeeded
  381. */
  382. function string_send_for_download($full_string, $forced = false, $name = '')
  383. {
  384. $filename = $name;
  385. $len = strlen($full_string);
  386. if ($forced)
  387. {
  388. //force the browser to save the file instead of opening it
  389. header('Content-type: application/octet-stream');
  390. //header('Content-Type: application/force-download');
  391. header('Content-length: '.$len);
  392. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT']))
  393. {
  394. header('Content-Disposition: filename= '.$filename);
  395. }
  396. else
  397. {
  398. header('Content-Disposition: attachment; filename= '.$filename);
  399. }
  400. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  401. {
  402. header('Pragma: ');
  403. header('Cache-Control: ');
  404. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  405. }
  406. header('Content-Description: '.$filename);
  407. header('Content-transfer-encoding: binary');
  408. //$fp = fopen($full_string, 'r');
  409. //fpassthru($fp);
  410. echo $full_string;
  411. return true;
  412. //You have to ensure that the calling script then stops processing (exit();)
  413. //otherwise it may cause subsequent use of the page to want to download
  414. //other pages in php rather than interpreting them.
  415. }
  416. else
  417. {
  418. //no forced download, just let the browser decide what to do according to the mimetype
  419. $content_type = DocumentManager::file_get_mime_type($filename);
  420. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  421. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  422. header('Cache-Control: no-cache, must-revalidate');
  423. header('Pragma: no-cache');
  424. header('Content-type: '.$content_type);
  425. header('Content-Length: '.$len);
  426. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  427. if (strpos($user_agent, 'msie'))
  428. {
  429. header('Content-Disposition: ; filename= '.$filename);
  430. }
  431. else
  432. {
  433. header('Content-Disposition: inline; filename= '.$filename);
  434. }
  435. echo($full_string);
  436. //You have to ensure that the calling script then stops processing (exit();)
  437. //otherwise it may cause subsequent use of the page to want to download
  438. //other pages in php rather than interpreting them.
  439. return true;
  440. }
  441. }
  442. /**
  443. * Fetches all document data for the given user/group
  444. *
  445. * @param array $_course
  446. * @param string $path
  447. * @param int $to_group_id
  448. * @param int $to_user_id
  449. * @param boolean $can_see_invisible
  450. * @return array with all document data
  451. */
  452. function get_all_document_data($_course, $path = '/', $to_group_id = 0, $to_user_id = NULL, $can_see_invisible = false)
  453. {
  454. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  455. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  456. //if to_user_id = NULL -> change query (IS NULL)
  457. //$to_user_id = (is_null($to_user_id))?'IS NULL':'= '.$to_user_id;
  458. if (!is_null($to_user_id))
  459. {
  460. $to_field = 'last.to_user_id';
  461. $to_value = $to_user_id;
  462. }
  463. else
  464. {
  465. $to_field = 'last.to_group_id';
  466. $to_value = $to_group_id;
  467. }
  468. //escape underscores in the path so they don't act as a wildcard
  469. $path = Database::escape_string(str_replace('_', '\_', $path));
  470. $to_user_id = Database::escape_string($to_user_id);
  471. $to_value = Database::escape_string($to_value);
  472. //if they can't see invisible files, they can only see files with visibility 1
  473. $visibility_bit = ' = 1';
  474. //if they can see invisible files, only deleted files (visibility 2) are filtered out
  475. if ($can_see_invisible)
  476. {
  477. $visibility_bit = ' <> 2';
  478. }
  479. //the given path will not end with a slash, unless it's the root '/'
  480. //so no root -> add slash
  481. $added_slash = ($path == '/') ? '' : '/';
  482. $sql = "SELECT *
  483. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  484. WHERE docs.id = last.ref
  485. AND docs.path LIKE '".$path.$added_slash."%'
  486. AND docs.path NOT LIKE '".$path.$added_slash."%/%'
  487. AND last.tool = '".TOOL_DOCUMENT."'
  488. AND ".$to_field." = ".$to_value."
  489. AND last.visibility".$visibility_bit;
  490. //echo $sql;
  491. $result = api_sql_query($sql);
  492. if ($result && Database::num_rows($result) != 0)
  493. {
  494. while ($row = Database::fetch_array($result,'ASSOC'))
  495. //while ($row = Database::fetch_array($result,MYSQL_NUM))
  496. {
  497. if($row['filetype']=='file' && pathinfo($row['path'],PATHINFO_EXTENSION)=='html'){
  498. //Templates management
  499. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  500. $sql_is_template = "SELECT id FROM $table_template
  501. WHERE course_code='".$_course['id']."'
  502. AND user_id='".api_get_user_id()."'
  503. AND ref_doc='".$row['id']."'";
  504. $template_result = api_sql_query($sql_is_template);
  505. if(Database::num_rows($template_result)>0){
  506. $row['is_template'] = 1;
  507. }
  508. else{
  509. $row['is_template'] = 0;
  510. }
  511. }
  512. $document_data[$row['id']] = $row;
  513. //$document_data[] = $row;
  514. }
  515. return $document_data;
  516. }
  517. else
  518. {
  519. //display_error("Error getting document info from database (".mysql_error().")!");
  520. return false;
  521. }
  522. }
  523. /**
  524. * Gets the paths of all folders in a course
  525. * can show all folders (exept for the deleted ones) or only visible ones
  526. * @param array $_course
  527. * @param boolean $can_see_invisible
  528. * @param int $to_group_id
  529. * @return array with paths
  530. */
  531. function get_all_document_folders($_course, $to_group_id = '0', $can_see_invisible = false)
  532. {
  533. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  534. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  535. if(empty($to_group_id)){$to_group_id = '0';} //avoid empty strings in $to_group_id
  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, SORT_ASC);
  553. //return results
  554. return $document_folders;
  555. }
  556. else
  557. {
  558. return false;
  559. }
  560. }
  561. //no invisible folders
  562. else
  563. {
  564. //get visible folders
  565. $visible_sql = "SELECT path
  566. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  567. WHERE docs.id = last.ref
  568. AND docs.filetype = 'folder'
  569. AND last.tool = '".TOOL_DOCUMENT."'
  570. AND last.to_group_id = ".$to_group_id."
  571. AND last.visibility = 1";
  572. $visibleresult = api_sql_query($visible_sql, __FILE__, __LINE__);
  573. while ($all_visible_folders = Database::fetch_array($visibleresult,'ASSOC'))
  574. {
  575. $visiblefolders[] = $all_visible_folders['path'];
  576. //echo "visible folders: ".$all_visible_folders['path']."<br>";
  577. }
  578. //get invisible folders
  579. $invisible_sql = "SELECT path
  580. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  581. WHERE docs.id = last.ref
  582. AND docs.filetype = 'folder'
  583. AND last.tool = '".TOOL_DOCUMENT."'
  584. AND last.to_group_id = ".$to_group_id."
  585. AND last.visibility = 0";
  586. $invisibleresult = api_sql_query($invisible_sql, __FILE__, __LINE__);
  587. while ($invisible_folders = Database::fetch_array($invisibleresult,'ASSOC'))
  588. {
  589. //get visible folders in the invisible ones -> they are invisible too
  590. //echo "invisible folders: ".$invisible_folders['path']."<br>";
  591. $folder_in_invisible_sql = "SELECT path
  592. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  593. WHERE docs.id = last.ref
  594. AND docs.path LIKE '".Database::escape_string($invisible_folders['path'])."/%'
  595. AND docs.filetype = 'folder'
  596. AND last.tool = '".TOOL_DOCUMENT."'
  597. AND last.to_group_id = ".$to_group_id."
  598. AND last.visibility = 1";
  599. $folder_in_invisible_result = api_sql_query($folder_in_invisible_sql, __FILE__, __LINE__);
  600. while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result,'ASSOC'))
  601. {
  602. $invisiblefolders[] = $folders_in_invisible_folder['path'];
  603. //echo "<br>folders in invisible folders: ".$folders_in_invisible_folder['path']."<br><br><br>";
  604. }
  605. }
  606. //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
  607. if (is_array($visiblefolders) && is_array($invisiblefolders))
  608. {
  609. $document_folders = array_diff($visiblefolders, $invisiblefolders);
  610. sort($document_folders, SORT_ASC);
  611. return $document_folders;
  612. }
  613. //only visible folders found
  614. elseif (is_array($visiblefolders))
  615. {
  616. sort($visiblefolders, SORT_ASC);
  617. return $visiblefolders;
  618. }
  619. //no visible folders found
  620. else
  621. {
  622. return false;
  623. }
  624. }
  625. }
  626. /**
  627. * This check if a document has the readonly property checked, then see if the user
  628. * is the owner of this file, if all this is true then return true.
  629. *
  630. * @param array $_course
  631. * @param int $user_id id of the current user
  632. * @param string $file path stored in the database
  633. * @param int $document_id in case you dont have the file path ,insert the id of the file here and leave $file in blank ''
  634. * @return boolean true/false
  635. **/
  636. function check_readonly($_course,$user_id,$file,$document_id='',$to_delete=false)
  637. {
  638. if(!(!empty($document_id) && is_numeric($document_id)))
  639. {
  640. $document_id = DocumentManager::get_document_id($_course, $file);
  641. }
  642. $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  643. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  644. if ($to_delete)
  645. {
  646. if (DocumentManager::is_folder($_course, $document_id))
  647. {
  648. if (!empty($file))
  649. {
  650. $path=$file;
  651. $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM ".$TABLE_DOCUMENT." td , $TABLE_PROPERTY tp WHERE tp.ref= td.id and (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
  652. //get all id's of documents that are deleted
  653. $what_to_check_result = api_sql_query($what_to_check_sql, __FILE__, __LINE__);
  654. if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0)
  655. {
  656. // file with readonly set to 1 exist?
  657. $readonly_set=false;
  658. while ($row = Database::fetch_array($what_to_check_result))
  659. {
  660. //query to delete from item_property table
  661. //echo $row['id']; echo "<br>";
  662. if ($row['readonly']==1)
  663. {
  664. if (!($row['insert_user_id'] == $user_id))
  665. {
  666. $readonly_set=true;
  667. break;
  668. }
  669. }
  670. }
  671. if ($readonly_set)
  672. {
  673. return true;
  674. }
  675. }
  676. }
  677. return false;
  678. }
  679. }
  680. if (!empty($document_id))
  681. {
  682. $sql= 'SELECT a.insert_user_id, b.readonly FROM '.$TABLE_PROPERTY.' a,'.$TABLE_DOCUMENT.' b WHERE a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
  683. $resultans = api_sql_query($sql, __FILE__, __LINE__);
  684. $doc_details = Database ::fetch_array($resultans,'ASSOC');
  685. if($doc_details['readonly']==1)
  686. {
  687. if ( $doc_details['insert_user_id'] == $user_id || api_is_platform_admin() )
  688. {
  689. return false;
  690. }
  691. else
  692. {
  693. return true;
  694. }
  695. }
  696. }
  697. return false;
  698. }
  699. /**
  700. * This check if a document is a folder or not
  701. * @param array $_course
  702. * @param int $document_id of the item
  703. * @return boolean true/false
  704. **/
  705. function is_folder($_course, $document_id)
  706. {
  707. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  708. //if (!empty($document_id))
  709. $resultans = api_sql_query('SELECT filetype FROM '.$TABLE_DOCUMENT.' WHERE id='.$document_id.'', __FILE__, __LINE__);
  710. $result= Database::fetch_array($resultans,'ASSOC');
  711. if ($result['filetype']=='folder')
  712. {
  713. return true;
  714. }
  715. else
  716. {
  717. return false;
  718. }
  719. }
  720. /**
  721. * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
  722. * Files/folders that are inside a deleted folder get visibility 2
  723. *
  724. * @param array $_course
  725. * @param string $path, path stored in the database
  726. * @param string ,$base_work_dir, path to the documents folder
  727. * @return boolean true/false
  728. * @todo now only files/folders in a folder get visibility 2, we should rename them too.
  729. */
  730. function delete_document($_course, $path, $base_work_dir)
  731. {
  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 = DocumentManager :: 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. DocumentManager::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. DocumentManager::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. DocumentManager::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. DocumentManager::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. DocumentManager::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. DocumentManager::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. DocumentManager::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. 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. function get_document_id($_course, $path)
  888. {
  889. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  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. {
  894. $row = Database::fetch_array($result);
  895. return $row[0];
  896. }
  897. else
  898. {
  899. return false;
  900. }
  901. }
  902. /**
  903. * Allow to set a specific document as a new template for FCKEditor for a particular user in a particular course
  904. *
  905. * @param string $title
  906. * @param string $description
  907. * @param int $document_id_for_template the document id
  908. * @param string $couse_code
  909. * @param int $user_id
  910. */
  911. function set_document_as_template($title, $description, $document_id_for_template, $couse_code, $user_id, $image)
  912. {
  913. // Database table definition
  914. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  915. // creating the sql statement
  916. $sql = "INSERT INTO ".$table_template."
  917. (title, description, course_code, user_id, ref_doc, image)
  918. VALUES (
  919. '".Database::escape_string($title)."',
  920. '".Database::escape_string($description)."',
  921. '".Database::escape_string($couse_code)."',
  922. '".Database::escape_string($user_id)."',
  923. '".Database::escape_string($document_id_for_template)."',
  924. '".Database::escape_string($image)."')";
  925. api_sql_query($sql);
  926. return true;
  927. }
  928. /**
  929. * Unset a document as template
  930. *
  931. * @param int $document_id
  932. * @param string $couse_code
  933. * @param int $user_id
  934. */
  935. function unset_document_as_template($document_id, $couse_code, $user_id){
  936. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  937. $sql = 'SELECT id FROM '.$table_template.' WHERE course_code="'.$couse_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  938. $result = api_sql_query($sql);
  939. $template_id = Database::result($result,0,0);
  940. include_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
  941. my_delete(api_get_path(SYS_CODE_PATH).'upload/template_thumbnails/'.$template_id.'.jpg');
  942. $sql = 'DELETE FROM '.$table_template.' WHERE course_code="'.$couse_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  943. api_sql_query($sql);
  944. }
  945. /**
  946. * return true if the documentpath have visibility=1 as item_property
  947. *
  948. * @param string $document_path the relative complete path of the document
  949. * @param array $course the _course array info of the document's course
  950. */
  951. function is_visible($doc_path, $course){
  952. $docTable = Database::get_course_table(TABLE_DOCUMENT, $course['dbName']);
  953. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);
  954. //note the extra / at the end of doc_path to match every path in the
  955. // document table that is part of the document 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. ?>