document.lib.php 261 KB

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