document.lib.php 139 KB

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