document.lib.php 164 KB

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