document.lib.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the document library for Dokeos.
  5. * It is / will be used to provide a service layer to all document-using tools.
  6. * and eliminate code duplication fro group documents, scorm documents, main documents.
  7. * Include/require it in your code to use its functionality.
  8. *
  9. * @version 1.1, January 2005
  10. * @package chamilo.library
  11. */
  12. /* DOCUMENTATION
  13. use the functions like this: DocumentManager::get_course_quota()
  14. */
  15. require_once api_get_path(LIBRARY_PATH).'course.lib.php';
  16. /* CONSTANTS */
  17. define("DISK_QUOTA_FIELD", "disk_quota"); //name of the database field
  18. /** default quota for the course documents folder */
  19. define("DEFAULT_DOCUMENT_QUOTA", api_get_setting('default_document_quotum'));
  20. /* VARIABLES */
  21. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  22. $baseServDir = api_get_path(SYS_PATH);
  23. $baseServUrl = $_configuration['url_append']."/";
  24. $baseWorkDir = $sys_course_path.(!empty($courseDir)?$courseDir:'');
  25. /*
  26. DocumentManager CLASS
  27. the class and its functions
  28. */
  29. class DocumentManager {
  30. private function __construct() {
  31. }
  32. /**
  33. * @return the document folder quuta of the current course, in bytes
  34. * @todo eliminate globals
  35. */
  36. public static function get_course_quota () {
  37. global $_course, $maxFilledSpace;
  38. $course_code = Database::escape_string($_course['sysCode']);
  39. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  40. $sql_query = "SELECT ".DISK_QUOTA_FIELD." FROM $course_table WHERE code = '$course_code'";
  41. $sql_result = Database::query($sql_query);
  42. $result = Database::fetch_array($sql_result);
  43. $course_quota = $result[DISK_QUOTA_FIELD];
  44. if ($course_quota == NULL)
  45. {
  46. //course table entry for quota was null
  47. //use default value
  48. $course_quota = DEFAULT_DOCUMENT_QUOTA;
  49. }
  50. return $course_quota;
  51. }
  52. /**
  53. * Get the content type of a file by checking the extension
  54. * We could use mime_content_type() with php-versions > 4.3,
  55. * but this doesn't work as it should on Windows installations
  56. *
  57. * @param string $filename or boolean TRUE to return complete array
  58. * @author ? first version
  59. * @author Bert Vanderkimpen
  60. *
  61. */
  62. public static function file_get_mime_type ($filename) {
  63. //all mime types in an array (from 1.6, this is the authorative source)
  64. //please keep this alphabetical if you add something to this list!!!
  65. $mime_types=array(
  66. "ai" => "application/postscript",
  67. "aif" => "audio/x-aiff",
  68. "aifc" => "audio/x-aiff",
  69. "aiff" => "audio/x-aiff",
  70. "asf" => "video/x-ms-asf",
  71. "asc" => "text/plain",
  72. "au" => "audio/basic",
  73. "avi" => "video/x-msvideo",
  74. "bcpio" => "application/x-bcpio",
  75. "bin" => "application/octet-stream",
  76. "bmp" => "image/bmp",
  77. "cdf" => "application/x-netcdf",
  78. "class" => "application/octet-stream",
  79. "cpio" => "application/x-cpio",
  80. "cpt" => "application/mac-compactpro",
  81. "csh" => "application/x-csh",
  82. "css" => "text/css",
  83. "dcr" => "application/x-director",
  84. "dir" => "application/x-director",
  85. "djv" => "image/vnd.djvu",
  86. "djvu" => "image/vnd.djvu",
  87. "dll" => "application/octet-stream",
  88. "dmg" => "application/x-diskcopy",
  89. "dms" => "application/octet-stream",
  90. "doc" => "application/msword",
  91. "dvi" => "application/x-dvi",
  92. "dwg" => "application/vnd.dwg",
  93. "dxf" => "application/vnd.dxf",
  94. "dxr" => "application/x-director",
  95. "eps" => "application/postscript",
  96. "etx" => "text/x-setext",
  97. "exe" => "application/octet-stream",
  98. "ez" => "application/andrew-inset",
  99. "gif" => "image/gif",
  100. "gtar" => "application/x-gtar",
  101. "gz" => "application/x-gzip",
  102. "hdf" => "application/x-hdf",
  103. "hqx" => "application/mac-binhex40",
  104. "htm" => "text/html",
  105. "html" => "text/html",
  106. "ice" => "x-conference-xcooltalk",
  107. "ief" => "image/ief",
  108. "iges" => "model/iges",
  109. "igs" => "model/iges",
  110. "jar" => "application/java-archiver",
  111. "jpe" => "image/jpeg",
  112. "jpeg" => "image/jpeg",
  113. "jpg" => "image/jpeg",
  114. "js" => "application/x-javascript",
  115. "kar" => "audio/midi",
  116. "latex" => "application/x-latex",
  117. "lha" => "application/octet-stream",
  118. "lzh" => "application/octet-stream",
  119. "m1a" => "audio/mpeg",
  120. "m2a" => "audio/mpeg",
  121. "m3u" => "audio/x-mpegurl",
  122. "man" => "application/x-troff-man",
  123. "me" => "application/x-troff-me",
  124. "mesh" => "model/mesh",
  125. "mid" => "audio/midi",
  126. "midi" => "audio/midi",
  127. "mov" => "video/quicktime",
  128. "movie" => "video/x-sgi-movie",
  129. "mp2" => "audio/mpeg",
  130. "mp3" => "audio/mpeg",
  131. "mp4" => "video/mpeg4-generic",
  132. "mpa" => "audio/mpeg",
  133. "mpe" => "video/mpeg",
  134. "mpeg" => "video/mpeg",
  135. "mpg" => "video/mpeg",
  136. "mpga" => "audio/mpeg",
  137. "ms" => "application/x-troff-ms",
  138. "msh" => "model/mesh",
  139. "mxu" => "video/vnd.mpegurl",
  140. "nc" => "application/x-netcdf",
  141. "oda" => "application/oda",
  142. "pbm" => "image/x-portable-bitmap",
  143. "pct" => "image/pict",
  144. "pdb" => "chemical/x-pdb",
  145. "pdf" => "application/pdf",
  146. "pgm" => "image/x-portable-graymap",
  147. "pgn" => "application/x-chess-pgn",
  148. "pict" => "image/pict",
  149. "png" => "image/png",
  150. "pnm" => "image/x-portable-anymap",
  151. "ppm" => "image/x-portable-pixmap",
  152. "ppt" => "application/vnd.ms-powerpoint",
  153. "pps" => "application/vnd.ms-powerpoint",
  154. "ps" => "application/postscript",
  155. "qt" => "video/quicktime",
  156. "ra" => "audio/x-realaudio",
  157. "ram" => "audio/x-pn-realaudio",
  158. "rar" => "image/x-rar-compressed",
  159. "ras" => "image/x-cmu-raster",
  160. "rgb" => "image/x-rgb",
  161. "rm" => "audio/x-pn-realaudio",
  162. "roff" => "application/x-troff",
  163. "rpm" => "audio/x-pn-realaudio-plugin",
  164. "rtf" => "text/rtf",
  165. "rtx" => "text/richtext",
  166. "sgm" => "text/sgml",
  167. "sgml" => "text/sgml",
  168. "sh" => "application/x-sh",
  169. "shar" => "application/x-shar",
  170. "silo" => "model/mesh",
  171. "sib" => "application/X-Sibelius-Score",
  172. "sit" => "application/x-stuffit",
  173. "skd" => "application/x-koan",
  174. "skm" => "application/x-koan",
  175. "skp" => "application/x-koan",
  176. "skt" => "application/x-koan",
  177. "smi" => "application/smil",
  178. "smil" => "application/smil",
  179. "snd" => "audio/basic",
  180. "so" => "application/octet-stream",
  181. "spl" => "application/x-futuresplash",
  182. "src" => "application/x-wais-source",
  183. "sv4cpio" => "application/x-sv4cpio",
  184. "sv4crc" => "application/x-sv4crc",
  185. "svf" => "application/vnd.svf",
  186. "swf" => "application/x-shockwave-flash",
  187. "sxc" => "application/vnd.sun.xml.calc",
  188. "sxi" => "application/vnd.sun.xml.impress",
  189. "sxw" => "application/vnd.sun.xml.writer",
  190. "t" => "application/x-troff",
  191. "tar" => "application/x-tar",
  192. "tcl" => "application/x-tcl",
  193. "tex" => "application/x-tex",
  194. "texi" => "application/x-texinfo",
  195. "texinfo" => "application/x-texinfo",
  196. "tga" => "image/x-targa",
  197. "tif" => "image/tif",
  198. "tiff" => "image/tiff",
  199. "tr" => "application/x-troff",
  200. "tsv" => "text/tab-seperated-values",
  201. "txt" => "text/plain",
  202. "ustar" => "application/x-ustar",
  203. "vcd" => "application/x-cdlink",
  204. "vrml" => "model/vrml",
  205. "wav" => "audio/x-wav",
  206. "wbmp" => "image/vnd.wap.wbmp",
  207. "wbxml" => "application/vnd.wap.wbxml",
  208. "wml" => "text/vnd.wap.wml",
  209. "wmlc" => "application/vnd.wap.wmlc",
  210. "wmls" => "text/vnd.wap.wmlscript",
  211. "wmlsc" => "application/vnd.wap.wmlscriptc",
  212. "wma" => "video/x-ms-wma",
  213. "wmv" => "audio/x-ms-wmv",
  214. "wrl" => "model/vrml",
  215. "xbm" => "image/x-xbitmap",
  216. "xht" => "application/xhtml+xml",
  217. "xhtml" => "application/xhtml+xml",
  218. "xls" => "application/vnd.ms-excel",
  219. "xml" => "text/xml",
  220. "xpm" => "image/x-xpixmap",
  221. "xsl" => "text/xml",
  222. "xwd" => "image/x-windowdump",
  223. "xyz" => "chemical/x-xyz",
  224. "zip" => "application/zip"
  225. );
  226. if ($filename === TRUE)
  227. {
  228. return $mime_types;
  229. }
  230. //get the extension of the file
  231. $extension = explode('.', $filename);
  232. //$filename will be an array if a . was found
  233. if (is_array($extension))
  234. {
  235. $extension = (strtolower($extension[sizeof($extension) - 1]));
  236. }
  237. //file without extension
  238. else
  239. {
  240. $extension = 'empty';
  241. }
  242. //if the extension is found, return the content type
  243. if (isset ($mime_types[$extension]))
  244. return $mime_types[$extension];
  245. //else return octet-stream
  246. return "application/octet-stream";
  247. }
  248. /**
  249. * @return true if the user is allowed to see the document, false otherwise
  250. * @author Sergio A Kessler, first version
  251. * @author Roan Embrechts, bugfix
  252. * @todo ??not only check if a file is visible, but also check if the user is allowed to see the file??
  253. */
  254. public static function file_visible_to_user ($this_course, $doc_url) {
  255. $current_session_id = api_get_session_id();
  256. $is_allowed_to_edit = api_is_allowed_to_edit(null,true);
  257. if ($is_allowed_to_edit)
  258. {
  259. return true;
  260. }
  261. else
  262. {
  263. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  264. $tbl_item_property = $this_course.'item_property';
  265. $doc_url = Database::escape_string($doc_url);
  266. //$doc_url = addslashes($doc_url);
  267. $query = "SELECT 1 FROM $tbl_document AS docs,$tbl_item_property AS props
  268. WHERE props.tool = 'document' AND docs.id=props.ref AND props.visibility <> '1' AND docs.path = '$doc_url'";
  269. //echo $query;
  270. $result = Database::query($query);
  271. return (Database::num_rows($result) == 0);
  272. }
  273. }
  274. /**
  275. * This function streams a file to the client
  276. *
  277. * @param string $full_file_name
  278. * @param boolean $forced
  279. * @param string $name
  280. * @return false if file doesn't exist, true if stream succeeded
  281. */
  282. public static function file_send_for_download ($full_file_name, $forced = false, $name = '') {
  283. if (!is_file($full_file_name))
  284. {
  285. return false;
  286. }
  287. $filename = ($name == '') ? basename($full_file_name) : $name;
  288. $len = filesize($full_file_name);
  289. if ($forced)
  290. {
  291. //force the browser to save the file instead of opening it
  292. header('Content-type: application/octet-stream');
  293. //header('Content-Type: application/force-download');
  294. header('Content-length: '.$len);
  295. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT']))
  296. {
  297. header('Content-Disposition: filename= '.$filename);
  298. }
  299. else
  300. {
  301. header('Content-Disposition: attachment; filename= '.$filename);
  302. }
  303. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  304. {
  305. header('Pragma: ');
  306. header('Cache-Control: ');
  307. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  308. }
  309. header('Content-Description: '.$filename);
  310. header('Content-transfer-encoding: binary');
  311. $fp = fopen($full_file_name, 'r');
  312. fpassthru($fp);
  313. return true;
  314. }
  315. else
  316. {
  317. //no forced download, just let the browser decide what to do according to the mimetype
  318. $content_type = self::file_get_mime_type($filename);
  319. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  320. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  321. // Commented to avoid double caching declaration when playing with IE and HTTPS
  322. //header('Cache-Control: no-cache, must-revalidate');
  323. //header('Pragma: no-cache');
  324. header('Content-type: '.$content_type);
  325. header('Content-Length: '.$len);
  326. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  327. if (strpos($user_agent, 'msie'))
  328. {
  329. header('Content-Disposition: ; filename= '.$filename);
  330. }
  331. else
  332. {
  333. header('Content-Disposition: inline; filename= '.$filename);
  334. }
  335. readfile($full_file_name);
  336. return true;
  337. }
  338. }
  339. /**
  340. * This function streams a string to the client for download.
  341. * You have to ensure that the calling script then stops processing (exit();)
  342. * otherwise it may cause subsequent use of the page to want to download
  343. * other pages in php rather than interpreting them.
  344. *
  345. * @param string The string contents
  346. * @param boolean Whether "save" mode is forced (or opening directly authorized)
  347. * @param string The name of the file in the end (including extension)
  348. * @return false if file doesn't exist, true if stream succeeded
  349. */
  350. public static function string_send_for_download ($full_string, $forced = false, $name = '') {
  351. $filename = $name;
  352. $len = strlen($full_string);
  353. if ($forced)
  354. {
  355. //force the browser to save the file instead of opening it
  356. header('Content-type: application/octet-stream');
  357. //header('Content-Type: application/force-download');
  358. header('Content-length: '.$len);
  359. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT']))
  360. {
  361. header('Content-Disposition: filename= '.$filename);
  362. }
  363. else
  364. {
  365. header('Content-Disposition: attachment; filename= '.$filename);
  366. }
  367. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  368. {
  369. header('Pragma: ');
  370. header('Cache-Control: ');
  371. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  372. }
  373. header('Content-Description: '.$filename);
  374. header('Content-transfer-encoding: binary');
  375. //$fp = fopen($full_string, 'r');
  376. //fpassthru($fp);
  377. echo $full_string;
  378. return true;
  379. //You have to ensure that the calling script then stops processing (exit();)
  380. //otherwise it may cause subsequent use of the page to want to download
  381. //other pages in php rather than interpreting them.
  382. }
  383. else
  384. {
  385. //no forced download, just let the browser decide what to do according to the mimetype
  386. $content_type = self::file_get_mime_type($filename);
  387. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  388. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  389. header('Cache-Control: no-cache, must-revalidate');
  390. header('Pragma: no-cache');
  391. header('Content-type: '.$content_type);
  392. header('Content-Length: '.$len);
  393. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  394. if (strpos($user_agent, 'msie'))
  395. {
  396. header('Content-Disposition: ; filename= '.$filename);
  397. }
  398. else
  399. {
  400. header('Content-Disposition: inline; filename= '.$filename);
  401. }
  402. echo($full_string);
  403. //You have to ensure that the calling script then stops processing (exit();)
  404. //otherwise it may cause subsequent use of the page to want to download
  405. //other pages in php rather than interpreting them.
  406. return true;
  407. }
  408. }
  409. /**
  410. * Fetches all document data for the given user/group
  411. *
  412. * @param array $_course
  413. * @param string $path
  414. * @param int $to_group_id
  415. * @param int $to_user_id
  416. * @param boolean $can_see_invisible
  417. * @return array with all document data
  418. */
  419. public static function get_all_document_data ($_course, $path = '/', $to_group_id = 0, $to_user_id = NULL, $can_see_invisible = false) {
  420. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  421. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  422. $TABLE_COURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  423. //if to_user_id = NULL -> change query (IS NULL)
  424. //$to_user_id = (is_null($to_user_id))?'IS NULL':'= '.$to_user_id;
  425. if (!is_null($to_user_id))
  426. {
  427. $to_field = 'last.to_user_id';
  428. $to_value = $to_user_id;
  429. }
  430. else
  431. {
  432. $to_field = 'last.to_group_id';
  433. $to_value = $to_group_id;
  434. }
  435. //escape underscores in the path so they don't act as a wildcard
  436. $path = Database::escape_string(str_replace('_', '\_', $path));
  437. $to_user_id = Database::escape_string($to_user_id);
  438. $to_value = Database::escape_string($to_value);
  439. //if they can't see invisible files, they can only see files with visibility 1
  440. $visibility_bit = ' = 1';
  441. //if they can see invisible files, only deleted files (visibility 2) are filtered out
  442. if ($can_see_invisible)
  443. {
  444. $visibility_bit = ' <> 2';
  445. }
  446. //the given path will not end with a slash, unless it's the root '/'
  447. //so no root -> add slash
  448. $added_slash = ($path == '/') ? '' : '/';
  449. //condition for the session
  450. $current_session_id = api_get_session_id();
  451. $condition_session = " AND (id_session = '$current_session_id' OR id_session = '0')";
  452. $sql = "SELECT docs.id, docs.filetype, docs.path, docs.title, docs.comment, docs.size, docs.readonly, last.visibility
  453. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  454. WHERE docs.id = last.ref
  455. AND docs.path LIKE '".$path.$added_slash."%'
  456. AND docs.path NOT LIKE '".$path.$added_slash."%/%'
  457. AND last.tool = '".TOOL_DOCUMENT."'
  458. AND ".$to_field." = ".$to_value."
  459. AND last.visibility".$visibility_bit . $condition_session;
  460. $result = Database::query($sql);
  461. if ($result && Database::num_rows($result) != 0)
  462. {
  463. while ($row = Database::fetch_array($result,'ASSOC'))
  464. //while ($row = Database::fetch_array($result, 'NUM'))
  465. {
  466. if($row['filetype']=='file' && pathinfo($row['path'],PATHINFO_EXTENSION)=='html'){
  467. //Templates management
  468. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  469. $sql_is_template = "SELECT id FROM $table_template
  470. WHERE course_code='".$_course['id']."'
  471. AND user_id='".api_get_user_id()."'
  472. AND ref_doc='".$row['id']."'";
  473. $template_result = Database::query($sql_is_template);
  474. if(Database::num_rows($template_result)>0){
  475. $row['is_template'] = 1;
  476. }
  477. else{
  478. $row['is_template'] = 0;
  479. }
  480. }
  481. $document_data[$row['id']] = $row;
  482. //$document_data[] = $row;
  483. }
  484. return $document_data;
  485. }
  486. else
  487. {
  488. //display_error("Error getting document info from database (".Database::error().")!");
  489. return false;
  490. }
  491. }
  492. /**
  493. * Gets the paths of all folders in a course
  494. * can show all folders (exept for the deleted ones) or only visible ones
  495. * @param array $_course
  496. * @param boolean $can_see_invisible
  497. * @param int $to_group_id
  498. * @return array with paths
  499. */
  500. public static function get_all_document_folders ($_course, $to_group_id = '0', $can_see_invisible = false) {
  501. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  502. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  503. /*if(empty($doc_url)){
  504. $to_group_id = '0';
  505. } else {
  506. $to_group_id = Database::escape_string($to_group_id);
  507. }*/
  508. if (!empty($to_group_id)) {
  509. $to_group_id = intval($to_group_id);
  510. }
  511. if ($can_see_invisible)
  512. {
  513. //condition for the session
  514. $session_id = api_get_session_id();
  515. $condition_session = api_get_session_condition($session_id);
  516. $sql = "SELECT path
  517. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  518. WHERE docs.id = last.ref
  519. AND docs.filetype = 'folder'
  520. AND last.tool = '".TOOL_DOCUMENT."'
  521. AND last.to_group_id = ".$to_group_id."
  522. AND last.visibility <> 2 $condition_session";
  523. $result = Database::query($sql);
  524. if ($result && Database::num_rows($result) != 0)
  525. {
  526. while ($row = Database::fetch_array($result,'ASSOC'))
  527. {
  528. $document_folders[] = $row['path'];
  529. }
  530. //sort($document_folders);
  531. natsort($document_folders);
  532. //return results
  533. return $document_folders;
  534. }
  535. else
  536. {
  537. return false;
  538. }
  539. }
  540. //no invisible folders
  541. else
  542. {
  543. //condition for the session
  544. $session_id = api_get_session_id();
  545. $condition_session = api_get_session_condition($session_id);
  546. //get visible folders
  547. $visible_sql = "SELECT path
  548. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  549. WHERE docs.id = last.ref
  550. AND docs.filetype = 'folder'
  551. AND last.tool = '".TOOL_DOCUMENT."'
  552. AND last.to_group_id = ".$to_group_id."
  553. AND last.visibility = 1 $condition_session";
  554. $visibleresult = Database::query($visible_sql);
  555. while ($all_visible_folders = Database::fetch_array($visibleresult,'ASSOC'))
  556. {
  557. $visiblefolders[] = $all_visible_folders['path'];
  558. //echo "visible folders: ".$all_visible_folders['path']."<br>";
  559. }
  560. //condition for the session
  561. $session_id = api_get_session_id();
  562. $condition_session = api_get_session_condition($session_id);
  563. //get invisible folders
  564. $invisible_sql = "SELECT path
  565. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  566. WHERE docs.id = last.ref
  567. AND docs.filetype = 'folder'
  568. AND last.tool = '".TOOL_DOCUMENT."'
  569. AND last.to_group_id = ".$to_group_id."
  570. AND last.visibility = 0 $condition_session";
  571. $invisibleresult = Database::query($invisible_sql);
  572. while ($invisible_folders = Database::fetch_array($invisibleresult,'ASSOC'))
  573. {
  574. //condition for the session
  575. $session_id = api_get_session_id();
  576. $condition_session = api_get_session_condition($session_id);
  577. //get visible folders in the invisible ones -> they are invisible too
  578. //echo "invisible folders: ".$invisible_folders['path']."<br>";
  579. $folder_in_invisible_sql = "SELECT path
  580. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  581. WHERE docs.id = last.ref
  582. AND docs.path LIKE '".Database::escape_string($invisible_folders['path'])."/%'
  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. $folder_in_invisible_result = Database::query($folder_in_invisible_sql);
  588. while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result,'ASSOC'))
  589. {
  590. $invisiblefolders[] = $folders_in_invisible_folder['path'];
  591. //echo "<br>folders in invisible folders: ".$folders_in_invisible_folder['path']."<br><br><br>";
  592. }
  593. }
  594. //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
  595. if (is_array($visiblefolders) && is_array($invisiblefolders))
  596. {
  597. $document_folders = array_diff($visiblefolders, $invisiblefolders);
  598. //sort($document_folders);
  599. natsort($document_folders);
  600. return $document_folders;
  601. }
  602. //only visible folders found
  603. elseif (is_array($visiblefolders))
  604. {
  605. //sort($visiblefolders);
  606. natsort($visiblefolders);
  607. return $visiblefolders;
  608. }
  609. //no visible folders found
  610. else
  611. {
  612. return false;
  613. }
  614. }
  615. }
  616. /**
  617. * This check if a document has the readonly property checked, then see if the user
  618. * is the owner of this file, if all this is true then return true.
  619. *
  620. * @param array $_course
  621. * @param int $user_id id of the current user
  622. * @param string $file path stored in the database
  623. * @param int $document_id in case you dont have the file path ,insert the id of the file here and leave $file in blank ''
  624. * @return boolean true/false
  625. **/
  626. public static function check_readonly ($_course,$user_id,$file,$document_id='',$to_delete=false) {
  627. if(!(!empty($document_id) && is_numeric($document_id)))
  628. {
  629. $document_id = self::get_document_id($_course, $file);
  630. }
  631. $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  632. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  633. if ($to_delete)
  634. {
  635. if (self::is_folder($_course, $document_id))
  636. {
  637. if (!empty($file))
  638. {
  639. $path = Database::escape_string($file);
  640. $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM ".$TABLE_DOCUMENT." td , $TABLE_PROPERTY tp
  641. WHERE tp.ref= td.id and (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
  642. //get all id's of documents that are deleted
  643. $what_to_check_result = Database::query($what_to_check_sql);
  644. if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0)
  645. {
  646. // file with readonly set to 1 exist?
  647. $readonly_set=false;
  648. while ($row = Database::fetch_array($what_to_check_result))
  649. {
  650. //query to delete from item_property table
  651. //echo $row['id']; echo "<br>";
  652. if ($row['readonly']==1)
  653. {
  654. if (!($row['insert_user_id'] == $user_id))
  655. {
  656. $readonly_set=true;
  657. break;
  658. }
  659. }
  660. }
  661. if ($readonly_set)
  662. {
  663. return true;
  664. }
  665. }
  666. }
  667. return false;
  668. }
  669. }
  670. if (!empty($document_id))
  671. {
  672. $sql= 'SELECT a.insert_user_id, b.readonly FROM '.$TABLE_PROPERTY.' a,'.$TABLE_DOCUMENT.' b
  673. WHERE a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
  674. $resultans = Database::query($sql);
  675. $doc_details = Database ::fetch_array($resultans,'ASSOC');
  676. if($doc_details['readonly']==1)
  677. {
  678. if ( $doc_details['insert_user_id'] == $user_id || api_is_platform_admin() )
  679. {
  680. return false;
  681. }
  682. else
  683. {
  684. return true;
  685. }
  686. }
  687. }
  688. return false;
  689. }
  690. /**
  691. * This check if a document is a folder or not
  692. * @param array $_course
  693. * @param int $document_id of the item
  694. * @return boolean true/false
  695. **/
  696. public static function is_folder ($_course, $document_id) {
  697. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  698. //if (!empty($document_id))
  699. $document_id = Database::escape_string($document_id);
  700. $resultans = Database::query('SELECT filetype FROM '.$TABLE_DOCUMENT.' WHERE id='.$document_id.'');
  701. $result= Database::fetch_array($resultans,'ASSOC');
  702. if ($result['filetype']=='folder') {
  703. return true;
  704. } else {
  705. return false;
  706. }
  707. }
  708. /**
  709. * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
  710. * Files/folders that are inside a deleted folder get visibility 2
  711. *
  712. * @param array $_course
  713. * @param string $path, path stored in the database
  714. * @param string ,$base_work_dir, path to the documents folder
  715. * @return boolean true/false
  716. * @todo now only files/folders in a folder get visibility 2, we should rename them too.
  717. */
  718. public static function delete_document ($_course, $path, $base_work_dir) {
  719. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  720. $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  721. //first, delete the actual document...
  722. $document_id = self :: get_document_id($_course, $path);
  723. $new_path = $path.'_DELETED_'.$document_id;
  724. $current_session_id = api_get_session_id();
  725. if ($document_id)
  726. {
  727. if (api_get_setting('permanently_remove_deleted_files') == 'true') //deleted files are *really* deleted
  728. {
  729. $what_to_delete_sql = "SELECT id FROM ".$TABLE_DOCUMENT." WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  730. //get all id's of documents that are deleted
  731. $what_to_delete_result = Database::query($what_to_delete_sql);
  732. if ($what_to_delete_result && Database::num_rows($what_to_delete_result) != 0)
  733. {
  734. //needed to deleted medadata
  735. require_once (api_get_path(SYS_CODE_PATH).'metadata/md_funcs.php');
  736. require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
  737. $mdStore = new mdstore(TRUE);
  738. //delete all item_property entries
  739. while ($row = Database::fetch_array($what_to_delete_result))
  740. {
  741. //query to delete from item_property table
  742. //avoid wrong behavior
  743. //$remove_from_item_property_sql = "DELETE FROM ".$TABLE_ITEMPROPERTY." WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  744. api_item_property_update($_course, TOOL_DOCUMENT, $row['id'], 'delete', api_get_user_id(),null,null,null,null,$current_session_id);
  745. //query to delete from document table
  746. $remove_from_document_sql = "DELETE FROM ".$TABLE_DOCUMENT." WHERE id = ".$row['id']."";
  747. self::unset_document_as_template($row['id'],$_course, api_get_user_id());
  748. //echo($remove_from_item_property_sql.'<br>');
  749. //Database::query($remove_from_item_property_sql);
  750. //echo($remove_from_document_sql.'<br>');
  751. Database::query($remove_from_document_sql);
  752. //delete metadata
  753. $eid = 'Document'.'.'.$row['id'];
  754. $mdStore->mds_delete($eid);
  755. $mdStore->mds_delete_offspring($eid);
  756. }
  757. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  758. //delete documents, do it like this so metadata get's deleted too
  759. //update_db_info('delete', $path);
  760. //throw it away
  761. my_delete($base_work_dir.$path);
  762. return true;
  763. }
  764. else
  765. {
  766. return false;
  767. }
  768. }
  769. else //set visibility to 2 and rename file/folder to qsdqsd_DELETED_#id
  770. {
  771. if (api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'delete', api_get_user_id(),null,null,null,null,$current_session_id))
  772. {
  773. //echo('item_property_update OK');
  774. if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path) )
  775. {
  776. if(rename($base_work_dir.$path, $base_work_dir.$new_path))
  777. {
  778. self::unset_document_as_template($document_id, api_get_course_id(), api_get_user_id());
  779. $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE id='".$document_id."'";
  780. if (Database::query($sql))
  781. {
  782. //if it is a folder it can contain files
  783. $sql = "SELECT id,path FROM ".$TABLE_DOCUMENT." WHERE path LIKE BINARY '".$path."/%'";
  784. $result = Database::query($sql);
  785. if ($result && Database::num_rows($result) > 0)
  786. {
  787. while ($deleted_items = Database::fetch_array($result,'ASSOC'))
  788. {
  789. //echo('to delete also: id '.$deleted_items['id']);
  790. api_item_property_update($_course, TOOL_DOCUMENT, $deleted_items['id'], 'delete', api_get_user_id(),null,null,null,null,$current_session_id);
  791. //Change path of subfolders and documents in database
  792. $old_item_path = $deleted_items['path'];
  793. $new_item_path = $new_path.substr($old_item_path, strlen($path));
  794. /*/
  795. * trying to fix this bug FS#2681
  796. echo $base_work_dir.$old_item_path;
  797. echo "<br>";
  798. echo $base_work_dir.$new_item_path;
  799. echo "<br>";echo "<br>";
  800. rename($base_work_dir.$old_item_path, $base_work_dir.$new_item_path);
  801. */
  802. self::unset_document_as_template($deleted_items['id'], api_get_course_id(), api_get_user_id());
  803. $sql = "UPDATE $TABLE_DOCUMENT set path = '".$new_item_path."' WHERE id = ".$deleted_items['id'];
  804. Database::query($sql);
  805. }
  806. }
  807. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  808. return true;
  809. }
  810. }
  811. else
  812. {
  813. //Couldn't rename - file permissions problem?
  814. error_log(__FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',0);
  815. }
  816. }
  817. else
  818. { //echo $base_work_dir.$path;
  819. //The file or directory isn't there anymore (on the filesystem)
  820. // This means it has been removed externally. To prevent a
  821. // blocking error from happening, we drop the related items from the
  822. // item_property and the document table.
  823. 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);
  824. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  825. $res = Database::query($sql);
  826. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  827. while ( $row = Database::fetch_array($res) )
  828. {
  829. $sqlipd = "DELETE FROM $TABLE_ITEMPROPERTY WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  830. $resipd = Database::query($sqlipd);
  831. self::unset_document_as_template($row['id'],api_get_course_id(), api_get_user_id());
  832. $sqldd = "DELETE FROM $TABLE_DOCUMENT WHERE id = ".$row['id'];
  833. $resdd = Database::query($sqldd);
  834. }
  835. }
  836. }
  837. }
  838. }
  839. return false;
  840. }
  841. /**
  842. * Removes documents from search engine database
  843. *
  844. * @param string $course_id Course code
  845. * @param int $document_id Document id to delete
  846. */
  847. public static function delete_document_from_search_engine ($course_id, $document_id) {
  848. // remove from search engine if enabled
  849. if (api_get_setting('search_enabled') == 'true') {
  850. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  851. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  852. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  853. $res = Database::query($sql);
  854. if (Database::num_rows($res) > 0) {
  855. $row2 = Database::fetch_array($res);
  856. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  857. $di = new DokeosIndexer();
  858. $di->remove_document((int)$row2['search_did']);
  859. }
  860. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  861. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  862. Database::query($sql);
  863. // remove terms from db
  864. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  865. delete_all_values_for_item($course_id, TOOL_DOCUMENT, $document_id);
  866. }
  867. }
  868. /**
  869. * Gets the id of a document with a given path
  870. *
  871. * @param array $_course
  872. * @param string $path
  873. * @return int id of document / false if no doc found
  874. */
  875. public static function get_document_id ($_course, $path) {
  876. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  877. $path = Database::escape_string($path);
  878. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path LIKE BINARY '$path'";
  879. $result = Database::query($sql);
  880. if ($result && Database::num_rows($result) == 1) {
  881. $row = Database::fetch_array($result);
  882. return $row[0];
  883. } else {
  884. return false;
  885. }
  886. }
  887. /**
  888. * Allow to set a specific document as a new template for FCKEditor for a particular user in a particular course
  889. *
  890. * @param string $title
  891. * @param string $description
  892. * @param int $document_id_for_template the document id
  893. * @param string $couse_code
  894. * @param int $user_id
  895. */
  896. public static function set_document_as_template ($title, $description, $document_id_for_template, $couse_code, $user_id, $image) {
  897. // Database table definition
  898. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  899. // creating the sql statement
  900. $sql = "INSERT INTO ".$table_template."
  901. (title, description, course_code, user_id, ref_doc, image)
  902. VALUES (
  903. '".Database::escape_string($title)."',
  904. '".Database::escape_string($description)."',
  905. '".Database::escape_string($couse_code)."',
  906. '".Database::escape_string($user_id)."',
  907. '".Database::escape_string($document_id_for_template)."',
  908. '".Database::escape_string($image)."')";
  909. Database::query($sql);
  910. return true;
  911. }
  912. /**
  913. * Unset a document as template
  914. *
  915. * @param int $document_id
  916. * @param string $couse_code
  917. * @param int $user_id
  918. */
  919. public static function unset_document_as_template ($document_id, $course_code, $user_id) {
  920. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  921. $course_code = Database::escape_string($course_code);
  922. $user_id = Database::escape_string($user_id);
  923. $document_id = Database::escape_string($document_id);
  924. $sql = 'SELECT id FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  925. $result = Database::query($sql);
  926. $template_id = Database::result($result,0,0);
  927. include_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
  928. my_delete(api_get_path(SYS_CODE_PATH).'upload/template_thumbnails/'.$template_id.'.jpg');
  929. $sql = 'DELETE FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  930. Database::query($sql);
  931. }
  932. /**
  933. * return true if the documentpath have visibility=1 as item_property
  934. *
  935. * @param string $document_path the relative complete path of the document
  936. * @param array $course the _course array info of the document's course
  937. */
  938. public static function is_visible ($doc_path, $course) {
  939. $docTable = Database::get_course_table(TABLE_DOCUMENT, $course['dbName']);
  940. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);
  941. //note the extra / at the end of doc_path to match every path in the
  942. // document table that is part of the document path
  943. $doc_path = Database::escape_string($doc_path);
  944. $sql = "SELECT path FROM $docTable d, $propTable ip " .
  945. "where d.id=ip.ref AND ip.tool='".TOOL_DOCUMENT."' AND d.filetype='file' AND visibility=0 AND ".
  946. "locate(concat(path,'/'),'".$doc_path."/')=1";
  947. $result = Database::query($sql);
  948. if (Database::num_rows($result) > 0){
  949. $row = Database::fetch_array($result);
  950. //echo "$row[0] not visible";
  951. return false;
  952. }
  953. //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.
  954. if ($_SESSION ['is_allowed_in_course'] || api_is_platform_admin())
  955. {
  956. return true; // ok, document is visible
  957. }
  958. else
  959. {
  960. return false;
  961. }
  962. }
  963. /**
  964. * Gets the list of included resources as a list of absolute or relative paths from a html file or string html
  965. * This allows for a better SCORM export or replace urls inside content html from copy course
  966. * The list will generally include pictures, flash objects, java applets, or any other
  967. * stuff included in the source of the current item. The current item is expected
  968. * to be an HTML file or string html. If it is not, then the function will return and empty list.
  969. * @param string source html (content or path)
  970. * @param bool is file or string html
  971. * @param string type (one of the Dokeos tools) - optional (otherwise takes the current item's type)
  972. * @param int level of recursivity we're in
  973. * @return array List of file paths. An additional field containing 'local' or 'remote' helps determine if the file should be copied into the zip or just linked
  974. */
  975. function get_resources_from_source_html($source_html, $is_file = false, $type=null, $recursivity=1)
  976. {
  977. $max = 5;
  978. $attributes = array();
  979. $wanted_attributes = array('src','url','@import','href','value');
  980. $abs_path = '';
  981. if ($recursivity > $max) {
  982. return array();
  983. }
  984. if (!isset($type)) {
  985. $type = TOOL_DOCUMENT;
  986. }
  987. if (!$is_file) {
  988. $attributes = DocumentManager::parse_HTML_attributes($source_html,$wanted_attributes);
  989. } else {
  990. if (is_file($source_html)) {
  991. $abs_path = $source_html;
  992. //for now, read the whole file in one go (that's gonna be a problem when the file is too big)
  993. $info = pathinfo($abs_path);
  994. $ext = $info['extension'];
  995. switch (strtolower($ext)) {
  996. case 'html' :
  997. case 'htm' :
  998. case 'shtml':
  999. case 'css' : $file_content = file_get_contents($abs_path);
  1000. //get an array of attributes from the HTML source
  1001. $attributes = DocumentManager::parse_HTML_attributes($file_content,$wanted_attributes);
  1002. break;
  1003. default : break;
  1004. }
  1005. } else {
  1006. return false;
  1007. }
  1008. }
  1009. switch($type)
  1010. {
  1011. case TOOL_DOCUMENT :
  1012. case TOOL_QUIZ:
  1013. case 'sco':
  1014. foreach($wanted_attributes as $attr)
  1015. {
  1016. if(isset($attributes[$attr]))
  1017. {
  1018. //find which kind of path these are (local or remote)
  1019. $sources = $attributes[$attr];
  1020. foreach($sources as $source)
  1021. {
  1022. //skip what is obviously not a resource
  1023. if(strpos($source,"+this.")) continue; //javascript code - will still work unaltered
  1024. if(strpos($source,'.')=== false) continue; //no dot, should not be an external file anyway
  1025. if(strpos($source,'mailto:')) continue; //mailto link
  1026. if(strpos($source,';') && !strpos($source,'&amp;')) continue; //avoid code - that should help
  1027. if($attr == 'value')
  1028. {
  1029. if(strpos($source , 'mp3file'))
  1030. {
  1031. $files_list[] = array(substr($source, 0, strpos($source , '.swf')+4),'local','abs');
  1032. $mp3file = substr($source , strpos($source , 'mp3file=')+8);
  1033. if(substr($mp3file,0,1) == '/')
  1034. $files_list[] = array($mp3file,'local','abs');
  1035. else
  1036. $files_list[] = array($mp3file,'local','rel');
  1037. }
  1038. elseif(strpos($source, 'flv=')===0)
  1039. {
  1040. $source = substr($source, 4);
  1041. if(strpos($source, '&')>0)
  1042. {
  1043. $source = substr($source,0,strpos($source, '&'));
  1044. }
  1045. if(strpos($source,'://')>0)
  1046. {
  1047. if(strpos($source,api_get_path(WEB_PATH))!==false)
  1048. {
  1049. //we found the current portal url
  1050. $files_list[] = array($source,'local','url');
  1051. }
  1052. else
  1053. {
  1054. //we didn't find any trace of current portal
  1055. $files_list[] = array($source,'remote','url');
  1056. }
  1057. }
  1058. else
  1059. {
  1060. $files_list[] = array($source,'local','abs');
  1061. }
  1062. continue; //skipping anything else to avoid two entries (while the others can have sub-files in their url, flv's can't)
  1063. }
  1064. }
  1065. if(strpos($source,'://') > 0)
  1066. {
  1067. //cut at '?' in a URL with params
  1068. if(strpos($source,'?')>0)
  1069. {
  1070. $second_part = substr($source,strpos($source,'?'));
  1071. if(strpos($second_part,'://')>0)
  1072. {//if the second part of the url contains a url too, treat the second one before cutting
  1073. $pos1 = strpos($second_part,'=');
  1074. $pos2 = strpos($second_part,'&');
  1075. $second_part = substr($second_part,$pos1+1,$pos2-($pos1+1));
  1076. if(strpos($second_part,api_get_path(WEB_PATH))!==false)
  1077. {
  1078. //we found the current portal url
  1079. $files_list[] = array($second_part,'local','url');
  1080. $in_files_list[] = DocumentManager::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, recursivity+1);
  1081. if(count($in_files_list)>0)
  1082. {
  1083. $files_list = array_merge($files_list,$in_files_list);
  1084. }
  1085. }
  1086. else
  1087. {
  1088. //we didn't find any trace of current portal
  1089. $files_list[] = array($second_part,'remote','url');
  1090. }
  1091. }
  1092. elseif(strpos($second_part,'=')>0)
  1093. {
  1094. if(substr($second_part,0,1) === '/')
  1095. { //link starts with a /, making it absolute (relative to DocumentRoot)
  1096. $files_list[] = array($second_part,'local','abs');
  1097. $in_files_list[] = DocumentManager::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT,$recursivity+1);
  1098. if(count($in_files_list)>0)
  1099. {
  1100. $files_list = array_merge($files_list,$in_files_list);
  1101. }
  1102. }
  1103. elseif(strstr($second_part,'..') === 0)
  1104. { //link is relative but going back in the hierarchy
  1105. $files_list[] = array($second_part,'local','rel');
  1106. //$dir = api_get_path(SYS_CODE_PATH);//dirname($abs_path);
  1107. //$new_abs_path = realpath($dir.'/'.$second_part);
  1108. $dir = '';
  1109. if (!empty($abs_path)) {
  1110. $dir = dirname($abs_path).'/';
  1111. }
  1112. $new_abs_path = realpath($dir.$second_part);
  1113. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT,$recursivity+1);
  1114. if(count($in_files_list)>0)
  1115. {
  1116. $files_list = array_merge($files_list,$in_files_list);
  1117. }
  1118. }
  1119. else
  1120. { //no starting '/', making it relative to current document's path
  1121. if(substr($second_part,0,2) == './')
  1122. {
  1123. $second_part = substr($second_part,2);
  1124. }
  1125. $files_list[] = array($second_part,'local','rel');
  1126. $dir = '';
  1127. if (!empty($abs_path)) {
  1128. $dir = dirname($abs_path).'/';
  1129. }
  1130. $new_abs_path = realpath($dir.$second_part);
  1131. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT,$recursivity+1);
  1132. if(count($in_files_list)>0)
  1133. {
  1134. $files_list = array_merge($files_list,$in_files_list);
  1135. }
  1136. }
  1137. }
  1138. //leave that second part behind now
  1139. $source = substr($source,0,strpos($source,'?'));
  1140. if(strpos($source,'://') > 0)
  1141. {
  1142. if(strpos($source,api_get_path(WEB_PATH))!==false)
  1143. {
  1144. //we found the current portal url
  1145. $files_list[] = array($source,'local','url');
  1146. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity+1);
  1147. if(count($in_files_list)>0)
  1148. {
  1149. $files_list = array_merge($files_list,$in_files_list);
  1150. }
  1151. }
  1152. else
  1153. {
  1154. //we didn't find any trace of current portal
  1155. $files_list[] = array($source,'remote','url');
  1156. }
  1157. }
  1158. else
  1159. {
  1160. //no protocol found, make link local
  1161. if(substr($source,0,1) === '/')
  1162. { //link starts with a /, making it absolute (relative to DocumentRoot)
  1163. $files_list[] = array($source,'local','abs');
  1164. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity+1);
  1165. if(count($in_files_list)>0)
  1166. {
  1167. $files_list = array_merge($files_list,$in_files_list);
  1168. }
  1169. }
  1170. elseif(strstr($source,'..') === 0)
  1171. { //link is relative but going back in the hierarchy
  1172. $files_list[] = array($source,'local','rel');
  1173. $dir = '';
  1174. if (!empty($abs_path)) {
  1175. $dir = dirname($abs_path).'/';
  1176. }
  1177. $new_abs_path = realpath($dir.$source);
  1178. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity+1);
  1179. if(count($in_files_list)>0)
  1180. {
  1181. $files_list = array_merge($files_list,$in_files_list);
  1182. }
  1183. }
  1184. else
  1185. { //no starting '/', making it relative to current document's path
  1186. if(substr($source,0,2) == './')
  1187. {
  1188. $source = substr($source,2);
  1189. }
  1190. $files_list[] = array($source,'local','rel');
  1191. $dir = '';
  1192. if (!empty($abs_path)) {
  1193. $dir = dirname($abs_path).'/';
  1194. }
  1195. $new_abs_path = realpath($dir.$source);
  1196. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity+1);
  1197. if(count($in_files_list)>0)
  1198. {
  1199. $files_list = array_merge($files_list,$in_files_list);
  1200. }
  1201. }
  1202. }
  1203. }
  1204. //found some protocol there
  1205. if(strpos($source,api_get_path(WEB_PATH))!==false)
  1206. {
  1207. //we found the current portal url
  1208. $files_list[] = array($source,'local','url');
  1209. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity+1);
  1210. if(count($in_files_list)>0)
  1211. {
  1212. $files_list = array_merge($files_list,$in_files_list);
  1213. }
  1214. }
  1215. else
  1216. {
  1217. //we didn't find any trace of current portal
  1218. $files_list[] = array($source,'remote','url');
  1219. }
  1220. }
  1221. else
  1222. {
  1223. //no protocol found, make link local
  1224. if(substr($source,0,1) === '/')
  1225. { //link starts with a /, making it absolute (relative to DocumentRoot)
  1226. $files_list[] = array($source,'local','abs');
  1227. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity+1);
  1228. if(count($in_files_list)>0)
  1229. {
  1230. $files_list = array_merge($files_list,$in_files_list);
  1231. }
  1232. }
  1233. elseif(strpos($source,'..') === 0)
  1234. { //link is relative but going back in the hierarchy
  1235. $files_list[] = array($source,'local','rel');
  1236. $dir = '';
  1237. if (!empty($abs_path)) {
  1238. $dir = dirname($abs_path).'/';
  1239. }
  1240. $new_abs_path = realpath($dir.$source);
  1241. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT,$recursivity+1);
  1242. if(count($in_files_list)>0)
  1243. {
  1244. $files_list = array_merge($files_list,$in_files_list);
  1245. }
  1246. }
  1247. else
  1248. { //no starting '/', making it relative to current document's path
  1249. if(substr($source,0,2) == './')
  1250. {
  1251. $source = substr($source,2);
  1252. }
  1253. $files_list[] = array($source,'local','rel');
  1254. $dir = '';
  1255. if (!empty($abs_path)) {
  1256. $dir = dirname($abs_path).'/';
  1257. }
  1258. $new_abs_path = realpath($dir.$source);
  1259. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity+1);
  1260. if(count($in_files_list)>0)
  1261. {
  1262. $files_list = array_merge($files_list,$in_files_list);
  1263. }
  1264. }
  1265. }
  1266. }
  1267. }
  1268. }
  1269. break;
  1270. default: //ignore
  1271. break;
  1272. }
  1273. $checked_files_list = array();
  1274. $checked_array_list = array();
  1275. if (count($files_list ) > 0) {
  1276. foreach($files_list as $idx => $file)
  1277. {
  1278. if(!empty($file[0]))
  1279. {
  1280. if(!in_array($file[0],$checked_files_list))
  1281. {
  1282. $checked_files_list[] = $files_list[$idx][0];
  1283. $checked_array_list[] = $files_list[$idx];
  1284. }
  1285. }
  1286. }
  1287. }
  1288. return $checked_array_list;
  1289. }
  1290. /**
  1291. * Parses the HTML attributes given as string.
  1292. *
  1293. * @param string HTML attribute string
  1294. * @param array List of attributes that we want to get back
  1295. * @return array An associative array of attributes
  1296. * @author Based on a function from the HTML_Common2 PEAR module
  1297. */
  1298. function parse_HTML_attributes($attrString,$wanted=array())
  1299. {
  1300. $attributes = array();
  1301. $regs = array();
  1302. $reduced = false;
  1303. if(count($wanted)>0)
  1304. {
  1305. $reduced = true;
  1306. }
  1307. try {
  1308. //Find all occurences of something that looks like a URL
  1309. // The structure of this regexp is:
  1310. // (find protocol) then
  1311. // (optionally find some kind of space 1 or more times) then
  1312. // find (either an equal sign or a bracket) followed by an optional space
  1313. // followed by some text without quotes (between quotes itself or not)
  1314. // then possible closing brackets if we were in the opening bracket case
  1315. // OR something like @import()
  1316. $res = preg_match_all(
  1317. '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]*))' .
  1318. // '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]|[^\x00-\x7F])*)' . -> seems to be taking too much
  1319. // '/(((([A-Za-z_:])([^\x00-\x7F])*)' . -> takes only last letter of parameter name
  1320. '([ \n\t\r]+)?(' .
  1321. // '(=([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+))' . -> doesn't restrict close enough to the url itself
  1322. '(=([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+))' .
  1323. '|' .
  1324. // '(\(([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)\))' . -> doesn't restrict close enough to the url itself
  1325. '(\(([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+)\))' .
  1326. '))' .
  1327. '|' .
  1328. // '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))?/', -> takes a lot (like 100's of thousands of empty possibilities)
  1329. '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))/',
  1330. $attrString,
  1331. $regs
  1332. );
  1333. } catch (Exception $e) {
  1334. error_log('Caught exception: '. $e->getMessage(),0) ;
  1335. }
  1336. if ($res) {
  1337. for ($i = 0; $i < count($regs[1]); $i++) {
  1338. $name = trim($regs[3][$i]);
  1339. $check = trim($regs[0][$i]);
  1340. $value = trim($regs[10][$i]);
  1341. if(empty($value) and !empty($regs[13][$i])){
  1342. $value = $regs[13][$i];
  1343. }
  1344. if(empty($name) && !empty($regs[16][$i]))
  1345. {
  1346. $name = '@import';
  1347. $value = trim($regs[16][$i]);
  1348. }
  1349. if(!empty($name))
  1350. {
  1351. if(!$reduced OR in_array(strtolower($name),$wanted))
  1352. {
  1353. if ($name == $check) {
  1354. $attributes[strtolower($name)][] = strtolower($name);
  1355. } else {
  1356. if (!empty($value) && ($value[0] == '\'' || $value[0] == '"')) {
  1357. $value = substr($value, 1, -1);
  1358. }
  1359. if ($value=='API.LMSGetValue(name') {
  1360. $value='API.LMSGetValue(name)';
  1361. }
  1362. $attributes[strtolower($name)][] = $value;
  1363. }
  1364. }
  1365. }
  1366. }
  1367. }else{
  1368. error_log('preg_match did not find anything',0);
  1369. }
  1370. return $attributes;
  1371. }
  1372. /**
  1373. * Replace urls inside content html from a copy course
  1374. * @param string content html
  1375. * @param string origin course code
  1376. * @param string destination course directory
  1377. * @return string new content html with replaced urls or return false if content is not a string
  1378. */
  1379. function replace_urls_inside_content_html_from_copy_course($content_html, $origin_course_code, $destination_course_directory) {
  1380. if (!is_string($content_html)) {
  1381. return false;
  1382. }
  1383. $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
  1384. $orig_course_info = api_get_course_info($origin_course_code);
  1385. $orig_course_path = api_get_path(SYS_PATH).'courses/'.$orig_course_info['path'].'/';
  1386. $destination_course_code = CourseManager::get_course_id_from_path ($destination_course_directory);
  1387. $dest_course_path = api_get_path(SYS_COURSE_PATH).$destination_course_directory.'/';
  1388. foreach ($orig_source_html as $source) {
  1389. //var_dump($source);
  1390. // get information about source url
  1391. $real_orig_url = $source[0]; // url
  1392. $scope_url = $source[1]; // scope (local, remote)
  1393. $type_url = $source[2]; // tyle (rel, abs, url)
  1394. // get path and query from origin url
  1395. $orig_parse_url = parse_url($real_orig_url);
  1396. $real_orig_path = $orig_parse_url['path'];
  1397. $real_orig_query = $orig_parse_url['query'];
  1398. // replace origin course code by destination course code from origin url query
  1399. $dest_url_query = '';
  1400. if (!empty($real_orig_query)) {
  1401. $dest_url_query = '?'.$real_orig_query;
  1402. if (strpos($dest_url_query,$origin_course_code) !== false) {
  1403. $dest_url_query = str_replace($origin_course_code,$destination_course_code,$dest_url_query);
  1404. }
  1405. }
  1406. if ($scope_url == 'local') {
  1407. if ( $type_url == 'abs' || $type_url == 'rel') {
  1408. $document_file = strstr($real_orig_path,'document');
  1409. if (strpos($real_orig_path,$document_file) !== false) {
  1410. $origin_filepath = $orig_course_path.$document_file;
  1411. $destination_filepath = $dest_course_path.$document_file;
  1412. // copy origin file inside destination course
  1413. if (file_exists($origin_filepath)) {
  1414. $filepath_dir = dirname($destination_filepath);
  1415. if (!is_dir($filepath_dir)) {
  1416. $perm = api_get_setting('permissions_for_new_directories');
  1417. $perm = octdec(!empty($perm)?$perm:0777);
  1418. @mkdir($filepath_dir,$perm,true);
  1419. }
  1420. if (!file_exists($destination_filepath)) {
  1421. @copy($origin_filepath,$destination_filepath);
  1422. }
  1423. }
  1424. // replace origin course path by destination course path
  1425. if (strpos($content_html,$real_orig_url) !== false) {
  1426. $url_course_path = str_replace($orig_course_info['path'].'/'.$document_file,'',$real_orig_path);
  1427. $destination_url = $url_course_path.$destination_course_directory.'/'.$document_file.$dest_url_query;
  1428. $content_html = str_replace($real_orig_url,$destination_url, $content_html);
  1429. }
  1430. }
  1431. // replace origin course code by destination course code from origin url
  1432. if (strpos($real_orig_url,'?') === 0) {
  1433. $dest_url = str_replace($origin_course_code,$destination_course_code,$real_orig_url);
  1434. $content_html = str_replace($real_orig_url,$dest_url, $content_html);
  1435. }
  1436. }
  1437. }
  1438. }
  1439. return $content_html;
  1440. }
  1441. }
  1442. //end class DocumentManager
  1443. ?>