document.lib.php 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471
  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. * @package chamilo.library
  10. */
  11. require_once api_get_path(LIBRARY_PATH).'course.lib.php';
  12. require_once api_get_path(LIBRARY_PATH).'usermanager.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. $default_quota = api_get_setting('default_document_quotum');
  17. //Just in case the setting is not correctly set
  18. if (empty($default_quota)) {
  19. $default_quota = 100000000;
  20. }
  21. define('DEFAULT_DOCUMENT_QUOTA', $default_quota);
  22. class DocumentManager {
  23. private function __construct() {
  24. }
  25. /**
  26. * @return the document folder quota for the current course, in bytes, or the default quota
  27. * @todo eliminate globals
  28. */
  29. public static function get_course_quota() {
  30. $course_info = api_get_course_info();
  31. if (empty($course_info)) {
  32. return DEFAULT_DOCUMENT_QUOTA;
  33. }
  34. $course_code = Database::escape_string($course_info['code']);
  35. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  36. $sql_query = "SELECT ".DISK_QUOTA_FIELD." FROM $course_table WHERE code = '$course_code'";
  37. $sql_result = Database::query($sql_query);
  38. $course_quota = null;
  39. if (Database::num_rows($sql_result)) {
  40. $result = Database::fetch_array($sql_result);
  41. $course_quota = $result[DISK_QUOTA_FIELD];
  42. }
  43. if (is_null($course_quota) || empty($course_quota)) {
  44. // Course table entry for quota was null, then use default value
  45. $course_quota = DEFAULT_DOCUMENT_QUOTA;
  46. }
  47. return $course_quota;
  48. }
  49. /**
  50. * Get the content type of a file by checking the extension
  51. * We could use mime_content_type() with php-versions > 4.3,
  52. * but this doesn't work as it should on Windows installations
  53. *
  54. * @param string $filename or boolean TRUE to return complete array
  55. * @author ? first version
  56. * @author Bert Vanderkimpen
  57. *
  58. */
  59. public static function file_get_mime_type($filename) {
  60. // All MIME types in an array (from 1.6, this is the authorative source)
  61. // Please, keep this alphabetical if you add something to this list!
  62. $mime_types = array(
  63. 'ai' => 'application/postscript',
  64. 'aif' => 'audio/x-aiff',
  65. 'aifc' => 'audio/x-aiff',
  66. 'aiff' => 'audio/x-aiff',
  67. 'asf' => 'video/x-ms-asf',
  68. 'asc' => 'text/plain',
  69. 'au' => 'audio/basic',
  70. 'avi' => 'video/x-msvideo',
  71. 'bcpio' => 'application/x-bcpio',
  72. 'bin' => 'application/octet-stream',
  73. 'bmp' => 'image/bmp',
  74. 'cdf' => 'application/x-netcdf',
  75. 'class' => 'application/octet-stream',
  76. 'cpio' => 'application/x-cpio',
  77. 'cpt' => 'application/mac-compactpro',
  78. 'csh' => 'application/x-csh',
  79. 'css' => 'text/css',
  80. 'dcr' => 'application/x-director',
  81. 'dir' => 'application/x-director',
  82. 'djv' => 'image/vnd.djvu',
  83. 'djvu' => 'image/vnd.djvu',
  84. 'dll' => 'application/octet-stream',
  85. 'dmg' => 'application/x-diskcopy',
  86. 'dms' => 'application/octet-stream',
  87. 'doc' => 'application/msword',
  88. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  89. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  90. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  91. 'dvi' => 'application/x-dvi',
  92. 'dwg' => 'application/vnd.dwg',
  93. 'dxf' => 'application/vnd.dxf',
  94. 'dxr' => 'application/x-director',
  95. 'eps' => 'application/postscript',
  96. 'epub' => 'application/epub+zip',
  97. 'etx' => 'text/x-setext',
  98. 'exe' => 'application/octet-stream',
  99. 'ez' => 'application/andrew-inset',
  100. 'gif' => 'image/gif',
  101. 'gtar' => 'application/x-gtar',
  102. 'gz' => 'application/x-gzip',
  103. 'hdf' => 'application/x-hdf',
  104. 'hqx' => 'application/mac-binhex40',
  105. 'htm' => 'text/html',
  106. 'html' => 'text/html',
  107. 'ice' => 'x-conference-xcooltalk',
  108. 'ief' => 'image/ief',
  109. 'iges' => 'model/iges',
  110. 'igs' => 'model/iges',
  111. 'jar' => 'application/java-archiver',
  112. 'jpe' => 'image/jpeg',
  113. 'jpeg' => 'image/jpeg',
  114. 'jpg' => 'image/jpeg',
  115. 'js' => 'application/x-javascript',
  116. 'kar' => 'audio/midi',
  117. 'lam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  118. 'latex' => 'application/x-latex',
  119. 'lha' => 'application/octet-stream',
  120. 'log' => 'text/plain',
  121. 'lzh' => 'application/octet-stream',
  122. 'm1a' => 'audio/mpeg',
  123. 'm2a' => 'audio/mpeg',
  124. 'm3u' => 'audio/x-mpegurl',
  125. 'man' => 'application/x-troff-man',
  126. 'me' => 'application/x-troff-me',
  127. 'mesh' => 'model/mesh',
  128. 'mid' => 'audio/midi',
  129. 'midi' => 'audio/midi',
  130. 'mov' => 'video/quicktime',
  131. 'movie' => 'video/x-sgi-movie',
  132. 'mp2' => 'audio/mpeg',
  133. 'mp3' => 'audio/mpeg',
  134. 'mp4' => 'video/mpeg4-generic',
  135. 'mpa' => 'audio/mpeg',
  136. 'mpe' => 'video/mpeg',
  137. 'mpeg' => 'video/mpeg',
  138. 'mpg' => 'video/mpeg',
  139. 'mpga' => 'audio/mpeg',
  140. 'ms' => 'application/x-troff-ms',
  141. 'msh' => 'model/mesh',
  142. 'mxu' => 'video/vnd.mpegurl',
  143. 'nc' => 'application/x-netcdf',
  144. 'oda' => 'application/oda',
  145. 'oga'=> 'audio/ogg',
  146. 'ogg'=> 'application/ogg',
  147. 'ogx'=> 'application/ogg',
  148. 'ogv'=> 'video/ogg',
  149. 'pbm' => 'image/x-portable-bitmap',
  150. 'pct' => 'image/pict',
  151. 'pdb' => 'chemical/x-pdb',
  152. 'pdf' => 'application/pdf',
  153. 'pgm' => 'image/x-portable-graymap',
  154. 'pgn' => 'application/x-chess-pgn',
  155. 'pict' => 'image/pict',
  156. 'png' => 'image/png',
  157. 'pnm' => 'image/x-portable-anymap',
  158. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  159. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  160. 'pps' => 'application/vnd.ms-powerpoint',
  161. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  162. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  163. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  164. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  165. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  166. 'ppm' => 'image/x-portable-pixmap',
  167. 'ppt' => 'application/vnd.ms-powerpoint',
  168. 'pps' => 'application/vnd.ms-powerpoint',
  169. 'ps' => 'application/postscript',
  170. 'qt' => 'video/quicktime',
  171. 'ra' => 'audio/x-realaudio',
  172. 'ram' => 'audio/x-pn-realaudio',
  173. 'rar' => 'image/x-rar-compressed',
  174. 'ras' => 'image/x-cmu-raster',
  175. 'rgb' => 'image/x-rgb',
  176. 'rm' => 'audio/x-pn-realaudio',
  177. 'roff' => 'application/x-troff',
  178. 'rpm' => 'audio/x-pn-realaudio-plugin',
  179. 'rtf' => 'text/rtf',
  180. 'rtx' => 'text/richtext',
  181. 'sgm' => 'text/sgml',
  182. 'sgml' => 'text/sgml',
  183. 'sh' => 'application/x-sh',
  184. 'shar' => 'application/x-shar',
  185. 'silo' => 'model/mesh',
  186. 'sib' => 'application/X-Sibelius-Score',
  187. 'sit' => 'application/x-stuffit',
  188. 'skd' => 'application/x-koan',
  189. 'skm' => 'application/x-koan',
  190. 'skp' => 'application/x-koan',
  191. 'skt' => 'application/x-koan',
  192. 'smi' => 'application/smil',
  193. 'smil' => 'application/smil',
  194. 'snd' => 'audio/basic',
  195. 'so' => 'application/octet-stream',
  196. 'spl' => 'application/x-futuresplash',
  197. 'src' => 'application/x-wais-source',
  198. 'sv4cpio' => 'application/x-sv4cpio',
  199. 'sv4crc' => 'application/x-sv4crc',
  200. 'svf' => 'application/vnd.svf',
  201. 'svg' => 'image/svg+xml',
  202. //'svgz' => 'image/svg+xml',
  203. 'swf' => 'application/x-shockwave-flash',
  204. 'sxc' => 'application/vnd.sun.xml.calc',
  205. 'sxi' => 'application/vnd.sun.xml.impress',
  206. 'sxw' => 'application/vnd.sun.xml.writer',
  207. 't' => 'application/x-troff',
  208. 'tar' => 'application/x-tar',
  209. 'tcl' => 'application/x-tcl',
  210. 'tex' => 'application/x-tex',
  211. 'texi' => 'application/x-texinfo',
  212. 'texinfo' => 'application/x-texinfo',
  213. 'tga' => 'image/x-targa',
  214. 'tif' => 'image/tif',
  215. 'tiff' => 'image/tiff',
  216. 'tr' => 'application/x-troff',
  217. 'tsv' => 'text/tab-seperated-values',
  218. 'txt' => 'text/plain',
  219. 'ustar' => 'application/x-ustar',
  220. 'vcd' => 'application/x-cdlink',
  221. 'vrml' => 'model/vrml',
  222. 'wav' => 'audio/x-wav',
  223. 'wbmp' => 'image/vnd.wap.wbmp',
  224. 'wbxml' => 'application/vnd.wap.wbxml',
  225. 'wml' => 'text/vnd.wap.wml',
  226. 'wmlc' => 'application/vnd.wap.wmlc',
  227. 'wmls' => 'text/vnd.wap.wmlscript',
  228. 'wmlsc' => 'application/vnd.wap.wmlscriptc',
  229. 'wma' => 'video/x-ms-wma',
  230. 'wmv' => 'audio/x-ms-wmv',
  231. 'wrl' => 'model/vrml',
  232. 'xbm' => 'image/x-xbitmap',
  233. 'xht' => 'application/xhtml+xml',
  234. 'xhtml' => 'application/xhtml+xml',
  235. 'xls' => 'application/vnd.ms-excel',
  236. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  237. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  238. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  239. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  240. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  241. 'xml' => 'text/xml',
  242. 'xpm' => 'image/x-xpixmap',
  243. 'xsl' => 'text/xml',
  244. 'xwd' => 'image/x-windowdump',
  245. 'xyz' => 'chemical/x-xyz',
  246. 'zip' => 'application/zip'
  247. );
  248. if ($filename === true) {
  249. return $mime_types;
  250. }
  251. //get the extension of the file
  252. $extension = explode('.', $filename);
  253. //$filename will be an array if a . was found
  254. if (is_array($extension)) {
  255. $extension = strtolower($extension[sizeof($extension) - 1]);
  256. }
  257. //file without extension
  258. else {
  259. $extension = 'empty';
  260. }
  261. //if the extension is found, return the content type
  262. if (isset($mime_types[$extension])) {
  263. return $mime_types[$extension];
  264. }
  265. //else return octet-stream
  266. return 'application/octet-stream';
  267. }
  268. /**
  269. * @return true if the user is allowed to see the document, false otherwise
  270. * @author Sergio A Kessler, first version
  271. * @author Roan Embrechts, bugfix
  272. * @todo ??not only check if a file is visible, but also check if the user is allowed to see the file??
  273. */
  274. public static function file_visible_to_user ($this_course, $doc_url) {
  275. $current_session_id = api_get_session_id();
  276. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  277. if ($is_allowed_to_edit) {
  278. return true;
  279. } else {
  280. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  281. $tbl_item_property = $this_course.'item_property';
  282. $doc_url = Database::escape_string($doc_url);
  283. //$doc_url = addslashes($doc_url);
  284. $query = "SELECT 1 FROM $tbl_document AS docs,$tbl_item_property AS props
  285. WHERE props.tool = 'document' AND docs.id=props.ref AND props.visibility <> '1' AND docs.path = '$doc_url'";
  286. //echo $query;
  287. $result = Database::query($query);
  288. return (Database::num_rows($result) == 0);
  289. }
  290. }
  291. /**
  292. * This function streams a file to the client
  293. *
  294. * @param string $full_file_name
  295. * @param boolean $forced
  296. * @param string $name
  297. * @return false if file doesn't exist, true if stream succeeded
  298. */
  299. public static function file_send_for_download($full_file_name, $forced = false, $name = '') {
  300. if (!is_file($full_file_name)) {
  301. return false;
  302. }
  303. $filename = ($name == '') ? basename($full_file_name) : replace_dangerous_char($name);
  304. $len = filesize($full_file_name);
  305. if ($forced) {
  306. //force the browser to save the file instead of opening it
  307. header('Content-type: application/octet-stream');
  308. //header('Content-Type: application/force-download');
  309. header('Content-length: '.$len);
  310. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
  311. header('Content-Disposition: filename= '.$filename);
  312. } else {
  313. header('Content-Disposition: attachment; filename= '.$filename);
  314. }
  315. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
  316. header('Pragma: ');
  317. header('Cache-Control: ');
  318. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  319. }
  320. header('Content-Description: '.$filename);
  321. header('Content-transfer-encoding: binary');
  322. $fp = fopen($full_file_name, 'r');
  323. fpassthru($fp);
  324. return true;
  325. } else {
  326. //no forced download, just let the browser decide what to do according to the mimetype
  327. $content_type = self::file_get_mime_type($filename);
  328. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  329. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  330. // Commented to avoid double caching declaration when playing with IE and HTTPS
  331. //header('Cache-Control: no-cache, must-revalidate');
  332. //header('Pragma: no-cache');
  333. switch ($content_type) {
  334. case 'text/html':
  335. $encoding = @api_detect_encoding_html(file_get_contents($full_file_name));
  336. if (!empty($encoding)) {
  337. $content_type .= '; charset='.$encoding;
  338. }
  339. break;
  340. case 'text/plain':
  341. $encoding = @api_detect_encoding(strip_tags(file_get_contents($full_file_name)));
  342. if (!empty($encoding)) {
  343. $content_type .= '; charset='.$encoding;
  344. }
  345. break;
  346. }
  347. header('Content-type: '.$content_type);
  348. header('Content-Length: '.$len);
  349. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  350. if (strpos($user_agent, 'msie')) {
  351. header('Content-Disposition: ; filename= '.$filename);
  352. } else {
  353. header('Content-Disposition: inline; filename= '.$filename);
  354. }
  355. readfile($full_file_name);
  356. return true;
  357. }
  358. }
  359. /**
  360. * This function streams a string to the client for download.
  361. * You have to ensure that the calling script then stops processing (exit();)
  362. * otherwise it may cause subsequent use of the page to want to download
  363. * other pages in php rather than interpreting them.
  364. *
  365. * @param string The string contents
  366. * @param boolean Whether "save" mode is forced (or opening directly authorized)
  367. * @param string The name of the file in the end (including extension)
  368. * @return false if file doesn't exist, true if stream succeeded
  369. */
  370. public static function string_send_for_download($full_string, $forced = false, $name = '') {
  371. $filename = $name;
  372. $len = strlen($full_string);
  373. if ($forced) {
  374. //force the browser to save the file instead of opening it
  375. header('Content-type: application/octet-stream');
  376. //header('Content-Type: application/force-download');
  377. header('Content-length: '.$len);
  378. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
  379. header('Content-Disposition: filename= '.$filename);
  380. } else {
  381. header('Content-Disposition: attachment; filename= '.$filename);
  382. }
  383. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
  384. header('Pragma: ');
  385. header('Cache-Control: ');
  386. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  387. }
  388. header('Content-Description: '.$filename);
  389. header('Content-transfer-encoding: binary');
  390. //$fp = fopen($full_string, 'r');
  391. //fpassthru($fp);
  392. echo $full_string;
  393. return true;
  394. //You have to ensure that the calling script then stops processing (exit();)
  395. //otherwise it may cause subsequent use of the page to want to download
  396. //other pages in php rather than interpreting them.
  397. } else {
  398. //no forced download, just let the browser decide what to do according to the mimetype
  399. $content_type = self::file_get_mime_type($filename);
  400. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  401. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  402. header('Cache-Control: no-cache, must-revalidate');
  403. header('Pragma: no-cache');
  404. switch ($content_type) {
  405. case 'text/html':
  406. $encoding = @api_detect_encoding_html($full_string);
  407. if (!empty($encoding)) {
  408. $content_type .= '; charset='.$encoding;
  409. }
  410. break;
  411. case 'text/plain':
  412. $encoding = @api_detect_encoding(strip_tags($full_string));
  413. if (!empty($encoding)) {
  414. $content_type .= '; charset='.$encoding;
  415. }
  416. break;
  417. }
  418. header('Content-type: '.$content_type);
  419. header('Content-Length: '.$len);
  420. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  421. if (strpos($user_agent, 'msie')) {
  422. header('Content-Disposition: ; filename= '.$filename);
  423. } else {
  424. header('Content-Disposition: inline; filename= '.$filename);
  425. }
  426. echo($full_string);
  427. //You have to ensure that the calling script then stops processing (exit();)
  428. //otherwise it may cause subsequent use of the page to want to download
  429. //other pages in php rather than interpreting them.
  430. return true;
  431. }
  432. }
  433. /**
  434. * Fetches all document data for the given user/group
  435. *
  436. * @param array $_course
  437. * @param string $path
  438. * @param int $to_group_id
  439. * @param int $to_user_id
  440. * @param boolean $can_see_invisible
  441. * @return array with all document data
  442. */
  443. public static function get_all_document_data($_course, $path = '/', $to_group_id = 0, $to_user_id = NULL, $can_see_invisible = false, $search =false) {
  444. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  445. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  446. $TABLE_COURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  447. //if to_user_id = NULL -> change query (IS NULL)
  448. //$to_user_id = (is_null($to_user_id)) ? 'IS NULL' : '= '.$to_user_id;
  449. if (!is_null($to_user_id)) {
  450. $to_field = 'last.to_user_id';
  451. $to_value = $to_user_id;
  452. } else {
  453. $to_field = 'last.to_group_id';
  454. $to_value = $to_group_id;
  455. }
  456. //escape underscores in the path so they don't act as a wildcard
  457. $path = Database::escape_string(str_replace('_', '\_', $path));
  458. $to_user_id = Database::escape_string($to_user_id);
  459. $to_value = Database::escape_string($to_value);
  460. //if they can't see invisible files, they can only see files with visibility 1
  461. $visibility_bit = ' = 1';
  462. //if they can see invisible files, only deleted files (visibility 2) are filtered out
  463. //if ($can_see_invisible) {
  464. $visibility_bit = ' <> 2';
  465. //}
  466. //the given path will not end with a slash, unless it's the root '/'
  467. //so no root -> add slash
  468. $added_slash = ($path == '/') ? '' : '/';
  469. //condition for the session
  470. $current_session_id = api_get_session_id();
  471. $condition_session = " AND (id_session = '$current_session_id' OR id_session = '0')";
  472. if (!$can_see_invisible) {
  473. //$condition_session = " AND (id_session = '$current_session_id' ) ";
  474. }
  475. //condition for search (get ALL folders and documents)
  476. if ($search) {
  477. $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, last.insert_user_id
  478. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  479. WHERE docs.id = last.ref
  480. AND last.tool = '".TOOL_DOCUMENT."'
  481. AND ".$to_field." = ".$to_value."
  482. AND last.visibility".$visibility_bit . $condition_session;
  483. } else {
  484. $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, last.insert_user_id
  485. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  486. WHERE docs.id = last.ref
  487. AND docs.path LIKE '".$path.$added_slash."%'
  488. AND docs.path NOT LIKE '".$path.$added_slash."%/%'
  489. AND last.tool = '".TOOL_DOCUMENT."'
  490. AND ".$to_field." = ".$to_value."
  491. AND last.visibility".$visibility_bit.$condition_session;
  492. }
  493. $result = Database::query($sql);
  494. $doc_list = array();
  495. $document_data = array();
  496. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  497. if ($result!==false && Database::num_rows($result) != 0) {
  498. while ($row = Database::fetch_array($result, 'ASSOC')) {
  499. if (api_is_coach()) {
  500. //Looking for course items that are invisible to hide it in the session
  501. if (in_array($row['id'], array_keys($doc_list))) {
  502. if ($doc_list[$row['id']]['item_property_session_id'] == 0 && $doc_list[$row['id']]['session_id'] == 0) {
  503. if ($doc_list[$row['id']]['visibility'] == 0) {
  504. unset($document_data[$row['id']]);
  505. continue;
  506. }
  507. }
  508. }
  509. $doc_list[$row['id']] = $row;
  510. }
  511. if (!api_is_coach() && !$is_allowed_to_edit) {
  512. $doc_list[] = $row;
  513. }
  514. if ($row['filetype'] == 'file' && pathinfo($row['path'], PATHINFO_EXTENSION) == 'html') {
  515. //Templates management
  516. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  517. $sql_is_template = "SELECT id FROM $table_template
  518. WHERE course_code='".$_course['id']."'
  519. AND user_id='".api_get_user_id()."'
  520. AND ref_doc='".$row['id']."'";
  521. $template_result = Database::query($sql_is_template);
  522. $row['is_template'] = (Database::num_rows($template_result) > 0) ? 1 : 0;
  523. }
  524. $document_data[$row['id']] = $row;
  525. }
  526. //Only for the student we filter the results see BT#1652
  527. if (!api_is_coach() && !$is_allowed_to_edit) {
  528. $ids_to_remove = array();
  529. $my_repeat_ids = $temp= array();
  530. //Selecting repetead ids
  531. foreach($doc_list as $row ) {
  532. if (in_array($row['id'], array_keys($temp))) {
  533. $my_repeat_ids[] = $row['id'];
  534. }
  535. $temp[$row['id']] = $row;
  536. }
  537. //Checking disponibility in a session
  538. foreach($my_repeat_ids as $id) {
  539. foreach($doc_list as $row ) {
  540. if ($id == $row['id']) {
  541. //var_dump($row['visibility'].' - '.$row['session_id'].' - '.$row['item_property_session_id']);
  542. if ($row['visibility'] == 0 && $row['item_property_session_id'] == 0) {
  543. $delete_repeated[$id] = true;
  544. }
  545. if ($row['visibility'] == 0 && $row['item_property_session_id'] != 0) {
  546. $delete_repeated[$id] = true;
  547. }
  548. }
  549. }
  550. }
  551. //var_dump($delete_repeated);
  552. foreach($doc_list as $key=>$row) {
  553. //&& !in_array($row['id'],$my_repeat_ids)
  554. //var_dump($row['id'].' - '.$row['visibility']);
  555. if (in_array($row['visibility'], array('0','2')) && !in_array($row['id'],$my_repeat_ids) ) {
  556. $ids_to_remove[] = $row['id'];
  557. unset($doc_list[$key]);
  558. }
  559. }
  560. //var_dump($ids_to_remove);
  561. foreach($document_data as $row) {
  562. if (in_array($row['id'], $ids_to_remove)) {
  563. unset($document_data[$row['id']]);
  564. }
  565. if (isset($delete_repeated[$row['id']]) && $delete_repeated[$row['id']]) {
  566. unset($document_data[$row['id']]);
  567. }
  568. }
  569. }
  570. return $document_data;
  571. } else {
  572. //display_error("Error getting document info from database (".Database::error().")!");
  573. return false;
  574. }
  575. }
  576. /**
  577. * Gets the paths of all folders in a course
  578. * can show all folders (exept for the deleted ones) or only visible ones
  579. * @param array $_course
  580. * @param boolean $can_see_invisible
  581. * @param int $to_group_id
  582. * @return array with paths
  583. */
  584. public static function get_all_document_folders ($_course, $to_group_id = '0', $can_see_invisible = false) {
  585. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  586. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  587. $to_group_id = intval($to_group_id);
  588. if ($can_see_invisible) {
  589. //condition for the session
  590. $session_id = api_get_session_id();
  591. $condition_session = api_get_session_condition($session_id);
  592. $sql = "SELECT DISTINCT path FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  593. WHERE docs.id = last.ref
  594. AND docs.filetype = 'folder'
  595. AND last.tool = '".TOOL_DOCUMENT."'
  596. AND last.to_group_id = ".$to_group_id."
  597. AND last.visibility <> 2 $condition_session";
  598. $result = Database::query($sql);
  599. if ($result && Database::num_rows($result) != 0) {
  600. while ($row = Database::fetch_array($result, 'ASSOC')) {
  601. $document_folders[] = $row['path'];
  602. }
  603. //sort($document_folders);
  604. natsort($document_folders);
  605. //return results
  606. return $document_folders;
  607. } else {
  608. return false;
  609. }
  610. } else {
  611. //no invisible folders
  612. //condition for the session
  613. $session_id = api_get_session_id();
  614. $condition_session = api_get_session_condition($session_id);
  615. //get visible folders
  616. $visible_sql = "SELECT DISTINCT path
  617. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  618. WHERE docs.id = last.ref
  619. AND docs.filetype = 'folder'
  620. AND last.tool = '".TOOL_DOCUMENT."'
  621. AND last.to_group_id = ".$to_group_id."
  622. AND last.visibility = 1 $condition_session";
  623. $visibleresult = Database::query($visible_sql);
  624. while ($all_visible_folders = Database::fetch_array($visibleresult, 'ASSOC')) {
  625. $visiblefolders[] = $all_visible_folders['path'];
  626. }
  627. //condition for the session
  628. $session_id = api_get_session_id();
  629. $condition_session = api_get_session_condition($session_id);
  630. //get invisible folders
  631. $invisible_sql = "SELECT DISTINCT path
  632. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  633. WHERE docs.id = last.ref
  634. AND docs.filetype = 'folder'
  635. AND last.tool = '".TOOL_DOCUMENT."'
  636. AND last.to_group_id = ".$to_group_id."
  637. AND last.visibility = 0 $condition_session";
  638. $invisibleresult = Database::query($invisible_sql);
  639. while ($invisible_folders = Database::fetch_array($invisibleresult, 'ASSOC')) {
  640. //condition for the session
  641. $session_id = api_get_session_id();
  642. $condition_session = api_get_session_condition($session_id);
  643. //get visible folders in the invisible ones -> they are invisible too
  644. $folder_in_invisible_sql = "SELECT DISTINCT path
  645. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  646. WHERE docs.id = last.ref
  647. AND docs.path LIKE '".Database::escape_string($invisible_folders['path'])."/%'
  648. AND docs.filetype = 'folder'
  649. AND last.tool = '".TOOL_DOCUMENT."'
  650. AND last.to_group_id = ".$to_group_id."
  651. AND last.visibility = 1 $condition_session";
  652. $folder_in_invisible_result = Database::query($folder_in_invisible_sql);
  653. while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result, 'ASSOC')) {
  654. $invisiblefolders[] = $folders_in_invisible_folder['path'];
  655. }
  656. }
  657. //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
  658. if (is_array($visiblefolders) && is_array($invisiblefolders)) {
  659. $document_folders = array_diff($visiblefolders, $invisiblefolders);
  660. //sort($document_folders);
  661. natsort($document_folders);
  662. return $document_folders;
  663. }
  664. //only visible folders found
  665. elseif (is_array($visiblefolders)) {
  666. //sort($visiblefolders);
  667. natsort($visiblefolders);
  668. return $visiblefolders;
  669. }
  670. //no visible folders found
  671. else {
  672. return false;
  673. }
  674. }
  675. }
  676. /**
  677. * This check if a document has the readonly property checked, then see if the user
  678. * is the owner of this file, if all this is true then return true.
  679. *
  680. * @param array $_course
  681. * @param int $user_id id of the current user
  682. * @param string $file path stored in the database
  683. * @param int $document_id in case you dont have the file path ,insert the id of the file here and leave $file in blank ''
  684. * @return boolean true/false
  685. **/
  686. public static function check_readonly($_course, $user_id, $file,$document_id = '', $to_delete = false) {
  687. if (!(!empty($document_id) && is_numeric($document_id))) {
  688. $document_id = self::get_document_id($_course, $file);
  689. }
  690. $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  691. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  692. if ($to_delete) {
  693. if (self::is_folder($_course, $document_id)) {
  694. if (!empty($file)) {
  695. $path = Database::escape_string($file);
  696. $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM ".$TABLE_DOCUMENT." td , $TABLE_PROPERTY tp
  697. WHERE tp.ref= td.id and (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
  698. //get all id's of documents that are deleted
  699. $what_to_check_result = Database::query($what_to_check_sql);
  700. if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0) {
  701. // file with readonly set to 1 exist?
  702. $readonly_set = false;
  703. while ($row = Database::fetch_array($what_to_check_result)) {
  704. //query to delete from item_property table
  705. if ($row['readonly'] == 1) {
  706. if (!($row['insert_user_id'] == $user_id)) {
  707. $readonly_set = true;
  708. break;
  709. }
  710. }
  711. }
  712. if ($readonly_set) {
  713. return true;
  714. }
  715. }
  716. }
  717. return false;
  718. }
  719. }
  720. if (!empty($document_id)) {
  721. $sql= 'SELECT a.insert_user_id, b.readonly FROM '.$TABLE_PROPERTY.' a,'.$TABLE_DOCUMENT.' b
  722. WHERE a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
  723. $resultans = Database::query($sql);
  724. $doc_details = Database ::fetch_array($resultans, 'ASSOC');
  725. if ($doc_details['readonly'] == 1) {
  726. return !($doc_details['insert_user_id'] == $user_id || api_is_platform_admin());
  727. }
  728. }
  729. return false;
  730. }
  731. /**
  732. * This check if a document is a folder or not
  733. * @param array $_course
  734. * @param int $document_id of the item
  735. * @return boolean true/false
  736. **/
  737. public static function is_folder($_course, $document_id) {
  738. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  739. //if (!empty($document_id))
  740. $document_id = Database::escape_string($document_id);
  741. $result = Database::fetch_array(Database::query('SELECT filetype FROM '.$TABLE_DOCUMENT.' WHERE id='.$document_id.''), 'ASSOC');
  742. return $result['filetype'] == 'folder';
  743. }
  744. /**
  745. * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
  746. * Files/folders that are inside a deleted folder get visibility 2
  747. *
  748. * @param array $_course
  749. * @param string $path, path stored in the database
  750. * @param string ,$base_work_dir, path to the documents folder
  751. * @return boolean true/false
  752. * @todo now only files/folders in a folder get visibility 2, we should rename them too.
  753. */
  754. public static function delete_document($_course, $path, $base_work_dir) {
  755. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
  756. $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
  757. //first, delete the actual document...
  758. $document_id = self :: get_document_id($_course, $path);
  759. $new_path = $path.'_DELETED_'.$document_id;
  760. $current_session_id = api_get_session_id();
  761. if ($document_id) {
  762. if (api_get_setting('permanently_remove_deleted_files') == 'true') { //deleted files are *really* deleted
  763. $what_to_delete_sql = "SELECT id FROM ".$TABLE_DOCUMENT." WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  764. //get all id's of documents that are deleted
  765. $what_to_delete_result = Database::query($what_to_delete_sql);
  766. if ($what_to_delete_result && Database::num_rows($what_to_delete_result) != 0) {
  767. //needed to deleted medadata
  768. require_once api_get_path(SYS_CODE_PATH).'metadata/md_funcs.php';
  769. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  770. $mdStore = new mdstore(true);
  771. //delete all item_property entries
  772. while ($row = Database::fetch_array($what_to_delete_result)) {
  773. //query to delete from item_property table
  774. //avoid wrong behavior
  775. //$remove_from_item_property_sql = "DELETE FROM ".$TABLE_ITEMPROPERTY." WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  776. api_item_property_update($_course, TOOL_DOCUMENT, $row['id'], 'delete', api_get_user_id(), null, null, null, null, $current_session_id);
  777. //query to delete from document table
  778. $remove_from_document_sql = "DELETE FROM ".$TABLE_DOCUMENT." WHERE id = ".$row['id'];
  779. self::unset_document_as_template($row['id'], $_course, api_get_user_id());
  780. Database::query($remove_from_document_sql);
  781. //delete metadata
  782. $eid = 'Document'.'.'.$row['id'];
  783. $mdStore->mds_delete($eid);
  784. $mdStore->mds_delete_offspring($eid);
  785. }
  786. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  787. //delete documents, do it like this so metadata get's deleted too
  788. //update_db_info('delete', $path);
  789. //throw it away
  790. my_delete($base_work_dir.$path);
  791. return true;
  792. } else {
  793. return false;
  794. }
  795. } else { //set visibility to 2 and rename file/folder to qsdqsd_DELETED_#id
  796. if (api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'delete', api_get_user_id(), null, null, null, null, $current_session_id)) {
  797. if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path)) {
  798. if(rename($base_work_dir.$path, $base_work_dir.$new_path)) {
  799. self::unset_document_as_template($document_id, api_get_course_id(), api_get_user_id());
  800. $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE id='".$document_id."'";
  801. if (Database::query($sql)) {
  802. //if it is a folder it can contain files
  803. $sql = "SELECT id,path FROM ".$TABLE_DOCUMENT." WHERE path LIKE BINARY '".$path."/%'";
  804. $result = Database::query($sql);
  805. if ($result && Database::num_rows($result) > 0) {
  806. while ($deleted_items = Database::fetch_array($result, 'ASSOC')) {
  807. api_item_property_update($_course, TOOL_DOCUMENT, $deleted_items['id'], 'delete', api_get_user_id(),null,null,null,null,$current_session_id);
  808. //Change path of subfolders and documents in database
  809. $old_item_path = $deleted_items['path'];
  810. $new_item_path = $new_path.substr($old_item_path, strlen($path));
  811. /*
  812. // Trying to fix this bug FS#2681
  813. echo $base_work_dir.$old_item_path;
  814. echo "<br />";
  815. echo $base_work_dir.$new_item_path;
  816. echo "<br /><br />";
  817. rename($base_work_dir.$old_item_path, $base_work_dir.$new_item_path);
  818. */
  819. self::unset_document_as_template($deleted_items['id'], api_get_course_id(), api_get_user_id());
  820. $sql = "UPDATE $TABLE_DOCUMENT set path = '".$new_item_path."' WHERE id = ".$deleted_items['id'];
  821. Database::query($sql);
  822. }
  823. }
  824. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  825. return true;
  826. }
  827. } else {
  828. //Couldn't rename - file permissions problem?
  829. error_log(__FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',0);
  830. }
  831. } else {
  832. //echo $base_work_dir.$path;
  833. //The file or directory isn't there anymore (on the filesystem)
  834. // This means it has been removed externally. To prevent a
  835. // blocking error from happening, we drop the related items from the
  836. // item_property and the document table.
  837. 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);
  838. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
  839. $res = Database::query($sql);
  840. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  841. while ($row = Database::fetch_array($res)) {
  842. $sqlipd = "DELETE FROM $TABLE_ITEMPROPERTY WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  843. $resipd = Database::query($sqlipd);
  844. self::unset_document_as_template($row['id'],api_get_course_id(), api_get_user_id());
  845. $sqldd = "DELETE FROM $TABLE_DOCUMENT WHERE id = ".$row['id'];
  846. $resdd = Database::query($sqldd);
  847. }
  848. }
  849. }
  850. }
  851. }
  852. return false;
  853. }
  854. /**
  855. * Removes documents from search engine database
  856. *
  857. * @param string $course_id Course code
  858. * @param int $document_id Document id to delete
  859. */
  860. public static function delete_document_from_search_engine ($course_id, $document_id) {
  861. // remove from search engine if enabled
  862. if (api_get_setting('search_enabled') == 'true') {
  863. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  864. $sql = 'SELECT * 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. $res = Database::query($sql);
  867. if (Database::num_rows($res) > 0) {
  868. $row2 = Database::fetch_array($res);
  869. require_once api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php';
  870. $di = new DokeosIndexer();
  871. $di->remove_document((int)$row2['search_did']);
  872. }
  873. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  874. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  875. Database::query($sql);
  876. // remove terms from db
  877. require_once api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php';
  878. delete_all_values_for_item($course_id, TOOL_DOCUMENT, $document_id);
  879. }
  880. }
  881. /**
  882. * Gets the id of a document with a given path
  883. *
  884. * @param array $_course
  885. * @param string $path
  886. * @return int id of document / false if no doc found
  887. */
  888. public static function get_document_id($course_info, $path) {
  889. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
  890. $path = Database::escape_string($path);
  891. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path LIKE BINARY '$path'";
  892. $result = Database::query($sql);
  893. if ($result && Database::num_rows($result) == 1) {
  894. $row = Database::fetch_array($result);
  895. return intval($row[0]);
  896. }
  897. return false;
  898. }
  899. /**
  900. * Gets the document data with a given id
  901. *
  902. * @param array $_course
  903. * @param string $path
  904. * @todo load parent_id
  905. * @return int id of document / false if no doc found
  906. */
  907. public static function get_document_data_by_id($id, $course_code) {
  908. $course_info = api_get_course_info($course_code);
  909. if (empty($course_info)) {
  910. return false;
  911. }
  912. $www = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/document';
  913. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
  914. $id = intval($id);
  915. $sql = "SELECT * FROM $TABLE_DOCUMENT WHERE id = $id ";
  916. $result = Database::query($sql);
  917. if ($result && Database::num_rows($result) == 1) {
  918. $row = Database::fetch_array($result,'ASSOC');
  919. //Public document URL
  920. $row['url'] = api_get_path(WEB_CODE_PATH).'document/showinframes.php?cidReq='.$course_code.'&id='.$id;
  921. $url_path = urlencode($row['path']);
  922. $path = str_replace('%2F', '/',$url_path);
  923. $row['direct_url'] = $www.$path;
  924. $row['parent_id'] = self::get_document_id($course_info, dirname($row['path']));
  925. return $row;
  926. }
  927. return false;
  928. }
  929. /**
  930. * Allow to set a specific document as a new template for FCKEditor for a particular user in a particular course
  931. *
  932. * @param string $title
  933. * @param string $description
  934. * @param int $document_id_for_template the document id
  935. * @param string $couse_code
  936. * @param int $user_id
  937. */
  938. public static function set_document_as_template($title, $description, $document_id_for_template, $couse_code, $user_id, $image) {
  939. // Database table definition
  940. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  941. // creating the sql statement
  942. $sql = "INSERT INTO ".$table_template."
  943. (title, description, course_code, user_id, ref_doc, image)
  944. VALUES (
  945. '".Database::escape_string($title)."',
  946. '".Database::escape_string($description)."',
  947. '".Database::escape_string($couse_code)."',
  948. '".Database::escape_string($user_id)."',
  949. '".Database::escape_string($document_id_for_template)."',
  950. '".Database::escape_string($image)."')";
  951. Database::query($sql);
  952. return true;
  953. }
  954. /**
  955. * Unset a document as template
  956. *
  957. * @param int $document_id
  958. * @param string $couse_code
  959. * @param int $user_id
  960. */
  961. public static function unset_document_as_template($document_id, $course_code, $user_id) {
  962. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  963. $course_code = Database::escape_string($course_code);
  964. $user_id = Database::escape_string($user_id);
  965. $document_id = Database::escape_string($document_id);
  966. $sql = 'SELECT id FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  967. $result = Database::query($sql);
  968. $template_id = Database::result($result,0,0);
  969. include_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
  970. my_delete(api_get_path(SYS_CODE_PATH).'upload/template_thumbnails/'.$template_id.'.jpg');
  971. $sql = 'DELETE FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  972. Database::query($sql);
  973. }
  974. /**
  975. * Return true if the documentpath have visibility=1 as item_property (you should use the is_visible_by_id)
  976. *
  977. * @param string $document_path the relative complete path of the document
  978. * @param array $course the _course array info of the document's course
  979. */
  980. public static function is_visible($doc_path, $course, $session_id = 0, $file_type = 'file') {
  981. $docTable = Database::get_course_table(TABLE_DOCUMENT, $course['dbName']);
  982. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);
  983. //note the extra / at the end of doc_path to match every path in the document table that is part of the document path
  984. $doc_path = Database::escape_string($doc_path);
  985. $session_id = intval($session_id);
  986. $condition = "AND id_session IN ('$session_id', '0') ";
  987. // The " d.filetype='file' " let the user see a file even if the folder is hidden see #2198
  988. //When using hotpotatoes files, new files are generated in the hotpotatoe folder, if user_id=1 does the exam a new html file will be generated: hotpotatoe.html.(user_id).t.html
  989. //so we remove that string in order to find correctly the origin file
  990. if (strpos($doc_path, 'HotPotatoes_files')) {
  991. $doc_path = substr($doc_path, 0, strlen($doc_path) - 8);
  992. }
  993. if (!in_array($file_type, array('file','folder'))) {
  994. $file_type = 'file';
  995. }
  996. $sql = "SELECT visibility FROM $docTable d, $propTable ip WHERE d.id=ip.ref AND ip.tool='".TOOL_DOCUMENT."' $condition AND filetype='$file_type' AND locate(concat(path,'/'),'".$doc_path."/')=1";
  997. $result = Database::query($sql);
  998. $is_visible = false;
  999. if (Database::num_rows($result) > 0) {
  1000. $row = Database::fetch_array($result,'ASSOC');
  1001. if ($row['visibility'] == 1) {
  1002. $is_visible = $_SESSION['is_allowed_in_course'] || api_is_platform_admin();
  1003. }
  1004. }
  1005. //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.
  1006. //return $_SESSION ['is_allowed_in_course'] || api_is_platform_admin();
  1007. return $is_visible;
  1008. }
  1009. /**
  1010. * return true if the documentpath have visibility=1 as item_property
  1011. *
  1012. * @param int document id
  1013. * @param array course info
  1014. * @param array $course the _course array info of the document's course
  1015. */
  1016. public static function is_visible_by_id($id, $course, $session_id = 0, $file_type = 'file') {
  1017. $docTable = Database::get_course_table(TABLE_DOCUMENT, $course['dbName']);
  1018. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);
  1019. $id = intval($id);
  1020. $session_id = intval($session_id);
  1021. //$condition = "AND id_session = $session_id";
  1022. $condition = "AND id_session IN ('$session_id', '0') ";
  1023. if (!in_array($file_type, array('file','folder'))) {
  1024. $file_type = 'file';
  1025. }
  1026. // The " d.filetype='file' " let the user see a file even if the folder is hidden see #2198
  1027. $sql = "SELECT visibility FROM $docTable d, $propTable ip WHERE d.id = ip.ref AND ip.tool='".TOOL_DOCUMENT."' $condition AND filetype='$file_type' AND d.id = $id";
  1028. $result = Database::query($sql);
  1029. $is_visible = false;
  1030. if (Database::num_rows($result) > 0) {
  1031. $row = Database::fetch_array($result,'ASSOC');
  1032. if ($row['visibility'] == 1) {
  1033. $is_visible = $_SESSION['is_allowed_in_course'] || api_is_platform_admin();
  1034. }
  1035. }
  1036. //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.
  1037. //return $_SESSION ['is_allowed_in_course'] || api_is_platform_admin();
  1038. return $is_visible;
  1039. }
  1040. /**
  1041. * Allow attach a certificate to a course
  1042. * @param string The course id
  1043. * @param int The document id
  1044. * @return void()
  1045. */
  1046. function attach_gradebook_certificate ($course_id, $document_id) {
  1047. $tbl_category = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1048. $session_id = api_get_session_id();
  1049. if ($session_id==0 || is_null($session_id)) {
  1050. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  1051. } elseif ($session_id>0) {
  1052. $sql_session='AND session_id='.Database::escape_string($session_id);
  1053. } else {
  1054. $sql_session='';
  1055. }
  1056. $sql='UPDATE '.$tbl_category.' SET document_id="'.Database::escape_string($document_id).'"
  1057. WHERE course_code="'.Database::escape_string($course_id).'" '.$sql_session;
  1058. $rs=Database::query($sql);
  1059. }
  1060. /**
  1061. * get the document id of default certificate
  1062. * @param string The course id
  1063. * @return int The default certificate id
  1064. */
  1065. function get_default_certificate_id($course_id) {
  1066. $tbl_category=Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1067. $session_id=api_get_session_id();
  1068. if ($session_id==0 || is_null($session_id)) {
  1069. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  1070. } elseif ($session_id>0) {
  1071. $sql_session='AND session_id='.Database::escape_string($session_id);
  1072. } else {
  1073. $sql_session='';
  1074. }
  1075. $sql='SELECT document_id FROM '.$tbl_category.' WHERE course_code="'.Database::escape_string($course_id).'" '.$sql_session;
  1076. $rs=Database::query($sql);
  1077. $row=Database::fetch_array($rs);
  1078. return $row['document_id'];
  1079. }
  1080. /**
  1081. * allow replace user info in file html
  1082. * @param string The course id
  1083. * @return string The html content of the certificate
  1084. */
  1085. function replace_user_info_into_html($user_id, $course_id, $is_preview = false) {
  1086. $user_id = intval($user_id);
  1087. $course_info = api_get_course_info($course_id);
  1088. $tbl_document = Database::get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
  1089. $document_id = self::get_default_certificate_id($course_id);
  1090. $sql = 'SELECT path FROM '.$tbl_document.' WHERE id="'.Database::escape_string($document_id).'" ';
  1091. $rs = Database::query($sql);
  1092. $new_content = '';
  1093. if (Database::num_rows($rs)) {
  1094. $row=Database::fetch_array($rs);
  1095. $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$row['path'];
  1096. if (is_file($filepath)) {
  1097. $my_content_html=file_get_contents($filepath);
  1098. }
  1099. $all_user_info = self::get_all_info_to_certificate($user_id, $is_preview);
  1100. $info_to_be_replaced_in_content_html=$all_user_info[0];
  1101. $info_to_replace_in_content_html=$all_user_info[1];
  1102. $new_content=str_replace($info_to_be_replaced_in_content_html,$info_to_replace_in_content_html, $my_content_html);
  1103. }
  1104. return $new_content;
  1105. }
  1106. /**
  1107. * return all content to replace and all content to be replace
  1108. */
  1109. function get_all_info_to_certificate($user_id, $is_preview = false) {
  1110. $info_list = array();
  1111. $user_id = intval($user_id);
  1112. $course_id = api_get_course_id();
  1113. $course_info = api_get_course_info($course_id);
  1114. //info portal
  1115. $organization_name = api_get_setting('Institution');
  1116. $portal_name = api_get_setting('siteName');
  1117. //Extra user data information
  1118. $extra_user_info_data = UserManager::get_extra_user_data($user_id, false, false, false, true);
  1119. //Student information
  1120. $user_info = api_get_user_info($user_id);
  1121. $first_name = $user_info['firstname'];
  1122. $last_name = $user_info['lastname'];
  1123. $official_code = $user_info['official_code'];
  1124. //Teacher information
  1125. $info_teacher_id = UserManager::get_user_id_of_course_admin_or_session_admin($course_id);
  1126. $teacher_info = api_get_user_info($info_teacher_id);
  1127. $teacher_first_name = $teacher_info['firstname'];
  1128. $teacher_last_name = $teacher_info['lastname'];
  1129. // info gradebook certificate
  1130. $info_grade_certificate = UserManager::get_info_gradebook_certificate($course_id, $user_id);
  1131. $date_certificate = $info_grade_certificate['created_at'];
  1132. $date_long_certificate = '';
  1133. if (!empty($date_certificate)) {
  1134. $date_long_certificate = api_convert_and_format_date($date_certificate);
  1135. }
  1136. if ($is_preview) {
  1137. $date_long_certificate = api_convert_and_format_date(api_get_utc_datetime());
  1138. }
  1139. //replace content
  1140. $info_to_replace_in_content_html = array($first_name,
  1141. $last_name,
  1142. $organization_name,
  1143. $portal_name,
  1144. $teacher_first_name,
  1145. $teacher_last_name,
  1146. $official_code,
  1147. $date_long_certificate,
  1148. $course_id,
  1149. $course_info['name'],
  1150. $info_grade_certificate['grade'],
  1151. );
  1152. $info_to_be_replaced_in_content_html = array('((user_firstname))',
  1153. '((user_lastname))',
  1154. '((gradebook_institution))',
  1155. '((gradebook_sitename))',
  1156. '((teacher_firstname))',
  1157. '((teacher_lastname))',
  1158. '((official_code))',
  1159. '((date_certificate))',
  1160. '((course_code))',
  1161. '((course_title))',
  1162. '((gradebook_grade))',
  1163. );
  1164. if (!empty($extra_user_info_data)) {
  1165. foreach ($extra_user_info_data as $key_extra=>$value_extra) {
  1166. $info_to_be_replaced_in_content_html[]='(('.strtolower($key_extra).'))';
  1167. $info_to_replace_in_content_html[]=$value_extra;
  1168. }
  1169. }
  1170. $info_list[]=$info_to_be_replaced_in_content_html;
  1171. $info_list[]=$info_to_replace_in_content_html;
  1172. return $info_list;
  1173. }
  1174. /**
  1175. * Remove default certificate
  1176. * @param string The course id
  1177. * @param int The document id of the default certificate
  1178. * @return void()
  1179. */
  1180. function remove_attach_certificate ($course_id,$default_certificate_id) {
  1181. $default_certificate=self::get_default_certificate_id($course_id);
  1182. if ((int)$default_certificate==(int)$default_certificate_id) {
  1183. $tbl_category=Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1184. $session_id=api_get_session_id();
  1185. if ($session_id==0 || is_null($session_id)) {
  1186. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  1187. } elseif ($session_id>0) {
  1188. $sql_session='AND session_id='.Database::escape_string($session_id);
  1189. } else {
  1190. $sql_session='';
  1191. }
  1192. $sql='UPDATE '.$tbl_category.' SET document_id=null
  1193. WHERE course_code="'.Database::escape_string($course_id).'" AND document_id="'.$default_certificate_id.'" '.$sql_session;
  1194. $rs=Database::query($sql);
  1195. }
  1196. }
  1197. /**
  1198. * Create directory certificate
  1199. * @param string The course id
  1200. * @return void()
  1201. */
  1202. function create_directory_certificate_in_course ($course_id) {
  1203. $course_info = api_get_course_info($course_id);
  1204. if (!empty($course_info)) {
  1205. $to_group_id=0;
  1206. $to_user_id=null;
  1207. $course_dir = $course_info['path']."/document/";
  1208. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  1209. $base_work_dir=$sys_course_path.$course_dir;
  1210. $base_work_dir_test=$base_work_dir.'certificates';
  1211. $dir_name='/certificates';
  1212. $post_dir_name=get_lang('CertificatesFiles');
  1213. $visibility_command='invisible';
  1214. if (!is_dir($base_work_dir_test)) {
  1215. $created_dir = create_unexisting_directory($course_info, api_get_user_id(), api_get_session_id(), $to_group_id,$to_user_id,$base_work_dir,$dir_name,$post_dir_name);
  1216. $update_id=DocumentManager::get_document_id_of_directory_certificate();
  1217. api_item_property_update($course_info, TOOL_DOCUMENT, $update_id, $visibility_command, api_get_user_id());
  1218. }
  1219. }
  1220. }
  1221. /**
  1222. * Get the document id of the directory certificate
  1223. * @param string The course id
  1224. * @return int The document id of the directory certificate
  1225. */
  1226. function get_document_id_of_directory_certificate () {
  1227. $tbl_document=Database::get_course_table(TABLE_DOCUMENT);
  1228. $sql='SELECT id FROM '.$tbl_document.' WHERE path="/certificates" ';
  1229. $rs=Database::query($sql);
  1230. $row=Database::fetch_array($rs);
  1231. return $row['id'];
  1232. }
  1233. /**
  1234. * Check if a directory given is for certificate
  1235. * @param string path of directory
  1236. * @return bool true if is a certificate or false otherwise
  1237. */
  1238. function is_certificate_mode($dir) {
  1239. //I'm in the certification module?
  1240. $is_certificate_mode = false;
  1241. $is_certificate_array = explode('/',$dir);
  1242. array_shift($is_certificate_array);
  1243. if ($is_certificate_array[0]=='certificates') {
  1244. $is_certificate_mode = true;
  1245. }
  1246. return $is_certificate_mode;
  1247. }
  1248. /**
  1249. * Gets the list of included resources as a list of absolute or relative paths from a html file or string html
  1250. * This allows for a better SCORM export or replace urls inside content html from copy course
  1251. * The list will generally include pictures, flash objects, java applets, or any other
  1252. * stuff included in the source of the current item. The current item is expected
  1253. * to be an HTML file or string html. If it is not, then the function will return and empty list.
  1254. * @param string source html (content or path)
  1255. * @param bool is file or string html
  1256. * @param string type (one of the Dokeos tools) - optional (otherwise takes the current item's type)
  1257. * @param int level of recursivity we're in
  1258. * @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
  1259. */
  1260. function get_resources_from_source_html($source_html, $is_file = false, $type = null, $recursivity = 1) {
  1261. $max = 5;
  1262. $attributes = array();
  1263. $wanted_attributes = array('src', 'url', '@import', 'href', 'value', 'flashvars');
  1264. $abs_path = '';
  1265. if ($recursivity > $max) {
  1266. return array();
  1267. }
  1268. if (!isset($type)) {
  1269. $type = TOOL_DOCUMENT;
  1270. }
  1271. if (!$is_file) {
  1272. $attributes = DocumentManager::parse_HTML_attributes($source_html, $wanted_attributes);
  1273. } else {
  1274. if (is_file($source_html)) {
  1275. $abs_path = $source_html;
  1276. //for now, read the whole file in one go (that's gonna be a problem when the file is too big)
  1277. $info = pathinfo($abs_path);
  1278. $ext = $info['extension'];
  1279. switch (strtolower($ext)) {
  1280. case 'html' :
  1281. case 'htm' :
  1282. case 'shtml':
  1283. case 'css' :
  1284. $file_content = file_get_contents($abs_path);
  1285. //get an array of attributes from the HTML source
  1286. $attributes = DocumentManager::parse_HTML_attributes($file_content, $wanted_attributes);
  1287. break;
  1288. default :
  1289. break;
  1290. }
  1291. } else {
  1292. return false;
  1293. }
  1294. }
  1295. switch ($type) {
  1296. case TOOL_DOCUMENT :
  1297. case TOOL_QUIZ:
  1298. case 'sco':
  1299. foreach ($wanted_attributes as $attr) {
  1300. if (isset($attributes[$attr])) {
  1301. //find which kind of path these are (local or remote)
  1302. $sources = $attributes[$attr];
  1303. foreach ($sources as $source) {
  1304. //skip what is obviously not a resource
  1305. if (strpos($source, '+this.')) continue; //javascript code - will still work unaltered
  1306. if (strpos($source, '.') === false) continue; //no dot, should not be an external file anyway
  1307. if (strpos($source, 'mailto:')) continue; //mailto link
  1308. if (strpos($source, ';') && !strpos($source, '&amp;')) continue; //avoid code - that should help
  1309. if ($attr == 'value') {
  1310. if (strpos($source , 'mp3file')) {
  1311. $files_list[] = array(substr($source, 0, strpos($source, '.swf') + 4), 'local', 'abs');
  1312. $mp3file = substr($source , strpos($source, 'mp3file=') + 8);
  1313. if (substr($mp3file, 0, 1) == '/') {
  1314. $files_list[] = array($mp3file, 'local', 'abs');
  1315. } else {
  1316. $files_list[] = array($mp3file, 'local', 'rel');
  1317. }
  1318. } elseif (strpos($source, 'flv=') === 0) {
  1319. $source = substr($source, 4);
  1320. if (strpos($source, '&') > 0) {
  1321. $source = substr($source, 0, strpos($source, '&'));
  1322. }
  1323. if (strpos($source,'://') > 0) {
  1324. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1325. //we found the current portal url
  1326. $files_list[] = array($source, 'local', 'url');
  1327. } else {
  1328. //we didn't find any trace of current portal
  1329. $files_list[] = array($source, 'remote', 'url');
  1330. }
  1331. } else {
  1332. $files_list[] = array($source, 'local', 'abs');
  1333. }
  1334. continue; //skipping anything else to avoid two entries (while the others can have sub-files in their url, flv's can't)
  1335. }
  1336. }
  1337. if (strpos($source, '://') > 0) {
  1338. //cut at '?' in a URL with params
  1339. if (strpos($source, '?') > 0) {
  1340. $second_part = substr($source,strpos($source, '?'));
  1341. if(strpos($second_part, '://') > 0) {
  1342. //if the second part of the url contains a url too, treat the second one before cutting
  1343. $pos1 = strpos($second_part, '=');
  1344. $pos2 = strpos($second_part, '&');
  1345. $second_part = substr($second_part, $pos1 + 1, $pos2 - ($pos1 + 1));
  1346. if (strpos($second_part, api_get_path(WEB_PATH)) !== false) {
  1347. //we found the current portal url
  1348. $files_list[] = array($second_part, 'local', 'url');
  1349. $in_files_list[] = DocumentManager::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, $recursivity + 1);
  1350. if (count($in_files_list) > 0) {
  1351. $files_list = array_merge($files_list, $in_files_list);
  1352. }
  1353. } else {
  1354. //we didn't find any trace of current portal
  1355. $files_list[] = array($second_part, 'remote', 'url');
  1356. }
  1357. } elseif (strpos($second_part, '=') > 0) {
  1358. if (substr($second_part, 0, 1) === '/') {
  1359. //link starts with a /, making it absolute (relative to DocumentRoot)
  1360. $files_list[] = array($second_part, 'local', 'abs');
  1361. $in_files_list[] = DocumentManager::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, $recursivity + 1);
  1362. if (count($in_files_list) > 0) {
  1363. $files_list = array_merge($files_list, $in_files_list);
  1364. }
  1365. } elseif(strstr($second_part, '..') === 0) {
  1366. //link is relative but going back in the hierarchy
  1367. $files_list[] = array($second_part, 'local', 'rel');
  1368. //$dir = api_get_path(SYS_CODE_PATH);//dirname($abs_path);
  1369. //$new_abs_path = realpath($dir.'/'.$second_part);
  1370. $dir = '';
  1371. if (!empty($abs_path)) {
  1372. $dir = dirname($abs_path).'/';
  1373. }
  1374. $new_abs_path = realpath($dir.$second_part);
  1375. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1376. if (count($in_files_list) > 0) {
  1377. $files_list = array_merge($files_list, $in_files_list);
  1378. }
  1379. } else {
  1380. //no starting '/', making it relative to current document's path
  1381. if (substr($second_part, 0, 2) == './') {
  1382. $second_part = substr($second_part, 2);
  1383. }
  1384. $files_list[] = array($second_part, 'local', 'rel');
  1385. $dir = '';
  1386. if (!empty($abs_path)) {
  1387. $dir = dirname($abs_path).'/';
  1388. }
  1389. $new_abs_path = realpath($dir.$second_part);
  1390. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1391. if (count($in_files_list) > 0) {
  1392. $files_list = array_merge($files_list, $in_files_list);
  1393. }
  1394. }
  1395. }
  1396. //leave that second part behind now
  1397. $source = substr($source, 0, strpos($source, '?'));
  1398. if (strpos($source, '://') > 0) {
  1399. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1400. //we found the current portal url
  1401. $files_list[] = array($source, 'local', 'url');
  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. } else {
  1407. //we didn't find any trace of current portal
  1408. $files_list[] = array($source, 'remote', 'url');
  1409. }
  1410. } else {
  1411. //no protocol found, make link local
  1412. if (substr($source, 0, 1) === '/') {
  1413. //link starts with a /, making it absolute (relative to DocumentRoot)
  1414. $files_list[] = array($source, 'local', 'abs');
  1415. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1416. if (count($in_files_list) > 0) {
  1417. $files_list = array_merge($files_list, $in_files_list);
  1418. }
  1419. } elseif (strstr($source, '..') === 0) { //link is relative but going back in the hierarchy
  1420. $files_list[] = array($source, 'local', 'rel');
  1421. $dir = '';
  1422. if (!empty($abs_path)) {
  1423. $dir = dirname($abs_path).'/';
  1424. }
  1425. $new_abs_path = realpath($dir.$source);
  1426. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1427. if (count($in_files_list) > 0) {
  1428. $files_list = array_merge($files_list, $in_files_list);
  1429. }
  1430. } else {
  1431. //no starting '/', making it relative to current document's path
  1432. if (substr($source, 0, 2) == './') {
  1433. $source = substr($source, 2);
  1434. }
  1435. $files_list[] = array($source, 'local', 'rel');
  1436. $dir = '';
  1437. if (!empty($abs_path)) {
  1438. $dir = dirname($abs_path).'/';
  1439. }
  1440. $new_abs_path = realpath($dir.$source);
  1441. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1442. if (count($in_files_list) > 0) {
  1443. $files_list = array_merge($files_list, $in_files_list);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. //found some protocol there
  1449. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1450. //we found the current portal url
  1451. $files_list[] = array($source, 'local', 'url');
  1452. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1453. if (count($in_files_list) > 0) {
  1454. $files_list = array_merge($files_list, $in_files_list);
  1455. }
  1456. } else {
  1457. //we didn't find any trace of current portal
  1458. $files_list[] = array($source, 'remote', 'url');
  1459. }
  1460. } else {
  1461. //no protocol found, make link local
  1462. if (substr($source, 0, 1) === '/') {
  1463. //link starts with a /, making it absolute (relative to DocumentRoot)
  1464. $files_list[] = array($source, 'local', 'abs');
  1465. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1466. if (count($in_files_list) > 0) {
  1467. $files_list = array_merge($files_list, $in_files_list);
  1468. }
  1469. } elseif (strpos($source, '..') === 0) {
  1470. //link is relative but going back in the hierarchy
  1471. $files_list[] = array($source, 'local', 'rel');
  1472. $dir = '';
  1473. if (!empty($abs_path)) {
  1474. $dir = dirname($abs_path).'/';
  1475. }
  1476. $new_abs_path = realpath($dir.$source);
  1477. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1478. if (count($in_files_list) > 0) {
  1479. $files_list = array_merge($files_list, $in_files_list);
  1480. }
  1481. } else {
  1482. //no starting '/', making it relative to current document's path
  1483. if (substr($source, 0, 2) == './') {
  1484. $source = substr($source, 2);
  1485. }
  1486. $files_list[] = array($source, 'local', 'rel');
  1487. $dir = '';
  1488. if (!empty($abs_path)) {
  1489. $dir = dirname($abs_path).'/';
  1490. }
  1491. $new_abs_path = realpath($dir.$source);
  1492. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1493. if (count($in_files_list) > 0) {
  1494. $files_list = array_merge($files_list, $in_files_list);
  1495. }
  1496. }
  1497. }
  1498. }
  1499. }
  1500. }
  1501. break;
  1502. default: //ignore
  1503. break;
  1504. }
  1505. $checked_files_list = array();
  1506. $checked_array_list = array();
  1507. if (count($files_list ) > 0) {
  1508. foreach ($files_list as $idx => $file) {
  1509. if (!empty($file[0])) {
  1510. if (!in_array($file[0], $checked_files_list)) {
  1511. $checked_files_list[] = $files_list[$idx][0];
  1512. $checked_array_list[] = $files_list[$idx];
  1513. }
  1514. }
  1515. }
  1516. }
  1517. return $checked_array_list;
  1518. }
  1519. /**
  1520. * Parses the HTML attributes given as string.
  1521. *
  1522. * @param string HTML attribute string
  1523. * @param array List of attributes that we want to get back
  1524. * @return array An associative array of attributes
  1525. * @author Based on a function from the HTML_Common2 PEAR module
  1526. */
  1527. function parse_HTML_attributes($attrString, $wanted = array()) {
  1528. $attributes = array();
  1529. $regs = array();
  1530. $reduced = false;
  1531. if (count($wanted) > 0) {
  1532. $reduced = true;
  1533. }
  1534. try {
  1535. //Find all occurences of something that looks like a URL
  1536. // The structure of this regexp is:
  1537. // (find protocol) then
  1538. // (optionally find some kind of space 1 or more times) then
  1539. // find (either an equal sign or a bracket) followed by an optional space
  1540. // followed by some text without quotes (between quotes itself or not)
  1541. // then possible closing brackets if we were in the opening bracket case
  1542. // OR something like @import()
  1543. $res = preg_match_all(
  1544. '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]*))' .
  1545. // '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]|[^\x00-\x7F])*)' . -> seems to be taking too much
  1546. // '/(((([A-Za-z_:])([^\x00-\x7F])*)' . -> takes only last letter of parameter name
  1547. '([ \n\t\r]+)?(' .
  1548. // '(=([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+))' . -> doesn't restrict close enough to the url itself
  1549. '(=([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+))' .
  1550. '|' .
  1551. // '(\(([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)\))' . -> doesn't restrict close enough to the url itself
  1552. '(\(([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+)\))' .
  1553. '))' .
  1554. '|' .
  1555. // '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))?/', -> takes a lot (like 100's of thousands of empty possibilities)
  1556. '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))/',
  1557. $attrString,
  1558. $regs
  1559. );
  1560. } catch (Exception $e) {
  1561. error_log('Caught exception: '. $e->getMessage(), 0) ;
  1562. }
  1563. if ($res) {
  1564. for ($i = 0; $i < count($regs[1]); $i++) {
  1565. $name = trim($regs[3][$i]);
  1566. $check = trim($regs[0][$i]);
  1567. $value = trim($regs[10][$i]);
  1568. if (empty($value) and !empty($regs[13][$i])) {
  1569. $value = $regs[13][$i];
  1570. }
  1571. if (empty($name) && !empty($regs[16][$i])) {
  1572. $name = '@import';
  1573. $value = trim($regs[16][$i]);
  1574. }
  1575. if (!empty($name)) {
  1576. if (!$reduced OR in_array(strtolower($name), $wanted)) {
  1577. if ($name == $check) {
  1578. $attributes[strtolower($name)][] = strtolower($name);
  1579. } else {
  1580. if (!empty($value) && ($value[0] == '\'' || $value[0] == '"')) {
  1581. $value = substr($value, 1, -1);
  1582. }
  1583. if ($value == 'API.LMSGetValue(name') {
  1584. $value = 'API.LMSGetValue(name)';
  1585. }
  1586. $attributes[strtolower($name)][] = $value;
  1587. }
  1588. }
  1589. }
  1590. }
  1591. } else {
  1592. error_log('preg_match did not find anything', 0);
  1593. }
  1594. return $attributes;
  1595. }
  1596. /**
  1597. * Replace urls inside content html from a copy course
  1598. * @param string content html
  1599. * @param string origin course code
  1600. * @param string destination course directory
  1601. * @return string new content html with replaced urls or return false if content is not a string
  1602. */
  1603. function replace_urls_inside_content_html_from_copy_course($content_html, $origin_course_code, $destination_course_directory) {
  1604. if (!is_string($content_html)) {
  1605. return false;
  1606. }
  1607. $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
  1608. $orig_course_info = api_get_course_info($origin_course_code);
  1609. $orig_course_path = api_get_path(SYS_PATH).'courses/'.$orig_course_info['path'].'/';
  1610. $destination_course_code = CourseManager::get_course_id_from_path ($destination_course_directory);
  1611. $dest_course_path = api_get_path(SYS_COURSE_PATH).$destination_course_directory.'/';
  1612. foreach ($orig_source_html as $source) {
  1613. // get information about source url
  1614. $real_orig_url = $source[0]; // url
  1615. $scope_url = $source[1]; // scope (local, remote)
  1616. $type_url = $source[2]; // tyle (rel, abs, url)
  1617. // Get path and query from origin url
  1618. $orig_parse_url = parse_url($real_orig_url);
  1619. $real_orig_path = $orig_parse_url['path'];
  1620. $real_orig_query = $orig_parse_url['query'];
  1621. // Replace origin course code by destination course code from origin url query
  1622. $dest_url_query = '';
  1623. if (!empty($real_orig_query)) {
  1624. $dest_url_query = '?'.$real_orig_query;
  1625. if (strpos($dest_url_query,$origin_course_code) !== false) {
  1626. $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
  1627. }
  1628. }
  1629. if ($scope_url == 'local') {
  1630. if ( $type_url == 'abs' || $type_url == 'rel') {
  1631. $document_file = strstr($real_orig_path, 'document');
  1632. if (strpos($real_orig_path,$document_file) !== false) {
  1633. $origin_filepath = $orig_course_path.$document_file;
  1634. $destination_filepath = $dest_course_path.$document_file;
  1635. // copy origin file inside destination course
  1636. if (file_exists($origin_filepath)) {
  1637. $filepath_dir = dirname($destination_filepath);
  1638. if (!is_dir($filepath_dir)) {
  1639. $perm = api_get_permissions_for_new_directories();
  1640. @mkdir($filepath_dir, $perm, true);
  1641. }
  1642. if (!file_exists($destination_filepath)) {
  1643. @copy($origin_filepath, $destination_filepath);
  1644. }
  1645. }
  1646. // Replace origin course path by destination course path
  1647. if (strpos($content_html,$real_orig_url) !== false) {
  1648. //$origin_course_code
  1649. $url_course_path = str_replace($orig_course_info['path'].'/'.$document_file, '', $real_orig_path);
  1650. $destination_url = $url_course_path.$destination_course_directory.'/'.$document_file.$dest_url_query;
  1651. //If the course code doesn't exist in the path? what we do? Nothing! see BT#1985
  1652. if (strpos($real_orig_path, $origin_course_code) === false) {
  1653. $url_course_path = $real_orig_path;
  1654. $destination_url = $real_orig_path;
  1655. }
  1656. $content_html = str_replace($real_orig_url, $destination_url, $content_html);
  1657. }
  1658. }
  1659. // replace origin course code by destination course code from origin url
  1660. if (strpos($real_orig_url, '?') === 0) {
  1661. $dest_url = str_replace($origin_course_code, $destination_course_code, $real_orig_url);
  1662. $content_html = str_replace($real_orig_url, $dest_url, $content_html);
  1663. }
  1664. } else {
  1665. if ($type_url == 'url') {
  1666. }
  1667. }
  1668. }
  1669. }
  1670. return $content_html;
  1671. }
  1672. /**
  1673. * Replace urls inside content html when moving a file
  1674. * @todo this code is only called in document.php but is commented
  1675. * @param string content html
  1676. * @param string origin
  1677. * @param string destination
  1678. * @return string new content html with replaced urls or return false if content is not a string
  1679. */
  1680. function replace_urls_inside_content_html_when_moving_file($file_name, $original_path, $destiny_path) {
  1681. if (substr($original_path, strlen($original_path) -1 , strlen($original_path)) == '/') {
  1682. $original = $original_path.$file_name;
  1683. } else {
  1684. $original = $original_path.'/'.$file_name;
  1685. }
  1686. if (substr($destiny_path, strlen($destiny_path) -1 , strlen($destiny_path)) == '/') {
  1687. $destination = $destiny_path.$file_name;
  1688. } else {
  1689. $destination = $destiny_path.'/'.$file_name;
  1690. }
  1691. var_dump("From $original ", "to $destination");
  1692. $original_count = count(explode('/', $original));
  1693. $destination_count = count(explode('/', $destination));
  1694. if ($original_count == $destination_count) {
  1695. //Nothing to change
  1696. return true;
  1697. }
  1698. $mode = '';
  1699. if ($original_count > $destination_count) {
  1700. $mode = 'outside';
  1701. } else {
  1702. $mode = 'inside';
  1703. }
  1704. echo $original_count.' '.$destination_count;
  1705. var_dump($mode);
  1706. //We do not select the $original_path becayse the file was already moved
  1707. $content_html = file_get_contents($destiny_path.'/'.$file_name);
  1708. $destination_file = $destiny_path.'/'.$file_name;
  1709. $pre_original = strstr($original_path, 'document');
  1710. $pre_destin = strstr($destiny_path, 'document');
  1711. var_dump ("pre_original $pre_original");
  1712. var_dump ("pre_destin $pre_destin");
  1713. $pre_original = substr($pre_original, 8, strlen($pre_original));
  1714. $pre_destin = substr($pre_destin, 8, strlen($pre_destin));
  1715. var_dump ("pre_original $pre_original");
  1716. var_dump ("pre_destin $pre_destin");
  1717. $levels = count(explode('/', $pre_destin)) - 1 ;
  1718. $link_to_add = '';
  1719. for ($i=1; $i <=$levels ; $i++) {
  1720. $link_to_add .= '../';
  1721. }
  1722. if ($pre_original == '/') {
  1723. $pre_original = '';
  1724. }
  1725. if ($pre_destin == '/') {
  1726. $pre_destin = '';
  1727. }
  1728. if ($pre_original != '') {
  1729. $pre_original = '..'.$pre_original.'/';
  1730. }
  1731. if ($pre_destin != '') {
  1732. $pre_destin = '..'.$pre_destin.'/';
  1733. }
  1734. var_dump($pre_original);
  1735. $levels = explode('/', $pre_original);
  1736. var_dump($levels);
  1737. $count_pre_destination_levels = 0;
  1738. foreach($levels as $item) {
  1739. if (!empty($item) && $item != '..') {
  1740. $count_pre_destination_levels++;
  1741. }
  1742. }
  1743. $count_pre_destination_levels--;
  1744. //$count_pre_destination_levels = count() - 3;
  1745. if ($count_pre_destination_levels == 0 ) {
  1746. $count_pre_destination_levels = 1;
  1747. }
  1748. echo '$count_pre_destination_levels '. $count_pre_destination_levels;
  1749. $pre_remove = '';
  1750. for ($i=1; $i <= $count_pre_destination_levels; $i++) {
  1751. $pre_remove .='..\/';
  1752. }
  1753. var_dump(' link to add '.$link_to_add.' -- remove '.$pre_remove);
  1754. $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
  1755. $orig_course_info = api_get_course_info($origin_course_code);
  1756. $orig_course_path = api_get_path(SYS_PATH).'courses/'.$orig_course_info['path'].'/';
  1757. //$destination_course_code = CourseManager::get_course_id_from_path ($destination_course_directory);
  1758. //$dest_course_path = api_get_path(SYS_COURSE_PATH).$destination_course_directory.'/';
  1759. var_dump($orig_source_html);
  1760. foreach ($orig_source_html as $source) {
  1761. // get information about source url
  1762. $real_orig_url = $source[0]; // url
  1763. $scope_url = $source[1]; // scope (local, remote)
  1764. $type_url = $source[2]; // tyle (rel, abs, url)
  1765. // Get path and query from origin url
  1766. $orig_parse_url = parse_url($real_orig_url);
  1767. $real_orig_path = $orig_parse_url['path'];
  1768. $real_orig_query = $orig_parse_url['query'];
  1769. // Replace origin course code by destination course code from origin url query
  1770. /*
  1771. $dest_url_query = '';
  1772. if (!empty($real_orig_query)) {
  1773. $dest_url_query = '?'.$real_orig_query;
  1774. if (strpos($dest_url_query,$origin_course_code) !== false) {
  1775. $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
  1776. }
  1777. }*/
  1778. if ($scope_url == 'local') {
  1779. if ( $type_url == 'abs' || $type_url == 'rel') {
  1780. $document_file = strstr($real_orig_path, 'document');
  1781. if (strpos($real_orig_path, $document_file) !== false) {
  1782. echo 'continue1';
  1783. continue;
  1784. } else {
  1785. $real_orig_url_temp = '';
  1786. if ($mode == 'inside') {
  1787. $real_orig_url_temp = str_replace('../', '', $real_orig_url);
  1788. $destination_url = $link_to_add.$real_orig_url_temp;
  1789. } else {
  1790. $real_orig_url_temp = $real_orig_url;
  1791. $destination_url = preg_replace("/".$pre_remove."/", '', $real_orig_url, 1);
  1792. }
  1793. if ($real_orig_url == $destination_url) {
  1794. echo 'continue2';
  1795. continue;
  1796. }
  1797. var_dump($real_orig_url_temp.' - '.$destination_url);
  1798. $content_html = str_replace($real_orig_url, $destination_url, $content_html);
  1799. }
  1800. } else {
  1801. echo 'continue3';
  1802. continue;
  1803. }
  1804. }
  1805. }
  1806. $return = file_put_contents($destination, $content_html);
  1807. //var_dump($destination, $content_html);
  1808. return $return;
  1809. }
  1810. public function export_to_pdf($document_id, $course_code) {
  1811. require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
  1812. $course_data = api_get_course_info($course_code);
  1813. $document_data = self::get_document_data_by_id($document_id, $course_code);
  1814. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$document_data['path'];
  1815. $pdf = new PDF();
  1816. $pdf->html_to_pdf($file_path, $document_data['title'], $course_code);
  1817. }
  1818. /**
  1819. * Uploads a document
  1820. *
  1821. * @param array the $_FILES variable
  1822. * @param string $path
  1823. * @param string title
  1824. * @param string comment
  1825. * @param int unzip or not the file
  1826. * @param int if_exists overwrite, rename or warn if exists (default)
  1827. * @param bool index document (search xapian module)
  1828. * @param bool print html messages
  1829. * @return unknown_type
  1830. */
  1831. public function upload_document($files, $path, $title = '', $comment = '', $unzip = 0, $if_exists = '', $index_document = false, $show_output = false) {
  1832. require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
  1833. $max_filled_space = self::get_course_quota();
  1834. $course_info = api_get_course_info();
  1835. $course_dir = $course_info['path'].'/document';
  1836. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  1837. $base_work_dir = $sys_course_path.$course_dir;
  1838. if (isset($files['file'])) {
  1839. $upload_ok = process_uploaded_file($files['file'], $show_output);
  1840. if ($upload_ok) {
  1841. // File got on the server without problems, now process it
  1842. $new_path = handle_uploaded_document($course_info, $files['file'], $base_work_dir, $path, api_get_user_id(), api_get_group_id(), null, $max_filled_space, $unzip, $if_exists, $show_output);
  1843. if ($new_path) {
  1844. $new_comment = isset($title) ? trim($comment) : '';
  1845. $new_title = isset($title) ? trim($title) : '';
  1846. $docid = DocumentManager::get_document_id($course_info, $new_path);
  1847. if ($new_path && ($new_comment || $new_title)) {
  1848. if (!empty($docid)) {
  1849. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  1850. $ct = '';
  1851. if ($new_comment) $ct .= ", comment='$new_comment'";
  1852. if ($new_title) $ct .= ", title='$new_title'";
  1853. Database::query("UPDATE $table_document SET ".substr($ct, 1)." WHERE id = $docid");
  1854. }
  1855. }
  1856. // Showing message when sending zip files
  1857. if ($new_path === true && $unzip == 1 && $show_output) {
  1858. Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />', false);
  1859. }
  1860. //@todo move this code somewhere else a.k.a Rework search module
  1861. if ((api_get_setting('search_enabled') == 'true') && $index_document && !empty($docid)) {
  1862. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  1863. $result = Database::query("SELECT * FROM $table_document WHERE id = '$docid' LIMIT 1");
  1864. if (Database::num_rows($result) == 1) {
  1865. $row = Database::fetch_array($result);
  1866. $doc_path = api_get_path(SYS_COURSE_PATH).$course_dir.$row['path'];
  1867. //TODO: mime_content_type is deprecated, fileinfo php extension is enabled by default as of PHP 5.3.0
  1868. // now versions of PHP on Debian testing(5.2.6-5) and Ubuntu(5.2.6-2ubuntu) are lower, so wait for a while
  1869. $doc_mime = mime_content_type($doc_path);
  1870. //echo $doc_mime;
  1871. //TODO: more mime types
  1872. $allowed_mime_types = array('text/plain', 'application/pdf', 'application/postscript', 'application/msword', 'text/html', 'text/rtf', 'application/vnd.ms-powerpoint', 'application/vnd.ms-excel');
  1873. // mime_content_type does not detect correctly some formats that are going to be supported for index, so an extensions array is used by the moment
  1874. if (empty($doc_mime)) {
  1875. $allowed_extensions = array('ppt', 'pps', 'xls');
  1876. $extensions = preg_split("/[\/\\.]/", $doc_path) ;
  1877. $doc_ext = strtolower($extensions[count($extensions) - 1]);
  1878. if (in_array($doc_ext, $allowed_extensions)) {
  1879. switch ($doc_ext) {
  1880. case 'ppt':
  1881. case 'pps':
  1882. $doc_mime = 'application/vnd.ms-powerpoint';
  1883. break;
  1884. case 'xls':
  1885. $doc_mime = 'application/vnd.ms-excel';
  1886. break;
  1887. }
  1888. }
  1889. }
  1890. //@todo move this nightmare in a search controller or something like that!!! J.M
  1891. if (in_array($doc_mime, $allowed_mime_types) && isset($index_document) && $index_document) {
  1892. $file_title = $row['title'];
  1893. $file_content = self::get_text_content($doc_path, $doc_mime);
  1894. $courseid = api_get_course_id();
  1895. $lang = isset($_POST['language']) ? Database::escape_string($_POST['language']) : 'english';
  1896. require_once api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php';
  1897. require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
  1898. $ic_slide = new IndexableChunk();
  1899. $ic_slide->addValue('title', $file_title);
  1900. $ic_slide->addCourseId($courseid);
  1901. $ic_slide->addToolId(TOOL_DOCUMENT);
  1902. $xapian_data = array(
  1903. SE_COURSE_ID => $courseid,
  1904. SE_TOOL_ID => TOOL_DOCUMENT,
  1905. SE_DATA => array('doc_id' => $docid),
  1906. SE_USER => api_get_user_id(),
  1907. );
  1908. //var_dump($xapian_data); echo '<pre>';
  1909. $ic_slide->xapian_data = serialize($xapian_data);
  1910. $di = new DokeosIndexer();
  1911. $return = $di->connectDb(null, null, $lang);
  1912. $specific_fields = get_specific_field_list();
  1913. // process different depending on what to do if file exists
  1914. /**
  1915. * FIXME: Find a way to really verify if the file had been
  1916. * overwriten. Now all work is done at
  1917. * handle_uploaded_document() and it's difficult to verify it
  1918. */
  1919. if (!empty($if_exists) && $if_exists == 'overwrite') {
  1920. // overwrite the file on search engine
  1921. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  1922. // Get search_did
  1923. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1924. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  1925. $sql = sprintf($sql, $tbl_se_ref, $courseid, TOOL_DOCUMENT, $docid);
  1926. $res = Database::query($sql);
  1927. if (Database::num_rows($res) > 0) {
  1928. $se_ref = Database::fetch_array($res);
  1929. $di->remove_document($se_ref['search_did']);
  1930. $all_specific_terms = '';
  1931. foreach ($specific_fields as $specific_field) {
  1932. delete_all_specific_field_value($courseid, $specific_field['id'], TOOL_DOCUMENT, $docid);
  1933. // Update search engine
  1934. $sterms = trim($_REQUEST[$specific_field['code']]);
  1935. $all_specific_terms .= ' '. $sterms;
  1936. $sterms = explode(',', $sterms);
  1937. foreach ($sterms as $sterm) {
  1938. $sterm = trim($sterm);
  1939. if (!empty($sterm)) {
  1940. $ic_slide->addTerm($sterm, $specific_field['code']);
  1941. add_specific_field_value($specific_field['id'], $courseid, TOOL_DOCUMENT, $docid, $value);
  1942. }
  1943. }
  1944. }
  1945. // Add terms also to content to make terms findable by probabilistic search
  1946. $file_content = $all_specific_terms .' '. $file_content;
  1947. $ic_slide->addValue('content', $file_content);
  1948. $di->addChunk($ic_slide);
  1949. // Index and return a new search engine document id
  1950. $did = $di->index();
  1951. //var_dump($did);
  1952. if ($did) {
  1953. // update the search_did on db
  1954. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1955. $sql = 'UPDATE %s SET search_did=%d WHERE id=%d LIMIT 1';
  1956. $sql = sprintf($sql, $tbl_se_ref, (int)$did, (int)$se_ref['id']);
  1957. Database::query($sql);
  1958. }
  1959. }
  1960. } else {
  1961. // Add all terms
  1962. $all_specific_terms = '';
  1963. foreach ($specific_fields as $specific_field) {
  1964. if (isset($_REQUEST[$specific_field['code']])) {
  1965. $sterms = trim($_REQUEST[$specific_field['code']]);
  1966. $all_specific_terms .= ' '. $sterms;
  1967. if (!empty($sterms)) {
  1968. $sterms = explode(',', $sterms);
  1969. foreach ($sterms as $sterm) {
  1970. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1971. add_specific_field_value($specific_field['id'], $courseid, TOOL_DOCUMENT, $docid, $sterm);
  1972. }
  1973. }
  1974. }
  1975. }
  1976. // Add terms also to content to make terms findable by probabilistic search
  1977. $file_content = $all_specific_terms .' '. $file_content;
  1978. $ic_slide->addValue('content', $file_content);
  1979. $di->addChunk($ic_slide);
  1980. // Index and return search engine document id
  1981. $did = $di->index();
  1982. if ($did) {
  1983. // Save it to db
  1984. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1985. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1986. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1987. $sql = sprintf($sql, $tbl_se_ref, $courseid, TOOL_DOCUMENT, $docid, $did);
  1988. Database::query($sql);
  1989. }
  1990. }
  1991. }
  1992. }
  1993. }
  1994. /*// Check for missing images in html files
  1995. $missing_files = check_for_missing_files($base_work_dir.$new_path);
  1996. if ($missing_files && $show_output) {
  1997. // Show a form to upload the missing files
  1998. Display::display_normal_message(build_missing_files_form($missing_files, $path, $files['file']['name']), false);
  1999. }*/
  2000. if (!empty($docid) && is_numeric($docid)) {
  2001. $document_data = self::get_document_data_by_id($docid, $course_info['code']);
  2002. return $document_data;
  2003. }
  2004. }
  2005. }
  2006. }
  2007. return false;
  2008. }
  2009. /**
  2010. * Obtains the text inside the file with the right parser
  2011. */
  2012. function get_text_content($doc_path, $doc_mime) {
  2013. // TODO: review w$ compatibility
  2014. // Use usual exec output lines array to store stdout instead of a temp file
  2015. // because we need to store it at RAM anyway before index on DokeosIndexer object
  2016. $ret_val = null;
  2017. switch ($doc_mime) {
  2018. case 'text/plain':
  2019. $handle = fopen($doc_path, 'r');
  2020. $output = array(fread($handle, filesize($doc_path)));
  2021. fclose($handle);
  2022. break;
  2023. case 'application/pdf':
  2024. exec("pdftotext $doc_path -", $output, $ret_val);
  2025. break;
  2026. case 'application/postscript':
  2027. $temp_file = tempnam(sys_get_temp_dir(), 'chamilo');
  2028. exec("ps2pdf $doc_path $temp_file", $output, $ret_val);
  2029. if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
  2030. return false;
  2031. }
  2032. exec("pdftotext $temp_file -", $output, $ret_val);
  2033. unlink($temp_file);
  2034. break;
  2035. case 'application/msword':
  2036. exec("catdoc $doc_path", $output, $ret_val);
  2037. break;
  2038. case 'text/html':
  2039. exec("html2text $doc_path", $output, $ret_val);
  2040. break;
  2041. case 'text/rtf':
  2042. // Note: correct handling of code pages in unrtf
  2043. // on debian lenny unrtf v0.19.2 can not, but unrtf v0.20.5 can
  2044. exec("unrtf --text $doc_path", $output, $ret_val);
  2045. if ($ret_val == 127) { // command not found
  2046. return false;
  2047. }
  2048. // Avoid index unrtf comments
  2049. if (is_array($output) && count($output) > 1) {
  2050. $parsed_output = array();
  2051. foreach ($output as & $line) {
  2052. if (!preg_match('/^###/', $line, $matches)) {
  2053. if (!empty($line)) {
  2054. $parsed_output[] = $line;
  2055. }
  2056. }
  2057. }
  2058. $output = $parsed_output;
  2059. }
  2060. break;
  2061. case 'application/vnd.ms-powerpoint':
  2062. exec("catppt $doc_path", $output, $ret_val);
  2063. break;
  2064. case 'application/vnd.ms-excel':
  2065. exec("xls2csv -c\" \" $doc_path", $output, $ret_val);
  2066. break;
  2067. }
  2068. $content = '';
  2069. if (!is_null($ret_val)) {
  2070. if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
  2071. return false;
  2072. }
  2073. }
  2074. if (isset($output)) {
  2075. foreach ($output as & $line) {
  2076. $content .= $line."\n";
  2077. }
  2078. return $content;
  2079. }
  2080. else {
  2081. return false;
  2082. }
  2083. }
  2084. /**
  2085. * Calculates the total size of all documents in a course
  2086. *
  2087. * @author Bert vanderkimpen
  2088. * @param int $to_group_id (to calculate group document space)
  2089. * @return int total size
  2090. */
  2091. function documents_total_space($to_group_id = '0') {
  2092. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2093. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  2094. $sql = "SELECT SUM(size)
  2095. FROM ".$TABLE_ITEMPROPERTY." AS props, ".$TABLE_DOCUMENT." AS docs
  2096. WHERE docs.id = props.ref
  2097. AND props.tool = '".TOOL_DOCUMENT."'
  2098. AND props.to_group_id='".$to_group_id."'
  2099. AND props.visibility <> 2";
  2100. $result = Database::query($sql);
  2101. if ($result && Database::num_rows($result) != 0) {
  2102. $row = Database::fetch_row($result);
  2103. return $row[0];
  2104. } else {
  2105. return 0;
  2106. }
  2107. }
  2108. /**
  2109. * Here we count 1 kilobyte = 1000 byte, 12 megabyte = 1000 kilobyte.
  2110. */
  2111. function display_quota($course_quota, $already_consumed_space) {
  2112. $course_quota_m = round($course_quota / 1000000);
  2113. $already_consumed_space_m = round($already_consumed_space / 1000000);
  2114. $message = get_lang('MaximumAllowedQuota') . ' <strong>'.$course_quota_m.' megabyte</strong>.<br />';
  2115. $message .= get_lang('CourseCurrentlyUses') . ' <strong>' . $already_consumed_space_m . ' megabyte</strong>.<br />';
  2116. $percentage = $already_consumed_space / $course_quota * 100;
  2117. $percentage = round($percentage, 1);
  2118. $other_percentage = $percentage < 100 ? 100 - $percentage : 0;
  2119. // Decide where to place percentage in graph
  2120. if ($percentage >= 50) {
  2121. $text_in_filled = '&nbsp;'.$other_percentage.'%';
  2122. $text_in_unfilled = '';
  2123. } else {
  2124. $text_in_unfilled = '&nbsp;'.$other_percentage.'%';
  2125. $text_in_filled = '';
  2126. }
  2127. // Decide the background colour of the graph
  2128. if ($percentage < 65) {
  2129. $colour = '#00BB00'; // Safe - green
  2130. } elseif ($percentage < 90) {
  2131. $colour = '#ffd400'; // Filling up - yelloworange
  2132. } else {
  2133. $colour = '#DD0000'; // Full - red
  2134. }
  2135. // This is used for the table width: a table of only 100 pixels looks too small
  2136. $visual_percentage = 4 * $percentage;
  2137. $visual_other_percentage = 4 * $other_percentage;
  2138. $message .= get_lang('PercentageQuotaInUse') . ': <strong>'.$percentage.'%</strong>.<br />' .
  2139. get_lang('PercentageQuotaFree') . ': <strong>'.$other_percentage.'%</strong>.<br />';
  2140. $show_percentage = '&nbsp;'.$percentage.'%';
  2141. $message .= '<div style="width: 80%; text-align: center; -moz-border-radius: 5px 5px 5px 5px; border: 1px solid #aaa; background-image: url(\''.api_get_path(WEB_CODE_PATH).'css/'.api_get_visual_theme().'/images/bg-header4.png\');" class="document-quota-bar">'.
  2142. '<div style="width:'.$percentage.'%; background-color: #bbb; border-right:3px groove #bbb; -moz-border-radius:5px;">&nbsp;</div>'.
  2143. '<span style="margin-top: -15px; margin-left:-15px; position: absolute;font-weight:bold;">'.$show_percentage.'</span></div>';
  2144. echo $message;
  2145. }
  2146. /**
  2147. * Display the document quota in a simple way
  2148. *
  2149. * Here we count 1 kilobyte = 1000 byte, 12 megabyte = 1000 kilobyte.
  2150. */
  2151. function display_simple_quota($course_quota, $already_consumed_space) {
  2152. $course_quota_m = round($course_quota / 1000000);
  2153. $already_consumed_space_m = round($already_consumed_space / 1000000, 2);
  2154. $percentage = $already_consumed_space / $course_quota * 100;
  2155. $percentage = round($percentage, 1);
  2156. //$message = "You are currently using %s (%s) of your %s.";
  2157. $message = get_lang('YouAreCurrentlyUsingXOfYourX');
  2158. $message = sprintf($message, $already_consumed_space_m, $percentage.'%',$course_quota_m.' ');
  2159. echo Display::div($message, array('id'=>'document_quota'));
  2160. }
  2161. /**
  2162. * Checks if there is enough place to add a file on a directory
  2163. * on the base of a maximum directory size allowed
  2164. *
  2165. * @author Bert Vanderkimpen
  2166. * @param int file_size size of the file in byte
  2167. * @param array $_course
  2168. * @param int max_dir_space maximum size
  2169. * @return boolean true if there is enough space, false otherwise
  2170. *
  2171. * @see enough_space() uses documents_total_space() function
  2172. */
  2173. function enough_space($file_size, $max_dir_space) {
  2174. if ($max_dir_space) {
  2175. $already_filled_space = self::documents_total_space();
  2176. if (($file_size + $already_filled_space) > $max_dir_space) {
  2177. return false;
  2178. }
  2179. }
  2180. return true;
  2181. }
  2182. function generate_mp3_preview($i) {
  2183. $i = intval($i);
  2184. //shows all the player
  2185. $html = ' <div id="jquery_jplayer_'.$i.'" class="jp-jplayer"></div>
  2186. <div class="jp-audio">
  2187. <div class="jp-type-single">
  2188. <div id="jp_interface_'.$i.'" class="jp-interface">
  2189. <ul class="jp-controls">
  2190. <li><a href="#" class="jp-play" tabindex="'.$i.'">play</a></li>
  2191. <li><a href="#" class="jp-pause" tabindex="'.$i.'">pause</a></li>
  2192. <li><a href="#" class="jp-stop" tabindex="'.$i.'">stop</a></li>
  2193. <li><a href="#" class="jp-mute" tabindex="'.$i.'">mute</a></li>
  2194. <li><a href="#" class="jp-unmute" tabindex="'.$i.'">unmute</a></li>
  2195. </ul>
  2196. <div class="jp-progress">
  2197. <div class="jp-seek-bar">
  2198. <div class="jp-play-bar"></div>
  2199. </div>
  2200. </div>
  2201. <div class="jp-volume-bar">
  2202. <div class="jp-volume-bar-value"></div>
  2203. </div>
  2204. <div class="jp-current-time"></div>
  2205. <div class="jp-duration"></div>
  2206. </div>
  2207. </div>
  2208. </div>';
  2209. //Shows only the play button
  2210. $html = ' <div id="jquery_jplayer_'.$i.'" class="jp-jplayer"></div>
  2211. <div class="jp-audio">
  2212. <div class="jp-type-single">
  2213. <div id="jp_interface_'.$i.'" class="jp-interface">
  2214. <ul class="jp-controls">
  2215. <li><a href="#" class="jp-play" tabindex="1">play</a></li>
  2216. <li><a href="#" class="jp-pause" tabindex="1">pause</a></li>
  2217. </ul>
  2218. </div>
  2219. </div>
  2220. </div>';
  2221. return $html;
  2222. }
  2223. }
  2224. //end class DocumentManager