document.lib.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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. $current_session_id = api_get_session_id();
  289. $is_allowed_to_edit = api_is_allowed_to_edit(null,true);
  290. if ($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 = Database::escape_string($doc_url);
  299. //$doc_url = addslashes($doc_url);
  300. $query = "SELECT 1 FROM $tbl_document AS docs,$tbl_item_property AS props
  301. WHERE props.tool = 'document' AND docs.id=props.ref AND props.visibility <> '1' AND docs.path = '$doc_url'";
  302. //echo $query;
  303. $result = Database::query($query, __FILE__, __LINE__);
  304. return (Database::num_rows($result) == 0);
  305. }
  306. }
  307. /**
  308. * This function streams a file to the client
  309. *
  310. * @param string $full_file_name
  311. * @param boolean $forced
  312. * @param string $name
  313. * @return false if file doesn't exist, true if stream succeeded
  314. */
  315. public static function file_send_for_download ($full_file_name, $forced = false, $name = '') {
  316. if (!is_file($full_file_name))
  317. {
  318. return false;
  319. }
  320. $filename = ($name == '') ? basename($full_file_name) : $name;
  321. $len = filesize($full_file_name);
  322. if ($forced)
  323. {
  324. //force the browser to save the file instead of opening it
  325. header('Content-type: application/octet-stream');
  326. //header('Content-Type: application/force-download');
  327. header('Content-length: '.$len);
  328. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT']))
  329. {
  330. header('Content-Disposition: filename= '.$filename);
  331. }
  332. else
  333. {
  334. header('Content-Disposition: attachment; filename= '.$filename);
  335. }
  336. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  337. {
  338. header('Pragma: ');
  339. header('Cache-Control: ');
  340. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  341. }
  342. header('Content-Description: '.$filename);
  343. header('Content-transfer-encoding: binary');
  344. $fp = fopen($full_file_name, 'r');
  345. fpassthru($fp);
  346. return true;
  347. }
  348. else
  349. {
  350. //no forced download, just let the browser decide what to do according to the mimetype
  351. $content_type = self::file_get_mime_type($filename);
  352. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  353. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  354. // Commented to avoid double caching declaration when playing with IE and HTTPS
  355. //header('Cache-Control: no-cache, must-revalidate');
  356. //header('Pragma: no-cache');
  357. header('Content-type: '.$content_type);
  358. header('Content-Length: '.$len);
  359. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  360. if (strpos($user_agent, 'msie'))
  361. {
  362. header('Content-Disposition: ; filename= '.$filename);
  363. }
  364. else
  365. {
  366. header('Content-Disposition: inline; filename= '.$filename);
  367. }
  368. readfile($full_file_name);
  369. return true;
  370. }
  371. }
  372. /**
  373. * This function streams a string to the client for download.
  374. * You have to ensure that the calling script then stops processing (exit();)
  375. * otherwise it may cause subsequent use of the page to want to download
  376. * other pages in php rather than interpreting them.
  377. *
  378. * @param string The string contents
  379. * @param boolean Whether "save" mode is forced (or opening directly authorized)
  380. * @param string The name of the file in the end (including extension)
  381. * @return false if file doesn't exist, true if stream succeeded
  382. */
  383. public static function string_send_for_download ($full_string, $forced = false, $name = '') {
  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 = self::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. public static function get_all_document_data ($_course, $path = '/', $to_group_id = 0, $to_user_id = NULL, $can_see_invisible = false) {
  453. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  454. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  455. $TABLE_COURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  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. //condition for the session
  483. $current_session_id = api_get_session_id();
  484. $condition_session = " AND (id_session = '$current_session_id' OR (id_session = '0' AND insert_date <= (SELECT creation_date FROM $TABLE_COURSE WHERE code = '{$_course[id]}')))";
  485. $sql = "SELECT *
  486. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  487. WHERE docs.id = last.ref
  488. AND docs.path LIKE '".$path.$added_slash."%'
  489. AND docs.path NOT LIKE '".$path.$added_slash."%/%'
  490. AND last.tool = '".TOOL_DOCUMENT."'
  491. AND ".$to_field." = ".$to_value."
  492. AND last.visibility".$visibility_bit . $condition_session;
  493. $result = Database::query($sql,__FILE__,__LINE__);
  494. if ($result && Database::num_rows($result) != 0)
  495. {
  496. while ($row = Database::fetch_array($result,'ASSOC'))
  497. //while ($row = Database::fetch_array($result,MYSQL_NUM))
  498. {
  499. if($row['filetype']=='file' && pathinfo($row['path'],PATHINFO_EXTENSION)=='html'){
  500. //Templates management
  501. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  502. $sql_is_template = "SELECT id FROM $table_template
  503. WHERE course_code='".$_course['id']."'
  504. AND user_id='".api_get_user_id()."'
  505. AND ref_doc='".$row['id']."'";
  506. $template_result = Database::query($sql_is_template);
  507. if(Database::num_rows($template_result)>0){
  508. $row['is_template'] = 1;
  509. }
  510. else{
  511. $row['is_template'] = 0;
  512. }
  513. }
  514. $document_data[$row['id']] = $row;
  515. //$document_data[] = $row;
  516. }
  517. return $document_data;
  518. }
  519. else
  520. {
  521. //display_error("Error getting document info from database (".mysql_error().")!");
  522. return false;
  523. }
  524. }
  525. /**
  526. * Gets the paths of all folders in a course
  527. * can show all folders (exept for the deleted ones) or only visible ones
  528. * @param array $_course
  529. * @param boolean $can_see_invisible
  530. * @param int $to_group_id
  531. * @return array with paths
  532. */
  533. public static function get_all_document_folders ($_course, $to_group_id = '0', $can_see_invisible = false) {
  534. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  535. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  536. /*if(empty($doc_url)){
  537. $to_group_id = '0';
  538. } else {
  539. $to_group_id = Database::escape_string($to_group_id);
  540. }*/
  541. if (!empty($to_group_id)) {
  542. $to_group_id = intval($to_group_id);
  543. }
  544. if ($can_see_invisible)
  545. {
  546. //condition for the session
  547. $session_id = api_get_session_id();
  548. $condition_session = api_get_session_condition($session_id);
  549. $sql = "SELECT path
  550. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  551. WHERE docs.id = last.ref
  552. AND docs.filetype = 'folder'
  553. AND last.tool = '".TOOL_DOCUMENT."'
  554. AND last.to_group_id = ".$to_group_id."
  555. AND last.visibility <> 2 $condition_session";
  556. $result = Database::query($sql, __FILE__, __LINE__);
  557. if ($result && Database::num_rows($result) != 0)
  558. {
  559. while ($row = Database::fetch_array($result,'ASSOC'))
  560. {
  561. $document_folders[] = $row['path'];
  562. }
  563. //sort($document_folders);
  564. natsort($document_folders);
  565. //return results
  566. return $document_folders;
  567. }
  568. else
  569. {
  570. return false;
  571. }
  572. }
  573. //no invisible folders
  574. else
  575. {
  576. //condition for the session
  577. $session_id = api_get_session_id();
  578. $condition_session = api_get_session_condition($session_id);
  579. //get visible folders
  580. $visible_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 = 1 $condition_session";
  587. $visibleresult = Database::query($visible_sql, __FILE__, __LINE__);
  588. while ($all_visible_folders = Database::fetch_array($visibleresult,'ASSOC'))
  589. {
  590. $visiblefolders[] = $all_visible_folders['path'];
  591. //echo "visible folders: ".$all_visible_folders['path']."<br>";
  592. }
  593. //condition for the session
  594. $session_id = api_get_session_id();
  595. $condition_session = api_get_session_condition($session_id);
  596. //get invisible folders
  597. $invisible_sql = "SELECT path
  598. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  599. WHERE docs.id = last.ref
  600. AND docs.filetype = 'folder'
  601. AND last.tool = '".TOOL_DOCUMENT."'
  602. AND last.to_group_id = ".$to_group_id."
  603. AND last.visibility = 0 $condition_session";
  604. $invisibleresult = Database::query($invisible_sql, __FILE__, __LINE__);
  605. while ($invisible_folders = Database::fetch_array($invisibleresult,'ASSOC'))
  606. {
  607. //condition for the session
  608. $session_id = api_get_session_id();
  609. $condition_session = api_get_session_condition($session_id);
  610. //get visible folders in the invisible ones -> they are invisible too
  611. //echo "invisible folders: ".$invisible_folders['path']."<br>";
  612. $folder_in_invisible_sql = "SELECT path
  613. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  614. WHERE docs.id = last.ref
  615. AND docs.path LIKE '".Database::escape_string($invisible_folders['path'])."/%'
  616. AND docs.filetype = 'folder'
  617. AND last.tool = '".TOOL_DOCUMENT."'
  618. AND last.to_group_id = ".$to_group_id."
  619. AND last.visibility = 1 $condition_session";
  620. $folder_in_invisible_result = Database::query($folder_in_invisible_sql, __FILE__, __LINE__);
  621. while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result,'ASSOC'))
  622. {
  623. $invisiblefolders[] = $folders_in_invisible_folder['path'];
  624. //echo "<br>folders in invisible folders: ".$folders_in_invisible_folder['path']."<br><br><br>";
  625. }
  626. }
  627. //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
  628. if (is_array($visiblefolders) && is_array($invisiblefolders))
  629. {
  630. $document_folders = array_diff($visiblefolders, $invisiblefolders);
  631. //sort($document_folders);
  632. natsort($document_folders);
  633. return $document_folders;
  634. }
  635. //only visible folders found
  636. elseif (is_array($visiblefolders))
  637. {
  638. //sort($visiblefolders);
  639. natsort($visiblefolders);
  640. return $visiblefolders;
  641. }
  642. //no visible folders found
  643. else
  644. {
  645. return false;
  646. }
  647. }
  648. }
  649. /**
  650. * This check if a document has the readonly property checked, then see if the user
  651. * is the owner of this file, if all this is true then return true.
  652. *
  653. * @param array $_course
  654. * @param int $user_id id of the current user
  655. * @param string $file path stored in the database
  656. * @param int $document_id in case you dont have the file path ,insert the id of the file here and leave $file in blank ''
  657. * @return boolean true/false
  658. **/
  659. public static function check_readonly ($_course,$user_id,$file,$document_id='',$to_delete=false) {
  660. if(!(!empty($document_id) && is_numeric($document_id)))
  661. {
  662. $document_id = self::get_document_id($_course, $file);
  663. }
  664. $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  665. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  666. if ($to_delete)
  667. {
  668. if (self::is_folder($_course, $document_id))
  669. {
  670. if (!empty($file))
  671. {
  672. $path = Database::escape_string($file);
  673. $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM ".$TABLE_DOCUMENT." td , $TABLE_PROPERTY tp
  674. WHERE tp.ref= td.id and (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
  675. //get all id's of documents that are deleted
  676. $what_to_check_result = Database::query($what_to_check_sql, __FILE__, __LINE__);
  677. if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0)
  678. {
  679. // file with readonly set to 1 exist?
  680. $readonly_set=false;
  681. while ($row = Database::fetch_array($what_to_check_result))
  682. {
  683. //query to delete from item_property table
  684. //echo $row['id']; echo "<br>";
  685. if ($row['readonly']==1)
  686. {
  687. if (!($row['insert_user_id'] == $user_id))
  688. {
  689. $readonly_set=true;
  690. break;
  691. }
  692. }
  693. }
  694. if ($readonly_set)
  695. {
  696. return true;
  697. }
  698. }
  699. }
  700. return false;
  701. }
  702. }
  703. if (!empty($document_id))
  704. {
  705. $sql= 'SELECT a.insert_user_id, b.readonly FROM '.$TABLE_PROPERTY.' a,'.$TABLE_DOCUMENT.' b
  706. WHERE a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
  707. $resultans = Database::query($sql, __FILE__, __LINE__);
  708. $doc_details = Database ::fetch_array($resultans,'ASSOC');
  709. if($doc_details['readonly']==1)
  710. {
  711. if ( $doc_details['insert_user_id'] == $user_id || api_is_platform_admin() )
  712. {
  713. return false;
  714. }
  715. else
  716. {
  717. return true;
  718. }
  719. }
  720. }
  721. return false;
  722. }
  723. /**
  724. * This check if a document is a folder or not
  725. * @param array $_course
  726. * @param int $document_id of the item
  727. * @return boolean true/false
  728. **/
  729. public static function is_folder ($_course, $document_id) {
  730. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  731. //if (!empty($document_id))
  732. $document_id = Database::escape_string($document_id);
  733. $resultans = Database::query('SELECT filetype FROM '.$TABLE_DOCUMENT.' WHERE id='.$document_id.'', __FILE__, __LINE__);
  734. $result= Database::fetch_array($resultans,'ASSOC');
  735. if ($result['filetype']=='folder') {
  736. return true;
  737. } else {
  738. return false;
  739. }
  740. }
  741. /**
  742. * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
  743. * Files/folders that are inside a deleted folder get visibility 2
  744. *
  745. * @param array $_course
  746. * @param string $path, path stored in the database
  747. * @param string ,$base_work_dir, path to the documents folder
  748. * @return boolean true/false
  749. * @todo now only files/folders in a folder get visibility 2, we should rename them too.
  750. */
  751. public static function delete_document ($_course, $path, $base_work_dir) {
  752. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  753. $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  754. //first, delete the actual document...
  755. $document_id = self :: get_document_id($_course, $path);
  756. $new_path = $path.'_DELETED_'.$document_id;
  757. $current_session_id = api_get_session_id();
  758. if ($document_id)
  759. {
  760. if (api_get_setting('permanently_remove_deleted_files') == 'true') //deleted files are *really* deleted
  761. {
  762. $what_to_delete_sql = "SELECT id FROM ".$TABLE_DOCUMENT." WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  763. //get all id's of documents that are deleted
  764. $what_to_delete_result = Database::query($what_to_delete_sql, __FILE__, __LINE__);
  765. if ($what_to_delete_result && Database::num_rows($what_to_delete_result) != 0)
  766. {
  767. //needed to deleted medadata
  768. require_once (api_get_path(SYS_CODE_PATH).'metadata/md_funcs.php');
  769. require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
  770. $mdStore = new mdstore(TRUE);
  771. //delete all item_property entries
  772. while ($row = Database::fetch_array($what_to_delete_result))
  773. {
  774. //query to delete from item_property table
  775. //avoid wrong behavior
  776. //$remove_from_item_property_sql = "DELETE FROM ".$TABLE_ITEMPROPERTY." WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  777. api_item_property_update($_course, TOOL_DOCUMENT, $row['id'], 'delete', api_get_user_id(),null,null,null,null,$current_session_id);
  778. //query to delete from document table
  779. $remove_from_document_sql = "DELETE FROM ".$TABLE_DOCUMENT." WHERE id = ".$row['id']."";
  780. self::unset_document_as_template($row['id'],$_course, api_get_user_id());
  781. //echo($remove_from_item_property_sql.'<br>');
  782. //Database::query($remove_from_item_property_sql, __FILE__, __LINE__);
  783. //echo($remove_from_document_sql.'<br>');
  784. Database::query($remove_from_document_sql, __FILE__, __LINE__);
  785. //delete metadata
  786. $eid = 'Document'.'.'.$row['id'];
  787. $mdStore->mds_delete($eid);
  788. $mdStore->mds_delete_offspring($eid);
  789. }
  790. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  791. //delete documents, do it like this so metadata get's deleted too
  792. //update_db_info('delete', $path);
  793. //throw it away
  794. my_delete($base_work_dir.$path);
  795. return true;
  796. }
  797. else
  798. {
  799. return false;
  800. }
  801. }
  802. else //set visibility to 2 and rename file/folder to qsdqsd_DELETED_#id
  803. {
  804. if (api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'delete', api_get_user_id(),null,null,null,null,$current_session_id))
  805. {
  806. //echo('item_property_update OK');
  807. if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path) )
  808. {
  809. if(rename($base_work_dir.$path, $base_work_dir.$new_path))
  810. {
  811. self::unset_document_as_template($document_id, api_get_course_id(), api_get_user_id());
  812. $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE id='".$document_id."'";
  813. if (Database::query($sql, __FILE__, __LINE__))
  814. {
  815. //if it is a folder it can contain files
  816. $sql = "SELECT id,path FROM ".$TABLE_DOCUMENT." WHERE path LIKE BINARY '".$path."/%'";
  817. $result = Database::query($sql, __FILE__, __LINE__);
  818. if ($result && Database::num_rows($result) > 0)
  819. {
  820. while ($deleted_items = Database::fetch_array($result,'ASSOC'))
  821. {
  822. //echo('to delete also: id '.$deleted_items['id']);
  823. api_item_property_update($_course, TOOL_DOCUMENT, $deleted_items['id'], 'delete', api_get_user_id(),null,null,null,null,$current_session_id);
  824. //Change path of subfolders and documents in database
  825. $old_item_path = $deleted_items['path'];
  826. $new_item_path = $new_path.substr($old_item_path, strlen($path));
  827. /*/
  828. * trying to fix this bug FS#2681
  829. echo $base_work_dir.$old_item_path;
  830. echo "<br>";
  831. echo $base_work_dir.$new_item_path;
  832. echo "<br>";echo "<br>";
  833. rename($base_work_dir.$old_item_path, $base_work_dir.$new_item_path);
  834. */
  835. self::unset_document_as_template($deleted_items['id'], api_get_course_id(), api_get_user_id());
  836. $sql = "UPDATE $TABLE_DOCUMENT set path = '".$new_item_path."' WHERE id = ".$deleted_items['id'];
  837. Database::query($sql, __FILE__, __LINE__);
  838. }
  839. }
  840. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  841. return true;
  842. }
  843. }
  844. else
  845. {
  846. //Couldn't rename - file permissions problem?
  847. error_log(__FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',0);
  848. }
  849. }
  850. else
  851. { //echo $base_work_dir.$path;
  852. //The file or directory isn't there anymore (on the filesystem)
  853. // This means it has been removed externally. To prevent a
  854. // blocking error from happening, we drop the related items from the
  855. // item_property and the document table.
  856. 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);
  857. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  858. $res = Database::query($sql,__FILE__,__LINE__);
  859. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  860. while ( $row = Database::fetch_array($res) )
  861. {
  862. $sqlipd = "DELETE FROM $TABLE_ITEMPROPERTY WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  863. $resipd = Database::query($sqlipd,__FILE__,__LINE__);
  864. self::unset_document_as_template($row['id'],api_get_course_id(), api_get_user_id());
  865. $sqldd = "DELETE FROM $TABLE_DOCUMENT WHERE id = ".$row['id'];
  866. $resdd = Database::query($sqldd,__FILE__,__LINE__);
  867. }
  868. }
  869. }
  870. }
  871. }
  872. return false;
  873. }
  874. /**
  875. * Removes documents from search engine database
  876. *
  877. * @param string $course_id Course code
  878. * @param int $document_id Document id to delete
  879. */
  880. public static function delete_document_from_search_engine ($course_id, $document_id) {
  881. // remove from search engine if enabled
  882. if (api_get_setting('search_enabled') == 'true') {
  883. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  884. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  885. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  886. $res = Database::query($sql, __FILE__, __LINE__);
  887. if (Database::num_rows($res) > 0) {
  888. $row2 = Database::fetch_array($res);
  889. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  890. $di = new DokeosIndexer();
  891. $di->remove_document((int)$row2['search_did']);
  892. }
  893. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  894. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  895. Database::query($sql, __FILE__, __LINE__);
  896. // remove terms from db
  897. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  898. delete_all_values_for_item($course_id, TOOL_DOCUMENT, $document_id);
  899. }
  900. }
  901. /**
  902. * Gets the id of a document with a given path
  903. *
  904. * @param array $_course
  905. * @param string $path
  906. * @return int id of document / false if no doc found
  907. */
  908. public static function get_document_id ($_course, $path) {
  909. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  910. $path = Database::escape_string($path);
  911. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path LIKE BINARY '$path'";
  912. $result = Database::query($sql, __FILE__, __LINE__);
  913. if ($result && Database::num_rows($result) == 1) {
  914. $row = Database::fetch_array($result);
  915. return $row[0];
  916. } else {
  917. return false;
  918. }
  919. }
  920. /**
  921. * Allow to set a specific document as a new template for FCKEditor for a particular user in a particular course
  922. *
  923. * @param string $title
  924. * @param string $description
  925. * @param int $document_id_for_template the document id
  926. * @param string $couse_code
  927. * @param int $user_id
  928. */
  929. public static function set_document_as_template ($title, $description, $document_id_for_template, $couse_code, $user_id, $image) {
  930. // Database table definition
  931. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  932. // creating the sql statement
  933. $sql = "INSERT INTO ".$table_template."
  934. (title, description, course_code, user_id, ref_doc, image)
  935. VALUES (
  936. '".Database::escape_string($title)."',
  937. '".Database::escape_string($description)."',
  938. '".Database::escape_string($couse_code)."',
  939. '".Database::escape_string($user_id)."',
  940. '".Database::escape_string($document_id_for_template)."',
  941. '".Database::escape_string($image)."')";
  942. Database::query($sql);
  943. return true;
  944. }
  945. /**
  946. * Unset a document as template
  947. *
  948. * @param int $document_id
  949. * @param string $couse_code
  950. * @param int $user_id
  951. */
  952. public static function unset_document_as_template ($document_id, $course_code, $user_id) {
  953. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  954. $course_code = Database::escape_string($course_code);
  955. $user_id = Database::escape_string($user_id);
  956. $document_id = Database::escape_string($document_id);
  957. $sql = 'SELECT id FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  958. $result = Database::query($sql);
  959. $template_id = Database::result($result,0,0);
  960. include_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
  961. my_delete(api_get_path(SYS_CODE_PATH).'upload/template_thumbnails/'.$template_id.'.jpg');
  962. $sql = 'DELETE FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  963. Database::query($sql);
  964. }
  965. /**
  966. * return true if the documentpath have visibility=1 as item_property
  967. *
  968. * @param string $document_path the relative complete path of the document
  969. * @param array $course the _course array info of the document's course
  970. */
  971. public static function is_visible ($doc_path, $course) {
  972. $docTable = Database::get_course_table(TABLE_DOCUMENT, $course['dbName']);
  973. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);
  974. //note the extra / at the end of doc_path to match every path in the
  975. // document table that is part of the document path
  976. $doc_path = Database::escape_string($doc_path);
  977. $sql = "SELECT path FROM $docTable d, $propTable ip " .
  978. "where d.id=ip.ref AND ip.tool='".TOOL_DOCUMENT."' AND d.filetype='file' AND visibility=0 AND ".
  979. "locate(concat(path,'/'),'".$doc_path."/')=1";
  980. $result = Database::query($sql,__FILE__,__LINE__);
  981. if (Database::num_rows($result) > 0){
  982. $row = Database::fetch_array($result);
  983. //echo "$row[0] not visible";
  984. return false;
  985. }
  986. //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.
  987. if ($_SESSION ['is_allowed_in_course'] || api_is_platform_admin())
  988. {
  989. return true; // ok, document is visible
  990. }
  991. else
  992. {
  993. return false;
  994. }
  995. }
  996. }
  997. //end class DocumentManager
  998. ?>