document.lib.php 54 KB

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