document.lib.php 146 KB

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