document.lib.php 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965
  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. $document_data[$row['id']] = $row;
  533. }
  534. //Only for the student we filter the results see BT#1652
  535. if (!api_is_coach() && !$is_allowed_to_edit) {
  536. $ids_to_remove = array();
  537. $my_repeat_ids = $temp= array();
  538. //Selecting repetead ids
  539. foreach($doc_list as $row ) {
  540. if (in_array($row['id'], array_keys($temp))) {
  541. $my_repeat_ids[] = $row['id'];
  542. }
  543. $temp[$row['id']] = $row;
  544. }
  545. //@todo use the DocumentManager::is_visible function
  546. //Checking disponibility in a session
  547. foreach($my_repeat_ids as $id) {
  548. foreach($doc_list as $row ) {
  549. if ($id == $row['id']) {
  550. //var_dump($row['visibility'].' - '.$row['session_id'].' - '.$row['item_property_session_id']);
  551. if ($row['visibility'] == 0 && $row['item_property_session_id'] == 0) {
  552. $delete_repeated[$id] = true;
  553. }
  554. if ($row['visibility'] == 0 && $row['item_property_session_id'] != 0) {
  555. $delete_repeated[$id] = true;
  556. }
  557. }
  558. }
  559. }
  560. //var_dump($delete_repeated);
  561. foreach($doc_list as $key=>$row) {
  562. //&& !in_array($row['id'],$my_repeat_ids)
  563. //var_dump($row['id'].' - '.$row['visibility']);
  564. if (in_array($row['visibility'], array('0','2')) && !in_array($row['id'],$my_repeat_ids) ) {
  565. $ids_to_remove[] = $row['id'];
  566. unset($doc_list[$key]);
  567. }
  568. }
  569. //var_dump($ids_to_remove);
  570. foreach($document_data as $row) {
  571. if (in_array($row['id'], $ids_to_remove)) {
  572. unset($document_data[$row['id']]);
  573. }
  574. if (isset($delete_repeated[$row['id']]) && $delete_repeated[$row['id']]) {
  575. unset($document_data[$row['id']]);
  576. }
  577. }
  578. //Checking parents visibility
  579. $final_document_data = array();
  580. foreach($document_data as $row) {
  581. $is_visible = DocumentManager::check_visibility_tree($row['id'], $_course['code'], $current_session_id, api_get_user_id());
  582. if ($is_visible) {
  583. $final_document_data[$row['id']]=$row;
  584. }
  585. }
  586. } else {
  587. $final_document_data = $document_data;
  588. }
  589. return $final_document_data;
  590. } else {
  591. //display_error("Error getting document info from database (".Database::error().")!");
  592. return false;
  593. }
  594. }
  595. /**
  596. * Gets the paths of all folders in a course
  597. * can show all folders (exept for the deleted ones) or only visible ones
  598. * @param array $_course
  599. * @param boolean $can_see_invisible
  600. * @param int $to_group_id
  601. * @return array with paths
  602. */
  603. public static function get_all_document_folders ($_course, $to_group_id = '0', $can_see_invisible = false) {
  604. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  605. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  606. $to_group_id = intval($to_group_id);
  607. if ($can_see_invisible) {
  608. //condition for the session
  609. $session_id = api_get_session_id();
  610. $condition_session = api_get_session_condition($session_id);
  611. $sql = "SELECT DISTINCT path FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  612. WHERE docs.id = last.ref AND
  613. docs.filetype = 'folder' AND
  614. last.tool = '".TOOL_DOCUMENT."' AND
  615. last.to_group_id = ".$to_group_id." AND
  616. last.visibility <> 2 $condition_session AND
  617. docs.c_id = {$_course['real_id']} ";
  618. $result = Database::query($sql);
  619. if ($result && Database::num_rows($result) != 0) {
  620. while ($row = Database::fetch_array($result, 'ASSOC')) {
  621. $document_folders[] = $row['path'];
  622. }
  623. //sort($document_folders);
  624. natsort($document_folders);
  625. //return results
  626. return $document_folders;
  627. } else {
  628. return false;
  629. }
  630. } else {
  631. //no invisible folders
  632. //condition for the session
  633. $session_id = api_get_session_id();
  634. $condition_session = api_get_session_condition($session_id);
  635. //get visible folders
  636. $visible_sql = "SELECT DISTINCT path
  637. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  638. WHERE docs.id = last.ref
  639. AND docs.filetype = 'folder'
  640. AND last.tool = '".TOOL_DOCUMENT."'
  641. AND last.to_group_id = ".$to_group_id."
  642. AND last.visibility = 1 $condition_session AND docs.c_id = {$_course['real_id']} ";
  643. $visibleresult = Database::query($visible_sql);
  644. while ($all_visible_folders = Database::fetch_array($visibleresult, 'ASSOC')) {
  645. $visiblefolders[] = $all_visible_folders['path'];
  646. }
  647. //condition for the session
  648. $session_id = api_get_session_id();
  649. $condition_session = api_get_session_condition($session_id);
  650. //get invisible folders
  651. $invisible_sql = "SELECT DISTINCT path
  652. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  653. WHERE docs.id = last.ref
  654. AND docs.filetype = 'folder'
  655. AND last.tool = '".TOOL_DOCUMENT."'
  656. AND last.to_group_id = ".$to_group_id."
  657. AND last.visibility = 0 $condition_session AND docs.c_id = {$_course['real_id']} ";
  658. $invisibleresult = Database::query($invisible_sql);
  659. while ($invisible_folders = Database::fetch_array($invisibleresult, 'ASSOC')) {
  660. //condition for the session
  661. $session_id = api_get_session_id();
  662. $condition_session = api_get_session_condition($session_id);
  663. //get visible folders in the invisible ones -> they are invisible too
  664. $folder_in_invisible_sql = "SELECT DISTINCT path
  665. FROM ".$TABLE_ITEMPROPERTY." AS last, ".$TABLE_DOCUMENT." AS docs
  666. WHERE docs.id = last.ref
  667. AND docs.path LIKE '".Database::escape_string($invisible_folders['path'])."/%'
  668. AND docs.filetype = 'folder'
  669. AND last.tool = '".TOOL_DOCUMENT."'
  670. AND last.to_group_id = ".$to_group_id."
  671. AND last.visibility = 1 $condition_session AND docs.c_id = {$_course['real_id']} ";
  672. $folder_in_invisible_result = Database::query($folder_in_invisible_sql);
  673. while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result, 'ASSOC')) {
  674. $invisiblefolders[] = $folders_in_invisible_folder['path'];
  675. }
  676. }
  677. //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
  678. if (is_array($visiblefolders) && is_array($invisiblefolders)) {
  679. $document_folders = array_diff($visiblefolders, $invisiblefolders);
  680. natsort($document_folders);
  681. return $document_folders;
  682. } elseif (is_array($visiblefolders)) {
  683. //only visible folders found
  684. //sort($visiblefolders);
  685. natsort($visiblefolders);
  686. return $visiblefolders;
  687. } else {
  688. //no visible folders found
  689. return false;
  690. }
  691. }
  692. }
  693. /**
  694. * This check if a document has the readonly property checked, then see if the user
  695. * is the owner of this file, if all this is true then return true.
  696. *
  697. * @param array $_course
  698. * @param int $user_id id of the current user
  699. * @param string $file path stored in the database
  700. * @param int $document_id in case you dont have the file path ,insert the id of the file here and leave $file in blank ''
  701. * @return boolean true/false
  702. **/
  703. public static function check_readonly($_course, $user_id, $file,$document_id = '', $to_delete = false) {
  704. if (!(!empty($document_id) && is_numeric($document_id))) {
  705. $document_id = self::get_document_id($_course, $file);
  706. }
  707. $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  708. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  709. $course_id = $_course['real_id'];
  710. if ($to_delete) {
  711. if (self::is_folder($_course, $document_id)) {
  712. if (!empty($file)) {
  713. $path = Database::escape_string($file);
  714. $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM ".$TABLE_DOCUMENT." td , $TABLE_PROPERTY tp
  715. WHERE td.c_id = $course_id AND
  716. tp.c_id = $course_id AND
  717. tp.ref= td.id AND
  718. (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
  719. //get all id's of documents that are deleted
  720. $what_to_check_result = Database::query($what_to_check_sql);
  721. if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0) {
  722. // file with readonly set to 1 exist?
  723. $readonly_set = false;
  724. while ($row = Database::fetch_array($what_to_check_result)) {
  725. //query to delete from item_property table
  726. if ($row['readonly'] == 1) {
  727. if (!($row['insert_user_id'] == $user_id)) {
  728. $readonly_set = true;
  729. break;
  730. }
  731. }
  732. }
  733. if ($readonly_set) {
  734. return true;
  735. }
  736. }
  737. }
  738. return false;
  739. }
  740. }
  741. if (!empty($document_id)) {
  742. $sql= 'SELECT a.insert_user_id, b.readonly FROM '.$TABLE_PROPERTY.' a,'.$TABLE_DOCUMENT.' b
  743. WHERE
  744. a.c_id = $course_id AND
  745. b.c_id = $course_id AND
  746. a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
  747. $resultans = Database::query($sql);
  748. $doc_details = Database ::fetch_array($resultans, 'ASSOC');
  749. if ($doc_details['readonly'] == 1) {
  750. return !($doc_details['insert_user_id'] == $user_id || api_is_platform_admin());
  751. }
  752. }
  753. return false;
  754. }
  755. /**
  756. * This check if a document is a folder or not
  757. * @param array $_course
  758. * @param int $document_id of the item
  759. * @return boolean true/false
  760. **/
  761. public static function is_folder($_course, $document_id) {
  762. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  763. $course_id = $_course['real_id'];
  764. $document_id = Database::escape_string($document_id);
  765. $result = Database::fetch_array(Database::query("SELECT filetype FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND id= $document_id"), 'ASSOC');
  766. return $result['filetype'] == 'folder';
  767. }
  768. /**
  769. * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
  770. * Files/folders that are inside a deleted folder get visibility 2
  771. *
  772. * @param array $_course
  773. * @param string $path, path stored in the database
  774. * @param string ,$base_work_dir, path to the documents folder
  775. * @return boolean true/false
  776. * @todo now only files/folders in a folder get visibility 2, we should rename them too.
  777. */
  778. public static function delete_document($_course, $path, $base_work_dir) {
  779. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
  780. $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  781. $course_id = $_course['real_id'];
  782. //first, delete the actual document...
  783. $document_id = self :: get_document_id($_course, $path);
  784. $new_path = $path.'_DELETED_'.$document_id;
  785. $current_session_id = api_get_session_id();
  786. if ($document_id) {
  787. if (api_get_setting('permanently_remove_deleted_files') == 'true') { //deleted files are *really* deleted
  788. $what_to_delete_sql = "SELECT id FROM ".$TABLE_DOCUMENT." WHERE c_id = $course_id AND path='".$path."' OR path LIKE BINARY '".$path."/%'";
  789. //get all id's of documents that are deleted
  790. $what_to_delete_result = Database::query($what_to_delete_sql);
  791. if ($what_to_delete_result && Database::num_rows($what_to_delete_result) != 0) {
  792. //needed to deleted medadata
  793. require_once api_get_path(SYS_CODE_PATH).'metadata/md_funcs.php';
  794. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  795. $mdStore = new mdstore(true);
  796. //delete all item_property entries
  797. while ($row = Database::fetch_array($what_to_delete_result)) {
  798. //query to delete from item_property table
  799. //avoid wrong behavior
  800. //$remove_from_item_property_sql = "DELETE FROM ".$TABLE_ITEMPROPERTY." WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  801. api_item_property_update($_course, TOOL_DOCUMENT, $row['id'], 'delete', api_get_user_id(), null, null, null, null, $current_session_id);
  802. //query to delete from document table
  803. $remove_from_document_sql = "DELETE FROM ".$TABLE_DOCUMENT." WHERE id = ".$row['id'];
  804. self::unset_document_as_template($row['id'], $_course, api_get_user_id());
  805. Database::query($remove_from_document_sql);
  806. //delete metadata
  807. $eid = 'Document'.'.'.$row['id'];
  808. $mdStore->mds_delete($eid);
  809. $mdStore->mds_delete_offspring($eid);
  810. }
  811. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  812. //delete documents, do it like this so metadata get's deleted too
  813. //update_db_info('delete', $path);
  814. //throw it away
  815. my_delete($base_work_dir.$path);
  816. return true;
  817. } else {
  818. return false;
  819. }
  820. } else { //set visibility to 2 and rename file/folder to qsdqsd_DELETED_#id
  821. if (api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'delete', api_get_user_id(), null, null, null, null, $current_session_id)) {
  822. if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path)) {
  823. if(rename($base_work_dir.$path, $base_work_dir.$new_path)) {
  824. self::unset_document_as_template($document_id, api_get_course_id(), api_get_user_id());
  825. $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE c_id = $course_id AND id='".$document_id."'";
  826. if (Database::query($sql)) {
  827. //if it is a folder it can contain files
  828. $sql = "SELECT id,path FROM ".$TABLE_DOCUMENT." WHERE c_id = $course_id AND path LIKE BINARY '".$path."/%'";
  829. $result = Database::query($sql);
  830. if ($result && Database::num_rows($result) > 0) {
  831. while ($deleted_items = Database::fetch_array($result, 'ASSOC')) {
  832. api_item_property_update($_course, TOOL_DOCUMENT, $deleted_items['id'], 'delete', api_get_user_id(),null,null,null,null,$current_session_id);
  833. //Change path of subfolders and documents in database
  834. $old_item_path = $deleted_items['path'];
  835. $new_item_path = $new_path.substr($old_item_path, strlen($path));
  836. /*
  837. // Trying to fix this bug FS#2681
  838. echo $base_work_dir.$old_item_path;
  839. echo "<br />";
  840. echo $base_work_dir.$new_item_path;
  841. echo "<br /><br />";
  842. rename($base_work_dir.$old_item_path, $base_work_dir.$new_item_path);
  843. */
  844. self::unset_document_as_template($deleted_items['id'], api_get_course_id(), api_get_user_id());
  845. $sql = "UPDATE $TABLE_DOCUMENT set path = '".$new_item_path."' WHERE id = ".$deleted_items['id'];
  846. Database::query($sql);
  847. }
  848. }
  849. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  850. return true;
  851. }
  852. } else {
  853. //Couldn't rename - file permissions problem?
  854. error_log(__FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',0);
  855. }
  856. } else {
  857. //echo $base_work_dir.$path;
  858. //The file or directory isn't there anymore (on the filesystem)
  859. // This means it has been removed externally. To prevent a
  860. // blocking error from happening, we drop the related items from the
  861. // item_property and the document table.
  862. 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);
  863. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND path='".$path."' OR path LIKE BINARY '".$path."/%'";
  864. $res = Database::query($sql);
  865. self::delete_document_from_search_engine(api_get_course_id(), $document_id);
  866. while ($row = Database::fetch_array($res)) {
  867. $sqlipd = "DELETE FROM $TABLE_ITEMPROPERTY WHERE ref = ".$row['id']." AND tool='".TOOL_DOCUMENT."'";
  868. $resipd = Database::query($sqlipd);
  869. self::unset_document_as_template($row['id'],api_get_course_id(), api_get_user_id());
  870. $sqldd = "DELETE FROM $TABLE_DOCUMENT WHERE id = ".$row['id'];
  871. $resdd = Database::query($sqldd);
  872. }
  873. }
  874. }
  875. }
  876. }
  877. return false;
  878. }
  879. /**
  880. * Removes documents from search engine database
  881. *
  882. * @param string $course_id Course code
  883. * @param int $document_id Document id to delete
  884. */
  885. public static function delete_document_from_search_engine ($course_id, $document_id) {
  886. // remove from search engine if enabled
  887. if (api_get_setting('search_enabled') == 'true') {
  888. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  889. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  890. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  891. $res = Database::query($sql);
  892. if (Database::num_rows($res) > 0) {
  893. $row2 = Database::fetch_array($res);
  894. require_once api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php';
  895. $di = new DokeosIndexer();
  896. $di->remove_document((int)$row2['search_did']);
  897. }
  898. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  899. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  900. Database::query($sql);
  901. // remove terms from db
  902. require_once api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php';
  903. delete_all_values_for_item($course_id, TOOL_DOCUMENT, $document_id);
  904. }
  905. }
  906. /**
  907. * Gets the id of a document with a given path
  908. *
  909. * @param array $_course
  910. * @param string $path
  911. * @return int id of document / false if no doc found
  912. */
  913. public static function get_document_id($course_info, $path) {
  914. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
  915. $course_id = $course_info['real_id'];
  916. $path = Database::escape_string($path);
  917. $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND path LIKE BINARY '$path'";
  918. $result = Database::query($sql);
  919. if ($result && Database::num_rows($result) == 1) {
  920. $row = Database::fetch_array($result);
  921. return intval($row[0]);
  922. }
  923. return false;
  924. }
  925. /**
  926. * Gets the document data with a given id
  927. *
  928. * @param array $_course
  929. * @param string $path
  930. * @todo load parent_id
  931. * @return int id of document / false if no doc found
  932. */
  933. public static function get_document_data_by_id($id, $course_code, $load_parents = false) {
  934. $course_info = api_get_course_info($course_code);
  935. $course_id = $course_info['real_id'];
  936. if (empty($course_info)) {
  937. return false;
  938. }
  939. $www = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/document';
  940. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
  941. $id = intval($id);
  942. $sql = "SELECT * FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND id = $id ";
  943. $result = Database::query($sql);
  944. if ($result && Database::num_rows($result) == 1) {
  945. $row = Database::fetch_array($result,'ASSOC');
  946. //@todo need to clarify the name of the URLs not nice right now
  947. $url_path = urlencode($row['path']);
  948. $path = str_replace('%2F', '/',$url_path);
  949. $row['url'] = api_get_path(WEB_CODE_PATH).'document/showinframes.php?cidReq='.$course_code.'&id='.$id;
  950. $row['document_url'] = api_get_path(WEB_CODE_PATH).'document/document.php?cidReq='.$course_code.'&id='.$id;
  951. $row['direct_url'] = $www.$path;
  952. if (dirname($row['path']) == '.') {
  953. $row['parent_id'] = '0';
  954. } else {
  955. $row['parent_id'] = self::get_document_id($course_info, dirname($row['path']));
  956. }
  957. $parents = array();
  958. //Use to generate parents (needed for the breadcrumb)
  959. //@todo sorry but this for is here because there's not a parent_id in the document table so we parsed the path!!
  960. $visibility = true;
  961. if ($load_parents) {
  962. $dir_array = explode('/', $row['path']);
  963. $dir_array = array_filter($dir_array);
  964. $array_len = count($dir_array) +1 ;
  965. $real_dir = '';
  966. for ($i = 1; $i < $array_len; $i++) {
  967. $sub_visibility = true;
  968. $real_dir .= '/'.$dir_array[$i];
  969. $parent_id = self::get_document_id($course_info, $real_dir);
  970. if (!empty($parent_id)) {
  971. $sub_document_data = self::get_document_data_by_id($parent_id, $course_code, false);
  972. //@todo add visibility here
  973. /*$sub_visibility = self::is_visible_by_id($parent_id, $course_info, api_get_session_id(), api_get_user_id());
  974. if ($visibility && $sub_visibility == false) {
  975. $visibility = false;
  976. }
  977. */
  978. $parents[] = $sub_document_data;
  979. }
  980. }
  981. }
  982. //$row['visibility_for_user'] = $visibility;
  983. $row['parents'] = $parents;
  984. return $row;
  985. }
  986. return false;
  987. }
  988. /**
  989. * Allow to set a specific document as a new template for FCKEditor for a particular user in a particular course
  990. *
  991. * @param string $title
  992. * @param string $description
  993. * @param int $document_id_for_template the document id
  994. * @param string $couse_code
  995. * @param int $user_id
  996. */
  997. public static function set_document_as_template($title, $description, $document_id_for_template, $couse_code, $user_id, $image) {
  998. // Database table definition
  999. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  1000. // creating the sql statement
  1001. $sql = "INSERT INTO ".$table_template."
  1002. (title, description, course_code, user_id, ref_doc, image)
  1003. VALUES (
  1004. '".Database::escape_string($title)."',
  1005. '".Database::escape_string($description)."',
  1006. '".Database::escape_string($couse_code)."',
  1007. '".Database::escape_string($user_id)."',
  1008. '".Database::escape_string($document_id_for_template)."',
  1009. '".Database::escape_string($image)."')";
  1010. Database::query($sql);
  1011. return true;
  1012. }
  1013. /**
  1014. * Unset a document as template
  1015. *
  1016. * @param int $document_id
  1017. * @param string $couse_code
  1018. * @param int $user_id
  1019. */
  1020. public static function unset_document_as_template($document_id, $course_code, $user_id) {
  1021. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  1022. $course_code = Database::escape_string($course_code);
  1023. $user_id = Database::escape_string($user_id);
  1024. $document_id = Database::escape_string($document_id);
  1025. $sql = 'SELECT id FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  1026. $result = Database::query($sql);
  1027. $template_id = Database::result($result,0,0);
  1028. include_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
  1029. my_delete(api_get_path(SYS_CODE_PATH).'upload/template_thumbnails/'.$template_id.'.jpg');
  1030. $sql = 'DELETE FROM '.$table_template.' WHERE course_code="'.$course_code.'" AND user_id="'.$user_id.'" AND ref_doc="'.$document_id.'"';
  1031. Database::query($sql);
  1032. }
  1033. /**
  1034. * Return true if the documentpath have visibility=1 as item_property (you should use the is_visible_by_id)
  1035. *
  1036. * @param string $document_path the relative complete path of the document
  1037. * @param array $course the _course array info of the document's course
  1038. */
  1039. public static function is_visible($doc_path, $course, $session_id = 0, $file_type = 'file') {
  1040. $docTable = Database::get_course_table(TABLE_DOCUMENT);
  1041. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1042. $course_id = $course['real_id'];
  1043. //note the extra / at the end of doc_path to match every path in the document table that is part of the document path
  1044. $doc_path = Database::escape_string($doc_path);
  1045. $session_id = intval($session_id);
  1046. $condition = "AND id_session IN ('$session_id', '0') ";
  1047. // The " d.filetype='file' " let the user see a file even if the folder is hidden see #2198
  1048. //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
  1049. //so we remove that string in order to find correctly the origin file
  1050. if (strpos($doc_path, 'HotPotatoes_files')) {
  1051. $doc_path = substr($doc_path, 0, strlen($doc_path) - 8);
  1052. }
  1053. if (!in_array($file_type, array('file','folder'))) {
  1054. $file_type = 'file';
  1055. }
  1056. $sql = "SELECT visibility FROM $docTable d, $propTable ip
  1057. WHERE d.c_id = $course_id AND
  1058. ip.c_id = $course_id AND
  1059. d.id = ip.ref AND
  1060. ip.tool = '".TOOL_DOCUMENT."' $condition AND
  1061. filetype = '$file_type' AND locate(concat(path,'/'),'".$doc_path."/')=1";
  1062. $result = Database::query($sql);
  1063. $is_visible = false;
  1064. if (Database::num_rows($result) > 0) {
  1065. $row = Database::fetch_array($result,'ASSOC');
  1066. if ($row['visibility'] == 1) {
  1067. $is_visible = $_SESSION['is_allowed_in_course'] || api_is_platform_admin();
  1068. }
  1069. }
  1070. //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.
  1071. //return $_SESSION ['is_allowed_in_course'] || api_is_platform_admin();
  1072. return $is_visible;
  1073. }
  1074. /**
  1075. * Return true if user can see a file
  1076. *
  1077. * @param int document id
  1078. * @param array course info
  1079. * @param array $course the _course array info of the document's course
  1080. * @return bool
  1081. */
  1082. public static function is_visible_by_id($doc_id, $course_info, $session_id, $user_id, $admins_can_see_everything = true) {
  1083. $is_visible = false;
  1084. $user_in_course = false;
  1085. //1. Checking the course array
  1086. if (empty($course_info)) {
  1087. $course_info = api_get_course_info();
  1088. if (empty($course_info)) {
  1089. return false;
  1090. }
  1091. }
  1092. $doc_id = intval($doc_id);
  1093. $session_id = intval($session_id);
  1094. //2. Course and Session visibility are handle in local.inc.php/global.inc.php
  1095. //3. Checking if user exist in course/session
  1096. if ($session_id == 0 ) {
  1097. if (CourseManager::is_user_subscribed_in_course($user_id, $course_info['code']) || api_is_platform_admin()) {
  1098. $user_in_course = true;
  1099. }
  1100. //Check if course is open then we can consider that the student is regitered to the course
  1101. if (isset($course_info) && in_array($course_info['visibility'], array(2, 3))) {
  1102. $user_in_course = true;
  1103. }
  1104. } else {
  1105. $user_status = SessionManager::get_user_status_in_session($user_id, $course_info['code'], $session_id);
  1106. if (in_array($user_status, array('0', '2', '6'))) {
  1107. //is true if is an student, course session teacher or coach
  1108. $user_in_course = true;
  1109. }
  1110. }
  1111. //4. Checking document visibility (i'm repeating the code in order to be more clear when reading ) - jm
  1112. if ($user_in_course) {
  1113. //4.1 Checking document visibility for a Course
  1114. if ($session_id == 0) {
  1115. $item_info = api_get_item_property_info($course_info['real_id'], 'document', $doc_id, 0);
  1116. if (isset($item_info['visibility'])) {
  1117. // True for admins if document exists
  1118. if ($admins_can_see_everything && api_is_platform_admin()) {
  1119. return true;
  1120. }
  1121. if ($item_info['visibility'] == 1) {
  1122. return true;
  1123. }
  1124. }
  1125. } else {
  1126. //4.2 Checking document visibility for a Course in a Session
  1127. $item_info = api_get_item_property_info($course_info['real_id'], 'document', $doc_id, 0);
  1128. $item_info_in_session = api_get_item_property_info($course_info['real_id'], 'document', $doc_id, $session_id);
  1129. // True for admins if document exists
  1130. if (isset($item_info['visibility'])) {
  1131. if ($admins_can_see_everything && api_is_platform_admin())
  1132. return true;
  1133. }
  1134. if (isset($item_info_in_session['visibility'])) {
  1135. //if ($doc_id == 85) { var_dump($item_info_in_session);}
  1136. if ($item_info_in_session['visibility'] == 1) {
  1137. return true;
  1138. }
  1139. } else {
  1140. if ($item_info['visibility'] == 1) {
  1141. return true;
  1142. }
  1143. }
  1144. }
  1145. } elseif ($admins_can_see_everything && api_is_platform_admin()) {
  1146. return true;
  1147. }
  1148. return false;
  1149. }
  1150. /**
  1151. * Allow attach a certificate to a course
  1152. * @param string The course id
  1153. * @param int The document id
  1154. * @return void()
  1155. */
  1156. function attach_gradebook_certificate ($course_id, $document_id) {
  1157. $tbl_category = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1158. $session_id = api_get_session_id();
  1159. if ($session_id==0 || is_null($session_id)) {
  1160. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  1161. } elseif ($session_id>0) {
  1162. $sql_session='AND session_id='.Database::escape_string($session_id);
  1163. } else {
  1164. $sql_session='';
  1165. }
  1166. $sql='UPDATE '.$tbl_category.' SET document_id="'.Database::escape_string($document_id).'"
  1167. WHERE course_code="'.Database::escape_string($course_id).'" '.$sql_session;
  1168. $rs=Database::query($sql);
  1169. }
  1170. /**
  1171. * get the document id of default certificate
  1172. * @param string The course id
  1173. * @return int The default certificate id
  1174. */
  1175. function get_default_certificate_id($course_id) {
  1176. $tbl_category=Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1177. $session_id=api_get_session_id();
  1178. if ($session_id==0 || is_null($session_id)) {
  1179. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  1180. } elseif ($session_id>0) {
  1181. $sql_session='AND session_id='.Database::escape_string($session_id);
  1182. } else {
  1183. $sql_session='';
  1184. }
  1185. $sql='SELECT document_id FROM '.$tbl_category.' WHERE course_code="'.Database::escape_string($course_id).'" '.$sql_session;
  1186. $rs=Database::query($sql);
  1187. $row=Database::fetch_array($rs);
  1188. return $row['document_id'];
  1189. }
  1190. /**
  1191. * allow replace user info in file html
  1192. * @param string The course code
  1193. * @return string The html content of the certificate
  1194. */
  1195. function replace_user_info_into_html($user_id, $course_code, $is_preview = false) {
  1196. $user_id = intval($user_id);
  1197. $course_info = api_get_course_info($course_code);
  1198. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  1199. $course_id = $course_info['real_id'];
  1200. $document_id = self::get_default_certificate_id($course_code);
  1201. $sql = "SELECT path FROM $tbl_document WHERE c_id = $course_id AND id = $document_id";
  1202. $rs = Database::query($sql);
  1203. $new_content = '';
  1204. $all_user_info = array();
  1205. if (Database::num_rows($rs)) {
  1206. $row=Database::fetch_array($rs);
  1207. $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$row['path'];
  1208. if (is_file($filepath)) {
  1209. $my_content_html = file_get_contents($filepath);
  1210. }
  1211. $all_user_info = self::get_all_info_to_certificate($user_id, $course_code, $is_preview);
  1212. $info_to_be_replaced_in_content_html=$all_user_info[0];
  1213. $info_to_replace_in_content_html=$all_user_info[1];
  1214. $new_content=str_replace($info_to_be_replaced_in_content_html,$info_to_replace_in_content_html, $my_content_html);
  1215. }
  1216. return array('content' => $new_content, 'variables' => $all_user_info);
  1217. }
  1218. /**
  1219. * return all content to replace and all content to be replace
  1220. */
  1221. function get_all_info_to_certificate($user_id, $course_id, $is_preview = false) {
  1222. $info_list = array();
  1223. $user_id = intval($user_id);
  1224. $course_info = api_get_course_info($course_id);
  1225. //info portal
  1226. $organization_name = api_get_setting('Institution');
  1227. $portal_name = api_get_setting('siteName');
  1228. //Extra user data information
  1229. $extra_user_info_data = UserManager::get_extra_user_data($user_id, false, false, false, true);
  1230. //Student information
  1231. $user_info = api_get_user_info($user_id);
  1232. $first_name = $user_info['firstname'];
  1233. $last_name = $user_info['lastname'];
  1234. $official_code = $user_info['official_code'];
  1235. //Teacher information
  1236. $info_teacher_id = UserManager::get_user_id_of_course_admin_or_session_admin($course_id);
  1237. $teacher_info = api_get_user_info($info_teacher_id);
  1238. $teacher_first_name = $teacher_info['firstname'];
  1239. $teacher_last_name = $teacher_info['lastname'];
  1240. // info gradebook certificate
  1241. $info_grade_certificate = UserManager::get_info_gradebook_certificate($course_id, $user_id);
  1242. $date_certificate = $info_grade_certificate['created_at'];
  1243. $date_long_certificate = '';
  1244. if (!empty($date_certificate)) {
  1245. $date_long_certificate = api_convert_and_format_date($date_certificate);
  1246. }
  1247. if ($is_preview) {
  1248. $date_long_certificate = api_convert_and_format_date(api_get_utc_datetime());
  1249. }
  1250. $url = api_get_path(WEB_PATH).'certificates/?id='.$info_grade_certificate['id'];
  1251. //replace content
  1252. $info_to_replace_in_content_html = array($first_name,
  1253. $last_name,
  1254. $organization_name,
  1255. $portal_name,
  1256. $teacher_first_name,
  1257. $teacher_last_name,
  1258. $official_code,
  1259. $date_long_certificate,
  1260. $course_id,
  1261. $course_info['name'],
  1262. $info_grade_certificate['grade'],
  1263. $url,
  1264. '<a href="'.$url.'" target="_blank">'.get_lang('CertificateOnlineLink').'</a>',
  1265. '((certificate_barcode))',
  1266. );
  1267. $info_to_be_replaced_in_content_html = array('((user_firstname))',
  1268. '((user_lastname))',
  1269. '((gradebook_institution))',
  1270. '((gradebook_sitename))',
  1271. '((teacher_firstname))',
  1272. '((teacher_lastname))',
  1273. '((official_code))',
  1274. '((date_certificate))',
  1275. '((course_code))',
  1276. '((course_title))',
  1277. '((gradebook_grade))',
  1278. '((certificate_link))',
  1279. '((certificate_link_html))',
  1280. '((certificate_barcode))',
  1281. );
  1282. if (!empty($extra_user_info_data)) {
  1283. foreach ($extra_user_info_data as $key_extra=>$value_extra) {
  1284. $info_to_be_replaced_in_content_html[]='(('.strtolower($key_extra).'))';
  1285. $info_to_replace_in_content_html[]=$value_extra;
  1286. }
  1287. }
  1288. $info_list[]=$info_to_be_replaced_in_content_html;
  1289. $info_list[]=$info_to_replace_in_content_html;
  1290. return $info_list;
  1291. }
  1292. /**
  1293. * Remove default certificate
  1294. * @param string The course id
  1295. * @param int The document id of the default certificate
  1296. * @return void()
  1297. */
  1298. function remove_attach_certificate ($course_id,$default_certificate_id) {
  1299. $default_certificate=self::get_default_certificate_id($course_id);
  1300. if ((int)$default_certificate==(int)$default_certificate_id) {
  1301. $tbl_category=Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1302. $session_id=api_get_session_id();
  1303. if ($session_id==0 || is_null($session_id)) {
  1304. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  1305. } elseif ($session_id>0) {
  1306. $sql_session='AND session_id='.Database::escape_string($session_id);
  1307. } else {
  1308. $sql_session='';
  1309. }
  1310. $sql='UPDATE '.$tbl_category.' SET document_id=null
  1311. WHERE course_code="'.Database::escape_string($course_id).'" AND document_id="'.$default_certificate_id.'" '.$sql_session;
  1312. $rs=Database::query($sql);
  1313. }
  1314. }
  1315. /**
  1316. * Create directory certificate
  1317. * @param string The course id
  1318. * @return void()
  1319. */
  1320. function create_directory_certificate_in_course ($course_id) {
  1321. $course_info = api_get_course_info($course_id);
  1322. if (!empty($course_info)) {
  1323. $to_group_id=0;
  1324. $to_user_id=null;
  1325. $course_dir = $course_info['path']."/document/";
  1326. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  1327. $base_work_dir=$sys_course_path.$course_dir;
  1328. $base_work_dir_test=$base_work_dir.'certificates';
  1329. $dir_name='/certificates';
  1330. $post_dir_name=get_lang('CertificatesFiles');
  1331. $visibility_command='invisible';
  1332. if (!is_dir($base_work_dir_test)) {
  1333. $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);
  1334. $update_id = DocumentManager::get_document_id_of_directory_certificate();
  1335. api_item_property_update($course_info, TOOL_DOCUMENT, $update_id, $visibility_command, api_get_user_id());
  1336. }
  1337. }
  1338. }
  1339. /**
  1340. * Get the document id of the directory certificate
  1341. * @param string The course id
  1342. * @return int The document id of the directory certificate
  1343. */
  1344. function get_document_id_of_directory_certificate () {
  1345. $tbl_document=Database::get_course_table(TABLE_DOCUMENT);
  1346. $course_id = api_get_course_int_id();
  1347. $sql = "SELECT id FROM $tbl_document WHERE c_id = $course_id AND path='/certificates' ";
  1348. $rs=Database::query($sql);
  1349. $row=Database::fetch_array($rs);
  1350. return $row['id'];
  1351. }
  1352. /**
  1353. * Check if a directory given is for certificate
  1354. * @param string path of directory
  1355. * @return bool true if is a certificate or false otherwise
  1356. */
  1357. function is_certificate_mode($dir) {
  1358. //I'm in the certification module?
  1359. $is_certificate_mode = false;
  1360. $is_certificate_array = explode('/',$dir);
  1361. array_shift($is_certificate_array);
  1362. if ($is_certificate_array[0]=='certificates') {
  1363. $is_certificate_mode = true;
  1364. }
  1365. return $is_certificate_mode;
  1366. }
  1367. /**
  1368. * Gets the list of included resources as a list of absolute or relative paths from a html file or string html
  1369. * This allows for a better SCORM export or replace urls inside content html from copy course
  1370. * The list will generally include pictures, flash objects, java applets, or any other
  1371. * stuff included in the source of the current item. The current item is expected
  1372. * to be an HTML file or string html. If it is not, then the function will return and empty list.
  1373. * @param string source html (content or path)
  1374. * @param bool is file or string html
  1375. * @param string type (one of the Dokeos tools) - optional (otherwise takes the current item's type)
  1376. * @param int level of recursivity we're in
  1377. * @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
  1378. */
  1379. function get_resources_from_source_html($source_html, $is_file = false, $type = null, $recursivity = 1) {
  1380. $max = 5;
  1381. $attributes = array();
  1382. $wanted_attributes = array('src', 'url', '@import', 'href', 'value', 'flashvars');
  1383. $abs_path = '';
  1384. if ($recursivity > $max) {
  1385. return array();
  1386. }
  1387. if (!isset($type)) {
  1388. $type = TOOL_DOCUMENT;
  1389. }
  1390. if (!$is_file) {
  1391. $attributes = DocumentManager::parse_HTML_attributes($source_html, $wanted_attributes);
  1392. } else {
  1393. if (is_file($source_html)) {
  1394. $abs_path = $source_html;
  1395. //for now, read the whole file in one go (that's gonna be a problem when the file is too big)
  1396. $info = pathinfo($abs_path);
  1397. $ext = $info['extension'];
  1398. switch (strtolower($ext)) {
  1399. case 'html' :
  1400. case 'htm' :
  1401. case 'shtml':
  1402. case 'css' :
  1403. $file_content = file_get_contents($abs_path);
  1404. //get an array of attributes from the HTML source
  1405. $attributes = DocumentManager::parse_HTML_attributes($file_content, $wanted_attributes);
  1406. break;
  1407. default :
  1408. break;
  1409. }
  1410. } else {
  1411. return false;
  1412. }
  1413. }
  1414. switch ($type) {
  1415. case TOOL_DOCUMENT :
  1416. case TOOL_QUIZ:
  1417. case 'sco':
  1418. foreach ($wanted_attributes as $attr) {
  1419. if (isset($attributes[$attr])) {
  1420. //find which kind of path these are (local or remote)
  1421. $sources = $attributes[$attr];
  1422. foreach ($sources as $source) {
  1423. //skip what is obviously not a resource
  1424. if (strpos($source, '+this.')) continue; //javascript code - will still work unaltered
  1425. if (strpos($source, '.') === false) continue; //no dot, should not be an external file anyway
  1426. if (strpos($source, 'mailto:')) continue; //mailto link
  1427. if (strpos($source, ';') && !strpos($source, '&amp;')) continue; //avoid code - that should help
  1428. if ($attr == 'value') {
  1429. if (strpos($source , 'mp3file')) {
  1430. $files_list[] = array(substr($source, 0, strpos($source, '.swf') + 4), 'local', 'abs');
  1431. $mp3file = substr($source , strpos($source, 'mp3file=') + 8);
  1432. if (substr($mp3file, 0, 1) == '/') {
  1433. $files_list[] = array($mp3file, 'local', 'abs');
  1434. } else {
  1435. $files_list[] = array($mp3file, 'local', 'rel');
  1436. }
  1437. } elseif (strpos($source, 'flv=') === 0) {
  1438. $source = substr($source, 4);
  1439. if (strpos($source, '&') > 0) {
  1440. $source = substr($source, 0, strpos($source, '&'));
  1441. }
  1442. if (strpos($source,'://') > 0) {
  1443. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1444. //we found the current portal url
  1445. $files_list[] = array($source, 'local', 'url');
  1446. } else {
  1447. //we didn't find any trace of current portal
  1448. $files_list[] = array($source, 'remote', 'url');
  1449. }
  1450. } else {
  1451. $files_list[] = array($source, 'local', 'abs');
  1452. }
  1453. continue; //skipping anything else to avoid two entries (while the others can have sub-files in their url, flv's can't)
  1454. }
  1455. }
  1456. if (strpos($source, '://') > 0) {
  1457. //cut at '?' in a URL with params
  1458. if (strpos($source, '?') > 0) {
  1459. $second_part = substr($source,strpos($source, '?'));
  1460. if(strpos($second_part, '://') > 0) {
  1461. //if the second part of the url contains a url too, treat the second one before cutting
  1462. $pos1 = strpos($second_part, '=');
  1463. $pos2 = strpos($second_part, '&');
  1464. $second_part = substr($second_part, $pos1 + 1, $pos2 - ($pos1 + 1));
  1465. if (strpos($second_part, api_get_path(WEB_PATH)) !== false) {
  1466. //we found the current portal url
  1467. $files_list[] = array($second_part, 'local', 'url');
  1468. $in_files_list[] = DocumentManager::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, $recursivity + 1);
  1469. if (count($in_files_list) > 0) {
  1470. $files_list = array_merge($files_list, $in_files_list);
  1471. }
  1472. } else {
  1473. //we didn't find any trace of current portal
  1474. $files_list[] = array($second_part, 'remote', 'url');
  1475. }
  1476. } elseif (strpos($second_part, '=') > 0) {
  1477. if (substr($second_part, 0, 1) === '/') {
  1478. //link starts with a /, making it absolute (relative to DocumentRoot)
  1479. $files_list[] = array($second_part, 'local', 'abs');
  1480. $in_files_list[] = DocumentManager::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, $recursivity + 1);
  1481. if (count($in_files_list) > 0) {
  1482. $files_list = array_merge($files_list, $in_files_list);
  1483. }
  1484. } elseif(strstr($second_part, '..') === 0) {
  1485. //link is relative but going back in the hierarchy
  1486. $files_list[] = array($second_part, 'local', 'rel');
  1487. //$dir = api_get_path(SYS_CODE_PATH);//dirname($abs_path);
  1488. //$new_abs_path = realpath($dir.'/'.$second_part);
  1489. $dir = '';
  1490. if (!empty($abs_path)) {
  1491. $dir = dirname($abs_path).'/';
  1492. }
  1493. $new_abs_path = realpath($dir.$second_part);
  1494. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1495. if (count($in_files_list) > 0) {
  1496. $files_list = array_merge($files_list, $in_files_list);
  1497. }
  1498. } else {
  1499. //no starting '/', making it relative to current document's path
  1500. if (substr($second_part, 0, 2) == './') {
  1501. $second_part = substr($second_part, 2);
  1502. }
  1503. $files_list[] = array($second_part, 'local', 'rel');
  1504. $dir = '';
  1505. if (!empty($abs_path)) {
  1506. $dir = dirname($abs_path).'/';
  1507. }
  1508. $new_abs_path = realpath($dir.$second_part);
  1509. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1510. if (count($in_files_list) > 0) {
  1511. $files_list = array_merge($files_list, $in_files_list);
  1512. }
  1513. }
  1514. }
  1515. //leave that second part behind now
  1516. $source = substr($source, 0, strpos($source, '?'));
  1517. if (strpos($source, '://') > 0) {
  1518. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1519. //we found the current portal url
  1520. $files_list[] = array($source, 'local', 'url');
  1521. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity+1);
  1522. if (count($in_files_list) > 0) {
  1523. $files_list = array_merge($files_list, $in_files_list);
  1524. }
  1525. } else {
  1526. //we didn't find any trace of current portal
  1527. $files_list[] = array($source, 'remote', 'url');
  1528. }
  1529. } else {
  1530. //no protocol found, make link local
  1531. if (substr($source, 0, 1) === '/') {
  1532. //link starts with a /, making it absolute (relative to DocumentRoot)
  1533. $files_list[] = array($source, 'local', 'abs');
  1534. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1535. if (count($in_files_list) > 0) {
  1536. $files_list = array_merge($files_list, $in_files_list);
  1537. }
  1538. } elseif (strstr($source, '..') === 0) { //link is relative but going back in the hierarchy
  1539. $files_list[] = array($source, 'local', 'rel');
  1540. $dir = '';
  1541. if (!empty($abs_path)) {
  1542. $dir = dirname($abs_path).'/';
  1543. }
  1544. $new_abs_path = realpath($dir.$source);
  1545. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1546. if (count($in_files_list) > 0) {
  1547. $files_list = array_merge($files_list, $in_files_list);
  1548. }
  1549. } else {
  1550. //no starting '/', making it relative to current document's path
  1551. if (substr($source, 0, 2) == './') {
  1552. $source = substr($source, 2);
  1553. }
  1554. $files_list[] = array($source, 'local', 'rel');
  1555. $dir = '';
  1556. if (!empty($abs_path)) {
  1557. $dir = dirname($abs_path).'/';
  1558. }
  1559. $new_abs_path = realpath($dir.$source);
  1560. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1561. if (count($in_files_list) > 0) {
  1562. $files_list = array_merge($files_list, $in_files_list);
  1563. }
  1564. }
  1565. }
  1566. }
  1567. //found some protocol there
  1568. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1569. //we found the current portal url
  1570. $files_list[] = array($source, 'local', 'url');
  1571. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1572. if (count($in_files_list) > 0) {
  1573. $files_list = array_merge($files_list, $in_files_list);
  1574. }
  1575. } else {
  1576. //we didn't find any trace of current portal
  1577. $files_list[] = array($source, 'remote', 'url');
  1578. }
  1579. } else {
  1580. //no protocol found, make link local
  1581. if (substr($source, 0, 1) === '/') {
  1582. //link starts with a /, making it absolute (relative to DocumentRoot)
  1583. $files_list[] = array($source, 'local', 'abs');
  1584. $in_files_list[] = DocumentManager::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  1585. if (count($in_files_list) > 0) {
  1586. $files_list = array_merge($files_list, $in_files_list);
  1587. }
  1588. } elseif (strpos($source, '..') === 0) {
  1589. //link is relative but going back in the hierarchy
  1590. $files_list[] = array($source, 'local', 'rel');
  1591. $dir = '';
  1592. if (!empty($abs_path)) {
  1593. $dir = dirname($abs_path).'/';
  1594. }
  1595. $new_abs_path = realpath($dir.$source);
  1596. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1597. if (count($in_files_list) > 0) {
  1598. $files_list = array_merge($files_list, $in_files_list);
  1599. }
  1600. } else {
  1601. //no starting '/', making it relative to current document's path
  1602. if (substr($source, 0, 2) == './') {
  1603. $source = substr($source, 2);
  1604. }
  1605. $files_list[] = array($source, 'local', 'rel');
  1606. $dir = '';
  1607. if (!empty($abs_path)) {
  1608. $dir = dirname($abs_path).'/';
  1609. }
  1610. $new_abs_path = realpath($dir.$source);
  1611. $in_files_list[] = DocumentManager::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  1612. if (count($in_files_list) > 0) {
  1613. $files_list = array_merge($files_list, $in_files_list);
  1614. }
  1615. }
  1616. }
  1617. }
  1618. }
  1619. }
  1620. break;
  1621. default: //ignore
  1622. break;
  1623. }
  1624. $checked_files_list = array();
  1625. $checked_array_list = array();
  1626. if (count($files_list ) > 0) {
  1627. foreach ($files_list as $idx => $file) {
  1628. if (!empty($file[0])) {
  1629. if (!in_array($file[0], $checked_files_list)) {
  1630. $checked_files_list[] = $files_list[$idx][0];
  1631. $checked_array_list[] = $files_list[$idx];
  1632. }
  1633. }
  1634. }
  1635. }
  1636. return $checked_array_list;
  1637. }
  1638. /**
  1639. * Parses the HTML attributes given as string.
  1640. *
  1641. * @param string HTML attribute string
  1642. * @param array List of attributes that we want to get back
  1643. * @return array An associative array of attributes
  1644. * @author Based on a function from the HTML_Common2 PEAR module
  1645. */
  1646. function parse_HTML_attributes($attrString, $wanted = array()) {
  1647. $attributes = array();
  1648. $regs = array();
  1649. $reduced = false;
  1650. if (count($wanted) > 0) {
  1651. $reduced = true;
  1652. }
  1653. try {
  1654. //Find all occurences of something that looks like a URL
  1655. // The structure of this regexp is:
  1656. // (find protocol) then
  1657. // (optionally find some kind of space 1 or more times) then
  1658. // find (either an equal sign or a bracket) followed by an optional space
  1659. // followed by some text without quotes (between quotes itself or not)
  1660. // then possible closing brackets if we were in the opening bracket case
  1661. // OR something like @import()
  1662. $res = preg_match_all(
  1663. '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]*))' .
  1664. // '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]|[^\x00-\x7F])*)' . -> seems to be taking too much
  1665. // '/(((([A-Za-z_:])([^\x00-\x7F])*)' . -> takes only last letter of parameter name
  1666. '([ \n\t\r]+)?(' .
  1667. // '(=([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+))' . -> doesn't restrict close enough to the url itself
  1668. '(=([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+))' .
  1669. '|' .
  1670. // '(\(([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)\))' . -> doesn't restrict close enough to the url itself
  1671. '(\(([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+)\))' .
  1672. '))' .
  1673. '|' .
  1674. // '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))?/', -> takes a lot (like 100's of thousands of empty possibilities)
  1675. '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))/',
  1676. $attrString,
  1677. $regs
  1678. );
  1679. } catch (Exception $e) {
  1680. error_log('Caught exception: '. $e->getMessage(), 0) ;
  1681. }
  1682. if ($res) {
  1683. for ($i = 0; $i < count($regs[1]); $i++) {
  1684. $name = trim($regs[3][$i]);
  1685. $check = trim($regs[0][$i]);
  1686. $value = trim($regs[10][$i]);
  1687. if (empty($value) and !empty($regs[13][$i])) {
  1688. $value = $regs[13][$i];
  1689. }
  1690. if (empty($name) && !empty($regs[16][$i])) {
  1691. $name = '@import';
  1692. $value = trim($regs[16][$i]);
  1693. }
  1694. if (!empty($name)) {
  1695. if (!$reduced OR in_array(strtolower($name), $wanted)) {
  1696. if ($name == $check) {
  1697. $attributes[strtolower($name)][] = strtolower($name);
  1698. } else {
  1699. if (!empty($value) && ($value[0] == '\'' || $value[0] == '"')) {
  1700. $value = substr($value, 1, -1);
  1701. }
  1702. if ($value == 'API.LMSGetValue(name') {
  1703. $value = 'API.LMSGetValue(name)';
  1704. }
  1705. $attributes[strtolower($name)][] = $value;
  1706. }
  1707. }
  1708. }
  1709. }
  1710. } else {
  1711. error_log('preg_match did not find anything', 0);
  1712. }
  1713. return $attributes;
  1714. }
  1715. /**
  1716. * Replace urls inside content html from a copy course
  1717. * @param string content html
  1718. * @param string origin course code
  1719. * @param string destination course directory
  1720. * @return string new content html with replaced urls or return false if content is not a string
  1721. */
  1722. function replace_urls_inside_content_html_from_copy_course($content_html, $origin_course_code, $destination_course_directory) {
  1723. if (!is_string($content_html)) {
  1724. return false;
  1725. }
  1726. $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
  1727. $orig_course_info = api_get_course_info($origin_course_code);
  1728. $orig_course_path = api_get_path(SYS_PATH).'courses/'.$orig_course_info['path'].'/';
  1729. $destination_course_code = CourseManager::get_course_id_from_path ($destination_course_directory);
  1730. $dest_course_path = api_get_path(SYS_COURSE_PATH).$destination_course_directory.'/';
  1731. foreach ($orig_source_html as $source) {
  1732. // get information about source url
  1733. $real_orig_url = $source[0]; // url
  1734. $scope_url = $source[1]; // scope (local, remote)
  1735. $type_url = $source[2]; // tyle (rel, abs, url)
  1736. // Get path and query from origin url
  1737. $orig_parse_url = parse_url($real_orig_url);
  1738. $real_orig_path = $orig_parse_url['path'];
  1739. $real_orig_query = $orig_parse_url['query'];
  1740. // Replace origin course code by destination course code from origin url query
  1741. $dest_url_query = '';
  1742. if (!empty($real_orig_query)) {
  1743. $dest_url_query = '?'.$real_orig_query;
  1744. if (strpos($dest_url_query,$origin_course_code) !== false) {
  1745. $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
  1746. }
  1747. }
  1748. if ($scope_url == 'local') {
  1749. if ( $type_url == 'abs' || $type_url == 'rel') {
  1750. $document_file = strstr($real_orig_path, 'document');
  1751. if (strpos($real_orig_path,$document_file) !== false) {
  1752. $origin_filepath = $orig_course_path.$document_file;
  1753. $destination_filepath = $dest_course_path.$document_file;
  1754. // copy origin file inside destination course
  1755. if (file_exists($origin_filepath)) {
  1756. $filepath_dir = dirname($destination_filepath);
  1757. if (!is_dir($filepath_dir)) {
  1758. $perm = api_get_permissions_for_new_directories();
  1759. @mkdir($filepath_dir, $perm, true);
  1760. }
  1761. if (!file_exists($destination_filepath)) {
  1762. @copy($origin_filepath, $destination_filepath);
  1763. }
  1764. }
  1765. // Replace origin course path by destination course path
  1766. if (strpos($content_html,$real_orig_url) !== false) {
  1767. //$origin_course_code
  1768. $url_course_path = str_replace($orig_course_info['path'].'/'.$document_file, '', $real_orig_path);
  1769. $destination_url = $url_course_path.$destination_course_directory.'/'.$document_file.$dest_url_query;
  1770. //If the course code doesn't exist in the path? what we do? Nothing! see BT#1985
  1771. if (strpos($real_orig_path, $origin_course_code) === false) {
  1772. $url_course_path = $real_orig_path;
  1773. $destination_url = $real_orig_path;
  1774. }
  1775. $content_html = str_replace($real_orig_url, $destination_url, $content_html);
  1776. }
  1777. }
  1778. // replace origin course code by destination course code from origin url
  1779. if (strpos($real_orig_url, '?') === 0) {
  1780. $dest_url = str_replace($origin_course_code, $destination_course_code, $real_orig_url);
  1781. $content_html = str_replace($real_orig_url, $dest_url, $content_html);
  1782. }
  1783. } else {
  1784. if ($type_url == 'url') {
  1785. }
  1786. }
  1787. }
  1788. }
  1789. return $content_html;
  1790. }
  1791. /**
  1792. * Replace urls inside content html when moving a file
  1793. * @todo this code is only called in document.php but is commented
  1794. * @param string content html
  1795. * @param string origin
  1796. * @param string destination
  1797. * @return string new content html with replaced urls or return false if content is not a string
  1798. */
  1799. function replace_urls_inside_content_html_when_moving_file($file_name, $original_path, $destiny_path) {
  1800. if (substr($original_path, strlen($original_path) -1 , strlen($original_path)) == '/') {
  1801. $original = $original_path.$file_name;
  1802. } else {
  1803. $original = $original_path.'/'.$file_name;
  1804. }
  1805. if (substr($destiny_path, strlen($destiny_path) -1 , strlen($destiny_path)) == '/') {
  1806. $destination = $destiny_path.$file_name;
  1807. } else {
  1808. $destination = $destiny_path.'/'.$file_name;
  1809. }
  1810. //var_dump("From $original ", "to $destination");
  1811. $original_count = count(explode('/', $original));
  1812. $destination_count = count(explode('/', $destination));
  1813. if ($original_count == $destination_count) {
  1814. //Nothing to change
  1815. return true;
  1816. }
  1817. $mode = '';
  1818. if ($original_count > $destination_count) {
  1819. $mode = 'outside';
  1820. } else {
  1821. $mode = 'inside';
  1822. }
  1823. //echo $original_count.' '.$destination_count; var_dump($mode);
  1824. //We do not select the $original_path becayse the file was already moved
  1825. $content_html = file_get_contents($destiny_path.'/'.$file_name);
  1826. $destination_file = $destiny_path.'/'.$file_name;
  1827. $pre_original = strstr($original_path, 'document');
  1828. $pre_destin = strstr($destiny_path, 'document');
  1829. //var_dump ("pre_original $pre_original");
  1830. //var_dump ("pre_destin $pre_destin");
  1831. $pre_original = substr($pre_original, 8, strlen($pre_original));
  1832. $pre_destin = substr($pre_destin, 8, strlen($pre_destin));
  1833. //var_dump ("pre_original $pre_original");
  1834. //var_dump ("pre_destin $pre_destin");
  1835. $levels = count(explode('/', $pre_destin)) - 1 ;
  1836. $link_to_add = '';
  1837. for ($i=1; $i <=$levels ; $i++) {
  1838. $link_to_add .= '../';
  1839. }
  1840. if ($pre_original == '/') {
  1841. $pre_original = '';
  1842. }
  1843. if ($pre_destin == '/') {
  1844. $pre_destin = '';
  1845. }
  1846. if ($pre_original != '') {
  1847. $pre_original = '..'.$pre_original.'/';
  1848. }
  1849. if ($pre_destin != '') {
  1850. $pre_destin = '..'.$pre_destin.'/';
  1851. }
  1852. //var_dump($pre_original);
  1853. $levels = explode('/', $pre_original);
  1854. //var_dump($levels);
  1855. $count_pre_destination_levels = 0;
  1856. foreach($levels as $item) {
  1857. if (!empty($item) && $item != '..') {
  1858. $count_pre_destination_levels++;
  1859. }
  1860. }
  1861. $count_pre_destination_levels--;
  1862. //$count_pre_destination_levels = count() - 3;
  1863. if ($count_pre_destination_levels == 0 ) {
  1864. $count_pre_destination_levels = 1;
  1865. }
  1866. //echo '$count_pre_destination_levels '. $count_pre_destination_levels;
  1867. $pre_remove = '';
  1868. for ($i=1; $i <= $count_pre_destination_levels; $i++) {
  1869. $pre_remove .='..\/';
  1870. }
  1871. //var_dump(' link to add '.$link_to_add.' -- remove '.$pre_remove);
  1872. $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
  1873. //var_dump($orig_source_html);
  1874. foreach ($orig_source_html as $source) {
  1875. // get information about source url
  1876. $real_orig_url = $source[0]; // url
  1877. $scope_url = $source[1]; // scope (local, remote)
  1878. $type_url = $source[2]; // tyle (rel, abs, url)
  1879. // Get path and query from origin url
  1880. $orig_parse_url = parse_url($real_orig_url);
  1881. $real_orig_path = $orig_parse_url['path'];
  1882. $real_orig_query = $orig_parse_url['query'];
  1883. // Replace origin course code by destination course code from origin url query
  1884. /*
  1885. $dest_url_query = '';
  1886. if (!empty($real_orig_query)) {
  1887. $dest_url_query = '?'.$real_orig_query;
  1888. if (strpos($dest_url_query,$origin_course_code) !== false) {
  1889. $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
  1890. }
  1891. }*/
  1892. if ($scope_url == 'local') {
  1893. if ( $type_url == 'abs' || $type_url == 'rel') {
  1894. $document_file = strstr($real_orig_path, 'document');
  1895. if (strpos($real_orig_path, $document_file) !== false) {
  1896. echo 'continue1';
  1897. continue;
  1898. } else {
  1899. $real_orig_url_temp = '';
  1900. if ($mode == 'inside') {
  1901. $real_orig_url_temp = str_replace('../', '', $real_orig_url);
  1902. $destination_url = $link_to_add.$real_orig_url_temp;
  1903. } else {
  1904. $real_orig_url_temp = $real_orig_url;
  1905. $destination_url = preg_replace("/".$pre_remove."/", '', $real_orig_url, 1);
  1906. }
  1907. if ($real_orig_url == $destination_url) {
  1908. echo 'continue2';
  1909. continue;
  1910. }
  1911. var_dump($real_orig_url_temp.' - '.$destination_url);
  1912. $content_html = str_replace($real_orig_url, $destination_url, $content_html);
  1913. }
  1914. } else {
  1915. echo 'continue3';
  1916. continue;
  1917. }
  1918. }
  1919. }
  1920. $return = file_put_contents($destination, $content_html);
  1921. return $return;
  1922. }
  1923. public function export_to_pdf($document_id, $course_code) {
  1924. require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
  1925. $course_data = api_get_course_info($course_code);
  1926. $document_data = self::get_document_data_by_id($document_id, $course_code);
  1927. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$document_data['path'];
  1928. $pdf = new PDF();
  1929. $pdf->html_to_pdf($file_path, $document_data['title'], $course_code);
  1930. }
  1931. /**
  1932. * Uploads a document
  1933. *
  1934. * @param array the $_FILES variable
  1935. * @param string $path
  1936. * @param string title
  1937. * @param string comment
  1938. * @param int unzip or not the file
  1939. * @param int if_exists overwrite, rename or warn if exists (default)
  1940. * @param bool index document (search xapian module)
  1941. * @param bool print html messages
  1942. * @return unknown_type
  1943. */
  1944. public function upload_document($files, $path, $title ='', $comment = '', $unzip = 0, $if_exists = '', $index_document = false, $show_output = false) {
  1945. require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
  1946. $max_filled_space = self::get_course_quota();
  1947. $course_info = api_get_course_info();
  1948. $course_dir = $course_info['path'].'/document';
  1949. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  1950. $base_work_dir = $sys_course_path.$course_dir;
  1951. if (isset($files['file'])) {
  1952. $upload_ok = process_uploaded_file($files['file'], $show_output);
  1953. if ($upload_ok) {
  1954. // File got on the server without problems, now process it
  1955. $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);
  1956. if ($new_path) {
  1957. $docid = DocumentManager::get_document_id($course_info, $new_path);
  1958. if (!empty($docid)) {
  1959. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  1960. $params = array();
  1961. if (!empty($title)) {
  1962. $params['title'] = trim($title);
  1963. } else {
  1964. $params['title'] = $files['file']['name'];
  1965. }
  1966. if (!empty($comment)) {
  1967. $params['comment'] = trim($comment);
  1968. }
  1969. Database::update($table_document, $params, array('id = ?' =>$docid));
  1970. }
  1971. // Showing message when sending zip files
  1972. if ($new_path === true && $unzip == 1 && $show_output) {
  1973. Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />', false);
  1974. }
  1975. /*// Check for missing images in html files
  1976. $missing_files = check_for_missing_files($base_work_dir.$new_path);
  1977. if ($missing_files && $show_output) {
  1978. // Show a form to upload the missing files
  1979. Display::display_normal_message(build_missing_files_form($missing_files, $path, $files['file']['name']), false);
  1980. }*/
  1981. if ($index_document) {
  1982. $idx_doc = self::index_document($docid,$course_info['code'],null,$_POST['language'],$_REQUEST,$if_exists);
  1983. }
  1984. if (!empty($docid) && is_numeric($docid)) {
  1985. $document_data = self::get_document_data_by_id($docid, $course_info['code']);
  1986. return $document_data;
  1987. }
  1988. }
  1989. }
  1990. }
  1991. return false;
  1992. }
  1993. /**
  1994. * Obtains the text inside the file with the right parser
  1995. */
  1996. function get_text_content($doc_path, $doc_mime) {
  1997. // TODO: review w$ compatibility
  1998. // Use usual exec output lines array to store stdout instead of a temp file
  1999. // because we need to store it at RAM anyway before index on DokeosIndexer object
  2000. $ret_val = null;
  2001. switch ($doc_mime) {
  2002. case 'text/plain':
  2003. $handle = fopen($doc_path, 'r');
  2004. $output = array(fread($handle, filesize($doc_path)));
  2005. fclose($handle);
  2006. break;
  2007. case 'application/pdf':
  2008. exec("pdftotext $doc_path -", $output, $ret_val);
  2009. break;
  2010. case 'application/postscript':
  2011. $temp_file = tempnam(sys_get_temp_dir(), 'chamilo');
  2012. exec("ps2pdf $doc_path $temp_file", $output, $ret_val);
  2013. if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
  2014. return false;
  2015. }
  2016. exec("pdftotext $temp_file -", $output, $ret_val);
  2017. unlink($temp_file);
  2018. break;
  2019. case 'application/msword':
  2020. exec("catdoc $doc_path", $output, $ret_val);
  2021. break;
  2022. case 'text/html':
  2023. exec("html2text $doc_path", $output, $ret_val);
  2024. break;
  2025. case 'text/rtf':
  2026. // Note: correct handling of code pages in unrtf
  2027. // on debian lenny unrtf v0.19.2 can not, but unrtf v0.20.5 can
  2028. exec("unrtf --text $doc_path", $output, $ret_val);
  2029. if ($ret_val == 127) { // command not found
  2030. return false;
  2031. }
  2032. // Avoid index unrtf comments
  2033. if (is_array($output) && count($output) > 1) {
  2034. $parsed_output = array();
  2035. foreach ($output as & $line) {
  2036. if (!preg_match('/^###/', $line, $matches)) {
  2037. if (!empty($line)) {
  2038. $parsed_output[] = $line;
  2039. }
  2040. }
  2041. }
  2042. $output = $parsed_output;
  2043. }
  2044. break;
  2045. case 'application/vnd.ms-powerpoint':
  2046. exec("catppt $doc_path", $output, $ret_val);
  2047. break;
  2048. case 'application/vnd.ms-excel':
  2049. exec("xls2csv -c\" \" $doc_path", $output, $ret_val);
  2050. break;
  2051. }
  2052. $content = '';
  2053. if (!is_null($ret_val)) {
  2054. if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
  2055. return false;
  2056. }
  2057. }
  2058. if (isset($output)) {
  2059. foreach ($output as & $line) {
  2060. $content .= $line."\n";
  2061. }
  2062. return $content;
  2063. }
  2064. else {
  2065. return false;
  2066. }
  2067. }
  2068. /**
  2069. * Calculates the total size of all documents in a course
  2070. *
  2071. * @author Bert vanderkimpen
  2072. * @param int $to_group_id (to calculate group document space)
  2073. * @return int total size
  2074. */
  2075. function documents_total_space($to_group_id = '0') {
  2076. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2077. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  2078. $course_id = api_get_course_int_id();
  2079. $sql = "SELECT SUM(size) FROM ".$TABLE_ITEMPROPERTY." AS props, ".$TABLE_DOCUMENT." AS docs
  2080. WHERE props.c_id = $course_id AND
  2081. docs.c_id = $course_id AND
  2082. docs.id = props.ref AND
  2083. props.tool = '".TOOL_DOCUMENT."' AND
  2084. props.to_group_id='".$to_group_id."' AND
  2085. props.visibility <> 2";
  2086. $result = Database::query($sql);
  2087. if ($result && Database::num_rows($result) != 0) {
  2088. $row = Database::fetch_row($result);
  2089. return $row[0];
  2090. } else {
  2091. return 0;
  2092. }
  2093. }
  2094. /**
  2095. * Here we count 1 kilobyte = 1000 byte, 12 megabyte = 1000 kilobyte.
  2096. */
  2097. function display_quota($course_quota, $already_consumed_space) {
  2098. $course_quota_m = round($course_quota / 1000000);
  2099. $already_consumed_space_m = round($already_consumed_space / 1000000);
  2100. $message = get_lang('MaximumAllowedQuota') . ' <strong>'.$course_quota_m.' megabyte</strong>.<br />';
  2101. $message .= get_lang('CourseCurrentlyUses') . ' <strong>' . $already_consumed_space_m . ' megabyte</strong>.<br />';
  2102. $percentage = $already_consumed_space / $course_quota * 100;
  2103. $percentage = round($percentage, 1);
  2104. $other_percentage = $percentage < 100 ? 100 - $percentage : 0;
  2105. // Decide where to place percentage in graph
  2106. if ($percentage >= 50) {
  2107. $text_in_filled = '&nbsp;'.$other_percentage.'%';
  2108. $text_in_unfilled = '';
  2109. } else {
  2110. $text_in_unfilled = '&nbsp;'.$other_percentage.'%';
  2111. $text_in_filled = '';
  2112. }
  2113. // Decide the background colour of the graph
  2114. if ($percentage < 65) {
  2115. $colour = '#00BB00'; // Safe - green
  2116. } elseif ($percentage < 90) {
  2117. $colour = '#ffd400'; // Filling up - yelloworange
  2118. } else {
  2119. $colour = '#DD0000'; // Full - red
  2120. }
  2121. // This is used for the table width: a table of only 100 pixels looks too small
  2122. $visual_percentage = 4 * $percentage;
  2123. $visual_other_percentage = 4 * $other_percentage;
  2124. $message .= get_lang('PercentageQuotaInUse') . ': <strong>'.$percentage.'%</strong>.<br />' .
  2125. get_lang('PercentageQuotaFree') . ': <strong>'.$other_percentage.'%</strong>.<br />';
  2126. $show_percentage = '&nbsp;'.$percentage.'%';
  2127. $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">'.
  2128. '<div style="width:'.$percentage.'%; background-color: #bbb; border-right:3px groove #bbb; -moz-border-radius:5px;">&nbsp;</div>'.
  2129. '<span style="margin-top: -15px; margin-left:-15px; position: absolute;font-weight:bold;">'.$show_percentage.'</span></div>';
  2130. echo $message;
  2131. }
  2132. /**
  2133. * Display the document quota in a simple way
  2134. *
  2135. * Here we count 1 kilobyte = 1000 byte, 12 megabyte = 1000 kilobyte.
  2136. */
  2137. function display_simple_quota($course_quota, $already_consumed_space) {
  2138. $course_quota_m = round($course_quota / 1000000);
  2139. $already_consumed_space_m = round($already_consumed_space / 1000000, 2);
  2140. $percentage = $already_consumed_space / $course_quota * 100;
  2141. $percentage = round($percentage, 1);
  2142. //$message = "You are currently using %s (%s) of your %s.";
  2143. $message = get_lang('YouAreCurrentlyUsingXOfYourX');
  2144. $message = sprintf($message, $already_consumed_space_m, $percentage.'%',$course_quota_m.' ');
  2145. echo Display::div($message, array('id'=>'document_quota'));
  2146. }
  2147. /**
  2148. * Checks if there is enough place to add a file on a directory
  2149. * on the base of a maximum directory size allowed
  2150. *
  2151. * @author Bert Vanderkimpen
  2152. * @param int file_size size of the file in byte
  2153. * @param array $_course
  2154. * @param int max_dir_space maximum size
  2155. * @return boolean true if there is enough space, false otherwise
  2156. *
  2157. * @see enough_space() uses documents_total_space() function
  2158. */
  2159. function enough_space($file_size, $max_dir_space) {
  2160. if ($max_dir_space) {
  2161. $already_filled_space = self::documents_total_space();
  2162. if (($file_size + $already_filled_space) > $max_dir_space) {
  2163. return false;
  2164. }
  2165. }
  2166. return true;
  2167. }
  2168. /**
  2169. *
  2170. * Shows a play icon next to the document title in the document list
  2171. * @param int
  2172. * @return string html content
  2173. */
  2174. function generate_media_preview($i) {
  2175. $i = intval($i);
  2176. /*//shows all the player
  2177. $html = '<div id="jquery_jplayer_'.$i.'" class="jp-jplayer"></div>
  2178. <div class="jp-audio">
  2179. <div class="jp-type-single">
  2180. <div id="jp_interface_'.$i.'" class="jp-interface">
  2181. <ul class="jp-controls">
  2182. <li><a href="#" class="jp-play" tabindex="'.$i.'">play</a></li>
  2183. <li><a href="#" class="jp-pause" tabindex="'.$i.'">pause</a></li>
  2184. <li><a href="#" class="jp-stop" tabindex="'.$i.'">stop</a></li>
  2185. <li><a href="#" class="jp-mute" tabindex="'.$i.'">mute</a></li>
  2186. <li><a href="#" class="jp-unmute" tabindex="'.$i.'">unmute</a></li>
  2187. </ul>
  2188. <div class="jp-progress">
  2189. <div class="jp-seek-bar">
  2190. <div class="jp-play-bar"></div>
  2191. </div>
  2192. </div>
  2193. <div class="jp-volume-bar">
  2194. <div class="jp-volume-bar-value"></div>
  2195. </div>
  2196. <div class="jp-current-time"></div>
  2197. <div class="jp-duration"></div>
  2198. </div>
  2199. </div>
  2200. </div>';*/
  2201. //Shows only the play button
  2202. $html = ' <div id="jquery_jplayer_'.$i.'" class="jp-jplayer"></div>
  2203. <div class="jp-audio">
  2204. <div class="jp-type-single">
  2205. <div id="jp_interface_'.$i.'" class="jp-interface">
  2206. <ul class="jp-controls">
  2207. <li><a href="#" class="jp-play" tabindex="1">play</a></li>
  2208. <li><a href="#" class="jp-pause" tabindex="1">pause</a></li>
  2209. </ul>
  2210. </div>
  2211. </div>
  2212. </div>';
  2213. return $html;
  2214. }
  2215. function get_document_preview($course_info, $lp_id = false, $target = '', $session_id = 0) {
  2216. $course_info = api_get_course_info($course_info['code']);
  2217. if (empty($course_info) || !is_array($course_info)) {
  2218. return '';
  2219. }
  2220. $user_id = api_get_user_id();
  2221. $user_in_course = false;
  2222. if (api_is_platform_admin()) {
  2223. $user_in_course = true;
  2224. }
  2225. if (!$user_in_course) {
  2226. if (CourseManager::is_course_teacher($user_id, $course_info['code'])) {
  2227. $user_in_course = true;
  2228. }
  2229. }
  2230. //condition for the session
  2231. $session_id = intval($session_id);
  2232. if (!$user_in_course) {
  2233. if (empty($session_id)) {
  2234. if (CourseManager::is_user_subscribed_in_course($user_id, $course_info['code'])) {
  2235. $user_in_course = true;
  2236. }
  2237. //Check if course is open then we can consider that the student is regitered to the course
  2238. if (isset($course_info) && in_array($course_info['visibility'], array(2, 3))) {
  2239. $user_in_course = true;
  2240. }
  2241. } else {
  2242. $user_status = SessionManager::get_user_status_in_session($user_id, $course_info['code'], $session_id);
  2243. if (in_array($user_status, array('0', '2', '6'))) { //is true if is an student, course session teacher or coach
  2244. $user_in_course = true;
  2245. }
  2246. }
  2247. }
  2248. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2249. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  2250. $tbl_item_prop = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2251. $path = '/';
  2252. $path = Database::escape_string(str_replace('_', '\_', $path));
  2253. $added_slash = ($path == '/') ? '' : '/';
  2254. //$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']."' )))";
  2255. $condition_session = " AND (id_session = '$session_id' OR id_session = '0' )";
  2256. $sql_doc = "SELECT last.visibility, docs.*
  2257. FROM $tbl_item_prop AS last, $tbl_doc AS docs
  2258. WHERE docs.id = last.ref ".
  2259. " AND docs.path LIKE '".$path.$added_slash."%' ".
  2260. " AND docs.path NOT LIKE '%_DELETED_%' ".
  2261. " AND last.tool = '".TOOL_DOCUMENT."' $condition_session ".
  2262. " AND last.visibility = '1' AND ".
  2263. " docs.c_id = {$course_info['real_id']} AND
  2264. last.c_id = {$course_info['real_id']} ".
  2265. "ORDER BY docs.path ASC";
  2266. $res_doc = Database::query($sql_doc);
  2267. $resources = Database::store_result($res_doc, 'ASSOC');
  2268. $return = '';
  2269. $resources_sorted = array();
  2270. if ($lp_id) {
  2271. $return .= '<div class="lp_resource_element">';
  2272. $return .= Display::return_icon('new_doc.gif', '', array(), 22);
  2273. $return .= Display::url(get_lang('NewDocument'), api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_DOCUMENT.'&lp_id='.$_SESSION['oLP']->lp_id);
  2274. $return .= '</div>';
  2275. } else {
  2276. $return .= Display::div(Display::url(Display::return_icon('delete.png', get_lang('Close'), array(), 22), 'javascript:void();', array('id'=>'close_div_'.$course_info['real_id'].'_'.$session_id,'class' =>'close_div')), array('style' => 'position:absolute;right:10px'));
  2277. }
  2278. // If you want to debug it, I advise you to do "echo" on the eval statements.
  2279. if (!empty($resources) && $user_in_course) {
  2280. foreach ($resources as $resource) {
  2281. $is_visible = self::is_visible_by_id($resource['id'], $course_info, $session_id, api_get_user_id());
  2282. if (!$is_visible) {
  2283. continue;
  2284. }
  2285. $resource_paths = explode('/', $resource['path']);
  2286. array_shift($resource_paths);
  2287. $path_to_eval = $last_path = '';
  2288. $is_file = false;
  2289. if ($resource['filetype'] == 'file') {
  2290. foreach ($resource_paths as $key => $resource_path) {
  2291. if ($key != count($resource_paths)-1) {
  2292. // It's a folder.
  2293. $path_to_eval .= "['$resource_path']['files']";
  2294. }
  2295. $is_file = true;
  2296. }
  2297. } else {
  2298. foreach ($resource_paths as $key => $resource_path) {
  2299. if ($key != count($resource_paths) - 1) {
  2300. // It's a folder.
  2301. $path_to_eval .= "['$resource_path']['files']";
  2302. }
  2303. }
  2304. }
  2305. $last_path = $resource_path;
  2306. //$data = json_encode(array('title'=>$resource['title'], 'path'=>$last_path));
  2307. //@todo not sure if it's a good thing using base64_encode. I tried with json_encode but i received the same error
  2308. //Some testing is needed in order to prove the performance
  2309. //Also change the explode to value from "/" to "|@j@|" it fixes #3780
  2310. $data = base64_encode($resource['title'].'|@j@|'.$last_path);
  2311. if ($is_file) {
  2312. //for backward compatibility
  2313. if (empty($resource['title'])) {
  2314. $resource['title'] = basename($resource['path']);
  2315. }
  2316. eval ('$resources_sorted'.$path_to_eval.'['.$resource['id'].'] = "'.$data.'" ; ');
  2317. } else {
  2318. eval ('$resources_sorted'.$path_to_eval.'["'.$last_path.'"]["id"]='.$resource['id'].';');
  2319. eval ('$resources_sorted'.$path_to_eval.'["'.$last_path.'"]["title"]= "'.$resource['title'].'";');
  2320. }
  2321. }
  2322. }
  2323. $label = get_lang('Documents');
  2324. $new_array[$label] = array('id' => 0, 'files' => $resources_sorted);
  2325. $write_result = self::write_resources_tree($course_info, $session_id, $new_array, 0, $lp_id, $target);
  2326. $return .= $write_result ;
  2327. $return = Display::div($return, array('class'=>'lp_resource'));
  2328. $img_path = api_get_path(WEB_IMG_PATH);
  2329. if ($lp_id == false) {
  2330. $return .= "<script>
  2331. $('.doc_folder').mouseover(function() {
  2332. var my_id = this.id.split('_')[2];
  2333. $('#'+my_id).show();
  2334. });
  2335. $('.close_div').click(function() {
  2336. var course_id = this.id.split('_')[2];
  2337. var session_id = this.id.split('_')[3];
  2338. $('#document_result_'+course_id+'_'+session_id).hide();
  2339. $('.lp_resource').remove();
  2340. });
  2341. </script>";
  2342. } else {
  2343. //For LPs
  2344. $return .= "<script>
  2345. function testResources(id, img) {
  2346. if (document.getElementById(id).style.display=='block'){
  2347. document.getElementById(id).style.display='none';
  2348. document.getElementById('img_'+id).src='".$img_path."nolines_plus.gif';
  2349. } else {
  2350. document.getElementById(id).style.display='block';
  2351. document.getElementById('img_'+id).src='".$img_path."nolines_minus.gif';
  2352. }
  2353. }
  2354. </script>";
  2355. }
  2356. if(!$user_in_course) {
  2357. $return = '';
  2358. }
  2359. return $return;
  2360. }
  2361. /**
  2362. * Generate and return an HTML list of resources based on a given array.
  2363. * This list is used to show the course creator a list of available resources to choose from
  2364. * when creating a learning path.
  2365. * @param array Array of elements to add to the list
  2366. * @param integer Enables the tree display by shifting the new elements a certain distance to the right
  2367. * @return string The HTML list
  2368. */
  2369. public function write_resources_tree($course_info, $session_id, $resources_sorted, $num = 0, $lp_id = false, $target = '') {
  2370. require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
  2371. $img_path = api_get_path(WEB_IMG_PATH);
  2372. $img_sys_path = api_get_path(SYS_CODE_PATH).'img/';
  2373. $web_code_path = api_get_path(WEB_CODE_PATH);
  2374. $return = '';
  2375. if (count($resources_sorted) > 0) {
  2376. foreach ($resources_sorted as $key => $resource) {
  2377. $title = $resource['title'];
  2378. if (empty($title)) {
  2379. $title = $key;
  2380. }
  2381. //echo '<pre>'; print_r($resource);
  2382. if (isset($resource['id']) && is_int($resource['id'])) {
  2383. // It's a folder.
  2384. //hide some folders
  2385. if (in_array($key, array('shared_folder','chat_files', 'HotPotatoes_files', 'css', 'certificates'))){
  2386. continue;
  2387. } elseif(preg_match('/_groupdocs/', $key)){
  2388. continue;
  2389. } elseif(preg_match('/sf_user_/', $key)){
  2390. continue;
  2391. } elseif(preg_match('/shared_folder_session_/', $key)){
  2392. continue;
  2393. }
  2394. //trad some titles
  2395. if ($key=='images') {
  2396. $key=get_lang('Images');
  2397. } elseif($key=='gallery') {
  2398. $key=get_lang('Gallery');
  2399. } elseif($key=='flash') {
  2400. $key=get_lang('Flash');
  2401. } elseif($key=='audio'){
  2402. $key=get_lang('Audio');
  2403. } elseif($key=='video') {
  2404. $key=get_lang('Video');
  2405. }
  2406. $onclick = '';
  2407. if ($lp_id) {
  2408. $onclick = 'onclick="javascript: testResources(\'' . $resource['id'] . '\',\'img_' . $resource['id'] . '\')"';
  2409. }
  2410. $return .= '<div class="doc_resource">';
  2411. $return .= '<div class="doc_folder" id="doc_id_'.$resource['id'].'" style="margin-left:'.($num * 18).'px; margin-right:5px;">';
  2412. if ($lp_id) {
  2413. $return .= '<img style="cursor: pointer;" src="'.$img_path.'nolines_plus.gif" align="absmiddle" id="img_' . $resource['id'] . '" '.$onclick.' >';
  2414. } else {
  2415. $return .= '<span style="margin-left:16px">&nbsp;</span>';
  2416. }
  2417. $return .= '<img alt="" src="'.$img_path.'lp_folder.gif" title="" align="absmiddle" />&nbsp;';
  2418. $return .= '<span '.$onclick.' style="cursor: pointer;" >'.$title.'</span>';
  2419. $return .= '</div>
  2420. <div style="display: none;" id="'.$resource['id'].'">';
  2421. if (isset($resource['files'])) {
  2422. $return .= self::write_resources_tree($course_info, $session_id, $resource['files'], $num +1, $lp_id, $target);
  2423. }
  2424. $return .= '</div></div>';
  2425. } else {
  2426. if (!is_array($resource)) {
  2427. //if (isset($resource)) {
  2428. //var_dump($resource);
  2429. $resource = base64_decode($resource);
  2430. // It's a file.
  2431. $icon = choose_image($resource);
  2432. $position = strrpos($icon, '.');
  2433. $icon = substr($icon, 0, $position) . '_small.gif';
  2434. $file_info = explode('|@j@|', $resource);
  2435. $my_file_title = $file_info[0];
  2436. $my_file_name = $file_info[1];
  2437. // Show the "image name" not the filename of the image.
  2438. if ($lp_id) {
  2439. //LP URL
  2440. $lp_id = $this->lp_id;
  2441. $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;
  2442. } else {
  2443. //Direct document URL
  2444. $url = $web_code_path.'document/document.php?cidReq='.$course_info['code'].'&id_session='.$session_id.'&id='.$key;
  2445. }
  2446. $img = $img_path.$icon;
  2447. if (!file_exists($img_sys_path.$icon)) {
  2448. $img = $img_path.'icons/16/default_small.gif';
  2449. }
  2450. $link = Display::url('<img alt="" src="'.$img.'" title="" />&nbsp;' . $my_file_title, $url, array('target' => $target));
  2451. $return .= '<div class="doc_resource"><div style="margin-left:' . (($num +1) * 18) . 'px;margin-right:5px;">';
  2452. $return .= $link;
  2453. $return .= '</div></div>';
  2454. }
  2455. }
  2456. }
  2457. }
  2458. return $return;
  2459. }
  2460. public function check_visibility_tree($doc_id, $course_code, $session_id, $user_id) {
  2461. $document_data = self::get_document_data_by_id($doc_id, $course_code);
  2462. if (!empty($document_data)) {
  2463. //if admin or course teacher, allow anyway
  2464. if (api_is_platform_admin() || CourseManager::is_course_teacher($user_id,$course_code)) { return true; }
  2465. $course_info = api_get_course_info($course_code);
  2466. if ($document_data['parent_id'] == false || empty($document_data['parent_id'])) {
  2467. $visible = self::is_visible_by_id($doc_id, $course_info, $session_id, $user_id);
  2468. return $visible;
  2469. } else {
  2470. $course_info = api_get_course_info($course_code);
  2471. $visible = self::is_visible_by_id($doc_id, $course_info, $session_id, $user_id);
  2472. if (!$visible) {
  2473. return false;
  2474. } else {
  2475. return self::check_visibility_tree($document_data['parent_id'], $course_code, $session_id, $user_id);
  2476. }
  2477. }
  2478. } else {
  2479. return false;
  2480. }
  2481. }
  2482. /**
  2483. * Index a given document.
  2484. * @param int Document ID inside its corresponding course
  2485. * @param string Course code
  2486. * @param int Session ID (not used yet)
  2487. * @param string Language of document's content (defaults to course language)
  2488. * @param array Array of specific fields (['code'=>'value',...])
  2489. * @param string What to do if the file already exists (default or overwrite)
  2490. * @param bool When set to true, this runs the indexer without actually saving anything to any database
  2491. * @return bool Returns true on presumed success, false on failure
  2492. */
  2493. public function index_document($docid, $course_code, $session_id=0, $lang='english', $specific_fields_values=array(), $if_exists = '', $simulation = false) {
  2494. if (api_get_setting('search_enabled') !== 'true') {
  2495. return false;
  2496. }
  2497. if (empty($docid) or $docid != intval($docid)) {
  2498. return false;
  2499. }
  2500. if (empty($session_id)) {
  2501. $session_id = api_get_session_id();
  2502. }
  2503. $course_info = api_get_course_info($course_code);
  2504. $course_dir = $course_info['path'].'/document';
  2505. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  2506. $base_work_dir = $sys_course_path.$course_dir;
  2507. $course_id = $course_info['real_id'];
  2508. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  2509. $qry = "SELECT path, title FROM $table_document WHERE c_id = $course_id AND id = '$docid' LIMIT 1";
  2510. $result = Database::query($qry);
  2511. if (Database::num_rows($result) == 1) {
  2512. $row = Database::fetch_array($result);
  2513. $doc_path = api_get_path(SYS_COURSE_PATH).$course_dir.$row['path'];
  2514. //TODO: mime_content_type is deprecated, fileinfo php extension is enabled by default as of PHP 5.3.0
  2515. // now versions of PHP on Debian testing(5.2.6-5) and Ubuntu(5.2.6-2ubuntu) are lower, so wait for a while
  2516. $doc_mime = mime_content_type($doc_path);
  2517. //echo $doc_mime;
  2518. $allowed_mime_types = self::file_get_mime_type(true);
  2519. // 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
  2520. if (empty($doc_mime)) {
  2521. $allowed_extensions = array('doc', 'docx', 'ppt', 'pptx', 'pps', 'ppsx', 'xls', 'xlsx', 'odt', 'odp', 'ods', 'pdf', 'txt', 'rtf', 'msg', 'csv', 'html', 'htm');
  2522. $extensions = preg_split("/[\/\\.]/", $doc_path) ;
  2523. $doc_ext = strtolower($extensions[count($extensions) - 1]);
  2524. if (in_array($doc_ext, $allowed_extensions)) {
  2525. switch ($doc_ext) {
  2526. case 'ppt':
  2527. case 'pps':
  2528. $doc_mime = 'application/vnd.ms-powerpoint';
  2529. break;
  2530. case 'xls':
  2531. $doc_mime = 'application/vnd.ms-excel';
  2532. break;
  2533. }
  2534. }
  2535. }
  2536. //@todo move this nightmare in a search controller or something like that!!! J.M
  2537. if (in_array($doc_mime, $allowed_mime_types)) {
  2538. $file_title = $row['title'];
  2539. $file_content = self::get_text_content($doc_path, $doc_mime);
  2540. $course_code = Database::escape_string($course_code);
  2541. require_once api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php';
  2542. require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
  2543. $ic_slide = new IndexableChunk();
  2544. $ic_slide->addValue('title', $file_title);
  2545. $ic_slide->addCourseId($course_code);
  2546. $ic_slide->addToolId(TOOL_DOCUMENT);
  2547. $xapian_data = array(
  2548. SE_COURSE_ID => $course_code,
  2549. SE_TOOL_ID => TOOL_DOCUMENT,
  2550. SE_DATA => array('doc_id' => $docid),
  2551. SE_USER => api_get_user_id(),
  2552. );
  2553. //var_dump($xapian_data); echo '<pre>';
  2554. $ic_slide->xapian_data = serialize($xapian_data);
  2555. $di = new DokeosIndexer();
  2556. $return = $di->connectDb(null, null, $lang);
  2557. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2558. $specific_fields = get_specific_field_list();
  2559. // process different depending on what to do if file exists
  2560. /**
  2561. * @TODO Find a way to really verify if the file had been
  2562. * overwriten. Now all work is done at
  2563. * handle_uploaded_document() and it's difficult to verify it
  2564. */
  2565. if (!empty($if_exists) && $if_exists == 'overwrite') {
  2566. // Overwrite the file on search engine
  2567. // Actually, it consists on a delete of terms from db,
  2568. // insert new ones, create a new search engine document,
  2569. // and remove the old one
  2570. // Get search_did
  2571. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2572. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  2573. $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid);
  2574. $res = Database::query($sql);
  2575. if (Database::num_rows($res) > 0) {
  2576. $se_ref = Database::fetch_array($res);
  2577. if (!$simulation) {
  2578. $di->remove_document($se_ref['search_did']);
  2579. }
  2580. $all_specific_terms = '';
  2581. foreach ($specific_fields as $specific_field) {
  2582. if (!$simulation) {
  2583. delete_all_specific_field_value($course_code, $specific_field['id'], TOOL_DOCUMENT, $docid);
  2584. }
  2585. // Update search engine
  2586. if (isset($specific_fields_values[$specific_field['code']])) {
  2587. $sterms = trim($specific_fields_values[$specific_field['code']]);
  2588. } else { //if the specific field is not defined, force an empty one
  2589. $sterms = '';
  2590. }
  2591. $all_specific_terms .= ' '. $sterms;
  2592. $sterms = explode(',', $sterms);
  2593. foreach ($sterms as $sterm) {
  2594. $sterm = trim($sterm);
  2595. if (!empty($sterm)) {
  2596. $ic_slide->addTerm($sterm, $specific_field['code']);
  2597. // updated the last param here from $value to $sterm without being sure - see commit15464
  2598. if (!$simulation) {
  2599. add_specific_field_value($specific_field['id'], $course_code, TOOL_DOCUMENT, $docid, $sterm);
  2600. }
  2601. }
  2602. }
  2603. }
  2604. // Add terms also to content to make terms findable by probabilistic search
  2605. $file_content = $all_specific_terms .' '. $file_content;
  2606. if (!$simulation) {
  2607. $ic_slide->addValue('content', $file_content);
  2608. $di->addChunk($ic_slide);
  2609. // Index and return a new search engine document id
  2610. $did = $di->index();
  2611. //var_dump($did);
  2612. if ($did) {
  2613. // update the search_did on db
  2614. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2615. $sql = 'UPDATE %s SET search_did=%d WHERE id=%d LIMIT 1';
  2616. $sql = sprintf($sql, $tbl_se_ref, (int)$did, (int)$se_ref['id']);
  2617. Database::query($sql);
  2618. }
  2619. }
  2620. }
  2621. } else {
  2622. // Add all terms
  2623. $all_specific_terms = '';
  2624. foreach ($specific_fields as $specific_field) {
  2625. if (isset($specific_fields_values[$specific_field['code']])) {
  2626. $sterms = trim($specific_fields_values[$specific_field['code']]);
  2627. } else { //if the specific field is not defined, force an empty one
  2628. $sterms = '';
  2629. }
  2630. $all_specific_terms .= ' '. $sterms;
  2631. if (!empty($sterms)) {
  2632. $sterms = explode(',', $sterms);
  2633. foreach ($sterms as $sterm) {
  2634. if (!$simulation) {
  2635. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2636. add_specific_field_value($specific_field['id'], $course_code, TOOL_DOCUMENT, $docid, $sterm);
  2637. }
  2638. }
  2639. }
  2640. }
  2641. // Add terms also to content to make terms findable by probabilistic search
  2642. $file_content = $all_specific_terms .' '. $file_content;
  2643. if (!$simulation) {
  2644. $ic_slide->addValue('content', $file_content);
  2645. $di->addChunk($ic_slide);
  2646. // Index and return search engine document id
  2647. $did = $di->index();
  2648. if ($did) {
  2649. // Save it to db
  2650. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2651. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2652. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2653. $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid, $did);
  2654. Database::query($sql);
  2655. } else {
  2656. return false;
  2657. }
  2658. }
  2659. }
  2660. } else {
  2661. return false;
  2662. }
  2663. }
  2664. return true;
  2665. }
  2666. }
  2667. //end class DocumentManager