document.lib.php 157 KB

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