document.lib.php 118 KB

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