document.lib.php 137 KB

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