document.lib.php 250 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class DocumentManager
  5. * This is the document library for Chamilo.
  6. * It is / will be used to provide a service layer to all document-using tools.
  7. * and eliminate code duplication fro group documents, scorm documents, main documents.
  8. * Include/require it in your code to use its functionality.
  9. *
  10. * @package chamilo.library
  11. */
  12. class DocumentManager
  13. {
  14. /**
  15. * Construct
  16. */
  17. private function __construct()
  18. {
  19. }
  20. /**
  21. * @param string $course_code
  22. *
  23. * @return int the document folder quota for the current course in bytes
  24. * or the default quota
  25. */
  26. public static function get_course_quota($course_code = null)
  27. {
  28. if (empty($course_code)) {
  29. $course_info = api_get_course_info();
  30. } else {
  31. $course_info = api_get_course_info($course_code);
  32. }
  33. $course_quota = null;
  34. if (empty($course_info)) {
  35. return DEFAULT_DOCUMENT_QUOTA;
  36. } else {
  37. $course_quota = $course_info['disk_quota'];
  38. }
  39. if (is_null($course_quota) || empty($course_quota)) {
  40. // Course table entry for quota was null, then use default value
  41. $course_quota = DEFAULT_DOCUMENT_QUOTA;
  42. }
  43. return $course_quota;
  44. }
  45. /**
  46. * Get the content type of a file by checking the extension
  47. * We could use mime_content_type() with php-versions > 4.3,
  48. * but this doesn't work as it should on Windows installations
  49. *
  50. * @param string $filename or boolean TRUE to return complete array
  51. * @author ? first version
  52. * @author Bert Vanderkimpen
  53. * @return string
  54. *
  55. */
  56. public static function file_get_mime_type($filename)
  57. {
  58. // All MIME types in an array (from 1.6, this is the authorative source)
  59. // Please, keep this alphabetical if you add something to this list!
  60. $mime_types = array(
  61. 'ai' => 'application/postscript',
  62. 'aif' => 'audio/x-aiff',
  63. 'aifc' => 'audio/x-aiff',
  64. 'aiff' => 'audio/x-aiff',
  65. 'asf' => 'video/x-ms-asf',
  66. 'asc' => 'text/plain',
  67. 'au' => 'audio/basic',
  68. 'avi' => 'video/x-msvideo',
  69. 'bcpio' => 'application/x-bcpio',
  70. 'bin' => 'application/octet-stream',
  71. 'bmp' => 'image/bmp',
  72. 'cdf' => 'application/x-netcdf',
  73. 'class' => 'application/octet-stream',
  74. 'cpio' => 'application/x-cpio',
  75. 'cpt' => 'application/mac-compactpro',
  76. 'csh' => 'application/x-csh',
  77. 'css' => 'text/css',
  78. 'dcr' => 'application/x-director',
  79. 'dir' => 'application/x-director',
  80. 'djv' => 'image/vnd.djvu',
  81. 'djvu' => 'image/vnd.djvu',
  82. 'dll' => 'application/octet-stream',
  83. 'dmg' => 'application/x-diskcopy',
  84. 'dms' => 'application/octet-stream',
  85. 'doc' => 'application/msword',
  86. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  87. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  88. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  89. 'dvi' => 'application/x-dvi',
  90. 'dwg' => 'application/vnd.dwg',
  91. 'dwf' => 'application/vnd.dwf',
  92. 'dxf' => 'application/vnd.dxf',
  93. 'dxr' => 'application/x-director',
  94. 'eps' => 'application/postscript',
  95. 'epub' => 'application/epub+zip',
  96. 'etx' => 'text/x-setext',
  97. 'exe' => 'application/octet-stream',
  98. 'ez' => 'application/andrew-inset',
  99. 'gif' => 'image/gif',
  100. 'gtar' => 'application/x-gtar',
  101. 'gz' => 'application/x-gzip',
  102. 'hdf' => 'application/x-hdf',
  103. 'hqx' => 'application/mac-binhex40',
  104. 'htm' => 'text/html',
  105. 'html' => 'text/html',
  106. 'ice' => 'x-conference-xcooltalk',
  107. 'ief' => 'image/ief',
  108. 'iges' => 'model/iges',
  109. 'igs' => 'model/iges',
  110. 'jar' => 'application/java-archiver',
  111. 'jpe' => 'image/jpeg',
  112. 'jpeg' => 'image/jpeg',
  113. 'jpg' => 'image/jpeg',
  114. 'js' => 'application/x-javascript',
  115. 'kar' => 'audio/midi',
  116. 'lam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  117. 'latex' => 'application/x-latex',
  118. 'lha' => 'application/octet-stream',
  119. 'log' => 'text/plain',
  120. 'lzh' => 'application/octet-stream',
  121. 'm1a' => 'audio/mpeg',
  122. 'm2a' => 'audio/mpeg',
  123. 'm3u' => 'audio/x-mpegurl',
  124. 'man' => 'application/x-troff-man',
  125. 'me' => 'application/x-troff-me',
  126. 'mesh' => 'model/mesh',
  127. 'mid' => 'audio/midi',
  128. 'midi' => 'audio/midi',
  129. 'mov' => 'video/quicktime',
  130. 'movie' => 'video/x-sgi-movie',
  131. 'mp2' => 'audio/mpeg',
  132. 'mp3' => 'audio/mpeg',
  133. 'mp4' => 'video/mpeg4-generic',
  134. 'mpa' => 'audio/mpeg',
  135. 'mpe' => 'video/mpeg',
  136. 'mpeg' => 'video/mpeg',
  137. 'mpg' => 'video/mpeg',
  138. 'mpga' => 'audio/mpeg',
  139. 'ms' => 'application/x-troff-ms',
  140. 'msh' => 'model/mesh',
  141. 'mxu' => 'video/vnd.mpegurl',
  142. 'nc' => 'application/x-netcdf',
  143. 'oda' => 'application/oda',
  144. 'oga' => 'audio/ogg',
  145. 'ogg' => 'application/ogg',
  146. 'ogx' => 'application/ogg',
  147. 'ogv' => 'video/ogg',
  148. 'pbm' => 'image/x-portable-bitmap',
  149. 'pct' => 'image/pict',
  150. 'pdb' => 'chemical/x-pdb',
  151. 'pdf' => 'application/pdf',
  152. 'pgm' => 'image/x-portable-graymap',
  153. 'pgn' => 'application/x-chess-pgn',
  154. 'pict' => 'image/pict',
  155. 'png' => 'image/png',
  156. 'pnm' => 'image/x-portable-anymap',
  157. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  158. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  159. 'pps' => 'application/vnd.ms-powerpoint',
  160. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  161. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  162. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  163. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  164. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  165. 'ppm' => 'image/x-portable-pixmap',
  166. 'ppt' => 'application/vnd.ms-powerpoint',
  167. 'pps' => 'application/vnd.ms-powerpoint',
  168. 'ps' => 'application/postscript',
  169. 'qt' => 'video/quicktime',
  170. 'ra' => 'audio/x-realaudio',
  171. 'ram' => 'audio/x-pn-realaudio',
  172. 'rar' => 'image/x-rar-compressed',
  173. 'ras' => 'image/x-cmu-raster',
  174. 'rgb' => 'image/x-rgb',
  175. 'rm' => 'audio/x-pn-realaudio',
  176. 'roff' => 'application/x-troff',
  177. 'rpm' => 'audio/x-pn-realaudio-plugin',
  178. 'rtf' => 'text/rtf',
  179. 'rtx' => 'text/richtext',
  180. 'sgm' => 'text/sgml',
  181. 'sgml' => 'text/sgml',
  182. 'sh' => 'application/x-sh',
  183. 'shar' => 'application/x-shar',
  184. 'silo' => 'model/mesh',
  185. 'sib' => 'application/X-Sibelius-Score',
  186. 'sit' => 'application/x-stuffit',
  187. 'skd' => 'application/x-koan',
  188. 'skm' => 'application/x-koan',
  189. 'skp' => 'application/x-koan',
  190. 'skt' => 'application/x-koan',
  191. 'smi' => 'application/smil',
  192. 'smil' => 'application/smil',
  193. 'snd' => 'audio/basic',
  194. 'so' => 'application/octet-stream',
  195. 'spl' => 'application/x-futuresplash',
  196. 'src' => 'application/x-wais-source',
  197. 'sv4cpio' => 'application/x-sv4cpio',
  198. 'sv4crc' => 'application/x-sv4crc',
  199. 'svf' => 'application/vnd.svf',
  200. 'svg' => 'image/svg+xml',
  201. //'svgz' => 'image/svg+xml',
  202. 'swf' => 'application/x-shockwave-flash',
  203. 'sxc' => 'application/vnd.sun.xml.calc',
  204. 'sxi' => 'application/vnd.sun.xml.impress',
  205. 'sxw' => 'application/vnd.sun.xml.writer',
  206. 't' => 'application/x-troff',
  207. 'tar' => 'application/x-tar',
  208. 'tcl' => 'application/x-tcl',
  209. 'tex' => 'application/x-tex',
  210. 'texi' => 'application/x-texinfo',
  211. 'texinfo' => 'application/x-texinfo',
  212. 'tga' => 'image/x-targa',
  213. 'tif' => 'image/tif',
  214. 'tiff' => 'image/tiff',
  215. 'tr' => 'application/x-troff',
  216. 'tsv' => 'text/tab-seperated-values',
  217. 'txt' => 'text/plain',
  218. 'ustar' => 'application/x-ustar',
  219. 'vcd' => 'application/x-cdlink',
  220. 'vrml' => 'model/vrml',
  221. 'wav' => 'audio/x-wav',
  222. 'wbmp' => 'image/vnd.wap.wbmp',
  223. 'wbxml' => 'application/vnd.wap.wbxml',
  224. 'wml' => 'text/vnd.wap.wml',
  225. 'wmlc' => 'application/vnd.wap.wmlc',
  226. 'wmls' => 'text/vnd.wap.wmlscript',
  227. 'wmlsc' => 'application/vnd.wap.wmlscriptc',
  228. 'wma' => 'audio/x-ms-wma',
  229. 'wmv' => 'video/x-ms-wmv',
  230. 'wrl' => 'model/vrml',
  231. 'xbm' => 'image/x-xbitmap',
  232. 'xht' => 'application/xhtml+xml',
  233. 'xhtml' => 'application/xhtml+xml',
  234. 'xls' => 'application/vnd.ms-excel',
  235. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  236. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  237. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  238. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  239. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  240. 'xml' => 'text/xml',
  241. 'xpm' => 'image/x-xpixmap',
  242. 'xsl' => 'text/xml',
  243. 'xwd' => 'image/x-windowdump',
  244. 'xyz' => 'chemical/x-xyz',
  245. 'zip' => 'application/zip'
  246. );
  247. if ($filename === true) {
  248. return $mime_types;
  249. }
  250. //get the extension of the file
  251. $extension = explode('.', $filename);
  252. //$filename will be an array if a . was found
  253. if (is_array($extension)) {
  254. $extension = strtolower($extension[sizeof($extension) - 1]);
  255. } else {
  256. //file without extension
  257. $extension = 'empty';
  258. }
  259. //if the extension is found, return the content type
  260. if (isset($mime_types[$extension])) {
  261. return $mime_types[$extension];
  262. }
  263. //else return octet-stream
  264. return 'application/octet-stream';
  265. }
  266. /**
  267. * @param string
  268. * @param string
  269. * @return true if the user is allowed to see the document, false otherwise
  270. * @author Sergio A Kessler, first version
  271. * @author Roan Embrechts, bugfix
  272. * @todo not only check if a file is visible, but also check if the user is allowed to see the file??
  273. */
  274. public static function file_visible_to_user($this_course, $doc_url)
  275. {
  276. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  277. if ($is_allowed_to_edit) {
  278. return true;
  279. } else {
  280. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  281. $tbl_item_property = $this_course . 'item_property';
  282. $doc_url = Database::escape_string($doc_url);
  283. $query = "SELECT 1 FROM $tbl_document AS docs,$tbl_item_property AS props
  284. WHERE
  285. props.tool = 'document' AND
  286. docs.id=props.ref AND
  287. props.visibility <> '1' AND
  288. docs.path = '$doc_url'";
  289. $result = Database::query($query);
  290. return (Database::num_rows($result) == 0);
  291. }
  292. }
  293. /**
  294. * This function streams a file to the client
  295. *
  296. * @param string $full_file_name
  297. * @param boolean $forced
  298. * @param string $name
  299. *
  300. * @return false if file doesn't exist, true if stream succeeded
  301. */
  302. public static function file_send_for_download($full_file_name, $forced = false, $name = '')
  303. {
  304. session_write_close(); //we do not need write access to session anymore
  305. if (!is_file($full_file_name)) {
  306. return false;
  307. }
  308. $filename = ($name == '') ? basename($full_file_name) : api_replace_dangerous_char($name);
  309. $len = filesize($full_file_name);
  310. // Fixing error when file name contains a ","
  311. $filename = str_replace(',', '', $filename);
  312. global $_configuration;
  313. if ($forced) {
  314. // Force the browser to save the file instead of opening it
  315. if (isset($_configuration['enable_x_sendfile_headers']) &&
  316. !empty($_configuration['enable_x_sendfile_headers'])) {
  317. header("X-Sendfile: $filename");
  318. }
  319. header('Content-type: application/octet-stream');
  320. header('Content-length: ' . $len);
  321. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
  322. header('Content-Disposition: filename= ' . $filename);
  323. } else {
  324. header('Content-Disposition: attachment; filename= ' . $filename);
  325. }
  326. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
  327. header('Pragma: ');
  328. header('Cache-Control: ');
  329. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  330. }
  331. header('Content-Description: ' . $filename);
  332. header('Content-Transfer-Encoding: binary');
  333. $res = fopen($full_file_name, 'r');
  334. fpassthru($res);
  335. return true;
  336. } else {
  337. //no forced download, just let the browser decide what to do according to the mimetype
  338. $content_type = self::file_get_mime_type($filename);
  339. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  340. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  341. // Commented to avoid double caching declaration when playing with IE and HTTPS
  342. //header('Cache-Control: no-cache, must-revalidate');
  343. //header('Pragma: no-cache');
  344. switch ($content_type) {
  345. case 'text/html':
  346. if (isset($_configuration['lp_fixed_encoding']) && $_configuration['lp_fixed_encoding'] === 'true') {
  347. $content_type .= '; charset=UTF-8';
  348. } else {
  349. $encoding = @api_detect_encoding_html(file_get_contents($full_file_name));
  350. if (!empty($encoding)) {
  351. $content_type .= '; charset=' . $encoding;
  352. }
  353. }
  354. break;
  355. case 'text/plain':
  356. if (isset($_configuration['lp_fixed_encoding']) && $_configuration['lp_fixed_encoding'] === 'true') {
  357. $content_type .= '; charset=UTF-8';
  358. } else {
  359. $encoding = @api_detect_encoding(strip_tags(file_get_contents($full_file_name)));
  360. if (!empty($encoding)) {
  361. $content_type .= '; charset=' . $encoding;
  362. }
  363. }
  364. break;
  365. case 'application/vnd.dwg':
  366. case 'application/vnd.dwf':
  367. header('Content-type: application/octet-stream');
  368. break;
  369. }
  370. header('Content-type: ' . $content_type);
  371. header('Content-Length: ' . $len);
  372. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  373. if (strpos($user_agent, 'msie')) {
  374. header('Content-Disposition: ; filename= ' . $filename);
  375. } else {
  376. header('Content-Disposition: inline; filename= ' . $filename);
  377. }
  378. readfile($full_file_name);
  379. return true;
  380. }
  381. }
  382. /**
  383. * This function streams a string to the client for download.
  384. * You have to ensure that the calling script then stops processing (exit();)
  385. * otherwise it may cause subsequent use of the page to want to download
  386. * other pages in php rather than interpreting them.
  387. *
  388. * @param string $full_string The string contents
  389. * @param boolean $forced Whether "save" mode is forced (or opening directly authorized)
  390. * @param string $name The name of the file in the end (including extension)
  391. *
  392. * @return false if file doesn't exist, true if stream succeeded
  393. */
  394. public static function string_send_for_download($full_string, $forced = false, $name = '')
  395. {
  396. $filename = $name;
  397. $len = strlen($full_string);
  398. if ($forced) {
  399. //force the browser to save the file instead of opening it
  400. header('Content-type: application/octet-stream');
  401. //header('Content-Type: application/force-download');
  402. header('Content-length: ' . $len);
  403. if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
  404. header('Content-Disposition: filename= ' . $filename);
  405. } else {
  406. header('Content-Disposition: attachment; filename= ' . $filename);
  407. }
  408. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
  409. header('Pragma: ');
  410. header('Cache-Control: ');
  411. header('Cache-Control: public'); // IE cannot download from sessions without a cache
  412. }
  413. header('Content-Description: ' . $filename);
  414. header('Content-transfer-encoding: binary');
  415. echo $full_string;
  416. return true;
  417. //You have to ensure that the calling script then stops processing (exit();)
  418. //otherwise it may cause subsequent use of the page to want to download
  419. //other pages in php rather than interpreting them.
  420. } else {
  421. //no forced download, just let the browser decide what to do according to the mimetype
  422. $content_type = self::file_get_mime_type($filename);
  423. header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
  424. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  425. header('Cache-Control: no-cache, must-revalidate');
  426. header('Pragma: no-cache');
  427. switch ($content_type) {
  428. case 'text/html':
  429. $encoding = @api_detect_encoding_html($full_string);
  430. if (!empty($encoding)) {
  431. $content_type .= '; charset=' . $encoding;
  432. }
  433. break;
  434. case 'text/plain':
  435. $encoding = @api_detect_encoding(strip_tags($full_string));
  436. if (!empty($encoding)) {
  437. $content_type .= '; charset=' . $encoding;
  438. }
  439. break;
  440. }
  441. header('Content-type: ' . $content_type);
  442. header('Content-Length: ' . $len);
  443. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  444. if (strpos($user_agent, 'msie')) {
  445. header('Content-Disposition: ; filename= ' . $filename);
  446. } else {
  447. header('Content-Disposition: inline; filename= ' . $filename);
  448. }
  449. echo($full_string);
  450. //You have to ensure that the calling script then stops processing (exit();)
  451. //otherwise it may cause subsequent use of the page to want to download
  452. //other pages in php rather than interpreting them.
  453. return true;
  454. }
  455. }
  456. /**
  457. * Session folder filters
  458. *
  459. * @param string $path
  460. * @param int $sessionId
  461. *
  462. * @return null|string
  463. */
  464. public static function getSessionFolderFilters($path, $sessionId)
  465. {
  466. $sessionId = intval($sessionId);
  467. $condition = null;
  468. if (!empty($sessionId)) {
  469. // Chat folder filter
  470. if ($path == '/chat_files') {
  471. $condition .= " AND (id_session = '$sessionId') ";
  472. }
  473. // share_folder filter
  474. $condition .= " AND docs.path != '/shared_folder' ";
  475. }
  476. return $condition;
  477. }
  478. /**
  479. * Fetches all document data for the given user/group
  480. *
  481. * @param array $_course
  482. * @param string $path
  483. * @param int $to_group_id
  484. * @param int $to_user_id
  485. * @param boolean $can_see_invisible
  486. * @param boolean $search
  487. * @return array with all document data
  488. */
  489. public static function get_all_document_data(
  490. $_course,
  491. $path = '/',
  492. $to_group_id = 0,
  493. $to_user_id = null,
  494. $can_see_invisible = false,
  495. $search = false
  496. ) {
  497. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  498. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  499. $userGroupFilter = '';
  500. if (!is_null($to_user_id)) {
  501. $to_user_id = intval($to_user_id);
  502. $userGroupFilter = "last.to_user_id = $to_user_id";
  503. if (empty($to_user_id)) {
  504. $userGroupFilter = " (last.to_user_id = 0 OR last.to_user_id IS NULL) ";
  505. }
  506. } else {
  507. $to_group_id = intval($to_group_id);
  508. $userGroupFilter = "last.to_group_id = $to_group_id";
  509. if (empty($to_group_id)) {
  510. $userGroupFilter = "( last.to_group_id = 0 OR last.to_group_id IS NULL) ";
  511. }
  512. }
  513. // Escape underscores in the path so they don't act as a wildcard
  514. $originalPath = $path;
  515. $path = str_replace('_', '\_', $path);
  516. $visibility_bit = ' <> 2';
  517. // The given path will not end with a slash, unless it's the root '/'
  518. // so no root -> add slash
  519. $added_slash = $path == '/' ? '' : '/';
  520. // Condition for the session
  521. $sessionId = api_get_session_id();
  522. $condition_session = " AND (last.session_id = '$sessionId' OR (last.session_id = '0' OR last.session_id IS NULL) )";
  523. $condition_session .= self::getSessionFolderFilters($originalPath, $sessionId);
  524. $sharedCondition = null;
  525. if ($originalPath == '/shared_folder') {
  526. $students = CourseManager::get_user_list_from_course_code($_course['code'], $sessionId);
  527. if (!empty($students)) {
  528. $conditionList = array();
  529. foreach ($students as $studentId => $studentInfo) {
  530. $conditionList[] = '/shared_folder/sf_user_' . $studentInfo['user_id'];
  531. }
  532. $sharedCondition .= ' AND docs.path IN ("' . implode('","', $conditionList) . '")';
  533. }
  534. }
  535. $sql = "SELECT
  536. docs.id,
  537. docs.filetype,
  538. docs.path,
  539. docs.title,
  540. docs.comment,
  541. docs.size,
  542. docs.readonly,
  543. docs.session_id,
  544. last.session_id item_property_session_id,
  545. last.lastedit_date,
  546. last.visibility,
  547. last.insert_user_id
  548. FROM $TABLE_ITEMPROPERTY AS last
  549. INNER JOIN $TABLE_DOCUMENT AS docs
  550. ON (
  551. docs.id = last.ref AND
  552. last.tool = '".TOOL_DOCUMENT."' AND
  553. docs.c_id = {$_course['real_id']} AND
  554. last.c_id = {$_course['real_id']}
  555. )
  556. WHERE
  557. docs.path LIKE '" . Database::escape_string($path . $added_slash.'%'). "' AND
  558. docs.path NOT LIKE '" . Database::escape_string($path . $added_slash.'%/%')."' AND
  559. docs.path NOT LIKE '%_DELETED_%' AND
  560. $userGroupFilter AND
  561. last.visibility $visibility_bit
  562. $condition_session
  563. $sharedCondition
  564. ";
  565. $result = Database::query($sql);
  566. $doc_list = array();
  567. $document_data = array();
  568. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  569. $isCoach = api_is_coach();
  570. if ($result !== false && Database::num_rows($result) != 0) {
  571. while ($row = Database::fetch_array($result, 'ASSOC')) {
  572. if ($isCoach) {
  573. // Looking for course items that are invisible to hide it in the session
  574. if (in_array($row['id'], array_keys($doc_list))) {
  575. if ($doc_list[$row['id']]['item_property_session_id'] == 0 &&
  576. $doc_list[$row['id']]['session_id'] == 0
  577. ) {
  578. if ($doc_list[$row['id']]['visibility'] == 0) {
  579. unset($document_data[$row['id']]);
  580. continue;
  581. }
  582. }
  583. }
  584. $doc_list[$row['id']] = $row;
  585. }
  586. if (!$isCoach && !$is_allowed_to_edit) {
  587. $doc_list[] = $row;
  588. }
  589. if ($row['filetype'] == 'file' &&
  590. pathinfo($row['path'], PATHINFO_EXTENSION) == 'html'
  591. ) {
  592. // Templates management
  593. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  594. $sql = "SELECT id FROM $table_template
  595. WHERE
  596. course_code = '" . $_course['code'] . "' AND
  597. user_id = '".api_get_user_id()."' AND
  598. ref_doc = '".$row['id']."'";
  599. $template_result = Database::query($sql);
  600. $row['is_template'] = (Database::num_rows($template_result) > 0) ? 1 : 0;
  601. }
  602. // Just filling $document_data.
  603. $document_data[$row['id']] = $row;
  604. }
  605. // Only for the student we filter the results see BT#1652
  606. if (!$isCoach && !$is_allowed_to_edit) {
  607. $ids_to_remove = array();
  608. $my_repeat_ids = $temp = array();
  609. // Selecting repeated ids
  610. foreach ($doc_list as $row) {
  611. if (in_array($row['id'], array_keys($temp))) {
  612. $my_repeat_ids[] = $row['id'];
  613. }
  614. $temp[$row['id']] = $row;
  615. }
  616. //@todo use the DocumentManager::is_visible function
  617. // Checking visibility in a session
  618. foreach ($my_repeat_ids as $id) {
  619. foreach ($doc_list as $row) {
  620. if ($id == $row['id']) {
  621. if ($row['visibility'] == 0 && $row['item_property_session_id'] == 0) {
  622. $delete_repeated[$id] = true;
  623. }
  624. if ($row['visibility'] == 0 && $row['item_property_session_id'] != 0) {
  625. $delete_repeated[$id] = true;
  626. }
  627. }
  628. }
  629. }
  630. foreach ($doc_list as $key => $row) {
  631. if (in_array($row['visibility'], array('0', '2')) &&
  632. !in_array($row['id'], $my_repeat_ids)
  633. ) {
  634. $ids_to_remove[] = $row['id'];
  635. unset($doc_list[$key]);
  636. }
  637. }
  638. foreach ($document_data as $row) {
  639. if (in_array($row['id'], $ids_to_remove)) {
  640. unset($document_data[$row['id']]);
  641. }
  642. if (isset($delete_repeated[$row['id']]) && $delete_repeated[$row['id']]) {
  643. unset($document_data[$row['id']]);
  644. }
  645. }
  646. // Checking parents visibility.
  647. $final_document_data = array();
  648. foreach ($document_data as $row) {
  649. $is_visible = DocumentManager::check_visibility_tree(
  650. $row['id'],
  651. $_course['code'],
  652. $sessionId,
  653. api_get_user_id(),
  654. $to_group_id
  655. );
  656. if ($is_visible) {
  657. $final_document_data[$row['id']] = $row;
  658. }
  659. }
  660. } else {
  661. $final_document_data = $document_data;
  662. }
  663. return $final_document_data;
  664. } else {
  665. return false;
  666. }
  667. }
  668. /**
  669. * Gets the paths of all folders in a course
  670. * can show all folders (except for the deleted ones) or only visible ones
  671. *
  672. * @param array $_course
  673. * @param int $to_group_id
  674. * @param boolean $can_see_invisible
  675. *
  676. * @return array with paths
  677. */
  678. public static function get_all_document_folders(
  679. $_course,
  680. $to_group_id = 0,
  681. $can_see_invisible = false
  682. ) {
  683. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  684. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  685. $to_group_id = intval($to_group_id);
  686. $document_folders = array();
  687. $students = CourseManager::get_user_list_from_course_code(
  688. $_course['code'],
  689. api_get_session_id()
  690. );
  691. $sharedCondition = null;
  692. if (!empty($students)) {
  693. $conditionList = array();
  694. foreach ($students as $studentId => $studentInfo) {
  695. $conditionList[] = '/shared_folder/sf_user_' . $studentInfo['user_id'];
  696. }
  697. }
  698. $groupCondition = " last.to_group_id = $to_group_id";
  699. if (empty($to_group_id)) {
  700. $groupCondition = " (last.to_group_id = 0 OR last.to_group_id IS NULL)";
  701. }
  702. if ($can_see_invisible) {
  703. // condition for the session
  704. $session_id = api_get_session_id();
  705. $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id');
  706. $show_users_condition = "";
  707. if (api_get_setting('show_users_folders') == 'false') {
  708. $show_users_condition = " AND docs.path NOT LIKE '%shared_folder%'";
  709. }
  710. if ($to_group_id <> 0) {
  711. $sql = "SELECT DISTINCT docs.id, path
  712. FROM $TABLE_ITEMPROPERTY AS last
  713. INNER JOIN $TABLE_DOCUMENT AS docs
  714. ON (
  715. docs.id = last.ref AND
  716. last.tool = '" . TOOL_DOCUMENT . "' AND
  717. last.c_id = {$_course['real_id']} AND
  718. docs.c_id = {$_course['real_id']}
  719. )
  720. WHERE
  721. docs.filetype = 'folder' AND
  722. $groupCondition AND
  723. docs.path NOT LIKE '%shared_folder%' AND
  724. docs.path NOT LIKE '%_DELETED_%' AND
  725. last.visibility <> 2
  726. $condition_session ";
  727. } else {
  728. $sql = "SELECT DISTINCT docs.id, path
  729. FROM $TABLE_ITEMPROPERTY AS last
  730. INNER JOIN $TABLE_DOCUMENT AS docs
  731. ON (
  732. docs.id = last.ref AND
  733. last.tool = '" . TOOL_DOCUMENT . "' AND
  734. last.c_id = {$_course['real_id']} AND
  735. docs.c_id = {$_course['real_id']}
  736. )
  737. WHERE
  738. docs.filetype = 'folder' AND
  739. docs.path NOT LIKE '%_DELETED_%' AND
  740. $groupCondition AND
  741. last.visibility <> 2
  742. $show_users_condition $condition_session ";
  743. }
  744. $result = Database::query($sql);
  745. if ($result && Database::num_rows($result) != 0) {
  746. while ($row = Database::fetch_array($result, 'ASSOC')) {
  747. if (DocumentManager::is_folder_to_avoid($row['path'])) {
  748. continue;
  749. }
  750. if (strpos($row['path'], '/shared_folder/') !== false) {
  751. if (!in_array($row['path'], $conditionList)) {
  752. continue;
  753. }
  754. }
  755. $document_folders[$row['id']] = $row['path'];
  756. }
  757. if (!empty($document_folders)) {
  758. natsort($document_folders);
  759. }
  760. return $document_folders;
  761. } else {
  762. return false;
  763. }
  764. } else {
  765. // No invisible folders
  766. // Condition for the session
  767. $session_id = api_get_session_id();
  768. $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id');
  769. //get visible folders
  770. $sql = "SELECT DISTINCT docs.id, path
  771. FROM
  772. $TABLE_ITEMPROPERTY AS last, $TABLE_DOCUMENT AS docs
  773. WHERE
  774. docs.id = last.ref AND
  775. docs.filetype = 'folder' AND
  776. last.tool = '" . TOOL_DOCUMENT . "' AND
  777. $groupCondition AND
  778. last.visibility = 1
  779. $condition_session AND
  780. last.c_id = {$_course['real_id']} AND
  781. docs.c_id = {$_course['real_id']} ";
  782. $result = Database::query($sql);
  783. $visibleFolders = array();
  784. while ($row = Database::fetch_array($result, 'ASSOC')) {
  785. $visibleFolders[$row['id']] = $row['path'];
  786. }
  787. // Condition for the session
  788. $session_id = api_get_session_id();
  789. $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id');
  790. //get invisible folders
  791. $sql = "SELECT DISTINCT docs.id, path
  792. FROM $TABLE_ITEMPROPERTY AS last, $TABLE_DOCUMENT AS docs
  793. WHERE
  794. docs.id = last.ref AND
  795. docs.filetype = 'folder' AND
  796. last.tool = '" . TOOL_DOCUMENT . "' AND
  797. $groupCondition AND
  798. last.visibility = 0 $condition_session AND
  799. last.c_id = {$_course['real_id']} AND
  800. docs.c_id = {$_course['real_id']} ";
  801. $result = Database::query($sql);
  802. $invisibleFolders = array();
  803. while ($row = Database::fetch_array($result, 'ASSOC')) {
  804. //condition for the session
  805. $session_id = api_get_session_id();
  806. $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id');
  807. //get visible folders in the invisible ones -> they are invisible too
  808. $sql = "SELECT DISTINCT docs.id, path
  809. FROM $TABLE_ITEMPROPERTY AS last, $TABLE_DOCUMENT AS docs
  810. WHERE
  811. docs.id = last.ref AND
  812. docs.path LIKE '" . Database::escape_string($row['path'].'/%') . "' AND
  813. docs.filetype = 'folder' AND
  814. last.tool = '" . TOOL_DOCUMENT . "' AND
  815. $groupCondition AND
  816. last.visibility = 1 $condition_session AND
  817. last.c_id = {$_course['real_id']} AND
  818. docs.c_id = {$_course['real_id']} ";
  819. $folder_in_invisible_result = Database::query($sql);
  820. while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result, 'ASSOC')) {
  821. $invisibleFolders[$folders_in_invisible_folder['id']] = $folders_in_invisible_folder['path'];
  822. }
  823. }
  824. //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
  825. if (is_array($visibleFolders) && is_array($invisibleFolders)) {
  826. $document_folders = array_diff($visibleFolders, $invisibleFolders);
  827. natsort($document_folders);
  828. return $document_folders;
  829. } elseif (is_array($visibleFolders)) {
  830. natsort($visibleFolders);
  831. return $visibleFolders;
  832. } else {
  833. //no visible folders found
  834. return false;
  835. }
  836. }
  837. }
  838. /**
  839. * This check if a document has the readonly property checked, then see if the user
  840. * is the owner of this file, if all this is true then return true.
  841. *
  842. * @param array $_course
  843. * @param int $user_id id of the current user
  844. * @param string $file path stored in the database (if not defined, $documentId must be used)
  845. * @param int $document_id in case you dont have the file path ,
  846. * insert the id of the file here and leave $file in blank ''
  847. * @param bool $to_delete
  848. * @param int $sessionId
  849. * @return boolean true/false
  850. * */
  851. public static function check_readonly(
  852. $_course,
  853. $user_id,
  854. $file = null,
  855. $document_id = '',
  856. $to_delete = false,
  857. $sessionId = null,
  858. $documentId = null
  859. ) {
  860. if (empty($sessionId)) {
  861. $sessionId = api_get_session_id();
  862. } else {
  863. $sessionId = intval($sessionId);
  864. }
  865. if (empty($document_id) || !is_numeric($document_id)) {
  866. $document_id = self::get_document_id($_course, $file, $sessionId);
  867. } else {
  868. $document_id = intval($document_id);
  869. }
  870. $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  871. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  872. $course_id = $_course['real_id'];
  873. if ($to_delete) {
  874. if (self::is_folder($_course, $document_id)) {
  875. if (!empty($file)) {
  876. $path = Database::escape_string($file);
  877. // Check
  878. $sql = "SELECT td.id, readonly, tp.insert_user_id
  879. FROM $TABLE_DOCUMENT td, $TABLE_PROPERTY tp
  880. WHERE
  881. td.c_id = $course_id AND
  882. tp.c_id = $course_id AND
  883. td.session_id = $sessionId AND
  884. tp.ref= td.id AND
  885. (path='" . $path . "' OR path LIKE BINARY '" . $path . "/%' ) ";
  886. // Get all id's of documents that are deleted
  887. $what_to_check_result = Database::query($sql);
  888. if ($what_to_check_result && Database::num_rows($what_to_check_result) != 0) {
  889. // file with readonly set to 1 exist?
  890. $readonly_set = false;
  891. while ($row = Database::fetch_array($what_to_check_result)) {
  892. //query to delete from item_property table
  893. if ($row['readonly'] == 1) {
  894. if (!($row['insert_user_id'] == $user_id)) {
  895. $readonly_set = true;
  896. break;
  897. }
  898. }
  899. }
  900. if ($readonly_set) {
  901. return true;
  902. }
  903. }
  904. }
  905. return false;
  906. }
  907. }
  908. if (!empty($document_id)) {
  909. $sql = "SELECT a.insert_user_id, b.readonly
  910. FROM $TABLE_PROPERTY a, $TABLE_DOCUMENT b
  911. WHERE
  912. a.c_id = $course_id AND
  913. b.c_id = $course_id AND
  914. a.ref = b.id and a.ref = $document_id LIMIT 1";
  915. $result = Database::query($sql);
  916. $doc_details = Database ::fetch_array($result, 'ASSOC');
  917. if ($doc_details['readonly'] == 1) {
  918. return !($doc_details['insert_user_id'] == $user_id || api_is_platform_admin());
  919. }
  920. }
  921. return false;
  922. }
  923. /**
  924. * This check if a document is a folder or not
  925. * @param array $_course
  926. * @param int $document_id of the item
  927. * @return boolean true/false
  928. * */
  929. public static function is_folder($_course, $document_id)
  930. {
  931. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  932. $course_id = $_course['real_id'];
  933. $document_id = intval($document_id);
  934. $sql = "SELECT filetype FROM $TABLE_DOCUMENT
  935. WHERE c_id = $course_id AND id= $document_id";
  936. $result = Database::fetch_array(Database::query($sql), 'ASSOC');
  937. return $result['filetype'] == 'folder';
  938. }
  939. /**
  940. * @param int $document_id
  941. * @param array $course_info
  942. * @param int $session_id
  943. * @param bool $remove_content_from_db
  944. */
  945. public static function deleteDocumentFromDb(
  946. $document_id,
  947. $course_info = array(),
  948. $session_id = 0,
  949. $remove_content_from_db = false
  950. ) {
  951. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  952. $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  953. // Deleting from the DB
  954. $user_id = api_get_user_id();
  955. $document_id = intval($document_id);
  956. if (empty($course_info)) {
  957. $course_info = api_get_course_info();
  958. }
  959. if (empty($session_id)) {
  960. $session_id = api_get_session_id();
  961. }
  962. // Soft DB delete
  963. api_item_property_update(
  964. $course_info,
  965. TOOL_DOCUMENT,
  966. $document_id,
  967. 'delete',
  968. $user_id,
  969. null,
  970. null,
  971. null,
  972. null,
  973. $session_id
  974. );
  975. self::delete_document_from_search_engine($course_info['code'], $document_id);
  976. self::unset_document_as_template($document_id, $course_info['code'], $user_id);
  977. //Hard DB delete
  978. if ($remove_content_from_db) {
  979. $sql = "DELETE FROM $TABLE_ITEMPROPERTY
  980. WHERE
  981. c_id = {$course_info['real_id']} AND
  982. ref = ".$document_id." AND
  983. tool='".TOOL_DOCUMENT."'";
  984. Database::query($sql);
  985. $sql = "DELETE FROM $TABLE_DOCUMENT
  986. WHERE c_id = {$course_info['real_id']} AND id = ".$document_id;
  987. Database::query($sql);
  988. }
  989. }
  990. /**
  991. * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id
  992. * Files/folders that are inside a deleted folder get visibility 2
  993. *
  994. * @param array $_course
  995. * @param string $path, path stored in the database
  996. * @param string $base_work_dir, path to the documents folder (if not defined, $documentId must be used)
  997. * @param int $sessionId The ID of the session, if any
  998. * @param int $documentId The document id, if available
  999. * @param int $groupId
  1000. * @return boolean true/false
  1001. * @todo now only files/folders in a folder get visibility 2, we should rename them too.
  1002. * @todo We should be able to get rid of this later when using only documentId (check further usage)
  1003. */
  1004. public static function delete_document(
  1005. $_course,
  1006. $path = null,
  1007. $base_work_dir = null,
  1008. $sessionId = null,
  1009. $documentId = null,
  1010. $groupId = null
  1011. ) {
  1012. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  1013. if (empty($groupId)) {
  1014. $groupId = api_get_group_id();
  1015. } else {
  1016. $groupId = intval($groupId);
  1017. }
  1018. if (empty($sessionId)) {
  1019. $sessionId = api_get_session_id();
  1020. } else {
  1021. $sessionId = intval($sessionId);
  1022. }
  1023. $course_id = $_course['real_id'];
  1024. if (empty($course_id)) {
  1025. return false;
  1026. }
  1027. if (empty($base_work_dir)) {
  1028. return false;
  1029. }
  1030. if (empty($documentId)) {
  1031. $documentId = self::get_document_id($_course, $path, $sessionId);
  1032. $docInfo = self::get_document_data_by_id(
  1033. $documentId,
  1034. $_course['code'],
  1035. false,
  1036. $sessionId
  1037. );
  1038. $path = $docInfo['path'];
  1039. } else {
  1040. $docInfo = self::get_document_data_by_id(
  1041. $documentId,
  1042. $_course['code'],
  1043. false,
  1044. $sessionId
  1045. );
  1046. if (empty($docInfo)) {
  1047. return false;
  1048. }
  1049. $path = $docInfo['path'];
  1050. }
  1051. $documentId = intval($documentId);
  1052. if (empty($path) || empty($docInfo) || empty($documentId)) {
  1053. return false;
  1054. }
  1055. $itemInfo = api_get_item_property_info(
  1056. $_course['real_id'],
  1057. TOOL_DOCUMENT,
  1058. $documentId,
  1059. $sessionId
  1060. );
  1061. if (empty($itemInfo)) {
  1062. return false;
  1063. }
  1064. // File was already deleted.
  1065. if ($itemInfo['lastedit_type'] == 'DocumentDeleted' ||
  1066. $itemInfo['lastedit_type'] == 'delete' ||
  1067. $itemInfo['visibility'] == 2
  1068. ) {
  1069. return false;
  1070. }
  1071. // Filtering by group.
  1072. if ($itemInfo['to_group_id'] != $groupId) {
  1073. return false;
  1074. }
  1075. $document_exists_in_disk = file_exists($base_work_dir.$path);
  1076. $new_path = $path.'_DELETED_'.$documentId;
  1077. $file_deleted_from_db = false;
  1078. $file_deleted_from_disk = false;
  1079. $file_renamed_from_disk = false;
  1080. if ($documentId) {
  1081. // Deleting doc from the DB.
  1082. self::deleteDocumentFromDb($documentId, $_course, $sessionId);
  1083. // Checking
  1084. // $file_exists_in_db = self::get_document_data_by_id($documentId, $_course['code']);
  1085. $file_deleted_from_db = true;
  1086. }
  1087. // Looking for children.
  1088. if ($docInfo['filetype'] == 'folder') {
  1089. $cleanPath = Database::escape_string($path);
  1090. // Deleted files inside this folder.
  1091. $sql = "SELECT id FROM $TABLE_DOCUMENT
  1092. WHERE
  1093. c_id = $course_id AND
  1094. session_id = $sessionId AND
  1095. path LIKE BINARY '".$cleanPath."/%'";
  1096. // Get all id's of documents that are deleted.
  1097. $result = Database::query($sql);
  1098. if ($result && Database::num_rows($result) != 0) {
  1099. // Recursive delete.
  1100. while ($row = Database::fetch_array($result)) {
  1101. self::delete_document(
  1102. $_course,
  1103. null,
  1104. $base_work_dir,
  1105. $sessionId,
  1106. $row['id']
  1107. );
  1108. }
  1109. }
  1110. }
  1111. if ($document_exists_in_disk) {
  1112. if (api_get_setting('permanently_remove_deleted_files') == 'true') {
  1113. // Delete documents, do it like this so metadata gets deleted too
  1114. my_delete($base_work_dir.$path);
  1115. // Hard delete.
  1116. self::deleteDocumentFromDb($documentId, $_course, $sessionId, true);
  1117. $file_deleted_from_disk = true;
  1118. } else {
  1119. // Set visibility to 2 and rename file/folder to xxx_DELETED_#id (soft delete)
  1120. if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path)) {
  1121. if (rename($base_work_dir.$path, $base_work_dir.$new_path)) {
  1122. $new_path = Database::escape_string($new_path);
  1123. $sql = "UPDATE $TABLE_DOCUMENT
  1124. SET path = '".$new_path."'
  1125. WHERE
  1126. c_id = $course_id AND
  1127. session_id = $sessionId AND
  1128. id = ".$documentId;
  1129. Database::query($sql);
  1130. // Soft delete.
  1131. self::deleteDocumentFromDb($documentId, $_course, $sessionId);
  1132. // Change path of sub folders and documents in database.
  1133. $old_item_path = $docInfo['path'];
  1134. $new_item_path = $new_path.substr($old_item_path, strlen($path));
  1135. $new_item_path = Database::escape_string($new_item_path);
  1136. $sql = "UPDATE $TABLE_DOCUMENT
  1137. SET path = '".$new_item_path."'
  1138. WHERE
  1139. c_id = $course_id AND
  1140. session_id = $sessionId AND
  1141. id = ".$documentId;
  1142. Database::query($sql);
  1143. $file_renamed_from_disk = true;
  1144. } else {
  1145. // Couldn't rename - file permissions problem?
  1146. error_log(
  1147. __FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',
  1148. 0
  1149. );
  1150. }
  1151. }
  1152. }
  1153. }
  1154. // Checking inconsistency
  1155. //error_log('Doc status: (1 del db :'.($file_deleted_from_db?'yes':'no').') - (2 del disk: '.($file_deleted_from_disk?'yes':'no').') - (3 ren disk: '.($file_renamed_from_disk?'yes':'no').')');
  1156. if ($file_deleted_from_db && $file_deleted_from_disk ||
  1157. $file_deleted_from_db && $file_renamed_from_disk
  1158. ) {
  1159. return true;
  1160. } else {
  1161. //Something went wrong
  1162. //The file or directory isn't there anymore (on the filesystem)
  1163. // This means it has been removed externally. To prevent a
  1164. // blocking error from happening, we drop the related items from the
  1165. // item_property and the document table.
  1166. error_log(
  1167. __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',
  1168. 0
  1169. );
  1170. return false;
  1171. }
  1172. }
  1173. /**
  1174. * Removes documents from search engine database
  1175. *
  1176. * @param string $course_id Course code
  1177. * @param int $document_id Document id to delete
  1178. */
  1179. public static function delete_document_from_search_engine($course_id, $document_id)
  1180. {
  1181. // remove from search engine if enabled
  1182. if (api_get_setting('search_enabled') == 'true') {
  1183. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1184. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  1185. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  1186. $res = Database::query($sql);
  1187. if (Database::num_rows($res) > 0) {
  1188. $row2 = Database::fetch_array($res);
  1189. require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
  1190. $di = new ChamiloIndexer();
  1191. $di->remove_document((int) $row2['search_did']);
  1192. }
  1193. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  1194. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_DOCUMENT, $document_id);
  1195. Database::query($sql);
  1196. // remove terms from db
  1197. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  1198. delete_all_values_for_item($course_id, TOOL_DOCUMENT, $document_id);
  1199. }
  1200. }
  1201. /**
  1202. * Gets the id of a document with a given path
  1203. *
  1204. * @param array $courseInfo
  1205. * @param string $path
  1206. * @param int $sessionId
  1207. * @return int id of document / false if no doc found
  1208. */
  1209. public static function get_document_id($courseInfo, $path, $sessionId = null)
  1210. {
  1211. $table = Database :: get_course_table(TABLE_DOCUMENT);
  1212. $courseId = $courseInfo['real_id'];
  1213. if (!isset($sessionId)) {
  1214. $sessionId = api_get_session_id();
  1215. } else {
  1216. $sessionId = intval($sessionId);
  1217. }
  1218. $path = Database::escape_string($path);
  1219. if (!empty($courseId) && !empty($path)) {
  1220. $sql = "SELECT id FROM $table
  1221. WHERE
  1222. c_id = $courseId AND
  1223. path LIKE BINARY '$path' AND
  1224. session_id = $sessionId
  1225. LIMIT 1";
  1226. $result = Database::query($sql);
  1227. if (Database::num_rows($result)) {
  1228. $row = Database::fetch_array($result);
  1229. return intval($row['id']);
  1230. }
  1231. }
  1232. return false;
  1233. }
  1234. /**
  1235. * Gets the document data with a given id
  1236. *
  1237. * @param int $id Document Id (id field in c_document table)
  1238. * @param string $course_code Course code
  1239. * @param bool $load_parents load folder parents.
  1240. * @param int $session_id The session ID,
  1241. * 0 if requires context *out of* session, and null to use global context
  1242. * @return array document content
  1243. */
  1244. public static function get_document_data_by_id(
  1245. $id,
  1246. $course_code,
  1247. $load_parents = false,
  1248. $session_id = null
  1249. ) {
  1250. $course_info = api_get_course_info($course_code);
  1251. $course_id = $course_info['real_id'];
  1252. if (empty($course_info)) {
  1253. return false;
  1254. }
  1255. if (isset($session_id)) {
  1256. $session_id = intval($session_id);
  1257. } else {
  1258. $session_id = api_get_session_id();
  1259. }
  1260. $www = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/document';
  1261. $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
  1262. $id = intval($id);
  1263. $sql = "SELECT * FROM $TABLE_DOCUMENT
  1264. WHERE c_id = $course_id AND session_id = $session_id AND id = $id";
  1265. $result = Database::query($sql);
  1266. if ($result && Database::num_rows($result) == 1) {
  1267. $row = Database::fetch_array($result, 'ASSOC');
  1268. //@todo need to clarify the name of the URLs not nice right now
  1269. $url_path = urlencode($row['path']);
  1270. $path = str_replace('%2F', '/', $url_path);
  1271. $pathinfo = pathinfo($row['path']);
  1272. $row['url'] = api_get_path(WEB_CODE_PATH) . 'document/showinframes.php?cidReq=' . $course_code . '&id=' . $id;
  1273. $row['document_url'] = api_get_path(WEB_CODE_PATH) . 'document/document.php?cidReq=' . $course_code . '&id=' . $id;
  1274. $row['absolute_path'] = api_get_path(SYS_COURSE_PATH) . $course_info['path'] . '/document' . $row['path'];
  1275. $row['absolute_path_from_document'] = '/document' . $row['path'];
  1276. $row['absolute_parent_path'] = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$pathinfo['dirname'] . '/';
  1277. $row['direct_url'] = $www . $path;
  1278. if (dirname($row['path']) == '.') {
  1279. $row['parent_id'] = '0';
  1280. } else {
  1281. $row['parent_id'] = self::get_document_id($course_info, dirname($row['path']), $session_id);
  1282. }
  1283. $parents = array();
  1284. //Use to generate parents (needed for the breadcrumb)
  1285. //@todo sorry but this for is here because there's not a parent_id in the document table so we parsed the path!!
  1286. if ($load_parents) {
  1287. $dir_array = explode('/', $row['path']);
  1288. $dir_array = array_filter($dir_array);
  1289. $array_len = count($dir_array) + 1;
  1290. $real_dir = '';
  1291. for ($i = 1; $i < $array_len; $i++) {
  1292. $real_dir .= '/' . $dir_array[$i];
  1293. $parent_id = self::get_document_id($course_info, $real_dir);
  1294. if ($session_id != 0 && empty($parent_id)) {
  1295. $parent_id = self::get_document_id($course_info, $real_dir, 0);
  1296. }
  1297. if (!empty($parent_id)) {
  1298. $sub_document_data = self::get_document_data_by_id(
  1299. $parent_id,
  1300. $course_code,
  1301. false,
  1302. $session_id
  1303. );
  1304. if ($session_id != 0 and !$sub_document_data) {
  1305. $sub_document_data = self::get_document_data_by_id(
  1306. $parent_id,
  1307. $course_code,
  1308. false,
  1309. 0
  1310. );
  1311. }
  1312. //@todo add visibility here
  1313. $parents[] = $sub_document_data;
  1314. }
  1315. }
  1316. }
  1317. $row['parents'] = $parents;
  1318. return $row;
  1319. }
  1320. return false;
  1321. }
  1322. /**
  1323. * Allow to set a specific document as a new template for CKeditor
  1324. * for a particular user in a particular course
  1325. *
  1326. * @param string $title
  1327. * @param string $description
  1328. * @param int $document_id_for_template the document id
  1329. * @param string $course_code
  1330. * @param int $user_id
  1331. * @return bool
  1332. */
  1333. public static function set_document_as_template($title, $description, $document_id_for_template, $course_code, $user_id, $image)
  1334. {
  1335. // Database table definition
  1336. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  1337. $params = [
  1338. 'title' => $title,
  1339. 'description' => $description,
  1340. 'course_code' => $course_code,
  1341. 'user_id' => $user_id,
  1342. 'ref_doc' => $document_id_for_template,
  1343. 'image' => $image,
  1344. ];
  1345. Database::insert($table_template, $params);
  1346. return true;
  1347. }
  1348. /**
  1349. * Unset a document as template
  1350. *
  1351. * @param int $document_id
  1352. * @param string $course_code
  1353. * @param int $user_id
  1354. */
  1355. public static function unset_document_as_template($document_id, $course_code, $user_id)
  1356. {
  1357. $table_template = Database::get_main_table(TABLE_MAIN_TEMPLATES);
  1358. $course_code = Database::escape_string($course_code);
  1359. $user_id = intval($user_id);
  1360. $document_id = intval($document_id);
  1361. $sql = 'SELECT id FROM ' . $table_template . '
  1362. WHERE
  1363. course_code="' . $course_code . '" AND
  1364. user_id="' . $user_id . '" AND
  1365. ref_doc="' . $document_id . '"';
  1366. $result = Database::query($sql);
  1367. $template_id = Database::result($result, 0, 0);
  1368. my_delete(api_get_path(SYS_CODE_PATH) . 'upload/template_thumbnails/' . $template_id . '.jpg');
  1369. $sql = 'DELETE FROM ' . $table_template . '
  1370. WHERE
  1371. course_code="' . $course_code . '" AND
  1372. user_id="' . $user_id . '" AND
  1373. ref_doc="' . $document_id . '"';
  1374. Database::query($sql);
  1375. }
  1376. /**
  1377. * Return true if the documentpath have visibility=1 as
  1378. * item_property (you should use the is_visible_by_id)
  1379. *
  1380. * @param string $document_path the relative complete path of the document
  1381. * @param array $course the _course array info of the document's course
  1382. * @param int
  1383. * @param string
  1384. * @return bool
  1385. */
  1386. public static function is_visible($doc_path, $course, $session_id = 0, $file_type = 'file')
  1387. {
  1388. $docTable = Database::get_course_table(TABLE_DOCUMENT);
  1389. $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1390. $course_id = $course['real_id'];
  1391. //note the extra / at the end of doc_path to match every path in the document table that is part of the document path
  1392. $session_id = intval($session_id);
  1393. $condition = "AND d.session_id IN ('$session_id', '0') ";
  1394. // The " d.filetype='file' " let the user see a file even if the folder is hidden see #2198
  1395. /*
  1396. When using hotpotatoes files, a new html files are generated
  1397. in the hotpotatoes folder to display the test.
  1398. The genuine html file is copied to math4.htm(user_id).t.html
  1399. Images files are not copied, and keep same name.
  1400. To check the html file visibility, we don't have to check file math4.htm(user_id).t.html but file math4.htm
  1401. In this case, we have to remove (user_id).t.html to check the visibility of the file
  1402. For images, we just check the path of the image file.
  1403. Exemple of hotpotatoes folder :
  1404. A.jpg
  1405. maths4-consigne.jpg
  1406. maths4.htm
  1407. maths4.htm1.t.html
  1408. maths4.htm52.t.html
  1409. maths4.htm654.t.html
  1410. omega.jpg
  1411. theta.jpg
  1412. */
  1413. if (strpos($doc_path, 'HotPotatoes_files') && preg_match("/\.t\.html$/", $doc_path)) {
  1414. $doc_path = substr($doc_path, 0, strlen($doc_path) - 7 - strlen(api_get_user_id()));
  1415. }
  1416. if (!in_array($file_type, array('file', 'folder'))) {
  1417. $file_type = 'file';
  1418. }
  1419. $sql = "SELECT visibility
  1420. FROM $docTable d
  1421. INNER JOIN $propTable ip
  1422. ON (d.id = ip.ref AND d.c_id = $course_id AND ip.c_id = $course_id)
  1423. WHERE
  1424. ip.tool = '" . TOOL_DOCUMENT . "' $condition AND
  1425. filetype = '$file_type' AND
  1426. locate(concat(path,'/'), '" . Database::escape_string($doc_path.'/'). "')=1
  1427. ";
  1428. $result = Database::query($sql);
  1429. $is_visible = false;
  1430. if (Database::num_rows($result) > 0) {
  1431. $row = Database::fetch_array($result, 'ASSOC');
  1432. if ($row['visibility'] == 1) {
  1433. $is_visible = $_SESSION['is_allowed_in_course'] || api_is_platform_admin();
  1434. }
  1435. }
  1436. /* improved protection of documents viewable directly through the url:
  1437. incorporates the same protections of the course at the url of
  1438. documents:
  1439. access allowed for the whole world Open, access allowed for
  1440. users registered on the platform Private access, document accessible
  1441. only to course members (see the Users list), Completely closed;
  1442. the document is only accessible to the course admin and
  1443. teaching assistants.*/
  1444. //return $_SESSION ['is_allowed_in_course'] || api_is_platform_admin();
  1445. return $is_visible;
  1446. }
  1447. /**
  1448. * Return true if user can see a file
  1449. *
  1450. * @param int document id
  1451. * @param array course info
  1452. * @param int
  1453. * @param int
  1454. * @param bool
  1455. * @return bool
  1456. */
  1457. public static function is_visible_by_id(
  1458. $doc_id,
  1459. $course_info,
  1460. $session_id,
  1461. $user_id,
  1462. $admins_can_see_everything = true
  1463. ) {
  1464. $user_in_course = false;
  1465. //1. Checking the course array
  1466. if (empty($course_info)) {
  1467. $course_info = api_get_course_info();
  1468. if (empty($course_info)) {
  1469. return false;
  1470. }
  1471. }
  1472. $doc_id = intval($doc_id);
  1473. $session_id = intval($session_id);
  1474. //2. Course and Session visibility are handle in local.inc.php/global.inc.php
  1475. //3. Checking if user exist in course/session
  1476. if ($session_id == 0) {
  1477. if (CourseManager::is_user_subscribed_in_course($user_id, $course_info['code']) || api_is_platform_admin()
  1478. ) {
  1479. $user_in_course = true;
  1480. }
  1481. // Check if course is open then we can consider that the student is registered to the course
  1482. if (isset($course_info) &&
  1483. in_array(
  1484. $course_info['visibility'],
  1485. array(COURSE_VISIBILITY_OPEN_PLATFORM, COURSE_VISIBILITY_OPEN_WORLD)
  1486. )
  1487. ) {
  1488. $user_in_course = true;
  1489. }
  1490. } else {
  1491. $user_status = SessionManager::get_user_status_in_course_session(
  1492. $user_id,
  1493. $course_info['real_id'],
  1494. $session_id
  1495. );
  1496. if (in_array($user_status, array('0', '2', '6'))) {
  1497. //is true if is an student, course session teacher or coach
  1498. $user_in_course = true;
  1499. }
  1500. if (api_is_platform_admin()) {
  1501. $user_in_course = true;
  1502. }
  1503. }
  1504. // 4. Checking document visibility (i'm repeating the code in order to be more clear when reading ) - jm
  1505. if ($user_in_course) {
  1506. // 4.1 Checking document visibility for a Course
  1507. if ($session_id == 0) {
  1508. $item_info = api_get_item_property_info($course_info['real_id'], 'document', $doc_id, 0);
  1509. if (isset($item_info['visibility'])) {
  1510. // True for admins if document exists
  1511. if ($admins_can_see_everything && api_is_platform_admin()) {
  1512. return true;
  1513. }
  1514. if ($item_info['visibility'] == 1) {
  1515. return true;
  1516. }
  1517. }
  1518. } else {
  1519. // 4.2 Checking document visibility for a Course in a Session
  1520. $item_info = api_get_item_property_info(
  1521. $course_info['real_id'],
  1522. 'document',
  1523. $doc_id,
  1524. 0
  1525. );
  1526. $item_info_in_session = api_get_item_property_info(
  1527. $course_info['real_id'],
  1528. 'document',
  1529. $doc_id,
  1530. $session_id
  1531. );
  1532. // True for admins if document exists
  1533. if (isset($item_info['visibility'])) {
  1534. if ($admins_can_see_everything && api_is_platform_admin()) {
  1535. return true;
  1536. }
  1537. }
  1538. if (isset($item_info_in_session['visibility'])) {
  1539. if ($item_info_in_session['visibility'] == 1) {
  1540. return true;
  1541. }
  1542. } else {
  1543. if ($item_info['visibility'] == 1) {
  1544. return true;
  1545. }
  1546. }
  1547. }
  1548. } elseif ($admins_can_see_everything && api_is_platform_admin()) {
  1549. return true;
  1550. }
  1551. return false;
  1552. }
  1553. /**
  1554. * Allow attach a certificate to a course
  1555. * @param string $course_id
  1556. * @param int $document_id
  1557. * @param int $session_id
  1558. *
  1559. * @return void()
  1560. */
  1561. public static function attach_gradebook_certificate($course_id, $document_id, $session_id = 0)
  1562. {
  1563. $tbl_category = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1564. $session_id = intval($session_id);
  1565. if (empty($session_id)) {
  1566. $session_id = api_get_session_id();
  1567. }
  1568. if (empty($session_id)) {
  1569. $sql_session = 'AND (session_id = 0 OR isnull(session_id)) ';
  1570. } elseif ($session_id > 0) {
  1571. $sql_session = 'AND session_id=' . intval($session_id);
  1572. } else {
  1573. $sql_session = '';
  1574. }
  1575. $sql = 'UPDATE ' . $tbl_category . ' SET document_id="' . intval($document_id) . '"
  1576. WHERE course_code="' . Database::escape_string($course_id) . '" ' . $sql_session;
  1577. Database::query($sql);
  1578. }
  1579. /**
  1580. * get the document id of default certificate
  1581. * @param string $course_id
  1582. * @param int $session_id
  1583. *
  1584. * @return int The default certificate id
  1585. */
  1586. public static function get_default_certificate_id($course_id, $session_id = 0)
  1587. {
  1588. $tbl_category = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1589. $session_id = intval($session_id);
  1590. if (empty($session_id)) {
  1591. $session_id = api_get_session_id();
  1592. }
  1593. if (empty($session_id)) {
  1594. $sql_session = 'AND (session_id = 0 OR isnull(session_id)) ';
  1595. } elseif ($session_id > 0) {
  1596. $sql_session = 'AND session_id=' . intval($session_id);
  1597. } else {
  1598. $sql_session = '';
  1599. }
  1600. $sql = 'SELECT document_id FROM ' . $tbl_category . '
  1601. WHERE course_code="' . Database::escape_string($course_id) . '" ' . $sql_session;
  1602. $rs = Database::query($sql);
  1603. $num = Database::num_rows($rs);
  1604. if ($num == 0) {
  1605. return null;
  1606. }
  1607. $row = Database::fetch_array($rs);
  1608. return $row['document_id'];
  1609. }
  1610. /**
  1611. * allow replace user info in file html
  1612. * @param int $user_id
  1613. * @param string $course_code
  1614. * @param bool $is_preview
  1615. * @return string The html content of the certificate
  1616. */
  1617. public static function replace_user_info_into_html($user_id, $course_code, $is_preview = false)
  1618. {
  1619. $user_id = intval($user_id);
  1620. $course_info = api_get_course_info($course_code);
  1621. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  1622. $course_id = $course_info['real_id'];
  1623. $document_id = self::get_default_certificate_id($course_code);
  1624. $my_content_html = null;
  1625. if ($document_id) {
  1626. $sql = "SELECT path FROM $tbl_document
  1627. WHERE c_id = $course_id AND id = $document_id";
  1628. $rs = Database::query($sql);
  1629. $new_content = '';
  1630. $all_user_info = array();
  1631. if (Database::num_rows($rs)) {
  1632. $row = Database::fetch_array($rs);
  1633. $filepath = api_get_path(SYS_COURSE_PATH) . $course_info['path'] . '/document' . $row['path'];
  1634. if (is_file($filepath)) {
  1635. $my_content_html = file_get_contents($filepath);
  1636. }
  1637. $all_user_info = self::get_all_info_to_certificate($user_id, $course_code, $is_preview);
  1638. $info_to_be_replaced_in_content_html = $all_user_info[0];
  1639. $info_to_replace_in_content_html = $all_user_info[1];
  1640. $new_content = str_replace(
  1641. $info_to_be_replaced_in_content_html,
  1642. $info_to_replace_in_content_html,
  1643. $my_content_html
  1644. );
  1645. }
  1646. return array(
  1647. 'content' => $new_content,
  1648. 'variables' => $all_user_info,
  1649. );
  1650. }
  1651. return array();
  1652. }
  1653. /**
  1654. * Return all content to replace and all content to be replace
  1655. * @param int $user_id
  1656. * @param int $course_id
  1657. * @param bool $is_preview
  1658. * @return array
  1659. */
  1660. static function get_all_info_to_certificate($user_id, $course_id, $is_preview = false)
  1661. {
  1662. $info_list = array();
  1663. $user_id = intval($user_id);
  1664. $course_info = api_get_course_info($course_id);
  1665. //info portal
  1666. $organization_name = api_get_setting('Institution');
  1667. $portal_name = api_get_setting('siteName');
  1668. //Extra user data information
  1669. $extra_user_info_data = UserManager::get_extra_user_data(
  1670. $user_id,
  1671. false,
  1672. false,
  1673. false,
  1674. true
  1675. );
  1676. //Student information
  1677. $user_info = api_get_user_info($user_id);
  1678. $first_name = $user_info['firstname'];
  1679. $last_name = $user_info['lastname'];
  1680. $official_code = $user_info['official_code'];
  1681. //Teacher information
  1682. $info_teacher_id = UserManager::get_user_id_of_course_admin_or_session_admin($course_info);
  1683. $teacher_info = api_get_user_info($info_teacher_id);
  1684. $teacher_first_name = $teacher_info['firstname'];
  1685. $teacher_last_name = $teacher_info['lastname'];
  1686. // info gradebook certificate
  1687. $info_grade_certificate = UserManager::get_info_gradebook_certificate($course_id, $user_id);
  1688. $date_certificate = $info_grade_certificate['created_at'];
  1689. $date_long_certificate = '';
  1690. $date_no_time = api_convert_and_format_date(api_get_utc_datetime(), DATE_FORMAT_LONG_NO_DAY);
  1691. if (!empty($date_certificate)) {
  1692. $date_long_certificate = api_convert_and_format_date($date_certificate);
  1693. $date_no_time = api_convert_and_format_date($date_certificate, DATE_FORMAT_LONG_NO_DAY);
  1694. }
  1695. if ($is_preview) {
  1696. $date_long_certificate = api_convert_and_format_date(api_get_utc_datetime());
  1697. $date_no_time = api_convert_and_format_date(api_get_utc_datetime(), DATE_FORMAT_LONG_NO_DAY);
  1698. }
  1699. $url = api_get_path(WEB_PATH) . 'certificates/index.php?id=' . $info_grade_certificate['id'];
  1700. //replace content
  1701. $info_to_replace_in_content_html = array($first_name,
  1702. $last_name,
  1703. $organization_name,
  1704. $portal_name,
  1705. $teacher_first_name,
  1706. $teacher_last_name,
  1707. $official_code,
  1708. $date_long_certificate,
  1709. $date_no_time,
  1710. $course_id,
  1711. $course_info['name'],
  1712. $info_grade_certificate['grade'],
  1713. $url,
  1714. '<a href="' . $url . '" target="_blank">' . get_lang('CertificateOnlineLink') . '</a>',
  1715. '((certificate_barcode))',
  1716. );
  1717. $info_to_be_replaced_in_content_html = array('((user_firstname))',
  1718. '((user_lastname))',
  1719. '((gradebook_institution))',
  1720. '((gradebook_sitename))',
  1721. '((teacher_firstname))',
  1722. '((teacher_lastname))',
  1723. '((official_code))',
  1724. '((date_certificate))',
  1725. '((date_certificate_no_time))',
  1726. '((course_code))',
  1727. '((course_title))',
  1728. '((gradebook_grade))',
  1729. '((certificate_link))',
  1730. '((certificate_link_html))',
  1731. '((certificate_barcode))',
  1732. );
  1733. if (!empty($extra_user_info_data)) {
  1734. foreach ($extra_user_info_data as $key_extra => $value_extra) {
  1735. $info_to_be_replaced_in_content_html[] = '((' . strtolower($key_extra) . '))';
  1736. $info_to_replace_in_content_html[] = $value_extra;
  1737. }
  1738. }
  1739. $info_list[] = $info_to_be_replaced_in_content_html;
  1740. $info_list[] = $info_to_replace_in_content_html;
  1741. return $info_list;
  1742. }
  1743. /**
  1744. * Remove default certificate
  1745. * @param string $course_id The course code
  1746. * @param int $default_certificate_id The document id of the default certificate
  1747. * @return void()
  1748. */
  1749. public static function remove_attach_certificate($course_id, $default_certificate_id)
  1750. {
  1751. if (empty($default_certificate_id)) {
  1752. return false;
  1753. }
  1754. $default_certificate = self::get_default_certificate_id($course_id);
  1755. if ((int) $default_certificate == (int) $default_certificate_id) {
  1756. $tbl_category = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1757. $session_id = api_get_session_id();
  1758. if ($session_id == 0 || is_null($session_id)) {
  1759. $sql_session = 'AND (session_id=' . intval($session_id) . ' OR isnull(session_id)) ';
  1760. } elseif ($session_id > 0) {
  1761. $sql_session = 'AND session_id=' . intval($session_id);
  1762. } else {
  1763. $sql_session = '';
  1764. }
  1765. $sql = 'UPDATE ' . $tbl_category . ' SET document_id=null
  1766. WHERE
  1767. course_code = "' . Database::escape_string($course_id) . '" AND
  1768. document_id="' . $default_certificate_id . '" ' . $sql_session;
  1769. Database::query($sql);
  1770. }
  1771. }
  1772. /**
  1773. * Create directory certificate
  1774. * @param string $courseCode
  1775. * @return void()
  1776. */
  1777. public static function create_directory_certificate_in_course($courseCode)
  1778. {
  1779. $courseInfo = api_get_course_info($courseCode);
  1780. if (!empty($courseInfo)) {
  1781. $to_group_id = 0;
  1782. $to_user_id = null;
  1783. $course_dir = $courseInfo['path'] . "/document/";
  1784. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  1785. $base_work_dir = $sys_course_path . $course_dir;
  1786. $base_work_dir_test = $base_work_dir . 'certificates';
  1787. $dir_name = '/certificates';
  1788. $post_dir_name = get_lang('CertificatesFiles');
  1789. $visibility_command = 'invisible';
  1790. $id = self::get_document_id_of_directory_certificate();
  1791. if (empty($id)) {
  1792. create_unexisting_directory(
  1793. $courseInfo,
  1794. api_get_user_id(),
  1795. api_get_session_id(),
  1796. $to_group_id,
  1797. $to_user_id,
  1798. $base_work_dir,
  1799. $dir_name,
  1800. $post_dir_name,
  1801. null,
  1802. false
  1803. );
  1804. $id = self::get_document_id_of_directory_certificate();
  1805. if (empty($id)) {
  1806. $id = add_document(
  1807. $courseInfo,
  1808. $dir_name,
  1809. 'folder',
  1810. 0,
  1811. $post_dir_name,
  1812. null,
  1813. 0,
  1814. true,
  1815. $to_group_id
  1816. );
  1817. }
  1818. if (!empty($id)) {
  1819. api_item_property_update(
  1820. $courseInfo,
  1821. TOOL_DOCUMENT,
  1822. $id,
  1823. $visibility_command,
  1824. api_get_user_id()
  1825. );
  1826. }
  1827. }
  1828. }
  1829. }
  1830. /**
  1831. * Get the document id of the directory certificate
  1832. * @return int The document id of the directory certificate
  1833. */
  1834. public static function get_document_id_of_directory_certificate()
  1835. {
  1836. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  1837. $course_id = api_get_course_int_id();
  1838. $sql = "SELECT id FROM $tbl_document WHERE c_id = $course_id AND path='/certificates' ";
  1839. $rs = Database::query($sql);
  1840. $row = Database::fetch_array($rs);
  1841. return $row['id'];
  1842. }
  1843. /**
  1844. * Check if a directory given is for certificate
  1845. * @param string $dir path of directory
  1846. * @return bool true if is a certificate or false otherwise
  1847. */
  1848. public static function is_certificate_mode($dir)
  1849. {
  1850. // I'm in the certification module?
  1851. $is_certificate_mode = false;
  1852. $is_certificate_array = explode('/', $dir);
  1853. array_shift($is_certificate_array);
  1854. if (isset($is_certificate_array[0]) && $is_certificate_array[0] == 'certificates') {
  1855. $is_certificate_mode = true;
  1856. }
  1857. return $is_certificate_mode;
  1858. }
  1859. /**
  1860. * Gets the list of included resources as a list of absolute or relative paths from a html file or string html
  1861. * This allows for a better SCORM export or replace urls inside content html from copy course
  1862. * The list will generally include pictures, flash objects, java applets, or any other
  1863. * stuff included in the source of the current item. The current item is expected
  1864. * to be an HTML file or string html. If it is not, then the function will return and empty list.
  1865. * @param string source html (content or path)
  1866. * @param bool is file or string html
  1867. * @param string type (one of the app tools) - optional (otherwise takes the current item's type)
  1868. * @param int level of recursivity we're in
  1869. * @return array List of file paths. An additional field containing 'local' or 'remote' helps determine
  1870. * if the file should be copied into the zip or just linked
  1871. */
  1872. public static function get_resources_from_source_html($source_html, $is_file = false, $type = null, $recursivity = 1)
  1873. {
  1874. $max = 5;
  1875. $attributes = array();
  1876. $wanted_attributes = array('src', 'url', '@import', 'href', 'value', 'flashvars');
  1877. $explode_attributes = array('flashvars' => 'file');
  1878. $abs_path = '';
  1879. if ($recursivity > $max) {
  1880. return array();
  1881. }
  1882. if (!isset($type)) {
  1883. $type = TOOL_DOCUMENT;
  1884. }
  1885. if (!$is_file) {
  1886. $attributes = self::parse_HTML_attributes($source_html, $wanted_attributes, $explode_attributes);
  1887. } else {
  1888. if (is_file($source_html)) {
  1889. $abs_path = $source_html;
  1890. //for now, read the whole file in one go (that's gonna be a problem when the file is too big)
  1891. $info = pathinfo($abs_path);
  1892. $ext = $info['extension'];
  1893. switch (strtolower($ext)) {
  1894. case 'html':
  1895. case 'htm':
  1896. case 'shtml':
  1897. case 'css':
  1898. $file_content = file_get_contents($abs_path);
  1899. //get an array of attributes from the HTML source
  1900. $attributes = self::parse_HTML_attributes($file_content, $wanted_attributes, $explode_attributes);
  1901. break;
  1902. default:
  1903. break;
  1904. }
  1905. } else {
  1906. return false;
  1907. }
  1908. }
  1909. $files_list = array();
  1910. switch ($type) {
  1911. case TOOL_DOCUMENT:
  1912. case TOOL_QUIZ:
  1913. case 'sco':
  1914. foreach ($wanted_attributes as $attr) {
  1915. if (isset($attributes[$attr])) {
  1916. //find which kind of path these are (local or remote)
  1917. $sources = $attributes[$attr];
  1918. foreach ($sources as $source) {
  1919. //skip what is obviously not a resource
  1920. if (strpos($source, '+this.')) {
  1921. continue; //javascript code - will still work unaltered
  1922. }
  1923. if (strpos($source, '.') === false) {
  1924. continue; //no dot, should not be an external file anyway
  1925. }
  1926. if (strpos($source, 'mailto:')) {
  1927. continue; //mailto link
  1928. }
  1929. if (strpos($source, ';') && !strpos($source, '&amp;')) {
  1930. continue; //avoid code - that should help
  1931. }
  1932. if ($attr == 'value') {
  1933. if (strpos($source, 'mp3file')) {
  1934. $files_list[] = array(substr($source, 0, strpos($source, '.swf') + 4), 'local', 'abs');
  1935. $mp3file = substr($source, strpos($source, 'mp3file=') + 8);
  1936. if (substr($mp3file, 0, 1) == '/') {
  1937. $files_list[] = array($mp3file, 'local', 'abs');
  1938. } else {
  1939. $files_list[] = array($mp3file, 'local', 'rel');
  1940. }
  1941. } elseif (strpos($source, 'flv=') === 0) {
  1942. $source = substr($source, 4);
  1943. if (strpos($source, '&') > 0) {
  1944. $source = substr($source, 0, strpos($source, '&'));
  1945. }
  1946. if (strpos($source, '://') > 0) {
  1947. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1948. //we found the current portal url
  1949. $files_list[] = array($source, 'local', 'url');
  1950. } else {
  1951. //we didn't find any trace of current portal
  1952. $files_list[] = array($source, 'remote', 'url');
  1953. }
  1954. } else {
  1955. $files_list[] = array($source, 'local', 'abs');
  1956. }
  1957. /* skipping anything else to avoid two entries
  1958. (while the others can have sub-files in their url, flv's can't)*/
  1959. continue;
  1960. }
  1961. }
  1962. if (strpos($source, '://') > 0) {
  1963. //cut at '?' in a URL with params
  1964. if (strpos($source, '?') > 0) {
  1965. $second_part = substr($source, strpos($source, '?'));
  1966. if (strpos($second_part, '://') > 0) {
  1967. //if the second part of the url contains a url too, treat the second one before cutting
  1968. $pos1 = strpos($second_part, '=');
  1969. $pos2 = strpos($second_part, '&');
  1970. $second_part = substr($second_part, $pos1 + 1, $pos2 - ($pos1 + 1));
  1971. if (strpos($second_part, api_get_path(WEB_PATH)) !== false) {
  1972. //we found the current portal url
  1973. $files_list[] = array($second_part, 'local', 'url');
  1974. $in_files_list[] = self::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, $recursivity + 1);
  1975. if (count($in_files_list) > 0) {
  1976. $files_list = array_merge($files_list, $in_files_list);
  1977. }
  1978. } else {
  1979. //we didn't find any trace of current portal
  1980. $files_list[] = array($second_part, 'remote', 'url');
  1981. }
  1982. } elseif (strpos($second_part, '=') > 0) {
  1983. if (substr($second_part, 0, 1) === '/') {
  1984. //link starts with a /, making it absolute (relative to DocumentRoot)
  1985. $files_list[] = array($second_part, 'local', 'abs');
  1986. $in_files_list[] = self::get_resources_from_source_html($second_part, true, TOOL_DOCUMENT, $recursivity + 1);
  1987. if (count($in_files_list) > 0) {
  1988. $files_list = array_merge($files_list, $in_files_list);
  1989. }
  1990. } elseif (strstr($second_part, '..') === 0) {
  1991. //link is relative but going back in the hierarchy
  1992. $files_list[] = array($second_part, 'local', 'rel');
  1993. //$dir = api_get_path(SYS_CODE_PATH);//dirname($abs_path);
  1994. //$new_abs_path = realpath($dir.'/'.$second_part);
  1995. $dir = '';
  1996. if (!empty($abs_path)) {
  1997. $dir = dirname($abs_path) . '/';
  1998. }
  1999. $new_abs_path = realpath($dir . $second_part);
  2000. $in_files_list[] = self::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  2001. if (count($in_files_list) > 0) {
  2002. $files_list = array_merge($files_list, $in_files_list);
  2003. }
  2004. } else {
  2005. //no starting '/', making it relative to current document's path
  2006. if (substr($second_part, 0, 2) == './') {
  2007. $second_part = substr($second_part, 2);
  2008. }
  2009. $files_list[] = array($second_part, 'local', 'rel');
  2010. $dir = '';
  2011. if (!empty($abs_path)) {
  2012. $dir = dirname($abs_path) . '/';
  2013. }
  2014. $new_abs_path = realpath($dir . $second_part);
  2015. $in_files_list[] = self::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  2016. if (count($in_files_list) > 0) {
  2017. $files_list = array_merge($files_list, $in_files_list);
  2018. }
  2019. }
  2020. }
  2021. //leave that second part behind now
  2022. $source = substr($source, 0, strpos($source, '?'));
  2023. if (strpos($source, '://') > 0) {
  2024. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  2025. //we found the current portal url
  2026. $files_list[] = array($source, 'local', 'url');
  2027. $in_files_list[] = self::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  2028. if (count($in_files_list) > 0) {
  2029. $files_list = array_merge($files_list, $in_files_list);
  2030. }
  2031. } else {
  2032. //we didn't find any trace of current portal
  2033. $files_list[] = array($source, 'remote', 'url');
  2034. }
  2035. } else {
  2036. //no protocol found, make link local
  2037. if (substr($source, 0, 1) === '/') {
  2038. //link starts with a /, making it absolute (relative to DocumentRoot)
  2039. $files_list[] = array($source, 'local', 'abs');
  2040. $in_files_list[] = self::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  2041. if (count($in_files_list) > 0) {
  2042. $files_list = array_merge($files_list, $in_files_list);
  2043. }
  2044. } elseif (strstr($source, '..') === 0) { //link is relative but going back in the hierarchy
  2045. $files_list[] = array($source, 'local', 'rel');
  2046. $dir = '';
  2047. if (!empty($abs_path)) {
  2048. $dir = dirname($abs_path) . '/';
  2049. }
  2050. $new_abs_path = realpath($dir . $source);
  2051. $in_files_list[] = self::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  2052. if (count($in_files_list) > 0) {
  2053. $files_list = array_merge($files_list, $in_files_list);
  2054. }
  2055. } else {
  2056. //no starting '/', making it relative to current document's path
  2057. if (substr($source, 0, 2) == './') {
  2058. $source = substr($source, 2);
  2059. }
  2060. $files_list[] = array($source, 'local', 'rel');
  2061. $dir = '';
  2062. if (!empty($abs_path)) {
  2063. $dir = dirname($abs_path) . '/';
  2064. }
  2065. $new_abs_path = realpath($dir . $source);
  2066. $in_files_list[] = self::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  2067. if (count($in_files_list) > 0) {
  2068. $files_list = array_merge($files_list, $in_files_list);
  2069. }
  2070. }
  2071. }
  2072. }
  2073. //found some protocol there
  2074. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  2075. //we found the current portal url
  2076. $files_list[] = array($source, 'local', 'url');
  2077. $in_files_list[] = self::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  2078. if (count($in_files_list) > 0) {
  2079. $files_list = array_merge($files_list, $in_files_list);
  2080. }
  2081. } else {
  2082. //we didn't find any trace of current portal
  2083. $files_list[] = array($source, 'remote', 'url');
  2084. }
  2085. } else {
  2086. //no protocol found, make link local
  2087. if (substr($source, 0, 1) === '/') {
  2088. //link starts with a /, making it absolute (relative to DocumentRoot)
  2089. $files_list[] = array($source, 'local', 'abs');
  2090. $in_files_list[] = self::get_resources_from_source_html($source, true, TOOL_DOCUMENT, $recursivity + 1);
  2091. if (count($in_files_list) > 0) {
  2092. $files_list = array_merge($files_list, $in_files_list);
  2093. }
  2094. } elseif (strpos($source, '..') === 0) {
  2095. //link is relative but going back in the hierarchy
  2096. $files_list[] = array($source, 'local', 'rel');
  2097. $dir = '';
  2098. if (!empty($abs_path)) {
  2099. $dir = dirname($abs_path) . '/';
  2100. }
  2101. $new_abs_path = realpath($dir . $source);
  2102. $in_files_list[] = self::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  2103. if (count($in_files_list) > 0) {
  2104. $files_list = array_merge($files_list, $in_files_list);
  2105. }
  2106. } else {
  2107. //no starting '/', making it relative to current document's path
  2108. if (substr($source, 0, 2) == './') {
  2109. $source = substr($source, 2);
  2110. }
  2111. $files_list[] = array($source, 'local', 'rel');
  2112. $dir = '';
  2113. if (!empty($abs_path)) {
  2114. $dir = dirname($abs_path) . '/';
  2115. }
  2116. $new_abs_path = realpath($dir . $source);
  2117. $in_files_list[] = self::get_resources_from_source_html($new_abs_path, true, TOOL_DOCUMENT, $recursivity + 1);
  2118. if (count($in_files_list) > 0) {
  2119. $files_list = array_merge($files_list, $in_files_list);
  2120. }
  2121. }
  2122. }
  2123. }
  2124. }
  2125. }
  2126. break;
  2127. default: //ignore
  2128. break;
  2129. }
  2130. $checked_files_list = array();
  2131. $checked_array_list = array();
  2132. if (count($files_list) > 0) {
  2133. foreach ($files_list as $idx => $file) {
  2134. if (!empty($file[0])) {
  2135. if (!in_array($file[0], $checked_files_list)) {
  2136. $checked_files_list[] = $files_list[$idx][0];
  2137. $checked_array_list[] = $files_list[$idx];
  2138. }
  2139. }
  2140. }
  2141. }
  2142. return $checked_array_list;
  2143. }
  2144. /**
  2145. * Parses the HTML attributes given as string.
  2146. *
  2147. * @param string HTML attribute string
  2148. * @param array List of attributes that we want to get back
  2149. * @param array
  2150. * @return array An associative array of attributes
  2151. * @author Based on a function from the HTML_Common2 PEAR module *
  2152. */
  2153. public static function parse_HTML_attributes($attrString, $wanted = array(), $explode_variables = array())
  2154. {
  2155. $attributes = array();
  2156. $regs = array();
  2157. $reduced = false;
  2158. if (count($wanted) > 0) {
  2159. $reduced = true;
  2160. }
  2161. try {
  2162. //Find all occurences of something that looks like a URL
  2163. // The structure of this regexp is:
  2164. // (find protocol) then
  2165. // (optionally find some kind of space 1 or more times) then
  2166. // find (either an equal sign or a bracket) followed by an optional space
  2167. // followed by some text without quotes (between quotes itself or not)
  2168. // then possible closing brackets if we were in the opening bracket case
  2169. // OR something like @import()
  2170. $res = preg_match_all(
  2171. '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]*))' .
  2172. // '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]|[^\x00-\x7F])*)' . -> seems to be taking too much
  2173. // '/(((([A-Za-z_:])([^\x00-\x7F])*)' . -> takes only last letter of parameter name
  2174. '([ \n\t\r]+)?(' .
  2175. // '(=([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+))' . -> doesn't restrict close enough to the url itself
  2176. '(=([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+))' .
  2177. '|' .
  2178. // '(\(([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)\))' . -> doesn't restrict close enough to the url itself
  2179. '(\(([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+)\))' .
  2180. '))' .
  2181. '|' .
  2182. // '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))?/', -> takes a lot (like 100's of thousands of empty possibilities)
  2183. '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))/',
  2184. $attrString,
  2185. $regs
  2186. );
  2187. } catch (Exception $e) {
  2188. error_log('Caught exception: ' . $e->getMessage(), 0);
  2189. }
  2190. if ($res) {
  2191. for ($i = 0; $i < count($regs[1]); $i++) {
  2192. $name = trim($regs[3][$i]);
  2193. $check = trim($regs[0][$i]);
  2194. $value = trim($regs[10][$i]);
  2195. if (empty($value) and !empty($regs[13][$i])) {
  2196. $value = $regs[13][$i];
  2197. }
  2198. if (empty($name) && !empty($regs[16][$i])) {
  2199. $name = '@import';
  2200. $value = trim($regs[16][$i]);
  2201. }
  2202. if (!empty($name)) {
  2203. if (!$reduced OR in_array(strtolower($name), $wanted)) {
  2204. if ($name == $check) {
  2205. $attributes[strtolower($name)][] = strtolower($name);
  2206. } else {
  2207. if (!empty($value) && ($value[0] == '\'' || $value[0] == '"')) {
  2208. $value = substr($value, 1, -1);
  2209. }
  2210. if ($value == 'API.LMSGetValue(name') {
  2211. $value = 'API.LMSGetValue(name)';
  2212. }
  2213. //Gets the xx.flv value from the string flashvars="width=320&height=240&autostart=false&file=xxx.flv&repeat=false"
  2214. if (isset($explode_variables[$name])) {
  2215. $value_modified = str_replace('&amp;', '&', $value);
  2216. $value_array = explode('&', $value_modified);
  2217. foreach ($value_array as $item) {
  2218. list($key, $item_value) = explode('=', $item);
  2219. if ($key == $explode_variables[$name]) {
  2220. $attributes[strtolower($name)][] = $item_value;
  2221. }
  2222. }
  2223. }
  2224. $attributes[strtolower($name)][] = $value;
  2225. }
  2226. }
  2227. }
  2228. }
  2229. }
  2230. return $attributes;
  2231. }
  2232. /**
  2233. * Replace urls inside content html from a copy course
  2234. * @param string $content_html
  2235. * @param string $origin_course_code
  2236. * @param string $destination_course_directory
  2237. * @param string $origin_course_path_from_zip
  2238. * @param string $origin_course_info_path
  2239. *
  2240. * @return string new content html with replaced urls or return false if content is not a string
  2241. */
  2242. static function replace_urls_inside_content_html_from_copy_course(
  2243. $content_html,
  2244. $origin_course_code,
  2245. $destination_course_directory,
  2246. $origin_course_path_from_zip = null,
  2247. $origin_course_info_path = null
  2248. ) {
  2249. if (empty($content_html)) {
  2250. return false;
  2251. }
  2252. $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
  2253. $orig_course_info = api_get_course_info($origin_course_code);
  2254. // Course does not exist in the current DB probably this came from a zip file?
  2255. if (empty($orig_course_info)) {
  2256. if (!empty($origin_course_path_from_zip)) {
  2257. $orig_course_path = $origin_course_path_from_zip.'/';
  2258. $orig_course_info_path = $origin_course_info_path;
  2259. }
  2260. } else {
  2261. $orig_course_path = api_get_path(SYS_COURSE_PATH).$orig_course_info['path'] . '/';
  2262. $orig_course_info_path = $orig_course_info['path'];
  2263. }
  2264. $destination_course_code = CourseManager::get_course_id_from_path($destination_course_directory);
  2265. $destination_course_info = api_get_course_info($destination_course_code);
  2266. $dest_course_path = api_get_path(SYS_COURSE_PATH) . $destination_course_directory . '/';
  2267. $dest_course_path_rel = api_get_path(REL_COURSE_PATH) . $destination_course_directory . '/';
  2268. $user_id = api_get_user_id();
  2269. if (!empty($orig_source_html)) {
  2270. foreach ($orig_source_html as $source) {
  2271. // Get information about source url
  2272. $real_orig_url = $source[0]; // url
  2273. $scope_url = $source[1]; // scope (local, remote)
  2274. $type_url = $source[2]; // type (rel, abs, url)
  2275. // Get path and query from origin url
  2276. $orig_parse_url = parse_url($real_orig_url);
  2277. $real_orig_path = isset($orig_parse_url['path']) ? $orig_parse_url['path'] : null;
  2278. $real_orig_query = isset($orig_parse_url['query']) ? $orig_parse_url['query'] : null;
  2279. // Replace origin course code by destination course code from origin url query
  2280. $dest_url_query = '';
  2281. if (!empty($real_orig_query)) {
  2282. $dest_url_query = '?' . $real_orig_query;
  2283. if (strpos($dest_url_query, $origin_course_code) !== false) {
  2284. $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
  2285. }
  2286. }
  2287. if ($scope_url == 'local') {
  2288. if ($type_url == 'abs' || $type_url == 'rel') {
  2289. $document_file = strstr($real_orig_path, 'document');
  2290. if (strpos($real_orig_path, $document_file) !== false) {
  2291. $origin_filepath = $orig_course_path.$document_file;
  2292. $destination_filepath = $dest_course_path.$document_file;
  2293. // copy origin file inside destination course
  2294. if (file_exists($origin_filepath)) {
  2295. $filepath_dir = dirname($destination_filepath);
  2296. if (!is_dir($filepath_dir)) {
  2297. $perm = api_get_permissions_for_new_directories();
  2298. $result = @mkdir($filepath_dir, $perm, true);
  2299. if ($result) {
  2300. $filepath_to_add = str_replace(array($dest_course_path, 'document'), '', $filepath_dir);
  2301. //Add to item properties to the new folder
  2302. $doc_id = add_document(
  2303. $destination_course_info,
  2304. $filepath_to_add,
  2305. 'folder',
  2306. 0,
  2307. basename($filepath_to_add)
  2308. );
  2309. api_item_property_update(
  2310. $destination_course_info,
  2311. TOOL_DOCUMENT,
  2312. $doc_id,
  2313. 'FolderCreated',
  2314. $user_id,
  2315. null,
  2316. null,
  2317. null,
  2318. null
  2319. );
  2320. }
  2321. }
  2322. if (!file_exists($destination_filepath)) {
  2323. $result = @copy($origin_filepath, $destination_filepath);
  2324. if ($result) {
  2325. $filepath_to_add = str_replace(array($dest_course_path, 'document'), '', $destination_filepath);
  2326. $size = filesize($destination_filepath);
  2327. // Add to item properties to the file
  2328. $doc_id = add_document(
  2329. $destination_course_info,
  2330. $filepath_to_add,
  2331. 'file',
  2332. $size,
  2333. basename($filepath_to_add)
  2334. );
  2335. api_item_property_update(
  2336. $destination_course_info,
  2337. TOOL_DOCUMENT,
  2338. $doc_id,
  2339. 'FolderCreated',
  2340. $user_id,
  2341. null,
  2342. null,
  2343. null,
  2344. null
  2345. );
  2346. }
  2347. }
  2348. }
  2349. // Replace origin course path by destination course path.
  2350. if (strpos($content_html, $real_orig_url) !== false) {
  2351. $url_course_path = str_replace($orig_course_info_path.'/'.$document_file, '', $real_orig_path);
  2352. //$destination_url = $url_course_path . $destination_course_directory . '/' . $document_file . $dest_url_query;
  2353. // See BT#7780
  2354. $destination_url = $dest_course_path_rel . $document_file . $dest_url_query;
  2355. // If the course code doesn't exist in the path? what we do? Nothing! see BT#1985
  2356. if (strpos($real_orig_path, $origin_course_code) === false) {
  2357. $url_course_path = $real_orig_path;
  2358. $destination_url = $real_orig_path;
  2359. }
  2360. $content_html = str_replace($real_orig_url, $destination_url, $content_html);
  2361. }
  2362. }
  2363. // replace origin course code by destination course code from origin url
  2364. if (strpos($real_orig_url, '?') === 0) {
  2365. $dest_url = str_replace($origin_course_code, $destination_course_code, $real_orig_url);
  2366. $content_html = str_replace($real_orig_url, $dest_url, $content_html);
  2367. }
  2368. }
  2369. }
  2370. }
  2371. }
  2372. return $content_html;
  2373. }
  2374. /**
  2375. * Replace urls inside content html when moving a file
  2376. * @todo this code is only called in document.php but is commented
  2377. * @param string content html
  2378. * @param string origin
  2379. * @param string destination
  2380. * @return string new content html with replaced urls or return false if content is not a string
  2381. */
  2382. function replace_urls_inside_content_html_when_moving_file($file_name, $original_path, $destiny_path)
  2383. {
  2384. if (substr($original_path, strlen($original_path) - 1, strlen($original_path)) == '/') {
  2385. $original = $original_path . $file_name;
  2386. } else {
  2387. $original = $original_path . '/' . $file_name;
  2388. }
  2389. if (substr($destiny_path, strlen($destiny_path) - 1, strlen($destiny_path)) == '/') {
  2390. $destination = $destiny_path . $file_name;
  2391. } else {
  2392. $destination = $destiny_path . '/' . $file_name;
  2393. }
  2394. $original_count = count(explode('/', $original));
  2395. $destination_count = count(explode('/', $destination));
  2396. if ($original_count == $destination_count) {
  2397. //Nothing to change
  2398. return true;
  2399. }
  2400. if ($original_count > $destination_count) {
  2401. $mode = 'outside';
  2402. } else {
  2403. $mode = 'inside';
  2404. }
  2405. //We do not select the $original_path becayse the file was already moved
  2406. $content_html = file_get_contents($destiny_path . '/' . $file_name);
  2407. $destination_file = $destiny_path . '/' . $file_name;
  2408. $pre_original = strstr($original_path, 'document');
  2409. $pre_destin = strstr($destiny_path, 'document');
  2410. $pre_original = substr($pre_original, 8, strlen($pre_original));
  2411. $pre_destin = substr($pre_destin, 8, strlen($pre_destin));
  2412. $levels = count(explode('/', $pre_destin)) - 1;
  2413. $link_to_add = '';
  2414. for ($i = 1; $i <= $levels; $i++) {
  2415. $link_to_add .= '../';
  2416. }
  2417. if ($pre_original == '/') {
  2418. $pre_original = '';
  2419. }
  2420. if ($pre_destin == '/') {
  2421. $pre_destin = '';
  2422. }
  2423. if ($pre_original != '') {
  2424. $pre_original = '..' . $pre_original . '/';
  2425. }
  2426. if ($pre_destin != '') {
  2427. $pre_destin = '..' . $pre_destin . '/';
  2428. }
  2429. $levels = explode('/', $pre_original);
  2430. $count_pre_destination_levels = 0;
  2431. foreach ($levels as $item) {
  2432. if (!empty($item) && $item != '..') {
  2433. $count_pre_destination_levels++;
  2434. }
  2435. }
  2436. $count_pre_destination_levels--;
  2437. //$count_pre_destination_levels = count() - 3;
  2438. if ($count_pre_destination_levels == 0) {
  2439. $count_pre_destination_levels = 1;
  2440. }
  2441. //echo '$count_pre_destination_levels '. $count_pre_destination_levels;
  2442. $pre_remove = '';
  2443. for ($i = 1; $i <= $count_pre_destination_levels; $i++) {
  2444. $pre_remove .='..\/';
  2445. }
  2446. $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
  2447. foreach ($orig_source_html as $source) {
  2448. // get information about source url
  2449. $real_orig_url = $source[0]; // url
  2450. $scope_url = $source[1]; // scope (local, remote)
  2451. $type_url = $source[2]; // tyle (rel, abs, url)
  2452. // Get path and query from origin url
  2453. $orig_parse_url = parse_url($real_orig_url);
  2454. $real_orig_path = $orig_parse_url['path'];
  2455. $real_orig_query = $orig_parse_url['query'];
  2456. // Replace origin course code by destination course code from origin url query
  2457. /*
  2458. $dest_url_query = '';
  2459. if (!empty($real_orig_query)) {
  2460. $dest_url_query = '?'.$real_orig_query;
  2461. if (strpos($dest_url_query,$origin_course_code) !== false) {
  2462. $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
  2463. }
  2464. } */
  2465. if ($scope_url == 'local') {
  2466. if ($type_url == 'abs' || $type_url == 'rel') {
  2467. $document_file = strstr($real_orig_path, 'document');
  2468. if (strpos($real_orig_path, $document_file) !== false) {
  2469. echo 'continue1';
  2470. continue;
  2471. } else {
  2472. $real_orig_url_temp = '';
  2473. if ($mode == 'inside') {
  2474. $real_orig_url_temp = str_replace('../', '', $real_orig_url);
  2475. $destination_url = $link_to_add . $real_orig_url_temp;
  2476. } else {
  2477. $real_orig_url_temp = $real_orig_url;
  2478. $destination_url = preg_replace("/" . $pre_remove . "/", '', $real_orig_url, 1);
  2479. }
  2480. if ($real_orig_url == $destination_url) {
  2481. //echo 'continue2';
  2482. continue;
  2483. }
  2484. $content_html = str_replace($real_orig_url, $destination_url, $content_html);
  2485. }
  2486. } else {
  2487. echo 'continue3';
  2488. continue;
  2489. }
  2490. }
  2491. }
  2492. $return = file_put_contents($destination, $content_html);
  2493. return $return;
  2494. }
  2495. /**
  2496. * @param int $document_id
  2497. * @param string $course_code
  2498. */
  2499. public static function export_to_pdf($document_id, $course_code)
  2500. {
  2501. $course_data = api_get_course_info($course_code);
  2502. $document_data = self::get_document_data_by_id($document_id, $course_code);
  2503. $file_path = api_get_path(SYS_COURSE_PATH) . $course_data['path'] . '/document' . $document_data['path'];
  2504. $pdf = new PDF('A4-L', 'L');
  2505. $pdf->html_to_pdf($file_path, $document_data['title'], $course_code);
  2506. }
  2507. /**
  2508. * Uploads a document
  2509. *
  2510. * @param array $files the $_FILES variable
  2511. * @param string $path
  2512. * @param string $title
  2513. * @param string $comment
  2514. * @param int $unzip unzip or not the file
  2515. * @param string $if_exists overwrite, rename or warn (default)
  2516. * @param bool $index_document index document (search xapian module)
  2517. * @param bool $show_output print html messages
  2518. * @return array|bool
  2519. */
  2520. public static function upload_document(
  2521. $files,
  2522. $path,
  2523. $title = null,
  2524. $comment = null,
  2525. $unzip = 0,
  2526. $if_exists = null,
  2527. $index_document = false,
  2528. $show_output = false
  2529. ) {
  2530. $course_info = api_get_course_info();
  2531. $sessionId = api_get_session_id();
  2532. $course_dir = $course_info['path'] . '/document';
  2533. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  2534. $base_work_dir = $sys_course_path . $course_dir;
  2535. if (isset($files['file'])) {
  2536. $upload_ok = process_uploaded_file($files['file'], $show_output);
  2537. if ($upload_ok) {
  2538. // File got on the server without problems, now process it
  2539. $new_path = handle_uploaded_document(
  2540. $course_info,
  2541. $files['file'],
  2542. $base_work_dir,
  2543. $path,
  2544. api_get_user_id(),
  2545. api_get_group_id(),
  2546. null,
  2547. $unzip,
  2548. $if_exists,
  2549. $show_output,
  2550. false,
  2551. null,
  2552. $sessionId
  2553. );
  2554. if ($new_path) {
  2555. $documentId = DocumentManager::get_document_id(
  2556. $course_info,
  2557. $new_path,
  2558. $sessionId
  2559. );
  2560. if (!empty($documentId)) {
  2561. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  2562. $params = array();
  2563. /*if ($if_exists == 'rename') {
  2564. // Remove prefix
  2565. $suffix = DocumentManager::getDocumentSuffix(
  2566. $course_info,
  2567. $sessionId,
  2568. api_get_group_id()
  2569. );
  2570. $new_path = basename($new_path);
  2571. $new_path = str_replace($suffix, '', $new_path);
  2572. error_log('renamed');
  2573. error_log($new_path);
  2574. $params['title'] = get_document_title($new_path);
  2575. } else {
  2576. if (!empty($title)) {
  2577. $params['title'] = get_document_title($title);
  2578. } else {
  2579. $params['title'] = get_document_title($files['file']['name']);
  2580. }
  2581. }*/
  2582. if (!empty($comment)) {
  2583. $params['comment'] = trim($comment);
  2584. }
  2585. Database::update(
  2586. $table_document,
  2587. $params,
  2588. array(
  2589. 'id = ? AND c_id = ? ' => array(
  2590. $documentId,
  2591. $course_info['real_id']
  2592. )
  2593. )
  2594. );
  2595. }
  2596. // Showing message when sending zip files
  2597. if ($new_path === true && $unzip == 1 && $show_output) {
  2598. Display::display_confirmation_message(
  2599. get_lang('UplUploadSucceeded') . '<br />',
  2600. false
  2601. );
  2602. }
  2603. if ($index_document) {
  2604. self::index_document(
  2605. $documentId,
  2606. $course_info['code'],
  2607. null,
  2608. $_POST['language'],
  2609. $_REQUEST,
  2610. $if_exists
  2611. );
  2612. }
  2613. if (!empty($documentId) && is_numeric($documentId)) {
  2614. $documentData = self::get_document_data_by_id(
  2615. $documentId,
  2616. $course_info['code'],
  2617. false,
  2618. $sessionId
  2619. );
  2620. return $documentData;
  2621. }
  2622. }
  2623. }
  2624. }
  2625. return false;
  2626. }
  2627. /**
  2628. * Obtains the text inside the file with the right parser
  2629. */
  2630. public static function get_text_content($doc_path, $doc_mime)
  2631. {
  2632. // TODO: review w$ compatibility
  2633. // Use usual exec output lines array to store stdout instead of a temp file
  2634. // because we need to store it at RAM anyway before index on ChamiloIndexer object
  2635. $ret_val = null;
  2636. switch ($doc_mime) {
  2637. case 'text/plain':
  2638. $handle = fopen($doc_path, 'r');
  2639. $output = array(fread($handle, filesize($doc_path)));
  2640. fclose($handle);
  2641. break;
  2642. case 'application/pdf':
  2643. exec("pdftotext $doc_path -", $output, $ret_val);
  2644. break;
  2645. case 'application/postscript':
  2646. $temp_file = tempnam(sys_get_temp_dir(), 'chamilo');
  2647. exec("ps2pdf $doc_path $temp_file", $output, $ret_val);
  2648. if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
  2649. return false;
  2650. }
  2651. exec("pdftotext $temp_file -", $output, $ret_val);
  2652. unlink($temp_file);
  2653. break;
  2654. case 'application/msword':
  2655. exec("catdoc $doc_path", $output, $ret_val);
  2656. break;
  2657. case 'text/html':
  2658. exec("html2text $doc_path", $output, $ret_val);
  2659. break;
  2660. case 'text/rtf':
  2661. // Note: correct handling of code pages in unrtf
  2662. // on debian lenny unrtf v0.19.2 can not, but unrtf v0.20.5 can
  2663. exec("unrtf --text $doc_path", $output, $ret_val);
  2664. if ($ret_val == 127) { // command not found
  2665. return false;
  2666. }
  2667. // Avoid index unrtf comments
  2668. if (is_array($output) && count($output) > 1) {
  2669. $parsed_output = array();
  2670. foreach ($output as & $line) {
  2671. if (!preg_match('/^###/', $line, $matches)) {
  2672. if (!empty($line)) {
  2673. $parsed_output[] = $line;
  2674. }
  2675. }
  2676. }
  2677. $output = $parsed_output;
  2678. }
  2679. break;
  2680. case 'application/vnd.ms-powerpoint':
  2681. exec("catppt $doc_path", $output, $ret_val);
  2682. break;
  2683. case 'application/vnd.ms-excel':
  2684. exec("xls2csv -c\" \" $doc_path", $output, $ret_val);
  2685. break;
  2686. }
  2687. $content = '';
  2688. if (!is_null($ret_val)) {
  2689. if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
  2690. return false;
  2691. }
  2692. }
  2693. if (isset($output)) {
  2694. foreach ($output as & $line) {
  2695. $content .= $line . "\n";
  2696. }
  2697. return $content;
  2698. } else {
  2699. return false;
  2700. }
  2701. }
  2702. /**
  2703. * Calculates the total size of all documents in a course
  2704. *
  2705. * @author Bert vanderkimpen
  2706. * @param int $course_id
  2707. * @param int $group_id (to calculate group document space)
  2708. * @param int $session_id
  2709. *
  2710. * @return int total size
  2711. */
  2712. static function documents_total_space($course_id = null, $group_id = null, $session_id = null)
  2713. {
  2714. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2715. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  2716. if (isset($course_id)) {
  2717. $course_id = intval($course_id);
  2718. } else {
  2719. $course_id = api_get_course_int_id();
  2720. }
  2721. $group_condition = null;
  2722. if (isset($group_id)) {
  2723. $group_id = intval($group_id);
  2724. $group_condition = " AND props.to_group_id='" . $group_id . "' ";
  2725. }
  2726. $session_condition = null;
  2727. if (isset($session_id)) {
  2728. $session_id = intval($session_id);
  2729. $session_condition = " AND props.session_id='" . $session_id . "' ";
  2730. }
  2731. $sql = "SELECT SUM(size)
  2732. FROM $TABLE_ITEMPROPERTY AS props
  2733. INNER JOIN $TABLE_DOCUMENT AS docs
  2734. ON (docs.id = props.ref AND props.c_id = docs.c_id)
  2735. WHERE
  2736. props.c_id = $course_id AND
  2737. docs.c_id = $course_id AND
  2738. props.tool = '" . TOOL_DOCUMENT . "' AND
  2739. props.visibility <> 2
  2740. $group_condition
  2741. $session_condition
  2742. ";
  2743. $result = Database::query($sql);
  2744. if ($result && Database::num_rows($result) != 0) {
  2745. $row = Database::fetch_row($result);
  2746. return $row[0];
  2747. } else {
  2748. return 0;
  2749. }
  2750. }
  2751. /**
  2752. * Here we count 1 Kilobyte = 1024 Bytes, 1 Megabyte = 1048576 Bytes
  2753. */
  2754. static function display_quota($course_quota, $already_consumed_space)
  2755. {
  2756. $course_quota_m = round($course_quota / 1048576);
  2757. $already_consumed_space_m = round($already_consumed_space / 1048576);
  2758. $message = get_lang('MaximumAllowedQuota') . ' <strong>' . $course_quota_m . ' megabyte</strong>.<br />';
  2759. $message .= get_lang('CourseCurrentlyUses') . ' <strong>' . $already_consumed_space_m . ' megabyte</strong>.<br />';
  2760. $percentage = round(($already_consumed_space / $course_quota * 100), 1);
  2761. $other_percentage = $percentage < 100 ? 100 - $percentage : 0;
  2762. // Decide where to place percentage in graph
  2763. if ($percentage >= 50) {
  2764. $text_in_filled = '&nbsp;' . $other_percentage . '%';
  2765. $text_in_unfilled = '';
  2766. } else {
  2767. $text_in_unfilled = '&nbsp;' . $other_percentage . '%';
  2768. $text_in_filled = '';
  2769. }
  2770. // Decide the background colour of the graph
  2771. if ($percentage < 65) {
  2772. $colour = '#00BB00'; // Safe - green
  2773. } elseif ($percentage < 90) {
  2774. $colour = '#ffd400'; // Filling up - yelloworange
  2775. } else {
  2776. $colour = '#DD0000'; // Full - red
  2777. }
  2778. // This is used for the table width: a table of only 100 pixels looks too small
  2779. $visual_percentage = 4 * $percentage;
  2780. $visual_other_percentage = 4 * $other_percentage;
  2781. $message .= get_lang('PercentageQuotaInUse') . ': <strong>' . $percentage . '%</strong>.<br />' .
  2782. get_lang('PercentageQuotaFree') . ': <strong>' . $other_percentage . '%</strong>.<br />';
  2783. $show_percentage = '&nbsp;' . $percentage . '%';
  2784. $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">' .
  2785. '<div style="width:' . $percentage . '%; background-color: #bbb; border-right:3px groove #bbb; -moz-border-radius:5px;">&nbsp;</div>' .
  2786. '<span style="margin-top: -15px; margin-left:-15px; position: absolute;font-weight:bold;">' . $show_percentage . '</span></div>';
  2787. echo $message;
  2788. }
  2789. /**
  2790. * Display the document quota in a simple way
  2791. *
  2792. * Here we count 1 Kilobyte = 1024 Bytes, 1 Megabyte = 1048576 Bytes
  2793. */
  2794. static function display_simple_quota($course_quota, $already_consumed_space)
  2795. {
  2796. $course_quota_m = round($course_quota / 1048576);
  2797. $already_consumed_space_m = round($already_consumed_space / 1048576, 2);
  2798. $percentage = $already_consumed_space / $course_quota * 100;
  2799. $percentage = round($percentage, 1);
  2800. $message = get_lang('YouAreCurrentlyUsingXOfYourX');
  2801. $message = sprintf($message, $already_consumed_space_m, $percentage . '%', $course_quota_m . ' ');
  2802. echo Display::div($message, array('id' => 'document_quota'));
  2803. }
  2804. /**
  2805. * Checks if there is enough place to add a file on a directory
  2806. * on the base of a maximum directory size allowed
  2807. *
  2808. * @author Bert Vanderkimpen
  2809. * @param int file_size size of the file in byte
  2810. * @param int max_dir_space maximum size
  2811. * @return boolean true if there is enough space, false otherwise
  2812. *
  2813. * @see enough_space() uses documents_total_space() function
  2814. */
  2815. static function enough_space($file_size, $max_dir_space) {
  2816. if ($max_dir_space) {
  2817. $already_filled_space = self::documents_total_space();
  2818. if (($file_size + $already_filled_space) > $max_dir_space) {
  2819. return false;
  2820. }
  2821. }
  2822. return true;
  2823. }
  2824. /**
  2825. * @param array parameters: count, url, extension
  2826. * @return string
  2827. */
  2828. static function generate_jplayer_jquery($params = array())
  2829. {
  2830. $js_path = api_get_path(WEB_LIBRARY_PATH) . 'javascript/';
  2831. $js = ' $("#jquery_jplayer_' . $params['count'] . '").jPlayer({
  2832. ready: function() {
  2833. $(this).jPlayer("setMedia", {
  2834. ' . $params['extension'] . ' : "' . $params['url'] . '"
  2835. });
  2836. },
  2837. play: function() { // To avoid both jPlayers playing together.
  2838. $(this).jPlayer("pauseOthers");
  2839. },
  2840. //errorAlerts: true,
  2841. //warningAlerts: true,
  2842. swfPath: "' . $js_path . 'jquery-jplayer",
  2843. //supplied: "m4a, oga, mp3, ogg, wav",
  2844. supplied: "' . $params['extension'] . '",
  2845. wmode: "window",
  2846. solution: "flash, html", // Do not change this setting
  2847. cssSelectorAncestor: "#jp_container_' . $params['count'] . '",
  2848. }); ' . "\n\n";
  2849. return $js;
  2850. }
  2851. /**
  2852. *
  2853. * Shows a play icon next to the document title in the document list
  2854. * @param int
  2855. * @param string
  2856. * @return string html content
  2857. */
  2858. static function generate_media_preview($i, $type = 'simple')
  2859. {
  2860. $i = intval($i);
  2861. $extra_controls = $progress = '';
  2862. if ($type == 'advanced') {
  2863. $extra_controls = ' <li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>
  2864. <li><a href="#" class="jp-mute" tabindex="1">mute</a></li>
  2865. <li><a href="#" class="jp-unmute" tabindex="1">unmute</a></li>';
  2866. $progress = '<div class="jp-progress">
  2867. <div class="jp-seek-bar">
  2868. <div class="jp-play-bar"></div>
  2869. </div>
  2870. </div>';
  2871. }
  2872. //Shows only the play button
  2873. $html = '<div id="jquery_jplayer_' . $i . '" class="jp-jplayer"></div>
  2874. <div id="jp_container_' . $i . '" class="jp-audio">
  2875. <div class="jp-type-single">
  2876. <div class="jp-gui jp-interface">
  2877. <ul class="jp-controls">
  2878. <li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>
  2879. <li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>
  2880. ' . $extra_controls . '
  2881. </ul>
  2882. ' . $progress . '
  2883. </div>
  2884. </div>
  2885. </div>';
  2886. //<div id="jplayer_inspector_'.$i.'"></div>
  2887. return $html;
  2888. }
  2889. /**
  2890. * @param array $document_data
  2891. * @return string
  2892. */
  2893. static function generate_video_preview($document_data = array())
  2894. {
  2895. $html = '
  2896. <div id="jp_container_1" class="jp-video">
  2897. <div class="jp-type-single">
  2898. <div id="jquery_jplayer_1" class="jp-jplayer"></div>
  2899. <div class="jp-gui">
  2900. <div class="jp-video-play">
  2901. <a href="javascript:;" class="jp-video-play-icon" tabindex="1">play</a>
  2902. </div>
  2903. <div class="jp-interface">
  2904. <div class="jp-progress">
  2905. <div class="jp-seek-bar">
  2906. <div class="jp-play-bar"></div>
  2907. </div>
  2908. </div>
  2909. <div class="jp-current-time"></div>
  2910. <div class="jp-controls-holder">
  2911. <ul class="jp-controls">
  2912. <li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>
  2913. <li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>
  2914. <li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>
  2915. <li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>
  2916. <li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>
  2917. <li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>
  2918. </ul>
  2919. <div class="jp-volume-bar">
  2920. <div class="jp-volume-bar-value"></div>
  2921. </div>
  2922. <ul class="jp-toggles">
  2923. <li><a href="javascript:;" class="jp-full-screen" tabindex="1" title="full screen">full screen</a></li>
  2924. <li><a href="javascript:;" class="jp-restore-screen" tabindex="1" title="restore screen">restore screen</a></li>
  2925. <li><a href="javascript:;" class="jp-repeat" tabindex="1" title="repeat">repeat</a></li>
  2926. <li><a href="javascript:;" class="jp-repeat-off" tabindex="1" title="repeat off">repeat off</a></li>
  2927. </ul>
  2928. </div>
  2929. <div class="jp-title">
  2930. <ul>
  2931. <li>' . $document_data['title'] . '</li>
  2932. </ul>
  2933. </div>
  2934. </div>
  2935. </div>
  2936. <div class="jp-no-solution">
  2937. <span>' . get_lang('UpdateRequire') . '</span>
  2938. ' . get_lang("ToPlayTheMediaYouWillNeedToUpdateYourBrowserToARecentVersionYouCanAlsoDownloadTheFile") . '
  2939. </div>
  2940. </div>
  2941. </div>';
  2942. return $html;
  2943. }
  2944. /**
  2945. * @param array $course_info
  2946. * @param bool $lp_id
  2947. * @param string $target
  2948. * @param int $session_id
  2949. * @param bool $add_move_button
  2950. * @param string $filter_by_folder
  2951. * @param string $overwrite_url
  2952. * @param bool $showInvisibleFiles
  2953. * @param bool $showOnlyFolders
  2954. * @param int $folderId
  2955. * @return string
  2956. */
  2957. public static function get_document_preview(
  2958. $course_info,
  2959. $lp_id = false,
  2960. $target = '',
  2961. $session_id = 0,
  2962. $add_move_button = false,
  2963. $filter_by_folder = null,
  2964. $overwrite_url = null,
  2965. $showInvisibleFiles = false,
  2966. $showOnlyFolders = false,
  2967. $folderId = false
  2968. ) {
  2969. if (empty($course_info['real_id']) || empty($course_info['code']) || !is_array($course_info)) {
  2970. return '';
  2971. }
  2972. $overwrite_url = Security::remove_XSS($overwrite_url);
  2973. $user_id = api_get_user_id();
  2974. $user_in_course = false;
  2975. if (api_is_platform_admin()) {
  2976. $user_in_course = true;
  2977. }
  2978. if (!$user_in_course) {
  2979. if (CourseManager::is_course_teacher($user_id, $course_info['code'])) {
  2980. $user_in_course = true;
  2981. }
  2982. }
  2983. // Condition for the session
  2984. $session_id = intval($session_id);
  2985. if (!$user_in_course) {
  2986. if (empty($session_id)) {
  2987. if (CourseManager::is_user_subscribed_in_course($user_id, $course_info['code'])) {
  2988. $user_in_course = true;
  2989. }
  2990. // Check if course is open then we can consider that the student is registered to the course
  2991. if (isset($course_info) && in_array($course_info['visibility'], array(2, 3))) {
  2992. $user_in_course = true;
  2993. }
  2994. } else {
  2995. $user_status = SessionManager::get_user_status_in_course_session(
  2996. $user_id,
  2997. $course_info['real_id'],
  2998. $session_id
  2999. );
  3000. //is true if is an student, course session teacher or coach
  3001. if (in_array($user_status, array('0', '2', '6'))) {
  3002. $user_in_course = true;
  3003. }
  3004. }
  3005. }
  3006. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  3007. $tbl_item_prop = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3008. $condition_session = " AND (last.session_id = '$session_id' OR last.session_id = '0' OR last.session_id IS NULL)";
  3009. $add_folder_filter = null;
  3010. if (!empty($filter_by_folder)) {
  3011. $add_folder_filter = " AND docs.path LIKE '" . Database::escape_string($filter_by_folder) . "%'";
  3012. }
  3013. // If we are in LP display hidden folder https://support.chamilo.org/issues/6679
  3014. $lp_visibility_condition = null;
  3015. if ($lp_id) {
  3016. // $lp_visibility_condition = " OR filetype='folder'";
  3017. if ($showInvisibleFiles) {
  3018. $lp_visibility_condition .= ' OR last.visibility = 0';
  3019. }
  3020. }
  3021. $showOnlyFoldersCondition = null;
  3022. if ($showOnlyFolders) {
  3023. //$showOnlyFoldersCondition = " AND docs.filetype = 'folder' ";
  3024. }
  3025. $folderCondition = " AND docs.path LIKE '/%' ";
  3026. if (!api_is_allowed_to_edit()) {
  3027. $protectedFolders = self::getProtectedFolderFromStudent();
  3028. foreach ($protectedFolders as $folder) {
  3029. $folderCondition .= " AND docs.path NOT LIKE '$folder' ";
  3030. }
  3031. }
  3032. $parentData = [];
  3033. if ($folderId !== false) {
  3034. $parentData = self::get_document_data_by_id($folderId, $course_info['code']);
  3035. if (!empty($parentData)) {
  3036. $cleanedPath = $parentData['path'];
  3037. $num = substr_count($cleanedPath, '/');
  3038. $notLikeCondition = null;
  3039. for ($i = 1; $i <= $num; $i++) {
  3040. $repeat = str_repeat('/%', $i+1);
  3041. $notLikeCondition .= " AND docs.path NOT LIKE '".Database::escape_string($cleanedPath.$repeat)."' ";
  3042. }
  3043. $folderCondition = " AND
  3044. docs.id <> $folderId AND
  3045. docs.path LIKE '".$cleanedPath."/%'
  3046. $notLikeCondition
  3047. ";
  3048. } else {
  3049. $folderCondition = " AND
  3050. docs.filetype = 'file' ";
  3051. }
  3052. }
  3053. $levelCondition = null;
  3054. if ($folderId === false) {
  3055. $levelCondition = " AND docs.path NOT LIKE'/%/%'";
  3056. }
  3057. $sql = "SELECT last.visibility, docs.*
  3058. FROM $tbl_item_prop AS last INNER JOIN $tbl_doc AS docs
  3059. ON (docs.id = last.ref AND docs.c_id = last.c_id)
  3060. WHERE
  3061. docs.path NOT LIKE '%_DELETED_%' AND
  3062. last.tool = '" . TOOL_DOCUMENT . "' $condition_session AND
  3063. (last.visibility = '1' $lp_visibility_condition) AND
  3064. last.visibility <> 2 AND
  3065. docs.c_id = {$course_info['real_id']} AND
  3066. last.c_id = {$course_info['real_id']}
  3067. $showOnlyFoldersCondition
  3068. $folderCondition
  3069. $levelCondition
  3070. $add_folder_filter
  3071. ORDER BY docs.filetype DESC, docs.title ASC";
  3072. $res_doc = Database::query($sql);
  3073. $resources = Database::store_result($res_doc, 'ASSOC');
  3074. $return = '';
  3075. if ($lp_id) {
  3076. if ($folderId === false) {
  3077. $return .= '<div class="lp_resource_element">';
  3078. $return .= Display::return_icon('new_doc.gif', '', array(), ICON_SIZE_SMALL);
  3079. $return .= Display::url(
  3080. get_lang('NewDocument'),
  3081. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_DOCUMENT.'&lp_id='.$_SESSION['oLP']->lp_id
  3082. );
  3083. $return .= '</div>';
  3084. }
  3085. } else {
  3086. $return .= Display::div(
  3087. Display::url(
  3088. Display::return_icon('close.png', get_lang('Close'), array(), ICON_SIZE_SMALL),
  3089. ' javascript:void(0);',
  3090. array('id' => 'close_div_' . $course_info['real_id'] . '_' . $session_id, 'class' => 'close_div')
  3091. ),
  3092. array('style' => 'position:absolute;right:10px')
  3093. );
  3094. }
  3095. // If you want to debug it, I advise you to do "echo" on the eval statements.
  3096. $newResources = array();
  3097. if (!empty($resources) && $user_in_course) {
  3098. foreach ($resources as $resource) {
  3099. $is_visible = self::is_visible_by_id(
  3100. $resource['id'],
  3101. $course_info,
  3102. $session_id,
  3103. api_get_user_id()
  3104. );
  3105. if (!$is_visible) {
  3106. continue;
  3107. }
  3108. $newResources[] = $resource;
  3109. }
  3110. }
  3111. $label = get_lang('Documents');
  3112. $documents = [];
  3113. if ($folderId === false) {
  3114. $documents[$label] = array(
  3115. 'id' => 0,
  3116. 'files' => $newResources
  3117. );
  3118. } else {
  3119. if (!empty($parentData)) {
  3120. $documents[$parentData['title']] = array(
  3121. 'id' => intval($folderId),
  3122. 'files' => $newResources
  3123. );
  3124. }
  3125. }
  3126. $write_result = self::write_resources_tree(
  3127. $course_info,
  3128. $session_id,
  3129. $documents,
  3130. $lp_id,
  3131. $target,
  3132. $add_move_button,
  3133. $overwrite_url,
  3134. $folderId
  3135. );
  3136. $return .= $write_result;
  3137. $img_path = api_get_path(WEB_IMG_PATH);
  3138. if ($lp_id == false) {
  3139. $url = api_get_path(WEB_AJAX_PATH).'lp.ajax.php?a=get_documents&url='.$overwrite_url.'&lp_id='.$lp_id.'&cidReq='.$course_info['code'];
  3140. $return .= "<script>
  3141. $('.doc_folder').click(function() {
  3142. var realId = this.id;
  3143. var my_id = this.id.split('_')[2];
  3144. var tempId = 'temp_'+my_id;
  3145. $('#res_'+my_id).show();
  3146. var tempDiv = $('#'+realId).find('#'+tempId);
  3147. if (tempDiv.length == 0) {
  3148. $.ajax({
  3149. async: false,
  3150. type: 'GET',
  3151. url: '".$url."',
  3152. data: 'folder_id='+my_id,
  3153. success: function(data) {
  3154. $('#'+realId).append('<div id='+tempId+'>'+data+'</div>');
  3155. }
  3156. });
  3157. }
  3158. });
  3159. $('.close_div').click(function() {
  3160. var course_id = this.id.split('_')[2];
  3161. var session_id = this.id.split('_')[3];
  3162. $('#document_result_'+course_id+'_'+session_id).hide();
  3163. $('.lp_resource').remove();
  3164. $('.document_preview_container').html('');
  3165. });
  3166. </script>";
  3167. } else {
  3168. //For LPs
  3169. $url = api_get_path(WEB_AJAX_PATH).'lp.ajax.php?a=get_documents&lp_id='.$lp_id.'&'.api_get_cidreq();
  3170. $return .= "<script>
  3171. function testResources(id, img) {
  3172. var numericId = id.split('_')[1];
  3173. var parentId = 'doc_id_'+numericId;
  3174. var tempId = 'temp_'+numericId;
  3175. var image = $('#'+img);
  3176. if (image.hasClass('open')) {
  3177. image.removeClass('open');
  3178. image.attr('src', '" . $img_path . "nolines_plus.gif');
  3179. $('#'+id).show();
  3180. $('#'+tempId).hide();
  3181. } else {
  3182. image.addClass('open');
  3183. image.attr('src', '" . $img_path . "nolines_minus.gif');
  3184. $('#'+id).hide();
  3185. $('#'+tempId).show();
  3186. var tempDiv = $('#'+parentId).find('#'+tempId);
  3187. if (tempDiv.length == 0) {
  3188. $.ajax({
  3189. type: 'GET',
  3190. async: false,
  3191. url: '".$url."',
  3192. data: 'folder_id='+numericId,
  3193. success: function(data) {
  3194. tempDiv = $('#doc_id_'+numericId).append('<div id='+tempId+'>'+data+'</div>');
  3195. }
  3196. });
  3197. }
  3198. }
  3199. }
  3200. </script>";
  3201. }
  3202. if (!$user_in_course) {
  3203. $return = '';
  3204. }
  3205. return $return;
  3206. }
  3207. /**
  3208. * @param array $course_info
  3209. * @param int $session_id
  3210. * @param array $resource
  3211. * @param int $lp_id
  3212. * @param bool $add_move_button
  3213. * @param string $target
  3214. * @param string $overwrite_url
  3215. * @return null|string
  3216. */
  3217. private static function parseFile(
  3218. $course_info,
  3219. $session_id,
  3220. $resource,
  3221. $lp_id,
  3222. $add_move_button,
  3223. $target,
  3224. $overwrite_url
  3225. ) {
  3226. $img_path = api_get_path(WEB_IMG_PATH);
  3227. $img_sys_path = api_get_path(SYS_CODE_PATH) . 'img/';
  3228. $web_code_path = api_get_path(WEB_CODE_PATH);
  3229. $documentId = $resource['id'];
  3230. $path = $resource['path'];
  3231. if (empty($path)) {
  3232. $num = 0;
  3233. } else {
  3234. $num = substr_count($path, '/') - 1;
  3235. }
  3236. // It's a file.
  3237. $icon = choose_image($path);
  3238. $position = strrpos($icon, '.');
  3239. $icon = substr($icon, 0, $position) . '_small.gif';
  3240. $my_file_title = $resource['title'];
  3241. $visibility = $resource['visibility'];
  3242. // If title is empty we try to use the path
  3243. if (empty($my_file_title)) {
  3244. $my_file_title = basename($path);
  3245. }
  3246. // Show the "image name" not the filename of the image.
  3247. if ($lp_id) {
  3248. //LP URL
  3249. $url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&amp;action=add_item&amp;type=' . TOOL_DOCUMENT . '&amp;file=' . $documentId . '&amp;lp_id=' . $lp_id;
  3250. if (!empty($overwrite_url)) {
  3251. $url = $overwrite_url . '&cidReq=' . $course_info['code'] . '&id_session=' . $session_id . '&document_id=' . $documentId.'';
  3252. }
  3253. } else {
  3254. // Direct document URL
  3255. $url = $web_code_path . 'document/document.php?cidReq=' . $course_info['code'] . '&id_session=' . $session_id . '&id=' . $documentId;
  3256. if (!empty($overwrite_url)) {
  3257. $url = $overwrite_url . '&cidReq=' . $course_info['code'] . '&id_session=' . $session_id . '&document_id=' . $documentId;
  3258. }
  3259. }
  3260. $img = $img_path . $icon;
  3261. if (!file_exists($img_sys_path . $icon)) {
  3262. $img = $img_path . 'icons/16/default_small.gif';
  3263. }
  3264. $link = Display::url(
  3265. '<img alt="" src="' . $img . '" title="" />&nbsp;' . $my_file_title, $url,
  3266. array('target' => $target)
  3267. );
  3268. $visibilityClass = null;
  3269. if ($visibility == 0) {
  3270. $visibilityClass = ' invisible ';
  3271. }
  3272. $return = null;
  3273. if ($lp_id == false) {
  3274. $return .= '<li class="doc_resource '.$visibilityClass.' " data_id="' . $documentId . '" data_type="document" title="' . $my_file_title . '" >';
  3275. } else {
  3276. $return .= '<li class="doc_resource lp_resource_element '.$visibilityClass.' " data_id="' . $documentId . '" data_type="document" title="' . $my_file_title . '" >';
  3277. }
  3278. $return .= '<div class="item_data" style="margin-left:' . ($num * 18) . 'px;margin-right:5px;">';
  3279. if ($add_move_button) {
  3280. $return .= '<a class="moved" href="#">';
  3281. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
  3282. $return .= '</a> ';
  3283. }
  3284. $return .= $link;
  3285. $return .= '</div></li>';
  3286. return $return;
  3287. }
  3288. /**
  3289. * @param int $folderId
  3290. * @param array $resource
  3291. * @param int $lp_id
  3292. * @return null|string
  3293. */
  3294. private static function parseFolder($folderId, $resource, $lp_id)
  3295. {
  3296. $title = isset($resource['title']) ? $resource['title'] : null;
  3297. $path = isset($resource['path']) ? $resource['path'] : null;
  3298. $img_path = api_get_path(WEB_IMG_PATH);
  3299. if (empty($path)) {
  3300. $num = 0;
  3301. } else {
  3302. $num = substr_count($path, '/');
  3303. }
  3304. // It's a folder.
  3305. //hide some folders
  3306. if (in_array($path,
  3307. array('shared_folder', 'chat_files', 'HotPotatoes_files', 'css', 'certificates'))) {
  3308. return null;
  3309. } elseif (preg_match('/_groupdocs/', $path)) {
  3310. return null;
  3311. } elseif (preg_match('/sf_user_/', $path)) {
  3312. return null;
  3313. } elseif (preg_match('/shared_folder_session_/', $path)) {
  3314. return null;
  3315. }
  3316. //trad some titles
  3317. /*
  3318. if ($key == 'images') {
  3319. $key = get_lang('Images');
  3320. } elseif ($key == 'gallery') {
  3321. $key = get_lang('Gallery');
  3322. } elseif ($key == 'flash') {
  3323. $key = get_lang('Flash');
  3324. } elseif ($key == 'audio') {
  3325. $key = get_lang('Audio');
  3326. } elseif ($key == 'video') {
  3327. $key = get_lang('Video');
  3328. }*/
  3329. $onclick = '';
  3330. // if in LP, hidden folder are displayed in grey
  3331. $folder_class_hidden = "";
  3332. if ($lp_id) {
  3333. if (isset($resource['visible']) && $resource['visible'] == 0) {
  3334. $folder_class_hidden = "doc_folder_hidden"; // in base.css
  3335. }
  3336. $onclick = 'onclick="javascript: testResources(\'res_' . $resource['id'] . '\',\'img_' . $resource['id'] . '\')"';
  3337. }
  3338. $return = null;
  3339. if (empty($path)) {
  3340. $return = '<ul class="lp_resource">';
  3341. }
  3342. $return .= '<li class="doc_folder '.$folder_class_hidden.'" id="doc_id_' . $resource['id'] . '" style="margin-left:' . ($num * 18) . 'px; ">';
  3343. $image = $img_path.'nolines_plus.gif';
  3344. if (empty($path)) {
  3345. $image = $img_path.'nolines_minus.gif';
  3346. }
  3347. $return .= '<img style="cursor: pointer;" src="'.$image.'" align="absmiddle" id="img_'.$resource['id'] . '" '.$onclick.'>';
  3348. $return .= '<img alt="" src="' . $img_path . 'lp_folder.gif" title="" align="absmiddle" />&nbsp;';
  3349. $return .= '<span '.$onclick.' style="cursor: pointer;" >'.$title.'</span>';
  3350. $return .= '</li>';
  3351. if (empty($path)) {
  3352. if ($folderId == false) {
  3353. $return .= '<div id="res_' . $resource['id'] . '" >';
  3354. } else {
  3355. $return .= '<div id="res_' . $resource['id'] . '" style="display: none;" >';
  3356. }
  3357. }
  3358. return $return;
  3359. }
  3360. /**
  3361. * Generate and return an HTML list of resources based on a given array.
  3362. * This list is used to show the course creator a list of available resources to choose from
  3363. * when creating a learning path.
  3364. * @param array $course_info
  3365. * @param int $session_id
  3366. * @param array $documents
  3367. * @param bool $lp_id
  3368. * @param string $target
  3369. * @param bool $add_move_button
  3370. * @param string $overwrite_url
  3371. * @param int $folderId
  3372. *
  3373. * @return string
  3374. */
  3375. public static function write_resources_tree(
  3376. $course_info,
  3377. $session_id,
  3378. $documents,
  3379. $lp_id = false,
  3380. $target = '',
  3381. $add_move_button = false,
  3382. $overwrite_url = null,
  3383. $folderId = false
  3384. ) {
  3385. $return = '';
  3386. if (!empty($documents)) {
  3387. foreach ($documents as $key => $resource) {
  3388. if (isset($resource['id']) && is_int($resource['id'])) {
  3389. $mainFolderResource = array(
  3390. 'id' => $resource['id'],
  3391. 'title' => $key,
  3392. );
  3393. if ($folderId === false) {
  3394. $return .= self::parseFolder($folderId, $mainFolderResource, $lp_id);
  3395. }
  3396. if (isset($resource['files'])) {
  3397. $return .= self::write_resources_tree(
  3398. $course_info,
  3399. $session_id,
  3400. $resource['files'],
  3401. $lp_id,
  3402. $target,
  3403. $add_move_button,
  3404. $overwrite_url
  3405. );
  3406. }
  3407. $return .= '</div>';
  3408. $return .= '</ul>';
  3409. } else {
  3410. if ($resource['filetype'] == 'folder') {
  3411. $return .= self::parseFolder($folderId, $resource, $lp_id);
  3412. } else {
  3413. $return .= self::parseFile(
  3414. $course_info,
  3415. $session_id,
  3416. $resource,
  3417. $lp_id,
  3418. $add_move_button,
  3419. $target,
  3420. $overwrite_url
  3421. );
  3422. }
  3423. }
  3424. }
  3425. }
  3426. return $return;
  3427. }
  3428. /**
  3429. * @param int $doc_id
  3430. * @param string $course_code
  3431. * @param int $session_id
  3432. * @param int $user_id
  3433. * @param int $groupId
  3434. * @return bool
  3435. */
  3436. public static function check_visibility_tree(
  3437. $doc_id,
  3438. $course_code,
  3439. $session_id,
  3440. $user_id,
  3441. $groupId = 0
  3442. ) {
  3443. $document_data = self::get_document_data_by_id($doc_id, $course_code, null, $session_id);
  3444. if ($session_id != 0 && !$document_data) {
  3445. $document_data = self::get_document_data_by_id($doc_id, $course_code, null, 0);
  3446. }
  3447. if (!empty($document_data)) {
  3448. // If admin or course teacher, allow anyway
  3449. if (api_is_platform_admin() || CourseManager::is_course_teacher($user_id, $course_code)) {
  3450. return true;
  3451. }
  3452. $course_info = api_get_course_info($course_code);
  3453. if ($document_data['parent_id'] == false || empty($document_data['parent_id'])) {
  3454. if (!empty($groupId)) {
  3455. return true;
  3456. }
  3457. $visible = self::is_visible_by_id($doc_id, $course_info, $session_id, $user_id);
  3458. return $visible;
  3459. } else {
  3460. $visible = self::is_visible_by_id($doc_id, $course_info, $session_id, $user_id);
  3461. if (!$visible) {
  3462. return false;
  3463. } else {
  3464. return self::check_visibility_tree(
  3465. $document_data['parent_id'],
  3466. $course_code,
  3467. $session_id,
  3468. $user_id,
  3469. $groupId
  3470. );
  3471. }
  3472. }
  3473. } else {
  3474. return false;
  3475. }
  3476. }
  3477. /**
  3478. * Index a given document.
  3479. * @param int Document ID inside its corresponding course
  3480. * @param string Course code
  3481. * @param int Session ID (not used yet)
  3482. * @param string Language of document's content (defaults to course language)
  3483. * @param array Array of specific fields (['code'=>'value',...])
  3484. * @param string What to do if the file already exists (default or overwrite)
  3485. * @param bool When set to true, this runs the indexer without actually saving anything to any database
  3486. * @return bool Returns true on presumed success, false on failure
  3487. */
  3488. public static function index_document(
  3489. $docid,
  3490. $course_code,
  3491. $session_id = 0,
  3492. $lang = 'english',
  3493. $specific_fields_values = array(),
  3494. $if_exists = '',
  3495. $simulation = false
  3496. ) {
  3497. if (api_get_setting('search_enabled') !== 'true') {
  3498. return false;
  3499. }
  3500. if (empty($docid) or $docid != intval($docid)) {
  3501. return false;
  3502. }
  3503. if (empty($session_id)) {
  3504. $session_id = api_get_session_id();
  3505. }
  3506. $course_info = api_get_course_info($course_code);
  3507. $course_dir = $course_info['path'] . '/document';
  3508. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  3509. $base_work_dir = $sys_course_path . $course_dir;
  3510. $course_id = $course_info['real_id'];
  3511. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  3512. $qry = "SELECT path, title FROM $table_document WHERE c_id = $course_id AND id = '$docid' LIMIT 1";
  3513. $result = Database::query($qry);
  3514. if (Database::num_rows($result) == 1) {
  3515. $row = Database::fetch_array($result);
  3516. $doc_path = api_get_path(SYS_COURSE_PATH) . $course_dir . $row['path'];
  3517. //TODO: mime_content_type is deprecated, fileinfo php extension is enabled by default as of PHP 5.3.0
  3518. // now versions of PHP on Debian testing(5.2.6-5) and Ubuntu(5.2.6-2ubuntu) are lower, so wait for a while
  3519. $doc_mime = mime_content_type($doc_path);
  3520. $allowed_mime_types = self::file_get_mime_type(true);
  3521. // mime_content_type does not detect correctly some formats that are going to be supported for index, so an extensions array is used for the moment
  3522. if (empty($doc_mime)) {
  3523. $allowed_extensions = array('doc', 'docx', 'ppt', 'pptx', 'pps', 'ppsx', 'xls', 'xlsx', 'odt', 'odp', 'ods', 'pdf', 'txt', 'rtf', 'msg', 'csv', 'html', 'htm');
  3524. $extensions = preg_split("/[\/\\.]/", $doc_path);
  3525. $doc_ext = strtolower($extensions[count($extensions) - 1]);
  3526. if (in_array($doc_ext, $allowed_extensions)) {
  3527. switch ($doc_ext) {
  3528. case 'ppt':
  3529. case 'pps':
  3530. $doc_mime = 'application/vnd.ms-powerpoint';
  3531. break;
  3532. case 'xls':
  3533. $doc_mime = 'application/vnd.ms-excel';
  3534. break;
  3535. }
  3536. }
  3537. }
  3538. //@todo move this nightmare in a search controller or something like that!!! J.M
  3539. if (in_array($doc_mime, $allowed_mime_types)) {
  3540. $file_title = $row['title'];
  3541. $file_content = self::get_text_content($doc_path, $doc_mime);
  3542. $course_code = Database::escape_string($course_code);
  3543. require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
  3544. require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
  3545. $ic_slide = new IndexableChunk();
  3546. $ic_slide->addValue('title', $file_title);
  3547. $ic_slide->addCourseId($course_code);
  3548. $ic_slide->addToolId(TOOL_DOCUMENT);
  3549. $xapian_data = array(
  3550. SE_COURSE_ID => $course_code,
  3551. SE_TOOL_ID => TOOL_DOCUMENT,
  3552. SE_DATA => array('doc_id' => $docid),
  3553. SE_USER => api_get_user_id(),
  3554. );
  3555. $ic_slide->xapian_data = serialize($xapian_data);
  3556. $di = new ChamiloIndexer();
  3557. $return = $di->connectDb(null, null, $lang);
  3558. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  3559. $specific_fields = get_specific_field_list();
  3560. // process different depending on what to do if file exists
  3561. /**
  3562. * @TODO Find a way to really verify if the file had been
  3563. * overwriten. Now all work is done at
  3564. * handle_uploaded_document() and it's difficult to verify it
  3565. */
  3566. if (!empty($if_exists) && $if_exists == 'overwrite') {
  3567. // Overwrite the file on search engine
  3568. // Actually, it consists on a delete of terms from db,
  3569. // insert new ones, create a new search engine document,
  3570. // and remove the old one
  3571. // Get search_did
  3572. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  3573. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  3574. $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid);
  3575. $res = Database::query($sql);
  3576. if (Database::num_rows($res) > 0) {
  3577. $se_ref = Database::fetch_array($res);
  3578. if (!$simulation) {
  3579. $di->remove_document($se_ref['search_did']);
  3580. }
  3581. $all_specific_terms = '';
  3582. foreach ($specific_fields as $specific_field) {
  3583. if (!$simulation) {
  3584. delete_all_specific_field_value($course_code, $specific_field['id'], TOOL_DOCUMENT, $docid);
  3585. }
  3586. // Update search engine
  3587. if (isset($specific_fields_values[$specific_field['code']])) {
  3588. $sterms = trim($specific_fields_values[$specific_field['code']]);
  3589. } else { //if the specific field is not defined, force an empty one
  3590. $sterms = '';
  3591. }
  3592. $all_specific_terms .= ' ' . $sterms;
  3593. $sterms = explode(',', $sterms);
  3594. foreach ($sterms as $sterm) {
  3595. $sterm = trim($sterm);
  3596. if (!empty($sterm)) {
  3597. $ic_slide->addTerm($sterm, $specific_field['code']);
  3598. // updated the last param here from $value to $sterm without being sure - see commit15464
  3599. if (!$simulation) {
  3600. add_specific_field_value($specific_field['id'], $course_code, TOOL_DOCUMENT, $docid, $sterm);
  3601. }
  3602. }
  3603. }
  3604. }
  3605. // Add terms also to content to make terms findable by probabilistic search
  3606. $file_content = $all_specific_terms . ' ' . $file_content;
  3607. if (!$simulation) {
  3608. $ic_slide->addValue('content', $file_content);
  3609. $di->addChunk($ic_slide);
  3610. // Index and return a new search engine document id
  3611. $did = $di->index();
  3612. if ($did) {
  3613. // update the search_did on db
  3614. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  3615. $sql = 'UPDATE %s SET search_did=%d WHERE id=%d LIMIT 1';
  3616. $sql = sprintf($sql, $tbl_se_ref, (int) $did, (int) $se_ref['id']);
  3617. Database::query($sql);
  3618. }
  3619. }
  3620. }
  3621. } else {
  3622. // Add all terms
  3623. $all_specific_terms = '';
  3624. foreach ($specific_fields as $specific_field) {
  3625. if (isset($specific_fields_values[$specific_field['code']])) {
  3626. $sterms = trim($specific_fields_values[$specific_field['code']]);
  3627. } else { //if the specific field is not defined, force an empty one
  3628. $sterms = '';
  3629. }
  3630. $all_specific_terms .= ' ' . $sterms;
  3631. if (!empty($sterms)) {
  3632. $sterms = explode(',', $sterms);
  3633. foreach ($sterms as $sterm) {
  3634. if (!$simulation) {
  3635. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  3636. add_specific_field_value($specific_field['id'], $course_code, TOOL_DOCUMENT, $docid, $sterm);
  3637. }
  3638. }
  3639. }
  3640. }
  3641. // Add terms also to content to make terms findable by probabilistic search
  3642. $file_content = $all_specific_terms . ' ' . $file_content;
  3643. if (!$simulation) {
  3644. $ic_slide->addValue('content', $file_content);
  3645. $di->addChunk($ic_slide);
  3646. // Index and return search engine document id
  3647. $did = $di->index();
  3648. if ($did) {
  3649. // Save it to db
  3650. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  3651. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  3652. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  3653. $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid, $did);
  3654. Database::query($sql);
  3655. } else {
  3656. return false;
  3657. }
  3658. }
  3659. }
  3660. } else {
  3661. return false;
  3662. }
  3663. }
  3664. return true;
  3665. }
  3666. /**
  3667. * @return array
  3668. */
  3669. public static function get_web_odf_extension_list()
  3670. {
  3671. return array('ods', 'odt', 'odp');
  3672. }
  3673. /**
  3674. * Set of extension allowed to use Jodconverter
  3675. * @param $mode 'from'
  3676. * 'to'
  3677. * 'all'
  3678. * @param $format 'text'
  3679. * 'spreadsheet'
  3680. * 'presentation'
  3681. * 'drawing'
  3682. * 'all'
  3683. * @return array
  3684. */
  3685. public static function getJodconverterExtensionList($mode, $format)
  3686. {
  3687. $extensionList = array();
  3688. $extensionListFromText = array(
  3689. 'odt',
  3690. 'sxw',
  3691. 'rtf',
  3692. 'doc',
  3693. 'docx',
  3694. 'wpd',
  3695. 'txt',
  3696. );
  3697. $extensionListToText = array(
  3698. 'pdf',
  3699. 'odt',
  3700. 'sxw',
  3701. 'rtf',
  3702. 'doc',
  3703. 'docx',
  3704. 'txt',
  3705. );
  3706. $extensionListFromSpreadsheet = array(
  3707. 'ods',
  3708. 'sxc',
  3709. 'xls',
  3710. 'xlsx',
  3711. 'csv',
  3712. 'tsv',
  3713. );
  3714. $extensionListToSpreadsheet = array(
  3715. 'pdf',
  3716. 'ods',
  3717. 'sxc',
  3718. 'xls',
  3719. 'xlsx',
  3720. 'csv',
  3721. 'tsv',
  3722. );
  3723. $extensionListFromPresentation = array(
  3724. 'odp',
  3725. 'sxi',
  3726. 'ppt',
  3727. 'pptx',
  3728. );
  3729. $extensionListToPresentation = array(
  3730. 'pdf',
  3731. 'swf',
  3732. 'odp',
  3733. 'sxi',
  3734. 'ppt',
  3735. 'pptx',
  3736. );
  3737. $extensionListFromDrawing = array('odg');
  3738. $extensionListToDrawing = array('svg', 'swf');
  3739. if ($mode === 'from') {
  3740. if ($format === 'text') {
  3741. $extensionList = array_merge($extensionList, $extensionListFromText);
  3742. } elseif ($format === 'spreadsheet') {
  3743. $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
  3744. } elseif ($format === 'presentation') {
  3745. $extensionList = array_merge($extensionList, $extensionListFromPresentation);
  3746. } elseif ($format === 'drawing') {
  3747. $extensionList = array_merge($extensionList, $extensionListFromDrawing);
  3748. } elseif ($format === 'all') {
  3749. $extensionList = array_merge($extensionList, $extensionListFromText);
  3750. $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
  3751. $extensionList = array_merge($extensionList, $extensionListFromPresentation);
  3752. $extensionList = array_merge($extensionList, $extensionListFromDrawing);
  3753. }
  3754. } elseif ($mode === 'to') {
  3755. if ($format === 'text') {
  3756. $extensionList = array_merge($extensionList, $extensionListToText);
  3757. } elseif ($format === 'spreadsheet') {
  3758. $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
  3759. } elseif ($format === 'presentation') {
  3760. $extensionList = array_merge($extensionList, $extensionListToPresentation);
  3761. } elseif ($format === 'drawing') {
  3762. $extensionList = array_merge($extensionList, $extensionListToDrawing);
  3763. } elseif ($format === 'all') {
  3764. $extensionList = array_merge($extensionList, $extensionListToText);
  3765. $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
  3766. $extensionList = array_merge($extensionList, $extensionListToPresentation);
  3767. $extensionList = array_merge($extensionList, $extensionListToDrawing);
  3768. }
  3769. } elseif ($mode === 'all') {
  3770. if ($format === 'text') {
  3771. $extensionList = array_merge($extensionList, $extensionListFromText);
  3772. $extensionList = array_merge($extensionList, $extensionListToText);
  3773. } elseif ($format === 'spreadsheet') {
  3774. $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
  3775. $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
  3776. } elseif ($format === 'presentation') {
  3777. $extensionList = array_merge($extensionList, $extensionListFromPresentation);
  3778. $extensionList = array_merge($extensionList, $extensionListToPresentation);
  3779. } elseif ($format === 'drawing') {
  3780. $extensionList = array_merge($extensionList, $extensionListFromDrawing);
  3781. $extensionList = array_merge($extensionList, $extensionListToDrawing);
  3782. } elseif ($format === 'all') {
  3783. $extensionList = array_merge($extensionList, $extensionListFromText);
  3784. $extensionList = array_merge($extensionList, $extensionListToText);
  3785. $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
  3786. $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
  3787. $extensionList = array_merge($extensionList, $extensionListFromPresentation);
  3788. $extensionList = array_merge($extensionList, $extensionListToPresentation);
  3789. $extensionList = array_merge($extensionList, $extensionListFromDrawing);
  3790. $extensionList = array_merge($extensionList, $extensionListToDrawing);
  3791. }
  3792. }
  3793. return $extensionList;
  3794. }
  3795. /**
  3796. * Get Format type list by extension and mode
  3797. * @param string $mode Mode to search format type list
  3798. * @example 'from'
  3799. * @example 'to'
  3800. * @param string $extension file extension to check file type
  3801. * @return array
  3802. */
  3803. public static function getFormatTypeListConvertor($mode = 'from', $extension)
  3804. {
  3805. $formatTypesList = array();
  3806. $formatTypes = array('text', 'spreadsheet', 'presentation', 'drawing');
  3807. foreach ($formatTypes as $formatType) {
  3808. if (
  3809. in_array(
  3810. $extension,
  3811. self::getJodconverterExtensionList($mode, $formatType)
  3812. )
  3813. ) {
  3814. $formatTypesList[] = $formatType;
  3815. }
  3816. }
  3817. return $formatTypesList;
  3818. }
  3819. /**
  3820. * @param string $path
  3821. * @param bool $is_certificate_mode
  3822. * @return bool
  3823. */
  3824. public static function is_folder_to_avoid($path, $is_certificate_mode = false)
  3825. {
  3826. $foldersToAvoid = array(
  3827. '/HotPotatoes_files',
  3828. '/certificates',
  3829. );
  3830. $systemFolder = api_get_course_setting('show_system_folders');
  3831. if ($systemFolder == 1) {
  3832. $foldersToAvoid = array();
  3833. }
  3834. if (basename($path) == 'css') {
  3835. return true;
  3836. }
  3837. if ($is_certificate_mode == false) {
  3838. //Certificate results
  3839. if (strstr($path, 'certificates')) {
  3840. return true;
  3841. }
  3842. }
  3843. // Admin setting for Hide/Show the folders of all users
  3844. if (api_get_setting('show_users_folders') == 'false') {
  3845. $foldersToAvoid[] = '/shared_folder';
  3846. if (strstr($path, 'shared_folder_session_')) {
  3847. return true;
  3848. }
  3849. }
  3850. // Admin setting for Hide/Show Default folders to all users
  3851. if (api_get_setting('show_default_folders') == 'false') {
  3852. $foldersToAvoid[] = '/images';
  3853. $foldersToAvoid[] = '/flash';
  3854. $foldersToAvoid[] = '/audio';
  3855. $foldersToAvoid[] = '/video';
  3856. }
  3857. // Admin setting for Hide/Show chat history folder
  3858. if (api_get_setting('show_chat_folder') == 'false') {
  3859. $foldersToAvoid[] = '/chat_files';
  3860. }
  3861. if (is_array($foldersToAvoid)) {
  3862. return in_array($path, $foldersToAvoid);
  3863. } else {
  3864. return false;
  3865. }
  3866. }
  3867. /**
  3868. * @return array
  3869. */
  3870. public static function get_system_folders()
  3871. {
  3872. return array(
  3873. '/certificates',
  3874. '/HotPotatoes_files',
  3875. '/chat_files',
  3876. '/images',
  3877. '/flash',
  3878. '/audio',
  3879. '/video',
  3880. '/shared_folder',
  3881. '/learning_path'
  3882. );
  3883. }
  3884. /**
  3885. * @return array
  3886. */
  3887. public static function getProtectedFolderFromStudent()
  3888. {
  3889. return array(
  3890. '/certificates',
  3891. '/HotPotatoes_files',
  3892. '/chat_files',
  3893. '/shared_folder',
  3894. '/learning_path'
  3895. );
  3896. }
  3897. /**
  3898. * @param string $courseCode
  3899. * @return string 'visible' or 'invisible' string
  3900. */
  3901. public static function getDocumentDefaultVisibility($courseCode)
  3902. {
  3903. $settings = api_get_setting('tool_visible_by_default_at_creation');
  3904. $defaultVisibility = 'visible';
  3905. if (isset($settings['documents'])) {
  3906. $portalDefaultVisibility = 'invisible';
  3907. if ($settings['documents'] == 'true') {
  3908. $portalDefaultVisibility = 'visible';
  3909. }
  3910. $defaultVisibility = $portalDefaultVisibility;
  3911. }
  3912. if (api_get_setting('documents_default_visibility_defined_in_course') == 'true') {
  3913. $courseVisibility = api_get_course_setting('documents_default_visibility', $courseCode);
  3914. if (!empty($courseVisibility) && in_array($courseVisibility, array('visible', 'invisible'))) {
  3915. $defaultVisibility = $courseVisibility;
  3916. }
  3917. }
  3918. return $defaultVisibility;
  3919. }
  3920. /**
  3921. * @param array $courseInfo
  3922. * @param int $id doc id
  3923. * @param string $visibility visible/invisible
  3924. * @param int $userId
  3925. */
  3926. public static function updateVisibilityFromAllSessions($courseInfo, $id, $visibility, $userId)
  3927. {
  3928. $sessionList = SessionManager::get_session_by_course($courseInfo['real_id']);
  3929. if (!empty($sessionList)) {
  3930. foreach ($sessionList as $session) {
  3931. $sessionId = $session['id'];
  3932. api_item_property_update(
  3933. $courseInfo,
  3934. TOOL_DOCUMENT,
  3935. $id,
  3936. $visibility,
  3937. $userId,
  3938. null,
  3939. null,
  3940. null,
  3941. null,
  3942. $sessionId
  3943. );
  3944. }
  3945. }
  3946. }
  3947. /**
  3948. * @param string $file
  3949. * @return string
  3950. */
  3951. public static function readNanogongFile($file)
  3952. {
  3953. $nanoGongJarFile = api_get_path(WEB_LIBRARY_PATH).'nanogong/nanogong.jar';
  3954. $html = '<applet id="applet" archive="'.$nanoGongJarFile.'" code="gong.NanoGong" width="160" height="95">';
  3955. $html .= '<param name="SoundFileURL" value="'.$file.'" />';
  3956. $html .= '<param name="ShowSaveButton" value="false" />';
  3957. $html .= '<param name="ShowTime" value="true" />';
  3958. $html .= '<param name="ShowRecordButton" value="false" />';
  3959. $html .= '</applet>';
  3960. return $html;
  3961. }
  3962. /**
  3963. * @param string $filePath
  3964. * @param string $path
  3965. * @param array $courseInfo
  3966. * @param int $sessionId
  3967. * @param string $whatIfFileExists overwrite|rename
  3968. * @param int $userId
  3969. * @param int $groupId
  3970. * @param int $toUserId
  3971. * @param string $comment
  3972. * @return bool|path
  3973. */
  3974. public static function addFileToDocumentTool(
  3975. $filePath,
  3976. $path,
  3977. $courseInfo,
  3978. $sessionId,
  3979. $userId,
  3980. $whatIfFileExists = 'overwrite',
  3981. $groupId = null,
  3982. $toUserId = null,
  3983. $comment = null
  3984. ) {
  3985. if (!file_exists($filePath)) {
  3986. return false;
  3987. }
  3988. $fileInfo = pathinfo($filePath);
  3989. $file = array(
  3990. 'name' => $fileInfo['basename'],
  3991. 'tmp_name' => $filePath,
  3992. 'size' => filesize($filePath),
  3993. 'from_file' => true
  3994. );
  3995. $course_dir = $courseInfo['path'].'/document';
  3996. $baseWorkDir = api_get_path(SYS_COURSE_PATH).$course_dir;
  3997. $filePath = handle_uploaded_document(
  3998. $courseInfo,
  3999. $file,
  4000. $baseWorkDir,
  4001. $path,
  4002. $userId,
  4003. $groupId,
  4004. $toUserId,
  4005. false,
  4006. $whatIfFileExists,
  4007. false,
  4008. false,
  4009. $comment,
  4010. $sessionId
  4011. );
  4012. if ($filePath) {
  4013. return DocumentManager::get_document_id(
  4014. $courseInfo,
  4015. $filePath,
  4016. $sessionId
  4017. );
  4018. }
  4019. return false;
  4020. }
  4021. /**
  4022. * Converts wav to mp3 file.
  4023. * Requires the ffmpeg lib. In ubuntu: sudo apt-get install ffmpeg
  4024. * @param string $wavFile
  4025. * @param bool $removeWavFileIfSuccess
  4026. * @return bool
  4027. */
  4028. public static function convertWavToMp3($wavFile, $removeWavFileIfSuccess = false)
  4029. {
  4030. if (file_exists($wavFile)) {
  4031. try {
  4032. $ffmpeg = \FFMpeg\FFMpeg::create();
  4033. $video = $ffmpeg->open($wavFile);
  4034. $mp3File = str_replace('wav', 'mp3', $wavFile);
  4035. $result = $video->save(new FFMpeg\Format\Audio\Mp3(), $mp3File);
  4036. if ($result && $removeWavFileIfSuccess) {
  4037. unlink($wavFile);
  4038. }
  4039. if (file_exists($mp3File)) {
  4040. return $mp3File;
  4041. }
  4042. } catch (Exception $e) {
  4043. error_log($e->getMessage());
  4044. error_log($e->getPrevious()->getMessage());
  4045. }
  4046. }
  4047. return false;
  4048. }
  4049. /**
  4050. * @param string $documentData wav document information
  4051. * @param array $courseInfo
  4052. * @param int $sessionId
  4053. * @param int $userId user that adds the document
  4054. * @param string $whatIfFileExists
  4055. * @param bool $deleteWavFile
  4056. *
  4057. * @return bool
  4058. */
  4059. public static function addAndConvertWavToMp3(
  4060. $documentData,
  4061. $courseInfo,
  4062. $sessionId,
  4063. $userId,
  4064. $whatIfFileExists = 'overwrite',
  4065. $deleteWavFile = false
  4066. ) {
  4067. if (empty($documentData)) {
  4068. return false;
  4069. }
  4070. if (isset($documentData['absolute_path']) &&
  4071. file_exists($documentData['absolute_path'])
  4072. ) {
  4073. $mp3FilePath = self::convertWavToMp3($documentData['absolute_path']);
  4074. if (!empty($mp3FilePath) && file_exists($mp3FilePath)) {
  4075. $documentId = self::addFileToDocumentTool(
  4076. $mp3FilePath,
  4077. dirname($documentData['path']),
  4078. $courseInfo,
  4079. $sessionId,
  4080. $userId,
  4081. $whatIfFileExists,
  4082. null,
  4083. null,
  4084. $documentData['comment']
  4085. );
  4086. if (!empty($documentId)) {
  4087. if ($deleteWavFile) {
  4088. $coursePath = $courseInfo['directory'].'/document';
  4089. $documentPath = api_get_path(SYS_COURSE_PATH).$coursePath;
  4090. self::delete_document(
  4091. $courseInfo,
  4092. null,
  4093. $documentPath,
  4094. $sessionId,
  4095. $documentData['id']
  4096. );
  4097. }
  4098. return $documentId;
  4099. }
  4100. }
  4101. }
  4102. return false;
  4103. }
  4104. /**
  4105. * Sets
  4106. * @param string $file ($document_data['path'])
  4107. * @param string $file_url_sys
  4108. * @return string
  4109. */
  4110. public static function generateAudioTempFile($file, $file_url_sys)
  4111. {
  4112. //make temp audio
  4113. $temp_folder = api_get_path(SYS_ARCHIVE_PATH).'temp/audio';
  4114. if (!file_exists($temp_folder)) {
  4115. @mkdir($temp_folder, api_get_permissions_for_new_directories(), true);
  4116. }
  4117. //make htaccess with allow from all, and file index.html into temp/audio
  4118. $htaccess = api_get_path(SYS_ARCHIVE_PATH).'temp/audio/.htaccess';
  4119. if (!file_exists($htaccess)) {
  4120. $htaccess_content="order deny,allow\r\nallow from all\r\nOptions -Indexes";
  4121. $fp = @ fopen(api_get_path(SYS_ARCHIVE_PATH).'temp/audio/.htaccess', 'w');
  4122. if ($fp) {
  4123. fwrite($fp, $htaccess_content);
  4124. fclose($fp);
  4125. }
  4126. }
  4127. //encript temp name file
  4128. $name_crip = sha1(uniqid());//encript
  4129. $findext= explode(".", $file);
  4130. $extension = $findext[count($findext)-1];
  4131. $file_crip = $name_crip.'.'.$extension;
  4132. //copy file to temp/audio directory
  4133. $from_sys = $file_url_sys;
  4134. $to_sys = api_get_path(SYS_ARCHIVE_PATH).'temp/audio/'.$file_crip;
  4135. if (file_exists($from_sys)) {
  4136. copy($from_sys, $to_sys);
  4137. }
  4138. //get file from tmp directory
  4139. $_SESSION['temp_audio_nanogong'] = $to_sys;
  4140. return api_get_path(WEB_ARCHIVE_PATH).'temp/audio/'.$file_crip;
  4141. }
  4142. /**
  4143. * Erase temp nanogong audio.
  4144. */
  4145. public static function removeGeneratedAudioTempFile()
  4146. {
  4147. if (isset($_SESSION['temp_audio_nanogong'])
  4148. && !empty($_SESSION['temp_audio_nanogong'])
  4149. && is_file($_SESSION['temp_audio_nanogong'])) {
  4150. unlink($_SESSION['temp_audio_nanogong']);
  4151. unset($_SESSION['temp_audio_nanogong']);
  4152. }
  4153. }
  4154. /**
  4155. * Check if the past is used in this course.
  4156. * @param array $courseInfo
  4157. * @param string $path
  4158. *
  4159. * @return array
  4160. */
  4161. public static function getDocumentByPathInCourse($courseInfo, $path)
  4162. {
  4163. $table = Database::get_course_table(TABLE_DOCUMENT);
  4164. $path = Database::escape_string($path);
  4165. $courseId = $courseInfo['real_id'];
  4166. if (empty($courseId)) {
  4167. return false;
  4168. }
  4169. $sql = "SELECT * FROM $table WHERE c_id = $courseId AND path = '$path'";
  4170. $result = Database::query($sql);
  4171. return Database::store_result($result, 'ASSOC');
  4172. }
  4173. /**
  4174. * @param array $_course
  4175. * @return int
  4176. */
  4177. public static function createDefaultAudioFolder($_course)
  4178. {
  4179. if (!isset($_course['path'])) {
  4180. return false;
  4181. }
  4182. $audioId = null;
  4183. $path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  4184. if (!is_dir($path.'audio')) {
  4185. mkdir($path.'audio', api_get_permissions_for_new_directories());
  4186. $audioId = add_document($_course, '/audio', 'folder', 0, 'Audio');
  4187. api_item_property_update(
  4188. $_course,
  4189. TOOL_DOCUMENT,
  4190. $audioId,
  4191. 'FolderCreated',
  4192. api_get_user_id(),
  4193. null,
  4194. null,
  4195. null,
  4196. null,
  4197. api_get_session_id()
  4198. );
  4199. }
  4200. return $audioId;
  4201. }
  4202. /**
  4203. * Generate a default certificate for a courses
  4204. *
  4205. * @global string $css CSS directory
  4206. * @global string $img_dir image directory
  4207. * @global string $default_course_dir Course directory
  4208. * @global string $js JS directory
  4209. * @param array $courseData The course info
  4210. * @param bool $fromBaseCourse
  4211. * @param int $sessionId
  4212. */
  4213. public static function generateDefaultCertificate($courseData, $fromBaseCourse = false, $sessionId = 0)
  4214. {
  4215. global $css, $img_dir, $default_course_dir, $js;
  4216. $codePath = api_get_path(REL_CODE_PATH);
  4217. $dir = '/certificates';
  4218. $title = get_lang('DefaultCertificate');
  4219. $comment = null;
  4220. $fileName = api_replace_dangerous_char($title);
  4221. $filePath = api_get_path(SYS_COURSE_PATH) . "{$courseData['path']}/document{$dir}";
  4222. $fileFullPath = "{$filePath}/{$fileName}.html";
  4223. $fileSize = 0;
  4224. $fileType = 'file';
  4225. $templateContent = file_get_contents(api_get_path(SYS_CODE_PATH) . 'gradebook/certificate_template/template.html');
  4226. $search = array('{CSS}', '{IMG_DIR}', '{REL_CODE_PATH}', '{COURSE_DIR}');
  4227. $replace = array($css.$js, $img_dir, $codePath, $default_course_dir);
  4228. $fileContent = str_replace($search, $replace, $templateContent);
  4229. $saveFilePath = "{$dir}/{$fileName}.html";
  4230. if (!is_dir($filePath)) {
  4231. mkdir($filePath, api_get_permissions_for_new_directories());
  4232. }
  4233. if ($fromBaseCourse) {
  4234. $defaultCertificateId = self::get_default_certificate_id($courseData['code'], 0);
  4235. if (!empty($defaultCertificateId)) {
  4236. // We have a certificate from the course base
  4237. $documentData = DocumentManager::get_document_data_by_id(
  4238. $defaultCertificateId,
  4239. $courseData['code'],
  4240. false,
  4241. 0
  4242. );
  4243. if ($documentData) {
  4244. $fileContent = file_get_contents($documentData['absolute_path']);
  4245. }
  4246. }
  4247. }
  4248. $defaultCertificateFile = $fp = @fopen($fileFullPath, 'w');
  4249. if ($defaultCertificateFile != false) {
  4250. @fputs($defaultCertificateFile, $fileContent);
  4251. fclose($defaultCertificateFile);
  4252. chmod($fileFullPath, api_get_permissions_for_new_files());
  4253. $fileSize = filesize($fileFullPath);
  4254. }
  4255. $documentId = add_document(
  4256. $courseData,
  4257. $saveFilePath,
  4258. $fileType,
  4259. $fileSize,
  4260. $title,
  4261. $comment,
  4262. 0,//$readonly = 0,
  4263. true, //$save_visibility = true,
  4264. null, //$group_id = null,
  4265. $sessionId
  4266. );
  4267. api_item_property_update(
  4268. $courseData,
  4269. TOOL_DOCUMENT,
  4270. $documentId,
  4271. 'DocumentAdded',
  4272. api_get_user_id(),
  4273. null,
  4274. null,
  4275. null,
  4276. null,
  4277. $sessionId
  4278. );
  4279. $defaultCertificateId = self::get_default_certificate_id(
  4280. $courseData['code'],
  4281. $sessionId
  4282. );
  4283. if (!isset($defaultCertificateId)) {
  4284. self::attach_gradebook_certificate($courseData['code'], $documentId, $sessionId);
  4285. }
  4286. }
  4287. /**
  4288. * Update the document name
  4289. * @param int $documentId The document id
  4290. * @param string $newName The new name
  4291. */
  4292. public static function renameDocument($documentId, $newName)
  4293. {
  4294. $documentId = intval($documentId);
  4295. $newName = Database::escape_string($newName);
  4296. $docuentTable = Database::get_course_table(TABLE_DOCUMENT);
  4297. $values = array(
  4298. 'title' => $newName
  4299. );
  4300. $whereConditions = array(
  4301. 'id = ?' => $documentId
  4302. );
  4303. Database::update($docuentTable, $values, $whereConditions);
  4304. }
  4305. /**
  4306. * Get folder/file suffix
  4307. *
  4308. * @param array $courseInfo
  4309. * @param int $sessionId
  4310. * @param int $groupId
  4311. *
  4312. * @return string
  4313. */
  4314. public static function getDocumentSuffix($courseInfo, $sessionId, $groupId)
  4315. {
  4316. // If no session or group, then no suffix.
  4317. if (empty($sessionId) && empty($groupId)) {
  4318. return '';
  4319. }
  4320. return '__'.intval($sessionId).'__'.intval($groupId);
  4321. }
  4322. /**
  4323. * Fix a document name adding session id and group id
  4324. * Turns picture.jpg -> picture__1__2.jpg
  4325. * Where 1 = session id and 2 group id
  4326. * Of session id and group id are empty then the function returns:
  4327. * picture.jpg -> picture.jpg
  4328. *
  4329. * @param string $name folder or file name
  4330. * @param string $type 'folder' or 'file'
  4331. * @param array $courseInfo
  4332. * @param int $sessionId
  4333. * @param int $groupId
  4334. *
  4335. * @return string
  4336. */
  4337. public static function fixDocumentName($name, $type, $courseInfo, $sessionId, $groupId)
  4338. {
  4339. $suffix = self::getDocumentSuffix($courseInfo, $sessionId, $groupId);
  4340. switch ($type) {
  4341. case 'folder':
  4342. $name = $name.$suffix;
  4343. break;
  4344. case 'file':
  4345. $name = self::addSuffixToFileName($name, $suffix);
  4346. break;
  4347. }
  4348. return $name;
  4349. }
  4350. /**
  4351. * Add a suffix to a file Example:
  4352. * /folder/picture.jpg => to /folder/picture_this.jpg
  4353. * where "_this" is the suffix
  4354. * @param string $name
  4355. * @param string $suffix
  4356. * @return string
  4357. */
  4358. public static function addSuffixToFileName($name, $suffix)
  4359. {
  4360. $extension = pathinfo($name, PATHINFO_EXTENSION);
  4361. $fileName = pathinfo($name, PATHINFO_FILENAME);
  4362. $dir = pathinfo($name, PATHINFO_DIRNAME);
  4363. if ($dir == '.') {
  4364. $dir = null;
  4365. }
  4366. if (!empty($dir) && $dir != '/') {
  4367. $dir = $dir.'/';
  4368. }
  4369. $name = $dir.$fileName.$suffix.'.'.$extension;
  4370. return $name;
  4371. }
  4372. /**
  4373. * Check if folder exist in the course base or in the session course
  4374. * @param string $folder Example: /folder/folder2
  4375. * @param array $courseInfo
  4376. * @param int $sessionId
  4377. * @param int $groupId
  4378. *
  4379. * @return bool
  4380. */
  4381. public static function folderExists(
  4382. $folder,
  4383. $courseInfo,
  4384. $sessionId,
  4385. $groupId
  4386. ) {
  4387. $courseId = $courseInfo['real_id'];
  4388. if (empty($courseId)) {
  4389. return false;
  4390. }
  4391. $sessionId = intval($sessionId);
  4392. $folderWithSuffix = self::fixDocumentName(
  4393. $folder,
  4394. 'folder',
  4395. $courseInfo,
  4396. $sessionId,
  4397. $groupId
  4398. );
  4399. $folder = Database::escape_string($folder);
  4400. $folderWithSuffix = Database::escape_string($folderWithSuffix);
  4401. // Check if pathname already exists inside document table
  4402. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  4403. $sql = "SELECT id, path FROM $tbl_document
  4404. WHERE
  4405. filetype = 'folder' AND
  4406. c_id = $courseId AND
  4407. (path = '$folder' OR path = '$folderWithSuffix') AND
  4408. (session_id = 0 OR session_id = $sessionId)
  4409. ";
  4410. $rs = Database::query($sql);
  4411. if (Database::num_rows($rs)) {
  4412. return true;
  4413. }
  4414. return false;
  4415. }
  4416. /**
  4417. * Check if file exist in the course base or in the session course
  4418. * @param string $fileName Example: /folder/picture.jpg
  4419. * @param array $courseInfo
  4420. * @param int $sessionId
  4421. * @param int $groupId
  4422. *
  4423. * @return bool
  4424. */
  4425. public static function documentExists(
  4426. $fileName,
  4427. $courseInfo,
  4428. $sessionId,
  4429. $groupId
  4430. ) {
  4431. $courseId = $courseInfo['real_id'];
  4432. if (empty($courseId)) {
  4433. return false;
  4434. }
  4435. $sessionId = intval($sessionId);
  4436. $fileNameEscape = Database::escape_string($fileName);
  4437. $fileNameWithSuffix = self::fixDocumentName(
  4438. $fileName,
  4439. 'file',
  4440. $courseInfo,
  4441. $sessionId,
  4442. $groupId
  4443. );
  4444. $fileNameWithSuffix = Database::escape_string($fileNameWithSuffix);
  4445. // Check if pathname already exists inside document table
  4446. $table = Database::get_course_table(TABLE_DOCUMENT);
  4447. $sql = "SELECT id, path FROM $table
  4448. WHERE
  4449. filetype = 'file' AND
  4450. c_id = $courseId AND
  4451. (
  4452. path = '".$fileNameEscape."' OR
  4453. path = '$fileNameWithSuffix'
  4454. ) AND
  4455. (session_id = 0 OR session_id = $sessionId)
  4456. ";
  4457. $rs = Database::query($sql);
  4458. if (Database::num_rows($rs)) {
  4459. return true;
  4460. }
  4461. return false;
  4462. }
  4463. /**
  4464. * Undo the suffix applied to a file example:
  4465. * turns picture__1__1.jpg to picture.jpg
  4466. * @param string $name
  4467. * @param int $courseId
  4468. * @param int $sessionId
  4469. * @param int $groupId
  4470. *
  4471. * @return string
  4472. */
  4473. public static function undoFixDocumentName(
  4474. $name,
  4475. $courseId,
  4476. $sessionId,
  4477. $groupId
  4478. ) {
  4479. if (empty($sessionId) && empty($groupId)) {
  4480. return $name;
  4481. }
  4482. $suffix = self::getDocumentSuffix(
  4483. array('real_id' => $courseId),
  4484. $sessionId,
  4485. $groupId
  4486. );
  4487. $name = str_replace($suffix, '', $name);
  4488. return $name;
  4489. }
  4490. /**
  4491. * @param string $path
  4492. * @param string $name
  4493. * @param array $courseInfo
  4494. * @param int $sessionId
  4495. * @param int $groupId
  4496. *
  4497. * @return string
  4498. */
  4499. public static function getUniqueFileName($path, $name, $courseInfo, $sessionId, $groupId)
  4500. {
  4501. $counter = 1;
  4502. $filePath = $path.$name;
  4503. $uniqueName = $name;
  4504. while ($documentExists = self::documentExists(
  4505. $filePath,
  4506. $courseInfo,
  4507. $sessionId,
  4508. $groupId
  4509. )) {
  4510. $uniqueName = self::addSuffixToFileName($name, '_' . $counter);
  4511. $filePath = $path . $uniqueName;
  4512. $counter++;
  4513. }
  4514. return $uniqueName;
  4515. }
  4516. /**
  4517. * Builds the form that enables the user to
  4518. * select a directory to browse/upload in
  4519. *
  4520. * @param array An array containing the folders we want to be able to select
  4521. * @param string The current folder (path inside of the "document" directory, including the prefix "/")
  4522. * @param string Group directory, if empty, prevents documents to be uploaded (because group documents cannot be uploaded in root)
  4523. * @param boolean Whether to change the renderer (this will add a template <span> to the QuickForm object displaying the form)
  4524. * @todo this funcionality is really bad : jmontoya
  4525. * @return string html form
  4526. */
  4527. public static function build_directory_selector($folders, $document_id, $group_dir = '', $change_renderer = false)
  4528. {
  4529. $doc_table = Database::get_course_table(TABLE_DOCUMENT);
  4530. $course_id = api_get_course_int_id();
  4531. $folder_titles = array();
  4532. if (is_array($folders)) {
  4533. $escaped_folders = array();
  4534. foreach ($folders as $key => & $val) {
  4535. $escaped_folders[$key] = Database::escape_string($val);
  4536. }
  4537. $folder_sql = implode("','", $escaped_folders);
  4538. $sql = "SELECT * FROM $doc_table
  4539. WHERE filetype = 'folder' AND c_id = $course_id AND path IN ('" . $folder_sql . "')";
  4540. $res = Database::query($sql);
  4541. $folder_titles = array();
  4542. while ($obj = Database::fetch_object($res)) {
  4543. $folder_titles[$obj->path] = $obj->title;
  4544. }
  4545. }
  4546. $form = new FormValidator('selector', 'GET', api_get_self() . '?' . api_get_cidreq());
  4547. $form->addElement('hidden', 'cidReq', api_get_course_id());
  4548. $parent_select = $form->addElement('select', 'id', get_lang('CurrentDirectory'), '', 'onchange="javascript: document.selector.submit();"');
  4549. if ($change_renderer) {
  4550. $renderer = $form->defaultRenderer();
  4551. $renderer->setElementTemplate('<span>{label} : {element}</span> ', 'curdirpath');
  4552. }
  4553. // Group documents cannot be uploaded in the root
  4554. if (empty($group_dir)) {
  4555. $parent_select->addOption(get_lang('Documents'), '/');
  4556. if (is_array($folders)) {
  4557. foreach ($folders as $folder_id => & $folder) {
  4558. $selected = ($document_id == $folder_id) ? ' selected="selected"' : '';
  4559. $path_parts = explode('/', $folder);
  4560. $folder_titles[$folder] = cut($folder_titles[$folder], 80);
  4561. $counter = count($path_parts) - 2;
  4562. if ($counter > 0) {
  4563. $label = str_repeat('&nbsp;&nbsp;&nbsp;', $counter) . ' &mdash; ' . $folder_titles[$folder];
  4564. } else {
  4565. $label = ' &mdash; ' . $folder_titles[$folder];
  4566. }
  4567. $parent_select->addOption($label, $folder_id);
  4568. if ($selected != '') {
  4569. $parent_select->setSelected($folder_id);
  4570. }
  4571. }
  4572. }
  4573. } else {
  4574. if (!empty($folders)) {
  4575. foreach ($folders as $folder_id => & $folder) {
  4576. $selected = ($document_id == $folder_id) ? ' selected="selected"' : '';
  4577. $label = $folder_titles[$folder];
  4578. if ($folder == $group_dir) {
  4579. $label = get_lang('Documents');
  4580. } else {
  4581. $path_parts = explode('/', str_replace($group_dir, '', $folder));
  4582. $label = cut($label, 80);
  4583. $label = str_repeat('&nbsp;&nbsp;&nbsp;', count($path_parts) - 2) . ' &mdash; ' . $label;
  4584. }
  4585. $parent_select->addOption($label, $folder_id);
  4586. if ($selected != '') {
  4587. $parent_select->setSelected($folder_id);
  4588. }
  4589. }
  4590. }
  4591. }
  4592. $html = $form->toHtml();
  4593. return $html;
  4594. }
  4595. /**
  4596. * Create a html hyperlink depending on if it's a folder or a file
  4597. *
  4598. * @param string $www
  4599. * @param string $title
  4600. * @param string $path
  4601. * @param string $filetype (file/folder)
  4602. * @param int $visibility (1/0)
  4603. * @param int $show_as_icon - if it is true, only a clickable icon will be shown
  4604. * @return string url
  4605. */
  4606. public static function create_document_link(
  4607. $document_data,
  4608. $show_as_icon = false,
  4609. $counter = null,
  4610. $visibility
  4611. ) {
  4612. global $dbl_click_id;
  4613. $course_info = api_get_course_info();
  4614. $www = api_get_path(WEB_COURSE_PATH) . $course_info['path'] . '/document';
  4615. $webOdflist = DocumentManager::get_web_odf_extension_list();
  4616. // Get the title or the basename depending on what we're using
  4617. if ($document_data['title'] != '') {
  4618. $title = $document_data['title'];
  4619. } else {
  4620. $title = basename($document_data['path']);
  4621. }
  4622. $filetype = $document_data['filetype'];
  4623. $size = $filetype == 'folder' ? get_total_folder_size($document_data['path'], api_is_allowed_to_edit(null, true)) : $document_data['size'];
  4624. $path = $document_data['path'];
  4625. $url_path = urlencode($document_data['path']);
  4626. // Add class="invisible" on invisible files
  4627. $visibility_class = ($visibility == false) ? ' class="muted"' : '';
  4628. $forcedownload_link = null;
  4629. $forcedownload_icon = null;
  4630. $prevent_multiple_click = null;
  4631. if (!$show_as_icon) {
  4632. // Build download link (icon)
  4633. $forcedownload_link = ($filetype == 'folder') ? api_get_self() . '?' . api_get_cidreq() . '&action=downloadfolder&id=' . $document_data['id'] : api_get_self() . '?' . api_get_cidreq() . '&amp;action=download&amp;id=' . $document_data['id'];
  4634. // Folder download or file download?
  4635. $forcedownload_icon = ($filetype == 'folder') ? 'save_pack.png' : 'save.png';
  4636. // Prevent multiple clicks on zipped folder download
  4637. $prevent_multiple_click = ($filetype == 'folder') ? " onclick=\"javascript: if(typeof clic_$dbl_click_id == 'undefined' || !clic_$dbl_click_id) { clic_$dbl_click_id=true; window.setTimeout('clic_" . ($dbl_click_id++) . "=false;',10000); } else { return false; }\"" : '';
  4638. }
  4639. $target = '_self';
  4640. $is_browser_viewable_file = false;
  4641. if ($filetype == 'file') {
  4642. // Check the extension
  4643. $ext = explode('.', $path);
  4644. $ext = strtolower($ext[sizeof($ext) - 1]);
  4645. // HTML-files an some other types are shown in a frameset by default.
  4646. $is_browser_viewable_file = self::is_browser_viewable($ext);
  4647. if ($is_browser_viewable_file) {
  4648. if ($ext == 'pdf' || in_array($ext, $webOdflist)) {
  4649. $url = api_get_self() . '?' . api_get_cidreq() . '&amp;action=download&amp;id=' . $document_data['id'];
  4650. } else {
  4651. $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
  4652. }
  4653. } else {
  4654. // url-encode for problematic characters (we may not call them dangerous characters...)
  4655. $path = str_replace('%2F', '/', $url_path) . '?' . api_get_cidreq();
  4656. $url = $www . $path;
  4657. }
  4658. /*$path = str_replace('%2F', '/', $url_path); //yox view hack otherwise the image can't be well read
  4659. $url = $www . $path;*/
  4660. } else {
  4661. $url = api_get_self() . '?' . api_get_cidreq() . '&id=' . $document_data['id'];
  4662. }
  4663. // The little download icon
  4664. $tooltip_title = $title;
  4665. $tooltip_title_alt = $tooltip_title;
  4666. if ($path == '/shared_folder') {
  4667. $tooltip_title_alt = get_lang('UserFolders');
  4668. } elseif (strstr($path, 'shared_folder_session_')) {
  4669. $tooltip_title_alt = get_lang('UserFolders') . ' (' . api_get_session_name(api_get_session_id()) . ')';
  4670. } elseif (strstr($tooltip_title, 'sf_user_')) {
  4671. $userinfo = api_get_user_info(substr($tooltip_title, 8));
  4672. $tooltip_title_alt = get_lang('UserFolder') . ' ' . $userinfo['complete_name'];
  4673. } elseif ($path == '/chat_files') {
  4674. $tooltip_title_alt = get_lang('ChatFiles');
  4675. } elseif ($path == '/learning_path') {
  4676. $tooltip_title_alt = get_lang('LearningPaths');
  4677. } elseif ($path == '/video') {
  4678. $tooltip_title_alt = get_lang('Video');
  4679. } elseif ($path == '/audio') {
  4680. $tooltip_title_alt = get_lang('Audio');
  4681. } elseif ($path == '/flash') {
  4682. $tooltip_title_alt = get_lang('Flash');
  4683. } elseif ($path == '/images') {
  4684. $tooltip_title_alt = get_lang('Images');
  4685. } elseif ($path == '/images/gallery') {
  4686. $tooltip_title_alt = get_lang('DefaultCourseImages');
  4687. }
  4688. $current_session_id = api_get_session_id();
  4689. $copy_to_myfiles = $open_in_new_window_link = null;
  4690. $curdirpath = isset($_GET['curdirpath']) ? Security::remove_XSS($_GET['curdirpath']) : null;
  4691. $send_to = null;
  4692. if (!$show_as_icon) {
  4693. if ($filetype == 'folder') {
  4694. if (api_is_allowed_to_edit() ||
  4695. api_is_platform_admin() ||
  4696. api_get_setting('students_download_folders') == 'true'
  4697. ) {
  4698. //filter when I am into shared folder, I can show for donwload only my shared folder
  4699. if (DocumentManager::is_shared_folder($curdirpath, $current_session_id)) {
  4700. if (preg_match('/shared_folder\/sf_user_' . api_get_user_id() . '$/', urldecode($forcedownload_link)) ||
  4701. preg_match('/shared_folder_session_' . $current_session_id . '\/sf_user_' . api_get_user_id() . '$/', urldecode($forcedownload_link)) ||
  4702. api_is_allowed_to_edit() || api_is_platform_admin()
  4703. ) {
  4704. $force_download_html = ($size == 0) ? '' : '<a href="' . $forcedownload_link . '" style="float:right"' . $prevent_multiple_click . '>' .
  4705. Display::return_icon($forcedownload_icon, get_lang('Download'), array(), ICON_SIZE_SMALL) . '</a>';
  4706. }
  4707. } elseif (!preg_match('/shared_folder/', urldecode($forcedownload_link)) ||
  4708. api_is_allowed_to_edit() ||
  4709. api_is_platform_admin()
  4710. ) {
  4711. $force_download_html = ($size == 0) ? '' : '<a href="' . $forcedownload_link . '" style="float:right"' . $prevent_multiple_click . '>' .
  4712. Display::return_icon($forcedownload_icon, get_lang('Download'), array(), ICON_SIZE_SMALL) . '</a>';
  4713. }
  4714. }
  4715. } else {
  4716. $force_download_html = ($size == 0) ? '' : '<a href="' . $forcedownload_link . '" style="float:right"' . $prevent_multiple_click . '>' .
  4717. Display::return_icon($forcedownload_icon, get_lang('Download'), array(), ICON_SIZE_SMALL) . '</a>';
  4718. }
  4719. // Copy files to users myfiles
  4720. if (api_get_setting('allow_social_tool') == 'true' &&
  4721. api_get_setting('users_copy_files') == 'true' &&
  4722. !api_is_anonymous()
  4723. ) {
  4724. $copy_myfiles_link = ($filetype == 'file') ? api_get_self() . '?' . api_get_cidreq() . '&action=copytomyfiles&id=' . $document_data['id'] : api_get_self() . '?' . api_get_cidreq();
  4725. if ($filetype == 'file') {
  4726. $copy_to_myfiles = '<a href="' . $copy_myfiles_link . '" style="float:right"' . $prevent_multiple_click . '>' .
  4727. Display::return_icon('briefcase.png', get_lang('CopyToMyFiles'), array(), ICON_SIZE_SMALL) . '&nbsp;&nbsp;</a>';
  4728. }
  4729. if ($filetype == 'file') {
  4730. $send_to = Portfolio::share('document', $document_data['id'], array('style' => 'float:right;'));
  4731. }
  4732. }
  4733. $pdf_icon = '';
  4734. $extension = pathinfo($path, PATHINFO_EXTENSION);
  4735. if (!api_is_allowed_to_edit() &&
  4736. api_get_setting('students_export2pdf') == 'true' &&
  4737. $filetype == 'file' &&
  4738. in_array($extension, array('html', 'htm'))
  4739. ) {
  4740. $pdf_icon = ' <a style="float:right".' . $prevent_multiple_click . ' href="' . api_get_self() . '?' . api_get_cidreq() . '&action=export_to_pdf&id=' . $document_data['id'] . '">' .
  4741. Display::return_icon('pdf.png', get_lang('Export2PDF'), array(), ICON_SIZE_SMALL) . '</a> ';
  4742. }
  4743. if ($is_browser_viewable_file) {
  4744. $open_in_new_window_link = '<a href="' . $www . str_replace('%2F', '/', $url_path) . '?' . api_get_cidreq() . '" style="float:right"' . $prevent_multiple_click . ' target="_blank">' .
  4745. Display::return_icon('open_in_new_window.png', get_lang('OpenInANewWindow'), array(), ICON_SIZE_SMALL) . '&nbsp;&nbsp;</a>';
  4746. }
  4747. if ($filetype == 'file') {
  4748. // Sound preview with jplayer
  4749. if (preg_match('/mp3$/i', urldecode($url)) ||
  4750. (preg_match('/wav$/i', urldecode($url)) && !preg_match('/_chnano_.wav$/i', urldecode($url))) ||
  4751. preg_match('/ogg$/i', urldecode($url))
  4752. ) {
  4753. return '<span style="float:left" ' . $visibility_class . '>' .
  4754. $title .
  4755. '</span>' . $force_download_html . $send_to . $copy_to_myfiles . $open_in_new_window_link . $pdf_icon;
  4756. } elseif (
  4757. // Show preview
  4758. preg_match('/swf$/i', urldecode($url)) ||
  4759. preg_match('/png$/i', urldecode($url)) ||
  4760. preg_match('/gif$/i', urldecode($url)) ||
  4761. preg_match('/jpg$/i', urldecode($url)) ||
  4762. preg_match('/jpeg$/i', urldecode($url)) ||
  4763. preg_match('/bmp$/i', urldecode($url)) ||
  4764. preg_match('/svg$/i', urldecode($url)) ||
  4765. (
  4766. preg_match('/wav$/i', urldecode($url)) &&
  4767. preg_match('/_chnano_.wav$/i', urldecode($url)) &&
  4768. api_get_setting('enable_nanogong') == 'true'
  4769. )
  4770. ) {
  4771. // Simpler version of showinframesmin.php with no headers
  4772. $url = 'show_content.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
  4773. $class = 'ajax';
  4774. if ($visibility == false) {
  4775. $class = "ajax invisible";
  4776. }
  4777. return Display::url(
  4778. $title,
  4779. $url,
  4780. [
  4781. 'class' => $class,
  4782. 'title' => $tooltip_title_alt,
  4783. 'data-title' => $title,
  4784. 'style' => 'float: left;'
  4785. ]
  4786. )
  4787. . $force_download_html . $send_to . $copy_to_myfiles
  4788. . $open_in_new_window_link . $pdf_icon;
  4789. } else {
  4790. // For PDF Download the file.
  4791. $pdfPreview = null;
  4792. if ($ext != 'pdf' && !in_array($ext, $webOdflist)) {
  4793. $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
  4794. } else {
  4795. $pdfPreview = Display::url(
  4796. Display::return_icon('preview.gif', get_lang('Preview')),
  4797. api_get_path(WEB_CODE_PATH).'document/showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'],
  4798. array('style' => 'float:right')
  4799. );
  4800. }
  4801. // No plugin just the old and good showinframes.php page
  4802. return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" style="float:left" ' . $visibility_class . ' >' . $title . '</a>' .
  4803. $pdfPreview.$force_download_html . $send_to . $copy_to_myfiles . $open_in_new_window_link . $pdf_icon;
  4804. }
  4805. } else {
  4806. return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' . $title . '</a>' .
  4807. $force_download_html . $send_to . $copy_to_myfiles . $open_in_new_window_link . $pdf_icon;
  4808. }
  4809. // end copy files to users myfiles
  4810. } else {
  4811. // Icon column
  4812. if (preg_match('/shared_folder/', urldecode($url)) &&
  4813. preg_match('/shared_folder$/', urldecode($url)) == false &&
  4814. preg_match('/shared_folder_session_' . $current_session_id . '$/', urldecode($url)) == false
  4815. ) {
  4816. if ($filetype == 'file') {
  4817. //Sound preview with jplayer
  4818. if (preg_match('/mp3$/i', urldecode($url)) ||
  4819. (preg_match('/wav$/i', urldecode($url)) && !preg_match('/_chnano_.wav$/i', urldecode($url))) ||
  4820. preg_match('/ogg$/i', urldecode($url))) {
  4821. $sound_preview = DocumentManager::generate_media_preview($counter);
  4822. return $sound_preview;
  4823. } elseif (
  4824. // Show preview
  4825. preg_match('/swf$/i', urldecode($url)) ||
  4826. preg_match('/png$/i', urldecode($url)) ||
  4827. preg_match('/gif$/i', urldecode($url)) ||
  4828. preg_match('/jpg$/i', urldecode($url)) ||
  4829. preg_match('/jpeg$/i', urldecode($url)) ||
  4830. preg_match('/bmp$/i', urldecode($url)) ||
  4831. preg_match('/svg$/i', urldecode($url)) ||
  4832. (
  4833. preg_match('/wav$/i', urldecode($url)) &&
  4834. preg_match('/_chnano_.wav$/i', urldecode($url)) &&
  4835. api_get_setting('enable_nanogong') == 'true'
  4836. )
  4837. ) {
  4838. $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id'];
  4839. return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
  4840. DocumentManager::build_document_icon_tag($filetype, $path) .
  4841. Display::return_icon('shared.png', get_lang('ResourceShared'), array()) . '</a>';
  4842. } else {
  4843. return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
  4844. DocumentManager::build_document_icon_tag($filetype, $path) .
  4845. Display::return_icon('shared.png', get_lang('ResourceShared'), array()) . '</a>';
  4846. }
  4847. } else {
  4848. return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" target="' . $target . '"' . $visibility_class . ' style="float:left">' .
  4849. DocumentManager::build_document_icon_tag($filetype, $path) .
  4850. Display::return_icon('shared.png', get_lang('ResourceShared'), array()) . '</a>';
  4851. }
  4852. } else {
  4853. if ($filetype == 'file') {
  4854. // Sound preview with jplayer
  4855. if (preg_match('/mp3$/i', urldecode($url)) ||
  4856. (preg_match('/wav$/i', urldecode($url)) && !preg_match('/_chnano_.wav$/i', urldecode($url))) ||
  4857. preg_match('/ogg$/i', urldecode($url))) {
  4858. $sound_preview = DocumentManager::generate_media_preview($counter);
  4859. return $sound_preview;
  4860. } elseif (
  4861. //Show preview
  4862. preg_match('/html$/i', urldecode($url)) ||
  4863. preg_match('/htm$/i', urldecode($url)) ||
  4864. preg_match('/swf$/i', urldecode($url)) ||
  4865. preg_match('/png$/i', urldecode($url)) ||
  4866. preg_match('/gif$/i', urldecode($url)) ||
  4867. preg_match('/jpg$/i', urldecode($url)) ||
  4868. preg_match('/jpeg$/i', urldecode($url)) ||
  4869. preg_match('/bmp$/i', urldecode($url)) ||
  4870. preg_match('/svg$/i', urldecode($url)) ||
  4871. (
  4872. preg_match('/wav$/i', urldecode($url)) &&
  4873. preg_match('/_chnano_.wav$/i', urldecode($url)) &&
  4874. api_get_setting('enable_nanogong') == 'true'
  4875. )
  4876. ) {
  4877. $url = 'showinframes.php?' . api_get_cidreq() . '&id=' . $document_data['id']; //without preview
  4878. return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
  4879. DocumentManager::build_document_icon_tag($filetype, $path) . '</a>';
  4880. } else {
  4881. return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" ' . $visibility_class . ' style="float:left">' .
  4882. DocumentManager::build_document_icon_tag($filetype, $path) . '</a>';
  4883. }
  4884. } else {
  4885. return '<a href="' . $url . '" title="' . $tooltip_title_alt . '" target="' . $target . '"' . $visibility_class . ' style="float:left">' .
  4886. DocumentManager::build_document_icon_tag($filetype, $path) . '</a>';
  4887. }
  4888. }
  4889. }
  4890. }
  4891. /**
  4892. * Builds an img html tag for the file type
  4893. *
  4894. * @param string $type (file/folder)
  4895. * @param string $path
  4896. * @return string img html tag
  4897. */
  4898. public static function build_document_icon_tag($type, $path)
  4899. {
  4900. $basename = basename($path);
  4901. $current_session_id = api_get_session_id();
  4902. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  4903. $user_image = false;
  4904. if ($type == 'file') {
  4905. $icon = choose_image($basename);
  4906. if (preg_match('/_chnano_.wav$/i', $basename)) {
  4907. $icon = "jplayer_play.png";
  4908. $basename = 'wav' . ' ' . '(Nanogong)';
  4909. } else {
  4910. $basename = substr(strrchr($basename, '.'), 1);
  4911. }
  4912. } else {
  4913. if ($path == '/shared_folder') {
  4914. $icon = 'folder_users.gif';
  4915. if ($is_allowed_to_edit) {
  4916. $basename = get_lang('HelpUsersFolder');
  4917. } else {
  4918. $basename = get_lang('UserFolders');
  4919. }
  4920. } elseif (strstr($basename, 'sf_user_')) {
  4921. $userinfo = api_get_user_info(substr($basename, 8));
  4922. $icon = $userinfo['avatar_small'];
  4923. $basename = get_lang('UserFolder') . ' ' . $userinfo['complete_name'];
  4924. $user_image = true;
  4925. } elseif (strstr($path, 'shared_folder_session_')) {
  4926. if ($is_allowed_to_edit) {
  4927. $basename = '***(' . api_get_session_name($current_session_id) . ')*** ' . get_lang('HelpUsersFolder');
  4928. } else {
  4929. $basename = get_lang('UserFolders') . ' (' . api_get_session_name($current_session_id) . ')';
  4930. }
  4931. $icon = 'folder_users.gif';
  4932. } else {
  4933. $icon = 'folder_document.gif';
  4934. if ($path == '/audio') {
  4935. $icon = 'folder_audio.gif';
  4936. if (api_is_allowed_to_edit()) {
  4937. $basename = get_lang('HelpDefaultDirDocuments');
  4938. } else {
  4939. $basename = get_lang('Audio');
  4940. }
  4941. } elseif ($path == '/flash') {
  4942. $icon = 'folder_flash.gif';
  4943. if (api_is_allowed_to_edit()) {
  4944. $basename = get_lang('HelpDefaultDirDocuments');
  4945. } else {
  4946. $basename = get_lang('Flash');
  4947. }
  4948. } elseif ($path == '/images') {
  4949. $icon = 'folder_images.gif';
  4950. if (api_is_allowed_to_edit()) {
  4951. $basename = get_lang('HelpDefaultDirDocuments');
  4952. } else {
  4953. $basename = get_lang('Images');
  4954. }
  4955. } elseif ($path == '/video') {
  4956. $icon = 'folder_video.gif';
  4957. if (api_is_allowed_to_edit()) {
  4958. $basename = get_lang('HelpDefaultDirDocuments');
  4959. } else {
  4960. $basename = get_lang('Video');
  4961. }
  4962. } elseif ($path == '/images/gallery') {
  4963. $icon = 'folder_gallery.gif';
  4964. if (api_is_allowed_to_edit()) {
  4965. $basename = get_lang('HelpDefaultDirDocuments');
  4966. } else {
  4967. $basename = get_lang('Gallery');
  4968. }
  4969. } elseif ($path == '/chat_files') {
  4970. $icon = 'folder_chat.gif';
  4971. if (api_is_allowed_to_edit()) {
  4972. $basename = get_lang('HelpFolderChat');
  4973. } else {
  4974. $basename = get_lang('ChatFiles');
  4975. }
  4976. } elseif ($path == '/learning_path') {
  4977. $icon = 'folder_learningpath.gif';
  4978. if (api_is_allowed_to_edit()) {
  4979. $basename = get_lang('HelpFolderLearningPaths');
  4980. } else {
  4981. $basename = get_lang('LearningPaths');
  4982. }
  4983. }
  4984. }
  4985. }
  4986. if ($user_image) {
  4987. return Display::img($icon, $basename, array());
  4988. }
  4989. return Display::return_icon($icon, $basename, array());
  4990. }
  4991. /**
  4992. * Creates the row of edit icons for a file/folder
  4993. *
  4994. * @param string $curdirpath current path (cfr open folder)
  4995. * @param string $type (file/folder)
  4996. * @param string $path dbase path of file/folder
  4997. * @param int $visibility (1/0)
  4998. * @param int $id dbase id of the document
  4999. * @return string html img tags with hyperlinks
  5000. */
  5001. public static function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0, $visibility)
  5002. {
  5003. $web_odf_extension_list = DocumentManager::get_web_odf_extension_list();
  5004. $document_id = $document_data['id'];
  5005. $type = $document_data['filetype'];
  5006. $is_read_only = $document_data['readonly'];
  5007. $path = $document_data['path'];
  5008. $parent_id = DocumentManager::get_document_id(api_get_course_info(), dirname($path));
  5009. $curdirpath = dirname($document_data['path']);
  5010. $is_certificate_mode = DocumentManager::is_certificate_mode($path);
  5011. $curdirpath = urlencode($curdirpath);
  5012. $extension = pathinfo($path, PATHINFO_EXTENSION);
  5013. //@todo Implement remote support for converter
  5014. $usePpt2lp = (api_get_setting('service_ppt2lp', 'active') == 'true' && api_get_setting('service_ppt2lp', 'host') == 'localhost');
  5015. $formatTypeList = DocumentManager::getFormatTypeListConvertor('from', $extension);
  5016. $formatType = current($formatTypeList);
  5017. // Build URL-parameters for table-sorting
  5018. $sort_params = array();
  5019. if (isset($_GET['column'])) {
  5020. $sort_params[] = 'column=' . Security::remove_XSS($_GET['column']);
  5021. }
  5022. if (isset($_GET['page_nr'])) {
  5023. $sort_params[] = 'page_nr=' . Security::remove_XSS($_GET['page_nr']);
  5024. }
  5025. if (isset($_GET['per_page'])) {
  5026. $sort_params[] = 'per_page=' . Security::remove_XSS($_GET['per_page']);
  5027. }
  5028. if (isset($_GET['direction'])) {
  5029. $sort_params[] = 'direction=' . Security::remove_XSS($_GET['direction']);
  5030. }
  5031. $sort_params = implode('&amp;', $sort_params);
  5032. $visibility_icon = ($visibility == 0) ? 'invisible' : 'visible';
  5033. $visibility_command = ($visibility == 0) ? 'set_visible' : 'set_invisible';
  5034. $modify_icons = '';
  5035. // If document is read only *or* we're in a session and the document
  5036. // is from a non-session context, hide the edition capabilities
  5037. if ($is_read_only /* or ($session_id!=api_get_session_id()) */) {
  5038. if (api_is_course_admin() || api_is_platform_admin()) {
  5039. if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
  5040. $modify_icons = '<a href="edit_draw.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
  5041. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5042. } elseif (in_array($extension, $web_odf_extension_list) && api_get_setting('enabled_support_odf') === true) {
  5043. $modify_icons = '<a href="edit_odf.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
  5044. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5045. } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
  5046. $modify_icons = '<a href="edit_paint.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
  5047. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5048. } else {
  5049. $modify_icons = '<a href="edit_document.php?' . api_get_cidreq() . '&id=' . $document_id. '">' .
  5050. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5051. }
  5052. } else {
  5053. $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
  5054. }
  5055. $modify_icons .= '&nbsp;' . Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL);
  5056. if (api_is_allowed_to_edit() || api_is_platform_admin()) {
  5057. $modify_icons .= '&nbsp;' . Display::return_icon($visibility_icon . '.png', get_lang('VisibilityCannotBeChanged'), '', ICON_SIZE_SMALL);
  5058. }
  5059. $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('Delete'), array(), ICON_SIZE_SMALL);
  5060. } else {
  5061. //Edit button
  5062. if (in_array($path, DocumentManager::get_system_folders())) {
  5063. $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
  5064. } elseif ($is_certificate_mode ) {
  5065. // gradebook category doesn't seem to be taken into account
  5066. $modify_icons = '<a href="edit_document.php?' . api_get_cidreq() . '&amp;id=' . $document_id . '&curdirpath=/certificates">' . Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5067. } else {
  5068. if (api_get_session_id()) {
  5069. if ($document_data['session_id'] == api_get_session_id()) {
  5070. if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
  5071. $modify_icons = '<a href="edit_draw.php?' . api_get_cidreq() . '&amp;id=' . $document_id . '">' .
  5072. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5073. } elseif (in_array($extension, $web_odf_extension_list) && api_get_setting('enabled_support_odf') === true) {
  5074. $modify_icons = '<a href="edit_odf.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
  5075. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5076. } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
  5077. $modify_icons = '<a href="edit_paint.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
  5078. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5079. } else {
  5080. $modify_icons = '<a href="edit_document.php?' . api_get_cidreq() . '&amp;id=' . $document_id . '">' .
  5081. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5082. }
  5083. } else {
  5084. $modify_icons .= '&nbsp;' . Display::return_icon('edit_na.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>';
  5085. }
  5086. } else {
  5087. if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
  5088. $modify_icons = '<a href="edit_draw.php?' . api_get_cidreq() . '&amp;id=' . $document_id . '">' .
  5089. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5090. } elseif (in_array($extension, $web_odf_extension_list) && api_get_setting('enabled_support_odf') === true) {
  5091. $modify_icons = '<a href="edit_odf.php?' . api_get_cidreq() . '&id=' . $document_id . '">' .
  5092. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5093. } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
  5094. $modify_icons = '<a href="edit_paint.php?' . api_get_cidreq() . '&amp;id=' . $document_id . '">' .
  5095. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5096. } else {
  5097. $modify_icons = '<a href="edit_document.php?' . api_get_cidreq() . '&amp;id=' . $document_id . '">' .
  5098. Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
  5099. }
  5100. }
  5101. }
  5102. // Move button.
  5103. if ($is_certificate_mode || in_array($path, DocumentManager::get_system_folders())) {
  5104. $modify_icons .= '&nbsp;' . Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
  5105. } else {
  5106. if (api_get_session_id()) {
  5107. if ($document_data['session_id'] == api_get_session_id()) {
  5108. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;id=' . $parent_id . '&amp;move=' . $document_id . '">' .
  5109. Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
  5110. } else {
  5111. $modify_icons .= '&nbsp;' . Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
  5112. }
  5113. } else {
  5114. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;id=' . $parent_id . '&amp;move=' . $document_id . '">' .
  5115. Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL) . '</a>';
  5116. }
  5117. }
  5118. //Visibility button
  5119. if ($is_certificate_mode) {
  5120. $modify_icons .= '&nbsp;' . Display::return_icon($visibility_icon . '.png', get_lang('VisibilityCannotBeChanged'), array(), ICON_SIZE_SMALL) . '</a>';
  5121. } else {
  5122. if (api_is_allowed_to_edit() || api_is_platform_admin()) {
  5123. if ($visibility_icon == 'invisible') {
  5124. $tip_visibility = get_lang('Show');
  5125. } else {
  5126. $tip_visibility = get_lang('Hide');
  5127. }
  5128. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;id=' . $parent_id . '&amp;' . $visibility_command . '=' . $id . '&amp;' . $sort_params . '">' .
  5129. Display::return_icon($visibility_icon . '.png', $tip_visibility, '', ICON_SIZE_SMALL) . '</a>';
  5130. }
  5131. }
  5132. // Delete button
  5133. if (in_array($path, DocumentManager::get_system_folders())) {
  5134. $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('ThisFolderCannotBeDeleted'), array(), ICON_SIZE_SMALL);
  5135. } else {
  5136. $titleToShow = addslashes(basename($document_data['title']));
  5137. if (isset($_GET['curdirpath']) &&
  5138. $_GET['curdirpath'] == '/certificates' &&
  5139. DocumentManager::get_default_certificate_id(api_get_course_id()) == $id
  5140. ) {
  5141. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id.'&amp;' . $sort_params . 'delete_certificate_id=' . $id . '" onclick="return confirmation(\'' . $titleToShow . '\');">' .
  5142. Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
  5143. } else {
  5144. if ($is_certificate_mode) {
  5145. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid=' . $document_id . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow . '\');">' .
  5146. Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
  5147. } else {
  5148. if (api_get_session_id()) {
  5149. if ($document_data['session_id'] == api_get_session_id()) {
  5150. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow . '\');">'.
  5151. Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
  5152. } else {
  5153. $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('ThisFolderCannotBeDeleted'), array(), ICON_SIZE_SMALL);
  5154. }
  5155. } else {
  5156. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&action=delete_item&id='.$parent_id.'&deleteid='.$document_id . '&amp;' . $sort_params . '" onclick="return confirmation(\'' . $titleToShow. '\');">' .
  5157. Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
  5158. }
  5159. }
  5160. }
  5161. }
  5162. // Add action to covert to PDF, will create a new document whit same filename but .pdf extension
  5163. // @TODO: add prompt to select a format target
  5164. if (in_array($path, DocumentManager::get_system_folders())) {
  5165. // nothing to do
  5166. } else {
  5167. if ($usePpt2lp && $formatType) {
  5168. $modify_icons .= '&nbsp;<a class="convertAction" href="#" ' .
  5169. 'data-documentId = ' . $document_id .
  5170. ' data-formatType = ' . $formatType . '>' .
  5171. Display::return_icon(
  5172. 'convert.png',
  5173. get_lang('Convert'),
  5174. array(),
  5175. ICON_SIZE_SMALL
  5176. ) . '</a>';
  5177. }
  5178. }
  5179. }
  5180. if ($type == 'file' && ($extension == 'html' || $extension == 'htm')) {
  5181. if ($is_template == 0) {
  5182. if ((isset($_GET['curdirpath']) && $_GET['curdirpath'] != '/certificates') || !isset($_GET['curdirpath'])) {
  5183. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&amp;add_as_template=' . $id . '&amp;' . $sort_params . '">' .
  5184. Display::return_icon('wizard.png', get_lang('AddAsTemplate'), array(), ICON_SIZE_SMALL) . '</a>';
  5185. }
  5186. if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates') {//allow attach certificate to course
  5187. $visibility_icon_certificate = 'nocertificate';
  5188. if (DocumentManager::get_default_certificate_id(api_get_course_id()) == $id) {
  5189. $visibility_icon_certificate = 'certificate';
  5190. $certificate = get_lang('DefaultCertificate');
  5191. $preview = get_lang('PreviewCertificate');
  5192. $is_preview = true;
  5193. } else {
  5194. $is_preview = false;
  5195. $certificate = get_lang('NoDefaultCertificate');
  5196. }
  5197. if (isset($_GET['selectcat'])) {
  5198. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&amp;selectcat=' . Security::remove_XSS($_GET['selectcat']) . '&amp;set_certificate=' . $id . '&amp;' . $sort_params . '">
  5199. <img src="../img/' . $visibility_icon_certificate . '.png" border="0" title="' . $certificate . '" alt="" /></a>';
  5200. if ($is_preview) {
  5201. $modify_icons .= '&nbsp;<a target="_blank" href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . $curdirpath . '&amp;set_preview=' . $id . '&amp;' . $sort_params . '" >' .
  5202. Display::return_icon('preview_view.png', $preview, '', ICON_SIZE_SMALL) . '</a>';
  5203. }
  5204. }
  5205. }
  5206. } else {
  5207. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&curdirpath=' . $curdirpath . '&amp;remove_as_template=' . $id. '&amp;' . $sort_params . '">' .
  5208. Display::return_icon('wizard_na.png', get_lang('RemoveAsTemplate'), '', ICON_SIZE_SMALL) . '</a>';
  5209. }
  5210. $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?' . api_get_cidreq() . '&action=export_to_pdf&id=' . $id . '">' .
  5211. Display::return_icon('pdf.png', get_lang('Export2PDF'), array(), ICON_SIZE_SMALL) . '</a>';
  5212. }
  5213. return $modify_icons;
  5214. }
  5215. /**
  5216. * @param $folders
  5217. * @param $curdirpath
  5218. * @param $move_file
  5219. * @param string $group_dir
  5220. * @return string
  5221. */
  5222. public static function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir = '')
  5223. {
  5224. $form = new FormValidator('move_to', 'post', api_get_self().'?'.api_get_cidreq());
  5225. // Form title
  5226. $form->addElement('hidden', 'move_file', $move_file);
  5227. $options = array();
  5228. // Group documents cannot be uploaded in the root
  5229. if ($group_dir == '') {
  5230. if ($curdirpath != '/') {
  5231. $options['/'] = get_lang('Documents');
  5232. }
  5233. if (is_array($folders)) {
  5234. foreach ($folders as & $folder) {
  5235. // Hide some folders
  5236. if ($folder == '/HotPotatoes_files' ||
  5237. $folder == '/certificates' ||
  5238. basename($folder) == 'css'
  5239. ) {
  5240. continue;
  5241. }
  5242. // Admin setting for Hide/Show the folders of all users
  5243. if (api_get_setting('show_users_folders') == 'false' &&
  5244. (strstr($folder, '/shared_folder') || strstr($folder, 'shared_folder_session_'))
  5245. ) {
  5246. continue;
  5247. }
  5248. // Admin setting for Hide/Show Default folders to all users
  5249. if (api_get_setting('show_default_folders') == 'false' &&
  5250. (
  5251. $folder == '/images' ||
  5252. $folder == '/flash' ||
  5253. $folder == '/audio' ||
  5254. $folder == '/video' ||
  5255. strstr($folder, '/images/gallery') ||
  5256. $folder == '/video/flv'
  5257. )
  5258. ) {
  5259. continue;
  5260. }
  5261. // Admin setting for Hide/Show chat history folder
  5262. if (api_get_setting('show_chat_folder') == 'false' &&
  5263. $folder == '/chat_files') {
  5264. continue;
  5265. }
  5266. // You cannot move a file to:
  5267. // 1. current directory
  5268. // 2. inside the folder you want to move
  5269. // 3. inside a subfolder of the folder you want to move
  5270. if (($curdirpath != $folder) &&
  5271. ($folder != $move_file) &&
  5272. (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')
  5273. ) {
  5274. $path_displayed = $folder;
  5275. // If document title is used, we have to display titles instead of real paths...
  5276. $path_displayed = DocumentManager::get_titles_of_path($folder);
  5277. if (empty($path_displayed)) {
  5278. $path_displayed = get_lang('Untitled');
  5279. }
  5280. $options[$folder] = $path_displayed;
  5281. }
  5282. }
  5283. }
  5284. } else {
  5285. foreach ($folders as $folder) {
  5286. if (($curdirpath != $folder) &&
  5287. ($folder != $move_file) &&
  5288. (substr($folder, 0, strlen($move_file) + 1) != $move_file . '/')
  5289. ) {
  5290. // Cannot copy dir into his own subdir
  5291. $path_displayed = DocumentManager::get_titles_of_path($folder);
  5292. $display_folder = substr($path_displayed, strlen($group_dir));
  5293. $display_folder = ($display_folder == '') ? get_lang('Documents') : $display_folder;
  5294. //$form .= '<option value="'.$folder.'">'.$display_folder.'</option>';
  5295. $options[$folder] = $display_folder;
  5296. }
  5297. }
  5298. }
  5299. $form->addElement('select', 'move_to', get_lang('MoveTo'), $options);
  5300. $form->addButtonNext(get_lang('MoveElement'), 'move_file_submit');
  5301. return $form->returnForm();
  5302. }
  5303. /**
  5304. * Gets the path translated with title of docs and folders
  5305. * @param string $path the real path
  5306. * @return the path which should be displayed
  5307. */
  5308. public static function get_titles_of_path($path)
  5309. {
  5310. global $tmp_folders_titles;
  5311. $course_id = api_get_course_int_id();
  5312. $nb_slashes = substr_count($path, '/');
  5313. $current_slash_pos = 0;
  5314. $path_displayed = '';
  5315. for ($i = 0; $i < $nb_slashes; $i++) {
  5316. // For each folder of the path, retrieve title.
  5317. $current_slash_pos = strpos($path, '/', $current_slash_pos + 1);
  5318. $tmp_path = substr($path, strpos($path, '/', 0), $current_slash_pos);
  5319. if (empty($tmp_path)) {
  5320. // If empty, then we are in the final part of the path
  5321. $tmp_path = $path;
  5322. }
  5323. if (!empty($tmp_folders_titles[$tmp_path])) {
  5324. // If this path has soon been stored here we don't need a new query
  5325. $path_displayed .= $tmp_folders_titles[$tmp_path];
  5326. } else {
  5327. $sql = 'SELECT title FROM ' . Database::get_course_table(TABLE_DOCUMENT) . '
  5328. WHERE c_id = ' . $course_id . ' AND path LIKE BINARY "' . $tmp_path . '"';
  5329. $rs = Database::query($sql);
  5330. $tmp_title = '/' . Database::result($rs, 0, 0);
  5331. $path_displayed .= $tmp_title;
  5332. $tmp_folders_titles[$tmp_path] = $tmp_title;
  5333. }
  5334. }
  5335. return $path_displayed;
  5336. }
  5337. /**
  5338. * Creates form that asks for the directory name.
  5339. * @return string html-output text for the form
  5340. */
  5341. public static function create_dir_form($dirId)
  5342. {
  5343. global $document_id;
  5344. $form = new FormValidator('create_dir_form', 'post', api_get_self().'?'.api_get_cidreq());
  5345. $form->addElement('hidden', 'create_dir', 1);
  5346. $form->addElement('hidden', 'dir_id', intval($document_id));
  5347. $form->addElement('hidden', 'id', intval($dirId));
  5348. $form->addElement('header', get_lang('CreateDir'));
  5349. $form->addText('dirname', get_lang('NewDir'), array('autofocus' => 'autofocus'));
  5350. $form->addButtonCreate(get_lang('CreateFolder'));
  5351. return $form->returnForm();
  5352. }
  5353. /**
  5354. * Checks whether the user is in shared folder
  5355. * @return return bool Return true when user is into shared folder
  5356. */
  5357. public static function is_shared_folder($curdirpath, $current_session_id)
  5358. {
  5359. $clean_curdirpath = Security::remove_XSS($curdirpath);
  5360. if ($clean_curdirpath == '/shared_folder') {
  5361. return true;
  5362. } elseif ($clean_curdirpath == '/shared_folder_session_' . $current_session_id) {
  5363. return true;
  5364. } else {
  5365. return false;
  5366. }
  5367. }
  5368. /**
  5369. * Checks whether the user is into any user shared folder
  5370. * @return return bool Return true when user is in any user shared folder
  5371. */
  5372. public static function is_any_user_shared_folder($path, $current_session_id)
  5373. {
  5374. $clean_path = Security::remove_XSS($path);
  5375. if (strpos($clean_path, 'shared_folder/sf_user_')) {
  5376. return true;
  5377. } elseif (strpos($clean_path, 'shared_folder_session_' . $current_session_id . '/sf_user_')) {
  5378. return true;
  5379. } else {
  5380. return false;
  5381. }
  5382. }
  5383. /**
  5384. * Checks whether the user is into his shared folder or into a subfolder
  5385. * @return bool Return true when user is in his user shared folder or into a subfolder
  5386. */
  5387. public static function is_my_shared_folder($user_id, $path, $current_session_id)
  5388. {
  5389. $clean_path = Security::remove_XSS($path) . '/';
  5390. //for security does not remove the last slash
  5391. $main_user_shared_folder = '/shared_folder\/sf_user_' . $user_id . '\//';
  5392. //for security does not remove the last slash
  5393. $main_user_shared_folder_session = '/shared_folder_session_' . $current_session_id . '\/sf_user_' . $user_id . '\//';
  5394. if (preg_match($main_user_shared_folder, $clean_path)) {
  5395. return true;
  5396. } elseif (preg_match($main_user_shared_folder_session, $clean_path)) {
  5397. return true;
  5398. } else {
  5399. return false;
  5400. }
  5401. }
  5402. /**
  5403. * Check if the file name or folder searched exist
  5404. * @return return bool Return true when exist
  5405. */
  5406. public static function search_keyword($document_name, $keyword)
  5407. {
  5408. if (api_strripos($document_name, $keyword) !== false) {
  5409. return true;
  5410. } else {
  5411. return false;
  5412. }
  5413. }
  5414. /**
  5415. * Checks whether a document can be previewed by using the browser.
  5416. * @param string $file_extension The filename extension of the document (it must be in lower case).
  5417. * @return bool Returns TRUE or FALSE.
  5418. */
  5419. public static function is_browser_viewable($file_extension)
  5420. {
  5421. static $allowed_extensions = array(
  5422. 'htm', 'html', 'xhtml',
  5423. 'gif', 'jpg', 'jpeg', 'png', 'tif', 'tiff',
  5424. 'pdf', 'svg', 'swf',
  5425. 'txt', 'log',
  5426. 'mp4', 'ogg', 'ogv', 'ogx', 'mpg', 'mpeg', 'mov', 'avi', 'webm', 'wmv',
  5427. 'mp3', 'oga', 'wav', 'au', 'wma', 'mid', 'kar'
  5428. );
  5429. /*
  5430. //TODO: make a admin swich to strict mode
  5431. 1. global default $allowed_extensions only: 'htm', 'html', 'xhtml', 'gif', 'jpg', 'jpeg', 'png', 'bmp', 'txt', 'log'
  5432. if (in_array($file_extension, $allowed_extensions)) { // Assignment + a logical check.
  5433. return true;
  5434. }
  5435. 2. check native support
  5436. 3. check plugins: quicktime, mediaplayer, vlc, acrobat, flash, java
  5437. */
  5438. if (!($result = in_array($file_extension, $allowed_extensions))) { // Assignment + a logical check.
  5439. return false;
  5440. }
  5441. //check native support (Explorer, Opera, Firefox, Chrome, Safari)
  5442. if ($file_extension == "pdf") {
  5443. return api_browser_support('pdf');
  5444. } elseif ($file_extension == "mp3") {
  5445. return api_browser_support('mp3');
  5446. } elseif ($file_extension == "mp4") {
  5447. return api_browser_support('mp4');
  5448. } elseif ($file_extension == "ogg" || $file_extension == "ogx" || $file_extension == "ogv" || $file_extension == "oga") {
  5449. return api_browser_support('ogg');
  5450. } elseif ($file_extension == "svg") {
  5451. return api_browser_support('svg');
  5452. } elseif ($file_extension == "mpg" || $file_extension == "mpeg") {
  5453. return api_browser_support('mpg');
  5454. } elseif ($file_extension == "mov") {
  5455. return api_browser_support('mov');
  5456. } elseif ($file_extension == "wav") {
  5457. return api_browser_support('wav');
  5458. } elseif ($file_extension == "mid" || $file_extension == "kar") {
  5459. return api_browser_support('mid');
  5460. } elseif ($file_extension == "avi") {
  5461. return api_browser_support('avi');
  5462. } elseif ($file_extension == "wma") {
  5463. return api_browser_support('wma');
  5464. } elseif ($file_extension == "wmv") {
  5465. return api_browser_support('wmv');
  5466. } elseif ($file_extension == "tif" || $file_extension == "tiff") {
  5467. return api_browser_support('tif');
  5468. } elseif ($file_extension == "mov") {
  5469. return api_browser_support('mov');
  5470. } elseif ($file_extension == "au") {
  5471. return api_browser_support('au');
  5472. } elseif ($file_extension == "webm") {
  5473. return api_browser_support('webm');
  5474. }
  5475. return $result;
  5476. }
  5477. }