document.lib.php 157 KB

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