document.lib.php 156 KB

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