document.lib.php 261 KB

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