document.lib.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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", api_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 = Database::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 = Database::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. $result = Database::query($sql);
  488. if ($result && Database::num_rows($result) != 0)
  489. {
  490. while ($row = Database::fetch_array($result,'ASSOC'))
  491. //while ($row = Database::fetch_array($result,MYSQL_NUM))
  492. {
  493. if($row['filetype']=='file' && pathinfo($row['path'],PATHINFO_EXTENSION)=='html'){
  494. //Templates management
  495. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  496. $sql_is_template = "SELECT id FROM $table_template
  497. WHERE course_code='".$_course['id']."'
  498. AND user_id='".api_get_user_id()."'
  499. AND ref_doc='".$row['id']."'";
  500. $template_result = Database::query($sql_is_template);
  501. if(Database::num_rows($template_result)>0){
  502. $row['is_template'] = 1;
  503. }
  504. else{
  505. $row['is_template'] = 0;
  506. }
  507. }
  508. $document_data[$row['id']] = $row;
  509. //$document_data[] = $row;
  510. }
  511. return $document_data;
  512. }
  513. else
  514. {
  515. //display_error("Error getting document info from database (".mysql_error().")!");
  516. return false;
  517. }
  518. }
  519. /**
  520. * Gets the paths of all folders in a course
  521. * can show all folders (exept for the deleted ones) or only visible ones
  522. * @param array $_course
  523. * @param boolean $can_see_invisible
  524. * @param int $to_group_id
  525. * @return array with paths
  526. */
  527. public static function get_all_document_folders ($_course, $to_group_id = '0', $can_see_invisible = false) {
  528. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  529. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  530. /*if(empty($doc_url)){
  531. $to_group_id = '0';
  532. } else {
  533. $to_group_id = Database::escape_string($to_group_id);
  534. }*/
  535. if (!empty($to_group_id)) {
  536. $to_group_id = intval($to_group_id);
  537. }
  538. if ($can_see_invisible)
  539. {
  540. $sql = "SELECT path
  541. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  542. WHERE docs.id = last.ref
  543. AND docs.filetype = 'folder'
  544. AND last.tool = '".TOOL_DOCUMENT."'
  545. AND last.to_group_id = ".$to_group_id."
  546. AND last.visibility <> 2";
  547. $result = Database::query($sql, __FILE__, __LINE__);
  548. if ($result && Database::num_rows($result) != 0)
  549. {
  550. while ($row = Database::fetch_array($result,'ASSOC'))
  551. {
  552. $document_folders[] = $row['path'];
  553. }
  554. //sort($document_folders);
  555. natsort($document_folders);
  556. //return results
  557. return $document_folders;
  558. }
  559. else
  560. {
  561. return false;
  562. }
  563. }
  564. //no invisible folders
  565. else
  566. {
  567. //get visible folders
  568. $visible_sql = "SELECT path
  569. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  570. WHERE docs.id = last.ref
  571. AND docs.filetype = 'folder'
  572. AND last.tool = '".TOOL_DOCUMENT."'
  573. AND last.to_group_id = ".$to_group_id."
  574. AND last.visibility = 1";
  575. $visibleresult = Database::query($visible_sql, __FILE__, __LINE__);
  576. while ($all_visible_folders = Database::fetch_array($visibleresult,'ASSOC'))
  577. {
  578. $visiblefolders[] = $all_visible_folders['path'];
  579. //echo "visible folders: ".$all_visible_folders['path']."<br>";
  580. }
  581. //get invisible folders
  582. $invisible_sql = "SELECT path
  583. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  584. WHERE docs.id = last.ref
  585. AND docs.filetype = 'folder'
  586. AND last.tool = '".TOOL_DOCUMENT."'
  587. AND last.to_group_id = ".$to_group_id."
  588. AND last.visibility = 0";
  589. $invisibleresult = Database::query($invisible_sql, __FILE__, __LINE__);
  590. while ($invisible_folders = Database::fetch_array($invisibleresult,'ASSOC'))
  591. {
  592. //get visible folders in the invisible ones -> they are invisible too
  593. //echo "invisible folders: ".$invisible_folders['path']."<br>";
  594. $folder_in_invisible_sql = "SELECT path
  595. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  596. WHERE docs.id = last.ref
  597. AND docs.path LIKE '".Database::escape_string($invisible_folders['path'])."/%'
  598. AND docs.filetype = 'folder'
  599. AND last.tool = '".TOOL_DOCUMENT."'
  600. AND last.to_group_id = ".$to_group_id."
  601. AND last.visibility = 1";
  602. $folder_in_invisible_result = Database::query($folder_in_invisible_sql, __FILE__, __LINE__);
  603. while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result,'ASSOC'))
  604. {
  605. $invisiblefolders[] = $folders_in_invisible_folder['path'];
  606. //echo "<br>folders in invisible folders: ".$folders_in_invisible_folder['path']."<br><br><br>";
  607. }
  608. }
  609. //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
  610. if (is_array($visiblefolders) && is_array($invisiblefolders))
  611. {
  612. $document_folders = array_diff($visiblefolders, $invisiblefolders);
  613. //sort($document_folders);
  614. natsort($document_folders);
  615. return $document_folders;
  616. }
  617. //only visible folders found
  618. elseif (is_array($visiblefolders))
  619. {
  620. //sort($visiblefolders);
  621. natsort($visiblefolders);
  622. return $visiblefolders;
  623. }
  624. //no visible folders found
  625. else
  626. {
  627. return false;
  628. }
  629. }
  630. }
  631. /**
  632. * This check if a document has the readonly property checked, then see if the user
  633. * is the owner of this file, if all this is true then return true.
  634. *
  635. * @param array $_course
  636. * @param int $user_id id of the current user
  637. * @param string $file path stored in the database
  638. * @param int $document_id in case you dont have the file path ,insert the id of the file here and leave $file in blank ''
  639. * @return boolean true/false
  640. **/
  641. public static function check_readonly ($_course,$user_id,$file,$document_id='',$to_delete=false) {
  642. if(!(!empty($document_id) && is_numeric($document_id)))
  643. {
  644. $document_id = self::get_document_id($_course, $file);
  645. }
  646. $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  647. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  648. if ($to_delete)
  649. {
  650. if (self::is_folder($_course, $document_id))
  651. {
  652. if (!empty($file))
  653. {
  654. $path = Database::escape_string($file);
  655. $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM ".$TABLE_DOCUMENT." td , $TABLE_PROPERTY tp
  656. WHERE tp.ref= td.id and (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
  657. //get all id's of documents that are deleted
  658. $what_to_check_result = Database::query($what_to_check_sql, __FILE__, __LINE__);
  659. if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0)
  660. {
  661. // file with readonly set to 1 exist?
  662. $readonly_set=false;
  663. while ($row = Database::fetch_array($what_to_check_result))
  664. {
  665. //query to delete from item_property table
  666. //echo $row['id']; echo "<br>";
  667. if ($row['readonly']==1)
  668. {
  669. if (!($row['insert_user_id'] == $user_id))
  670. {
  671. $readonly_set=true;
  672. break;
  673. }
  674. }
  675. }
  676. if ($readonly_set)
  677. {
  678. return true;
  679. }
  680. }
  681. }
  682. return false;
  683. }
  684. }
  685. if (!empty($document_id))
  686. {
  687. $sql= 'SELECT a.insert_user_id, b.readonly FROM '.$TABLE_PROPERTY.' a,'.$TABLE_DOCUMENT.' b
  688. WHERE a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
  689. $resultans = Database::query($sql, __FILE__, __LINE__);
  690. $doc_details = Database ::fetch_array($resultans,'ASSOC');
  691. if($doc_details['readonly']==1)
  692. {
  693. if ( $doc_details['insert_user_id'] == $user_id || api_is_platform_admin() )
  694. {
  695. return false;
  696. }
  697. else
  698. {
  699. return true;
  700. }
  701. }
  702. }
  703. return false;
  704. }
  705. /**
  706. * This check if a document is a folder or not
  707. * @param array $_course
  708. * @param int $document_id of the item
  709. * @return boolean true/false
  710. **/
  711. public static function is_folder ($_course, $document_id) {
  712. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  713. //if (!empty($document_id))
  714. $document_id = Database::escape_string($document_id);
  715. $resultans = Database::query('SELECT filetype FROM '.$TABLE_DOCUMENT.' WHERE id='.$document_id.'', __FILE__, __LINE__);
  716. $result= Database::fetch_array($resultans,'ASSOC');
  717. if ($result['filetype']=='folder') {
  718. return true;
  719. } else {
  720. return false;
  721. }
  722. }
  723. /**
  724. * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
  725. * Files/folders that are inside a deleted folder get visibility 2
  726. *
  727. * @param array $_course
  728. * @param string $path, path stored in the database
  729. * @param string ,$base_work_dir, path to the documents folder
  730. * @return boolean true/false
  731. * @todo now only files/folders in a folder get visibility 2, we should rename them too.
  732. */
  733. public static function delete_document ($_course, $path, $base_work_dir) {
  734. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  735. $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  736. //first, delete the actual document...
  737. $document_id = self :: get_document_id($_course, $path);
  738. $new_path = $path.'_DELETED_'.$document_id;
  739. if ($document_id)
  740. {
  741. if (api_get_setting('permanently_remove_deleted_files') == 'true') //deleted files are *really* deleted
  742. {
  743. $what_to_delete_sql = "SELECT id FROM ".$TABLE_DOCUMENT." WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  744. //get all id's of documents that are deleted
  745. $what_to_delete_result = Database::query($what_to_delete_sql, __FILE__, __LINE__);
  746. if ($what_to_delete_result && Database::num_rows($what_to_delete_result) != 0)
  747. {
  748. //needed to deleted medadata
  749. require_once (api_get_path(SYS_CODE_PATH).'metadata/md_funcs.php');
  750. require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
  751. $mdStore = new mdstore(TRUE);
  752. //delete all item_property entries
  753. while ($row = Database::fetch_array($what_to_delete_result))
  754. {
  755. //query to delete from item_property table
  756. //avoid wrong behavior
  757. //$remove_from_item_property_sql = "DELETE FROM ".$TABLE_ITEMPROPERTY." WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  758. api_item_property_update($_course, TOOL_DOCUMENT, $row['id'], 'delete', api_get_user_id());
  759. //query to delete from document table
  760. $remove_from_document_sql = "DELETE FROM ".$TABLE_DOCUMENT." WHERE id = ".$row['id']."";
  761. self::unset_document_as_template($row['id'],$_course, api_get_user_id());
  762. //echo($remove_from_item_property_sql.'<br>');
  763. //Database::query($remove_from_item_property_sql, __FILE__, __LINE__);
  764. //echo($remove_from_document_sql.'<br>');
  765. Database::query($remove_from_document_sql, __FILE__, __LINE__);
  766. //delete metadata
  767. $eid = 'Document'.'.'.$row['id'];
  768. $mdStore->mds_delete($eid);
  769. $mdStore->mds_delete_offspring($eid);
  770. }
  771. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  772. //delete documents, do it like this so metadata get's deleted too
  773. //update_db_info('delete', $path);
  774. //throw it away
  775. my_delete($base_work_dir.$path);
  776. return true;
  777. }
  778. else
  779. {
  780. return false;
  781. }
  782. }
  783. else //set visibility to 2 and rename file/folder to qsdqsd_DELETED_#id
  784. {
  785. if (api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'delete', api_get_user_id()))
  786. {
  787. //echo('item_property_update OK');
  788. if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path) )
  789. {
  790. if(rename($base_work_dir.$path, $base_work_dir.$new_path))
  791. {
  792. self::unset_document_as_template($document_id, api_get_course_id(), api_get_user_id());
  793. $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE id='".$document_id."'";
  794. if (Database::query($sql, __FILE__, __LINE__))
  795. {
  796. //if it is a folder it can contain files
  797. $sql = "SELECT id,path FROM ".$TABLE_DOCUMENT." WHERE path LIKE BINARY '".$path."/%'";
  798. $result = Database::query($sql, __FILE__, __LINE__);
  799. if ($result && Database::num_rows($result) > 0)
  800. {
  801. while ($deleted_items = Database::fetch_array($result,'ASSOC'))
  802. {
  803. //echo('to delete also: id '.$deleted_items['id']);
  804. api_item_property_update($_course, TOOL_DOCUMENT, $deleted_items['id'], 'delete', api_get_user_id());
  805. //Change path of subfolders and documents in database
  806. $old_item_path = $deleted_items['path'];
  807. $new_item_path = $new_path.substr($old_item_path, strlen($path));
  808. /*/
  809. * trying to fix this bug FS#2681
  810. echo $base_work_dir.$old_item_path;
  811. echo "<br>";
  812. echo $base_work_dir.$new_item_path;
  813. echo "<br>";echo "<br>";
  814. rename($base_work_dir.$old_item_path, $base_work_dir.$new_item_path);
  815. */
  816. self::unset_document_as_template($deleted_items['id'], api_get_course_id(), api_get_user_id());
  817. $sql = "UPDATE $TABLE_DOCUMENT set path = '".$new_item_path."' WHERE id = ".$deleted_items['id'];
  818. Database::query($sql, __FILE__, __LINE__);
  819. }
  820. }
  821. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  822. return true;
  823. }
  824. }
  825. else
  826. {
  827. //Couldn't rename - file permissions problem?
  828. error_log(__FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',0);
  829. }
  830. }
  831. else
  832. { //echo $base_work_dir.$path;
  833. //The file or directory isn't there anymore (on the filesystem)
  834. // This means it has been removed externally. To prevent a
  835. // blocking error from happening, we drop the related items from the
  836. // item_property and the document table.
  837. 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);
  838. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  839. $res = Database::query($sql,__FILE__,__LINE__);
  840. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  841. while ( $row = Database::fetch_array($res) )
  842. {
  843. $sqlipd = "DELETE FROM $TABLE_ITEMPROPERTY WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  844. $resipd = Database::query($sqlipd,__FILE__,__LINE__);
  845. self::unset_document_as_template($row['id'],api_get_course_id(), api_get_user_id());
  846. $sqldd = "DELETE FROM $TABLE_DOCUMENT WHERE id = ".$row['id'];
  847. $resdd = Database::query($sqldd,__FILE__,__LINE__);
  848. }
  849. }
  850. }
  851. }
  852. }
  853. return false;
  854. }
  855. /**
  856. * Removes documents from search engine database
  857. *
  858. * @param string $course_id Course code
  859. * @param int $document_id Document id to delete
  860. */
  861. public static function delete_document_from_search_engine ($course_id, $document_id) {
  862. // remove from search engine if enabled
  863. if (api_get_setting('search_enabled') == 'true') {
  864. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  865. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  866. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  867. $res = Database::query($sql, __FILE__, __LINE__);
  868. if (Database::num_rows($res) > 0) {
  869. $row2 = Database::fetch_array($res);
  870. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  871. $di = new DokeosIndexer();
  872. $di->remove_document((int)$row2['search_did']);
  873. }
  874. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  875. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  876. Database::query($sql, __FILE__, __LINE__);
  877. // remove terms from db
  878. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  879. delete_all_values_for_item($course_id, TOOL_DOCUMENT, $document_id);
  880. }
  881. }
  882. /**
  883. * Gets the id of a document with a given path
  884. *
  885. * @param array $_course
  886. * @param string $path
  887. * @return int id of document / false if no doc found
  888. */
  889. public static function get_document_id ($_course, $path) {
  890. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  891. $path = Database::escape_string($path);
  892. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path LIKE BINARY '$path'";
  893. $result = Database::query($sql, __FILE__, __LINE__);
  894. if ($result && Database::num_rows($result) == 1) {
  895. $row = Database::fetch_array($result);
  896. return $row[0];
  897. } else {
  898. return false;
  899. }
  900. }
  901. /**
  902. * Allow to set a specific document as a new template for FCKEditor for a particular user in a particular course
  903. *
  904. * @param string $title
  905. * @param string $description
  906. * @param int $document_id_for_template the document id
  907. * @param string $couse_code
  908. * @param int $user_id
  909. */
  910. public static function set_document_as_template ($title, $description, $document_id_for_template, $couse_code, $user_id, $image) {
  911. // Database table definition
  912. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  913. // creating the sql statement
  914. $sql = "INSERT INTO ".$table_template."
  915. (title, description, course_code, user_id, ref_doc, image)
  916. VALUES (
  917. '".Database::escape_string($title)."',
  918. '".Database::escape_string($description)."',
  919. '".Database::escape_string($couse_code)."',
  920. '".Database::escape_string($user_id)."',
  921. '".Database::escape_string($document_id_for_template)."',
  922. '".Database::escape_string($image)."')";
  923. Database::query($sql);
  924. return true;
  925. }
  926. /**
  927. * Unset a document as template
  928. *
  929. * @param int $document_id
  930. * @param string $couse_code
  931. * @param int $user_id
  932. */
  933. public static function unset_document_as_template ($document_id, $course_code, $user_id) {
  934. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  935. $course_code = Database::escape_string($course_code);
  936. $user_id = Database::escape_string($user_id);
  937. $document_id = Database::escape_string($document_id);
  938. $sql = 'SELECT id FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  939. $result = Database::query($sql);
  940. $template_id = Database::result($result,0,0);
  941. include_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
  942. my_delete(api_get_path(SYS_CODE_PATH).'upload/template_thumbnails/'.$template_id.'.jpg');
  943. $sql = 'DELETE FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  944. Database::query($sql);
  945. }
  946. /**
  947. * return true if the documentpath have visibility=1 as item_property
  948. *
  949. * @param string $document_path the relative complete path of the document
  950. * @param array $course the _course array info of the document's course
  951. */
  952. public static function is_visible ($doc_path, $course) {
  953. $docTable = Database::get_course_table(TABLE_DOCUMENT, $course['dbName']);
  954. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);
  955. //note the extra / at the end of doc_path to match every path in the
  956. // document table that is part of the document path
  957. $doc_path = Database::escape_string($doc_path);
  958. $sql = "SELECT path FROM $docTable d, $propTable ip " .
  959. "where d.id=ip.ref AND ip.tool='".TOOL_DOCUMENT."' AND d.filetype='file' AND visibility=0 AND ".
  960. "locate(concat(path,'/'),'".$doc_path."/')=1";
  961. $result = Database::query($sql,__FILE__,__LINE__);
  962. if (Database::num_rows($result) > 0){
  963. $row = Database::fetch_array($result);
  964. //echo "$row[0] not visible";
  965. return false;
  966. }
  967. //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.
  968. if ($_SESSION ['is_allowed_in_course'] || api_is_platform_admin())
  969. {
  970. return true; // ok, document is visible
  971. }
  972. else
  973. {
  974. return false;
  975. }
  976. }
  977. }
  978. //end class DocumentManager
  979. ?>