document.lib.php 70 KB

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