document.lib.php 137 KB

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