document.lib.php 164 KB

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