document.lib.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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.lastedit_date, 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. * Allow attach certificate to course
  876. * @param string The course id
  877. * @param int The document id
  878. * @return void()
  879. */
  880. function attach_gradebook_certificate ($course_id,$document_id) {
  881. $tbl_category=Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  882. $session_id=api_get_session_id();
  883. if ($session_id==0 || is_null($session_id)) {
  884. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  885. } elseif ($session_id>0) {
  886. $sql_session='AND session_id='.Database::escape_string($session_id);
  887. } else {
  888. $sql_session='';
  889. }
  890. $sql='UPDATE '.$tbl_category.' SET document_id="'.Database::escape_string($document_id).'"
  891. WHERE course_code="'.Database::escape_string($course_id).'" '.$sql_session;
  892. $rs=Database::query($sql,__FILE__,__LINE__);
  893. }
  894. /**
  895. * get the document id of default certificate
  896. * @param string The course id
  897. * @return int The default certificate id
  898. */
  899. function get_default_certificate_id ($course_id) {
  900. $tbl_category=Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  901. $session_id=api_get_session_id();
  902. if ($session_id==0 || is_null($session_id)) {
  903. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  904. } elseif ($session_id>0) {
  905. $sql_session='AND session_id='.Database::escape_string($session_id);
  906. } else {
  907. $sql_session='';
  908. }
  909. $sql='SELECT document_id FROM '.$tbl_category.'
  910. WHERE course_code="'.Database::escape_string($course_id).'" '.$sql_session;
  911. $rs=Database::query($sql,__FILE__,__LINE__);
  912. $row=Database::fetch_array($rs);
  913. return $row['document_id'];
  914. }
  915. /**
  916. * allow replace user info in file html
  917. * @param string The course id
  918. * @return string The html content of the certificate
  919. */
  920. function replace_user_info_into_html($course_id) {
  921. global $_course;
  922. $course_info = api_get_course_info($course_id);
  923. $tbl_document=Database::get_course_table(TABLE_DOCUMENT,$course_info['dbName']);
  924. $document_id=self::get_default_certificate_id($course_id);
  925. $sql='SELECT path FROM '.$tbl_document.' WHERE id="'.Database::escape_string($document_id).'" ';
  926. $rs=Database::query($sql,__FILE__,__LINE__);
  927. $new_content = '';
  928. if (Database::num_rows($rs)) {
  929. $row=Database::fetch_array($rs);
  930. $filepath = api_get_path('SYS_COURSE_PATH').$course_info['path'].'/document'.$row['path'];
  931. if (is_file($filepath)) {
  932. $my_content_html=file_get_contents($filepath);
  933. }
  934. $all_user_info=self::get_all_info_to_certificate();
  935. $info_to_be_replaced_in_content_html=$all_user_info[0];
  936. $info_to_replace_in_content_html=$all_user_info[1];
  937. $new_content=str_replace($info_to_be_replaced_in_content_html,$info_to_replace_in_content_html,$my_content_html);
  938. }
  939. return $new_content;
  940. }
  941. /**
  942. * return all content to replace and all content to be replace
  943. */
  944. function get_all_info_to_certificate () {
  945. global $charset,$dateFormatLong;
  946. $info_list = array();
  947. $user_id = api_get_user_id();
  948. $course_id = api_get_course_id();
  949. //info portal
  950. $organization_name = api_get_setting('Institution');
  951. $portal_name = api_get_setting('siteName');
  952. //info extra user data
  953. $extra_user_info_data=UserManager::get_extra_user_data($user_id,false,false);
  954. //info student
  955. $user_info=api_get_user_info($user_id);
  956. $first_name=($user_info['firstName']);
  957. $last_name=($user_info['lastName']);
  958. $official_code=($user_info['official_code']);
  959. //info teacher
  960. $info_teacher_id=UserManager::get_user_id_of_course_admin_or_session_admin($course_id);
  961. $teacher_info=api_get_user_info($info_teacher_id);
  962. $teacher_first_name=($teacher_info['firstName']);
  963. $teacher_last_name=($teacher_info['lastName']);
  964. // info gradebook certificate
  965. $info_grade_certificate = UserManager::get_info_gradebook_certificate($course_id,$user_id);
  966. $date_certificate = $info_grade_certificate['date_certificate'];
  967. $date_long_certificate = '';
  968. if (!empty($date_certificate)) {
  969. $date_long_certificate = api_ucfirst(format_locale_date($dateFormatLong,convert_mysql_date($date_certificate)));
  970. }
  971. //replace content
  972. $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);
  973. $info_to_be_replaced_in_content_html=array('((user_firstname))','((user_lastname))','((gradebook_institution))',
  974. '((gradebook_sitename))','((teacher_firstname))','((teacher_lastname))','((official_code))','((date_certificate))');
  975. foreach ($extra_user_info_data as $key_extra=>$value_extra) {
  976. $info_to_be_replaced_in_content_html[]='(('.strtolower($key_extra).'))';
  977. $info_to_replace_in_content_html[]=$value_extra;
  978. }
  979. $info_list[]=$info_to_be_replaced_in_content_html;
  980. $info_list[]=$info_to_replace_in_content_html;
  981. return $info_list;
  982. }
  983. /**
  984. * Remove default certificate
  985. * @param string The course id
  986. * @param int The document id of the default certificate
  987. * @return void()
  988. */
  989. function remove_attach_certificate ($course_id,$default_certificate_id) {
  990. $default_certificate=self::get_default_certificate_id($course_id);
  991. if ((int)$default_certificate==(int)$default_certificate_id) {
  992. $tbl_category=Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  993. $session_id=api_get_session_id();
  994. if ($session_id==0 || is_null($session_id)) {
  995. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  996. } elseif ($session_id>0) {
  997. $sql_session='AND session_id='.Database::escape_string($session_id);
  998. } else {
  999. $sql_session='';
  1000. }
  1001. $sql='UPDATE '.$tbl_category.' SET document_id=null
  1002. WHERE course_code="'.Database::escape_string($course_id).'" AND document_id="'.$default_certificate_id.'" '.$sql_session;
  1003. $rs=Database::query($sql,__FILE__,__LINE__);
  1004. }
  1005. }
  1006. /**
  1007. * Create directory certificate
  1008. * @param string The course id
  1009. * @return void()
  1010. */
  1011. function create_directory_certificate_in_course ($course_id) {
  1012. global $_course;
  1013. global $_user;
  1014. $to_group_id=0;
  1015. $to_user_id=null;
  1016. $course_dir = $_course['path']."/document/";
  1017. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  1018. $base_work_dir=$sys_course_path.$course_dir;
  1019. $base_work_dir_test=$base_work_dir.'certificates';
  1020. $dir_name='/certificates';
  1021. $post_dir_name='certificates';
  1022. $visibility_command='invisible';
  1023. if (!is_dir($base_work_dir_test)) {
  1024. $created_dir = create_unexisting_directory($_course,$_user['user_id'],$to_group_id,$to_user_id,$base_work_dir,$dir_name,$post_dir_name);
  1025. $update_id=DocumentManager::get_document_id_of_directory_certificate();
  1026. api_item_property_update($_course, TOOL_DOCUMENT, $update_id, $visibility_command, $_user['user_id']);
  1027. }
  1028. }
  1029. /**
  1030. * Get the document id of the directory certificate
  1031. * @param string The course id
  1032. * @return int The document id of the directory certificate
  1033. */
  1034. function get_document_id_of_directory_certificate () {
  1035. global $_course;
  1036. $tbl_document=Database::get_course_table(TABLE_DOCUMENT);
  1037. $sql='SELECT id FROM '.$tbl_document.' WHERE path="/certificates" ';
  1038. $rs=Database::query($sql,__FILE__,__LINE__);
  1039. $row=Database::fetch_array($rs);
  1040. return $row['id'];
  1041. }
  1042. /**
  1043. * Check if a directory given is for certificate
  1044. * @param string path of directory
  1045. * @return bool true if is a certificate or false otherwise
  1046. */
  1047. function is_certificate_mode($dir) {
  1048. //I'm in the certification module?
  1049. $is_certificate_mode = false;
  1050. $is_certificate_array = explode('/',$dir);
  1051. array_shift($is_certificate_array);
  1052. if ($is_certificate_array[0]=='certificates') {
  1053. $is_certificate_mode = true;
  1054. }
  1055. return $is_certificate_mode;
  1056. }
  1057. /**
  1058. * Gets the list of included resources as a list of absolute or relative paths from a html file or string html
  1059. * This allows for a better SCORM export or replace urls inside content html from copy course
  1060. * The list will generally include pictures, flash objects, java applets, or any other
  1061. * stuff included in the source of the current item. The current item is expected
  1062. * to be an HTML file or string html. If it is not, then the function will return and empty list.
  1063. * @param string source html (content or path)
  1064. * @param bool is file or string html
  1065. * @param string type (one of the Dokeos tools) - optional (otherwise takes the current item's type)
  1066. * @param int level of recursivity we're in
  1067. * @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
  1068. */
  1069. function get_resources_from_source_html($source_html, $is_file = false, $type = null, $recursivity = 1) {
  1070. $max = 5;
  1071. $attributes = array();
  1072. $wanted_attributes = array('src', 'url', '@import', 'href', 'value');
  1073. $abs_path = '';
  1074. if ($recursivity > $max) {
  1075. return array();
  1076. }
  1077. if (!isset($type)) {
  1078. $type = TOOL_DOCUMENT;
  1079. }
  1080. if (!$is_file) {
  1081. $attributes = DocumentManager::parse_HTML_attributes($source_html, $wanted_attributes);
  1082. } else {
  1083. if (is_file($source_html)) {
  1084. $abs_path = $source_html;
  1085. //for now, read the whole file in one go (that's gonna be a problem when the file is too big)
  1086. $info = pathinfo($abs_path);
  1087. $ext = $info['extension'];
  1088. switch (strtolower($ext)) {
  1089. case 'html' :
  1090. case 'htm' :
  1091. case 'shtml':
  1092. case 'css' : $file_content = file_get_contents($abs_path);
  1093. //get an array of attributes from the HTML source
  1094. $attributes = DocumentManager::parse_HTML_attributes($file_content, $wanted_attributes);
  1095. break;
  1096. default : break;
  1097. }
  1098. } else {
  1099. return false;
  1100. }
  1101. }
  1102. switch ($type) {
  1103. case TOOL_DOCUMENT :
  1104. case TOOL_QUIZ:
  1105. case 'sco':
  1106. foreach ($wanted_attributes as $attr) {
  1107. if (isset($attributes[$attr])) {
  1108. //find which kind of path these are (local or remote)
  1109. $sources = $attributes[$attr];
  1110. foreach ($sources as $source) {
  1111. //skip what is obviously not a resource
  1112. if (strpos($source, '+this.')) continue; //javascript code - will still work unaltered
  1113. if (strpos($source, '.') === false) continue; //no dot, should not be an external file anyway
  1114. if (strpos($source, 'mailto:')) continue; //mailto link
  1115. if (strpos($source, ';') && !strpos($source, '&amp;')) continue; //avoid code - that should help
  1116. if ($attr == 'value') {
  1117. if (strpos($source , 'mp3file')) {
  1118. $files_list[] = array(substr($source, 0, strpos($source, '.swf') + 4), 'local', 'abs');
  1119. $mp3file = substr($source , strpos($source, 'mp3file=') + 8);
  1120. if (substr($mp3file, 0, 1) == '/') {
  1121. $files_list[] = array($mp3file, 'local', 'abs');
  1122. } else {
  1123. $files_list[] = array($mp3file, 'local', 'rel');
  1124. }
  1125. } elseif (strpos($source, 'flv=') === 0) {
  1126. $source = substr($source, 4);
  1127. if (strpos($source, '&') > 0) {
  1128. $source = substr($source, 0, strpos($source, '&'));
  1129. }
  1130. if (strpos($source,'://') > 0) {
  1131. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1132. //we found the current portal url
  1133. $files_list[] = array($source, 'local', 'url');
  1134. } else {
  1135. //we didn't find any trace of current portal
  1136. $files_list[] = array($source, 'remote', 'url');
  1137. }
  1138. } else {
  1139. $files_list[] = array($source, 'local', 'abs');
  1140. }
  1141. continue; //skipping anything else to avoid two entries (while the others can have sub-files in their url, flv's can't)
  1142. }
  1143. }
  1144. if (strpos($source, '://') > 0) {
  1145. //cut at '?' in a URL with params
  1146. if (strpos($source, '?') > 0) {
  1147. $second_part = substr($source,strpos($source, '?'));
  1148. if(strpos($second_part, '://') > 0) {
  1149. //if the second part of the url contains a url too, treat the second one before cutting
  1150. $pos1 = strpos($second_part, '=');
  1151. $pos2 = strpos($second_part, '&');
  1152. $second_part = substr($second_part, $pos1 + 1, $pos2 - ($pos1 + 1));
  1153. if (strpos($second_part, api_get_path(WEB_PATH)) !== false) {
  1154. //we found the current portal url
  1155. $files_list[] = array($second_part, 'local', 'url');
  1156. $in_files_list[] = DocumentManager::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, $recursivity + 1);
  1157. if (count($in_files_list) > 0) {
  1158. $files_list = array_merge($files_list, $in_files_list);
  1159. }
  1160. } else {
  1161. //we didn't find any trace of current portal
  1162. $files_list[] = array($second_part, 'remote', 'url');
  1163. }
  1164. } elseif (strpos($second_part, '=') > 0) {
  1165. if (substr($second_part, 0, 1) === '/') {
  1166. //link starts with a /, making it absolute (relative to DocumentRoot)
  1167. $files_list[] = array($second_part, 'local', 'abs');
  1168. $in_files_list[] = DocumentManager::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, $recursivity + 1);
  1169. if (count($in_files_list) > 0) {
  1170. $files_list = array_merge($files_list, $in_files_list);
  1171. }
  1172. } elseif(strstr($second_part, '..') === 0) {
  1173. //link is relative but going back in the hierarchy
  1174. $files_list[] = array($second_part, 'local', 'rel');
  1175. //$dir = api_get_path(SYS_CODE_PATH);//dirname($abs_path);
  1176. //$new_abs_path = realpath($dir.'/'.$second_part);
  1177. $dir = '';
  1178. if (!empty($abs_path)) {
  1179. $dir = dirname($abs_path).'/';
  1180. }
  1181. $new_abs_path = realpath($dir.$second_part);
  1182. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1183. if (count($in_files_list) > 0) {
  1184. $files_list = array_merge($files_list, $in_files_list);
  1185. }
  1186. } else {
  1187. //no starting '/', making it relative to current document's path
  1188. if (substr($second_part, 0, 2) == './') {
  1189. $second_part = substr($second_part, 2);
  1190. }
  1191. $files_list[] = array($second_part, 'local', 'rel');
  1192. $dir = '';
  1193. if (!empty($abs_path)) {
  1194. $dir = dirname($abs_path).'/';
  1195. }
  1196. $new_abs_path = realpath($dir.$second_part);
  1197. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1198. if (count($in_files_list) > 0) {
  1199. $files_list = array_merge($files_list, $in_files_list);
  1200. }
  1201. }
  1202. }
  1203. //leave that second part behind now
  1204. $source = substr($source, 0, strpos($source, '?'));
  1205. if (strpos($source, '://') > 0) {
  1206. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1207. //we found the current portal url
  1208. $files_list[] = array($source, 'local', 'url');
  1209. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity+1);
  1210. if (count($in_files_list) > 0) {
  1211. $files_list = array_merge($files_list, $in_files_list);
  1212. }
  1213. } else {
  1214. //we didn't find any trace of current portal
  1215. $files_list[] = array($source, 'remote', 'url');
  1216. }
  1217. } else {
  1218. //no protocol found, make link local
  1219. if (substr($source, 0, 1) === '/') {
  1220. //link starts with a /, making it absolute (relative to DocumentRoot)
  1221. $files_list[] = array($source, 'local', 'abs');
  1222. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1223. if (count($in_files_list) > 0) {
  1224. $files_list = array_merge($files_list, $in_files_list);
  1225. }
  1226. } elseif (strstr($source, '..') === 0) { //link is relative but going back in the hierarchy
  1227. $files_list[] = array($source, 'local', 'rel');
  1228. $dir = '';
  1229. if (!empty($abs_path)) {
  1230. $dir = dirname($abs_path).'/';
  1231. }
  1232. $new_abs_path = realpath($dir.$source);
  1233. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1234. if (count($in_files_list) > 0) {
  1235. $files_list = array_merge($files_list, $in_files_list);
  1236. }
  1237. } else {
  1238. //no starting '/', making it relative to current document's path
  1239. if (substr($source, 0, 2) == './') {
  1240. $source = substr($source, 2);
  1241. }
  1242. $files_list[] = array($source, 'local', 'rel');
  1243. $dir = '';
  1244. if (!empty($abs_path)) {
  1245. $dir = dirname($abs_path).'/';
  1246. }
  1247. $new_abs_path = realpath($dir.$source);
  1248. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1249. if (count($in_files_list) > 0) {
  1250. $files_list = array_merge($files_list, $in_files_list);
  1251. }
  1252. }
  1253. }
  1254. }
  1255. //found some protocol there
  1256. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1257. //we found the current portal url
  1258. $files_list[] = array($source, 'local', 'url');
  1259. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1260. if (count($in_files_list) > 0) {
  1261. $files_list = array_merge($files_list, $in_files_list);
  1262. }
  1263. } else {
  1264. //we didn't find any trace of current portal
  1265. $files_list[] = array($source, 'remote', 'url');
  1266. }
  1267. } else {
  1268. //no protocol found, make link local
  1269. if (substr($source, 0, 1) === '/') {
  1270. //link starts with a /, making it absolute (relative to DocumentRoot)
  1271. $files_list[] = array($source, 'local', 'abs');
  1272. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1273. if (count($in_files_list) > 0) {
  1274. $files_list = array_merge($files_list, $in_files_list);
  1275. }
  1276. } elseif (strpos($source, '..') === 0) {
  1277. //link is relative but going back in the hierarchy
  1278. $files_list[] = array($source, 'local', 'rel');
  1279. $dir = '';
  1280. if (!empty($abs_path)) {
  1281. $dir = dirname($abs_path).'/';
  1282. }
  1283. $new_abs_path = realpath($dir.$source);
  1284. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1285. if (count($in_files_list) > 0) {
  1286. $files_list = array_merge($files_list, $in_files_list);
  1287. }
  1288. } else {
  1289. //no starting '/', making it relative to current document's path
  1290. if (substr($source, 0, 2) == './') {
  1291. $source = substr($source, 2);
  1292. }
  1293. $files_list[] = array($source, 'local', 'rel');
  1294. $dir = '';
  1295. if (!empty($abs_path)) {
  1296. $dir = dirname($abs_path).'/';
  1297. }
  1298. $new_abs_path = realpath($dir.$source);
  1299. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1300. if (count($in_files_list) > 0) {
  1301. $files_list = array_merge($files_list, $in_files_list);
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. break;
  1309. default: //ignore
  1310. break;
  1311. }
  1312. $checked_files_list = array();
  1313. $checked_array_list = array();
  1314. if (count($files_list ) > 0) {
  1315. foreach ($files_list as $idx => $file) {
  1316. if (!empty($file[0])) {
  1317. if (!in_array($file[0], $checked_files_list)) {
  1318. $checked_files_list[] = $files_list[$idx][0];
  1319. $checked_array_list[] = $files_list[$idx];
  1320. }
  1321. }
  1322. }
  1323. }
  1324. return $checked_array_list;
  1325. }
  1326. /**
  1327. * Parses the HTML attributes given as string.
  1328. *
  1329. * @param string HTML attribute string
  1330. * @param array List of attributes that we want to get back
  1331. * @return array An associative array of attributes
  1332. * @author Based on a function from the HTML_Common2 PEAR module
  1333. */
  1334. function parse_HTML_attributes($attrString, $wanted = array()) {
  1335. $attributes = array();
  1336. $regs = array();
  1337. $reduced = false;
  1338. if (count($wanted) > 0) {
  1339. $reduced = true;
  1340. }
  1341. try {
  1342. //Find all occurences of something that looks like a URL
  1343. // The structure of this regexp is:
  1344. // (find protocol) then
  1345. // (optionally find some kind of space 1 or more times) then
  1346. // find (either an equal sign or a bracket) followed by an optional space
  1347. // followed by some text without quotes (between quotes itself or not)
  1348. // then possible closing brackets if we were in the opening bracket case
  1349. // OR something like @import()
  1350. $res = preg_match_all(
  1351. '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]*))' .
  1352. // '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]|[^\x00-\x7F])*)' . -> seems to be taking too much
  1353. // '/(((([A-Za-z_:])([^\x00-\x7F])*)' . -> takes only last letter of parameter name
  1354. '([ \n\t\r]+)?(' .
  1355. // '(=([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+))' . -> doesn't restrict close enough to the url itself
  1356. '(=([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+))' .
  1357. '|' .
  1358. // '(\(([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)\))' . -> doesn't restrict close enough to the url itself
  1359. '(\(([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+)\))' .
  1360. '))' .
  1361. '|' .
  1362. // '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))?/', -> takes a lot (like 100's of thousands of empty possibilities)
  1363. '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))/',
  1364. $attrString,
  1365. $regs
  1366. );
  1367. } catch (Exception $e) {
  1368. error_log('Caught exception: '. $e->getMessage(), 0) ;
  1369. }
  1370. if ($res) {
  1371. for ($i = 0; $i < count($regs[1]); $i++) {
  1372. $name = trim($regs[3][$i]);
  1373. $check = trim($regs[0][$i]);
  1374. $value = trim($regs[10][$i]);
  1375. if (empty($value) and !empty($regs[13][$i])) {
  1376. $value = $regs[13][$i];
  1377. }
  1378. if (empty($name) && !empty($regs[16][$i])) {
  1379. $name = '@import';
  1380. $value = trim($regs[16][$i]);
  1381. }
  1382. if (!empty($name)) {
  1383. if (!$reduced OR in_array(strtolower($name), $wanted)) {
  1384. if ($name == $check) {
  1385. $attributes[strtolower($name)][] = strtolower($name);
  1386. } else {
  1387. if (!empty($value) && ($value[0] == '\'' || $value[0] == '"')) {
  1388. $value = substr($value, 1, -1);
  1389. }
  1390. if ($value == 'API.LMSGetValue(name') {
  1391. $value = 'API.LMSGetValue(name)';
  1392. }
  1393. $attributes[strtolower($name)][] = $value;
  1394. }
  1395. }
  1396. }
  1397. }
  1398. } else {
  1399. error_log('preg_match did not find anything', 0);
  1400. }
  1401. return $attributes;
  1402. }
  1403. /**
  1404. * Replace urls inside content html from a copy course
  1405. * @param string content html
  1406. * @param string origin course code
  1407. * @param string destination course directory
  1408. * @return string new content html with replaced urls or return false if content is not a string
  1409. */
  1410. function replace_urls_inside_content_html_from_copy_course($content_html, $origin_course_code, $destination_course_directory) {
  1411. if (!is_string($content_html)) {
  1412. return false;
  1413. }
  1414. $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
  1415. $orig_course_info = api_get_course_info($origin_course_code);
  1416. $orig_course_path = api_get_path(SYS_PATH).'courses/'.$orig_course_info['path'].'/';
  1417. $destination_course_code = CourseManager::get_course_id_from_path ($destination_course_directory);
  1418. $dest_course_path = api_get_path(SYS_COURSE_PATH).$destination_course_directory.'/';
  1419. foreach ($orig_source_html as $source) {
  1420. // get information about source url
  1421. $real_orig_url = $source[0]; // url
  1422. $scope_url = $source[1]; // scope (local, remote)
  1423. $type_url = $source[2]; // tyle (rel, abs, url)
  1424. // get path and query from origin url
  1425. $orig_parse_url = parse_url($real_orig_url);
  1426. $real_orig_path = $orig_parse_url['path'];
  1427. $real_orig_query = $orig_parse_url['query'];
  1428. // replace origin course code by destination course code from origin url query
  1429. $dest_url_query = '';
  1430. if (!empty($real_orig_query)) {
  1431. $dest_url_query = '?'.$real_orig_query;
  1432. if (strpos($dest_url_query,$origin_course_code) !== false) {
  1433. $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
  1434. }
  1435. }
  1436. if ($scope_url == 'local') {
  1437. if ( $type_url == 'abs' || $type_url == 'rel') {
  1438. $document_file = strstr($real_orig_path, 'document');
  1439. if (strpos($real_orig_path,$document_file) !== false) {
  1440. $origin_filepath = $orig_course_path.$document_file;
  1441. $destination_filepath = $dest_course_path.$document_file;
  1442. // copy origin file inside destination course
  1443. if (file_exists($origin_filepath)) {
  1444. $filepath_dir = dirname($destination_filepath);
  1445. if (!is_dir($filepath_dir)) {
  1446. $perm = api_get_permissions_for_new_directories();
  1447. @mkdir($filepath_dir, $perm, true);
  1448. }
  1449. if (!file_exists($destination_filepath)) {
  1450. @copy($origin_filepath, $destination_filepath);
  1451. }
  1452. }
  1453. // replace origin course path by destination course path
  1454. if (strpos($content_html,$real_orig_url) !== false) {
  1455. $url_course_path = str_replace($orig_course_info['path'].'/'.$document_file, '', $real_orig_path);
  1456. $destination_url = $url_course_path.$destination_course_directory.'/'.$document_file.$dest_url_query;
  1457. $content_html = str_replace($real_orig_url, $destination_url, $content_html);
  1458. }
  1459. }
  1460. // replace origin course code by destination course code from origin url
  1461. if (strpos($real_orig_url, '?') === 0) {
  1462. $dest_url = str_replace($origin_course_code, $destination_course_code, $real_orig_url);
  1463. $content_html = str_replace($real_orig_url, $dest_url, $content_html);
  1464. }
  1465. }
  1466. }
  1467. }
  1468. return $content_html;
  1469. }
  1470. }
  1471. //end class DocumentManager