document.lib.php 146 KB

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