document.lib.php 157 KB

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