document.lib.php 136 KB

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