document.lib.php 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924
  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 = intval($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. false,
  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 generateVideoPreview($file, $extension)
  2930. {
  2931. $type = '';
  2932. /*if ($extension != 'flv') {
  2933. }*/
  2934. //$type = "video/$extension";
  2935. //$fileInfo = parse_url($file);
  2936. //$type = self::file_get_mime_type(basename($fileInfo['path']));
  2937. $html = '<video id="myvideo" controls>';
  2938. $html .= '<source src="'.$file.'" >';
  2939. $html .= '</video>';
  2940. return $html;
  2941. }
  2942. /**
  2943. * @param array $course_info
  2944. * @param bool $lp_id
  2945. * @param string $target
  2946. * @param int $session_id
  2947. * @param bool $add_move_button
  2948. * @param string $filter_by_folder
  2949. * @param string $overwrite_url
  2950. * @param bool $showInvisibleFiles
  2951. * @param bool $showOnlyFolders
  2952. * @param int $folderId
  2953. * @param bool $addCloseButton
  2954. *
  2955. * @return string
  2956. */
  2957. public static function get_document_preview(
  2958. $course_info,
  2959. $lp_id = false,
  2960. $target = '',
  2961. $session_id = 0,
  2962. $add_move_button = false,
  2963. $filter_by_folder = null,
  2964. $overwrite_url = '',
  2965. $showInvisibleFiles = false,
  2966. $showOnlyFolders = false,
  2967. $folderId = false,
  2968. $addCloseButton = true
  2969. ) {
  2970. if (empty($course_info['real_id']) || empty($course_info['code']) || !is_array($course_info)) {
  2971. return '';
  2972. }
  2973. $user_id = api_get_user_id();
  2974. $userInfo = api_get_user_info();
  2975. $user_in_course = api_is_platform_admin();
  2976. if (!$user_in_course) {
  2977. if (CourseManager::is_course_teacher($user_id, $course_info['code'])) {
  2978. $user_in_course = true;
  2979. }
  2980. }
  2981. // Condition for the session
  2982. $session_id = (int) $session_id;
  2983. if (!$user_in_course) {
  2984. if (empty($session_id)) {
  2985. if (CourseManager::is_user_subscribed_in_course($user_id, $course_info['code'])) {
  2986. $user_in_course = true;
  2987. }
  2988. // Check if course is open then we can consider that the student is registered to the course
  2989. if (isset($course_info) && in_array($course_info['visibility'], [2, 3])) {
  2990. $user_in_course = true;
  2991. }
  2992. } else {
  2993. $user_status = SessionManager::get_user_status_in_course_session(
  2994. $user_id,
  2995. $course_info['real_id'],
  2996. $session_id
  2997. );
  2998. //is true if is an student, course session teacher or coach
  2999. if (in_array($user_status, ['0', '2', '6'])) {
  3000. $user_in_course = true;
  3001. }
  3002. }
  3003. }
  3004. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  3005. $tbl_item_prop = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3006. $condition_session = " AND (last.session_id = '$session_id' OR last.session_id = '0' OR last.session_id IS NULL)";
  3007. $add_folder_filter = null;
  3008. if (!empty($filter_by_folder)) {
  3009. $add_folder_filter = " AND docs.path LIKE '".Database::escape_string($filter_by_folder)."%'";
  3010. }
  3011. // If we are in LP display hidden folder https://support.chamilo.org/issues/6679
  3012. $lp_visibility_condition = null;
  3013. if ($lp_id) {
  3014. if ($showInvisibleFiles) {
  3015. $lp_visibility_condition .= ' OR last.visibility = 0';
  3016. }
  3017. }
  3018. $folderCondition = " AND docs.path LIKE '/%' ";
  3019. if (!api_is_allowed_to_edit()) {
  3020. $protectedFolders = self::getProtectedFolderFromStudent();
  3021. foreach ($protectedFolders as $folder) {
  3022. $folderCondition .= " AND docs.path NOT LIKE '$folder' ";
  3023. }
  3024. }
  3025. $parentData = [];
  3026. if ($folderId !== false) {
  3027. $parentData = self::get_document_data_by_id(
  3028. $folderId,
  3029. $course_info['code'],
  3030. false,
  3031. $session_id
  3032. );
  3033. if (!empty($parentData)) {
  3034. $cleanedPath = $parentData['path'];
  3035. $num = substr_count($cleanedPath, '/');
  3036. $notLikeCondition = '';
  3037. for ($i = 1; $i <= $num; $i++) {
  3038. $repeat = str_repeat('/%', $i + 1);
  3039. $notLikeCondition .= " AND docs.path NOT LIKE '".Database::escape_string($cleanedPath.$repeat)."' ";
  3040. }
  3041. $folderId = (int) $folderId;
  3042. $folderCondition = " AND
  3043. docs.id <> $folderId AND
  3044. docs.path LIKE '".$cleanedPath."/%'
  3045. $notLikeCondition
  3046. ";
  3047. } else {
  3048. $folderCondition = " AND docs.filetype = 'file' ";
  3049. }
  3050. }
  3051. $levelCondition = '';
  3052. if ($folderId === false) {
  3053. $levelCondition = " AND docs.path NOT LIKE'/%/%'";
  3054. }
  3055. $sql = "SELECT DISTINCT last.visibility, docs.*
  3056. FROM $tbl_item_prop AS last
  3057. INNER JOIN $tbl_doc AS docs
  3058. ON (docs.id = last.ref AND docs.c_id = last.c_id)
  3059. WHERE
  3060. docs.path NOT LIKE '%_DELETED_%' AND
  3061. last.tool = '".TOOL_DOCUMENT."' $condition_session AND
  3062. (last.visibility = '1' $lp_visibility_condition) AND
  3063. last.visibility <> 2 AND
  3064. docs.c_id = {$course_info['real_id']} AND
  3065. last.c_id = {$course_info['real_id']}
  3066. $folderCondition
  3067. $levelCondition
  3068. $add_folder_filter
  3069. ORDER BY docs.filetype DESC, docs.title ASC";
  3070. $res_doc = Database::query($sql);
  3071. $resources = Database::store_result($res_doc, 'ASSOC');
  3072. $return = '';
  3073. if ($lp_id == false && $addCloseButton) {
  3074. if ($folderId === false) {
  3075. $return .= Display::div(
  3076. Display::url(
  3077. Display::return_icon('close.png', get_lang('Close'), [], ICON_SIZE_SMALL),
  3078. ' javascript:void(0);',
  3079. ['id' => 'close_div_'.$course_info['real_id'].'_'.$session_id, 'class' => 'close_div']
  3080. ),
  3081. ['style' => 'position:absolute;right:10px']
  3082. );
  3083. }
  3084. }
  3085. // If you want to debug it, I advise you to do "echo" on the eval statements.
  3086. $newResources = [];
  3087. if (!empty($resources) && $user_in_course) {
  3088. foreach ($resources as $resource) {
  3089. $is_visible = self::is_visible_by_id(
  3090. $resource['id'],
  3091. $course_info,
  3092. $session_id,
  3093. api_get_user_id()
  3094. );
  3095. if ($showInvisibleFiles === false) {
  3096. if (!$is_visible) {
  3097. continue;
  3098. }
  3099. }
  3100. $newResources[] = $resource;
  3101. }
  3102. }
  3103. $label = get_lang('Documents');
  3104. $documents = [];
  3105. if ($folderId === false) {
  3106. $documents[$label] = [
  3107. 'id' => 0,
  3108. 'files' => $newResources,
  3109. ];
  3110. } else {
  3111. if (is_array($parentData)) {
  3112. $documents[$parentData['title']] = [
  3113. 'id' => (int) $folderId,
  3114. 'files' => $newResources,
  3115. ];
  3116. }
  3117. }
  3118. $writeResult = self::write_resources_tree(
  3119. $userInfo,
  3120. $course_info,
  3121. $session_id,
  3122. $documents,
  3123. $lp_id,
  3124. $target,
  3125. $add_move_button,
  3126. $overwrite_url,
  3127. $folderId
  3128. );
  3129. $return .= $writeResult;
  3130. $lpAjaxUrl = api_get_path(WEB_AJAX_PATH).'lp.ajax.php';
  3131. if ($lp_id === false) {
  3132. $url = $lpAjaxUrl.'?a=get_documents&lp_id=&cidReq='.$course_info['code'];
  3133. $return .= "<script>
  3134. $(document).ready(function () {
  3135. $('.close_div').click(function() {
  3136. var course_id = this.id.split('_')[2];
  3137. var session_id = this.id.split('_')[3];
  3138. $('#document_result_'+course_id+'_'+session_id).hide();
  3139. $('.lp_resource').remove();
  3140. $('.document_preview_container').html('');
  3141. });
  3142. });
  3143. </script>";
  3144. } else {
  3145. // For LPs
  3146. $url = $lpAjaxUrl.'?a=get_documents&lp_id='.$lp_id.'&'.api_get_cidreq();
  3147. }
  3148. if (!empty($overwrite_url)) {
  3149. $url .= '&url='.Security::remove_XSS($overwrite_url);
  3150. }
  3151. if ($add_move_button) {
  3152. $url .= '&add_move_button=1';
  3153. }
  3154. $return .= "<script>
  3155. function testResources(id, img) {
  3156. var numericId = id.split('_')[1];
  3157. var parentId = 'doc_id_'+numericId;
  3158. var tempId = 'temp_'+numericId;
  3159. var image = $('#'+img);
  3160. if (image.hasClass('open')) {
  3161. image.removeClass('open');
  3162. image.attr('src', '".Display::returnIconPath('nolines_plus.gif')."');
  3163. $('#'+id).show();
  3164. $('#'+tempId).hide();
  3165. } else {
  3166. image.addClass('open');
  3167. image.attr('src', '".Display::returnIconPath('nolines_minus.gif')."');
  3168. $('#'+id).hide();
  3169. $('#'+tempId).show();
  3170. var tempDiv = $('#'+parentId).find('#'+tempId);
  3171. if (tempDiv.length == 0) {
  3172. $.ajax({
  3173. type: 'GET',
  3174. async: false,
  3175. url: '".$url."',
  3176. data: 'folder_id='+numericId,
  3177. success: function(data) {
  3178. tempDiv = $('#doc_id_'+numericId).append('<div id='+tempId+'>'+data+'</div>');
  3179. }
  3180. });
  3181. }
  3182. }
  3183. }
  3184. </script>";
  3185. if (!$user_in_course) {
  3186. $return = '';
  3187. }
  3188. return $return;
  3189. }
  3190. /**
  3191. * Generate and return an HTML list of resources based on a given array.
  3192. * This list is used to show the course creator a list of available resources to choose from
  3193. * when creating a learning path.
  3194. *
  3195. * @param array $userInfo current user info
  3196. * @param array $course_info
  3197. * @param int $session_id
  3198. * @param array $documents
  3199. * @param bool $lp_id
  3200. * @param string $target
  3201. * @param bool $add_move_button
  3202. * @param string $overwrite_url
  3203. * @param int $folderId
  3204. *
  3205. * @return string
  3206. */
  3207. public static function write_resources_tree(
  3208. $userInfo,
  3209. $course_info,
  3210. $session_id,
  3211. $documents,
  3212. $lp_id = false,
  3213. $target = '',
  3214. $add_move_button = false,
  3215. $overwrite_url = '',
  3216. $folderId = false
  3217. ) {
  3218. $return = '';
  3219. if (!empty($documents)) {
  3220. foreach ($documents as $key => $resource) {
  3221. if (isset($resource['id']) && is_int($resource['id'])) {
  3222. $mainFolderResource = [
  3223. 'id' => $resource['id'],
  3224. 'title' => $key,
  3225. ];
  3226. if ($folderId === false) {
  3227. $return .= self::parseFolder($folderId, $mainFolderResource, $lp_id);
  3228. }
  3229. if (isset($resource['files'])) {
  3230. $return .= self::write_resources_tree(
  3231. $userInfo,
  3232. $course_info,
  3233. $session_id,
  3234. $resource['files'],
  3235. $lp_id,
  3236. $target,
  3237. $add_move_button,
  3238. $overwrite_url
  3239. );
  3240. }
  3241. $return .= '</div>';
  3242. $return .= '</ul>';
  3243. } else {
  3244. if ($resource['filetype'] === 'folder') {
  3245. $return .= self::parseFolder($folderId, $resource, $lp_id);
  3246. } else {
  3247. $return .= self::parseFile(
  3248. $userInfo,
  3249. $course_info,
  3250. $session_id,
  3251. $resource,
  3252. $lp_id,
  3253. $add_move_button,
  3254. $target,
  3255. $overwrite_url
  3256. );
  3257. }
  3258. }
  3259. }
  3260. }
  3261. return $return;
  3262. }
  3263. /**
  3264. * @param int $doc_id
  3265. * @param array $courseInfo
  3266. * @param int $sessionId
  3267. * @param int $user_id
  3268. * @param int $groupId iid
  3269. * @param bool $checkParentVisibility
  3270. *
  3271. * @return bool
  3272. */
  3273. public static function check_visibility_tree(
  3274. $doc_id,
  3275. $courseInfo,
  3276. $sessionId,
  3277. $user_id,
  3278. $groupId = 0,
  3279. $checkParentVisibility = true
  3280. ) {
  3281. if (empty($courseInfo)) {
  3282. return false;
  3283. }
  3284. $courseCode = $courseInfo['code'];
  3285. if (empty($courseCode)) {
  3286. return false;
  3287. }
  3288. $document_data = self::get_document_data_by_id(
  3289. $doc_id,
  3290. $courseCode,
  3291. null,
  3292. $sessionId
  3293. );
  3294. if ($sessionId != 0 && !$document_data) {
  3295. $document_data = self::get_document_data_by_id(
  3296. $doc_id,
  3297. $courseCode,
  3298. null,
  3299. 0
  3300. );
  3301. }
  3302. if (!empty($document_data)) {
  3303. // If admin or course teacher, allow anyway
  3304. if (api_is_platform_admin() || CourseManager::is_course_teacher($user_id, $courseCode)) {
  3305. return true;
  3306. }
  3307. if ($document_data['parent_id'] == false || empty($document_data['parent_id'])) {
  3308. if (!empty($groupId)) {
  3309. return true;
  3310. }
  3311. $visible = self::is_visible_by_id($doc_id, $courseInfo, $sessionId, $user_id);
  3312. return $visible;
  3313. } else {
  3314. $visible = self::is_visible_by_id($doc_id, $courseInfo, $sessionId, $user_id);
  3315. if (!$visible) {
  3316. return false;
  3317. } else {
  3318. if ($checkParentVisibility) {
  3319. return self::check_visibility_tree(
  3320. $document_data['parent_id'],
  3321. $courseInfo,
  3322. $sessionId,
  3323. $user_id,
  3324. $groupId
  3325. );
  3326. }
  3327. return true;
  3328. }
  3329. }
  3330. } else {
  3331. return false;
  3332. }
  3333. }
  3334. /**
  3335. * Index a given document.
  3336. *
  3337. * @param int Document ID inside its corresponding course
  3338. * @param string Course code
  3339. * @param int Session ID (not used yet)
  3340. * @param string Language of document's content (defaults to course language)
  3341. * @param array Array of specific fields (['code'=>'value',...])
  3342. * @param string What to do if the file already exists (default or overwrite)
  3343. * @param bool When set to true, this runs the indexer without actually saving anything to any database
  3344. *
  3345. * @return bool Returns true on presumed success, false on failure
  3346. */
  3347. public static function index_document(
  3348. $docid,
  3349. $course_code,
  3350. $session_id = 0,
  3351. $lang = 'english',
  3352. $specific_fields_values = [],
  3353. $if_exists = '',
  3354. $simulation = false
  3355. ) {
  3356. if (api_get_setting('search_enabled') !== 'true') {
  3357. return false;
  3358. }
  3359. if (empty($docid) or $docid != intval($docid)) {
  3360. return false;
  3361. }
  3362. if (empty($session_id)) {
  3363. $session_id = api_get_session_id();
  3364. }
  3365. $course_info = api_get_course_info($course_code);
  3366. $course_dir = $course_info['path'].'/document';
  3367. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  3368. $base_work_dir = $sys_course_path.$course_dir;
  3369. $course_id = $course_info['real_id'];
  3370. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  3371. $qry = "SELECT path, title FROM $table_document WHERE c_id = $course_id AND id = '$docid' LIMIT 1";
  3372. $result = Database::query($qry);
  3373. if (Database::num_rows($result) == 1) {
  3374. $row = Database::fetch_array($result);
  3375. $doc_path = api_get_path(SYS_COURSE_PATH).$course_dir.$row['path'];
  3376. //TODO: mime_content_type is deprecated, fileinfo php extension is enabled by default as of PHP 5.3.0
  3377. // now versions of PHP on Debian testing(5.2.6-5) and Ubuntu(5.2.6-2ubuntu) are lower, so wait for a while
  3378. $doc_mime = mime_content_type($doc_path);
  3379. $allowed_mime_types = self::file_get_mime_type(true);
  3380. // mime_content_type does not detect correctly some formats that
  3381. // are going to be supported for index, so an extensions array is used for the moment
  3382. if (empty($doc_mime)) {
  3383. $allowed_extensions = [
  3384. 'doc',
  3385. 'docx',
  3386. 'ppt',
  3387. 'pptx',
  3388. 'pps',
  3389. 'ppsx',
  3390. 'xls',
  3391. 'xlsx',
  3392. 'odt',
  3393. 'odp',
  3394. 'ods',
  3395. 'pdf',
  3396. 'txt',
  3397. 'rtf',
  3398. 'msg',
  3399. 'csv',
  3400. 'html',
  3401. 'htm',
  3402. ];
  3403. $extensions = preg_split("/[\/\\.]/", $doc_path);
  3404. $doc_ext = strtolower($extensions[count($extensions) - 1]);
  3405. if (in_array($doc_ext, $allowed_extensions)) {
  3406. switch ($doc_ext) {
  3407. case 'ppt':
  3408. case 'pps':
  3409. $doc_mime = 'application/vnd.ms-powerpoint';
  3410. break;
  3411. case 'xls':
  3412. $doc_mime = 'application/vnd.ms-excel';
  3413. break;
  3414. }
  3415. }
  3416. }
  3417. //@todo move this nightmare in a search controller or something like that!!! J.M
  3418. if (in_array($doc_mime, $allowed_mime_types)) {
  3419. $file_title = $row['title'];
  3420. $file_content = self::get_text_content($doc_path, $doc_mime);
  3421. $course_code = Database::escape_string($course_code);
  3422. $ic_slide = new IndexableChunk();
  3423. $ic_slide->addValue('title', $file_title);
  3424. $ic_slide->addCourseId($course_code);
  3425. $ic_slide->addToolId(TOOL_DOCUMENT);
  3426. $xapian_data = [
  3427. SE_COURSE_ID => $course_code,
  3428. SE_TOOL_ID => TOOL_DOCUMENT,
  3429. SE_DATA => ['doc_id' => $docid],
  3430. SE_USER => api_get_user_id(),
  3431. ];
  3432. $ic_slide->xapian_data = serialize($xapian_data);
  3433. $di = new ChamiloIndexer();
  3434. $return = $di->connectDb(null, null, $lang);
  3435. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  3436. $specific_fields = get_specific_field_list();
  3437. // process different depending on what to do if file exists
  3438. /**
  3439. * @TODO Find a way to really verify if the file had been
  3440. * overwriten. Now all work is done at
  3441. * handle_uploaded_document() and it's difficult to verify it
  3442. */
  3443. if (!empty($if_exists) && $if_exists == 'overwrite') {
  3444. // Overwrite the file on search engine
  3445. // Actually, it consists on a delete of terms from db,
  3446. // insert new ones, create a new search engine document,
  3447. // and remove the old one
  3448. // Get search_did
  3449. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  3450. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  3451. $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid);
  3452. $res = Database::query($sql);
  3453. if (Database::num_rows($res) > 0) {
  3454. $se_ref = Database::fetch_array($res);
  3455. if (!$simulation) {
  3456. $di->remove_document($se_ref['search_did']);
  3457. }
  3458. $all_specific_terms = '';
  3459. foreach ($specific_fields as $specific_field) {
  3460. if (!$simulation) {
  3461. delete_all_specific_field_value($course_code, $specific_field['id'], TOOL_DOCUMENT, $docid);
  3462. }
  3463. // Update search engine
  3464. if (isset($specific_fields_values[$specific_field['code']])) {
  3465. $sterms = trim($specific_fields_values[$specific_field['code']]);
  3466. } else { //if the specific field is not defined, force an empty one
  3467. $sterms = '';
  3468. }
  3469. $all_specific_terms .= ' '.$sterms;
  3470. $sterms = explode(',', $sterms);
  3471. foreach ($sterms as $sterm) {
  3472. $sterm = trim($sterm);
  3473. if (!empty($sterm)) {
  3474. $ic_slide->addTerm($sterm, $specific_field['code']);
  3475. // updated the last param here from $value to $sterm without being sure - see commit15464
  3476. if (!$simulation) {
  3477. add_specific_field_value(
  3478. $specific_field['id'],
  3479. $course_code,
  3480. TOOL_DOCUMENT,
  3481. $docid,
  3482. $sterm
  3483. );
  3484. }
  3485. }
  3486. }
  3487. }
  3488. // Add terms also to content to make terms findable by probabilistic search
  3489. $file_content = $all_specific_terms.' '.$file_content;
  3490. if (!$simulation) {
  3491. $ic_slide->addValue('content', $file_content);
  3492. $di->addChunk($ic_slide);
  3493. // Index and return a new search engine document id
  3494. $did = $di->index();
  3495. if ($did) {
  3496. // update the search_did on db
  3497. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  3498. $sql = 'UPDATE %s SET search_did=%d WHERE id=%d LIMIT 1';
  3499. $sql = sprintf($sql, $tbl_se_ref, (int) $did, (int) $se_ref['id']);
  3500. Database::query($sql);
  3501. }
  3502. }
  3503. }
  3504. } else {
  3505. // Add all terms
  3506. $all_specific_terms = '';
  3507. foreach ($specific_fields as $specific_field) {
  3508. if (isset($specific_fields_values[$specific_field['code']])) {
  3509. $sterms = trim($specific_fields_values[$specific_field['code']]);
  3510. } else { //if the specific field is not defined, force an empty one
  3511. $sterms = '';
  3512. }
  3513. $all_specific_terms .= ' '.$sterms;
  3514. if (!empty($sterms)) {
  3515. $sterms = explode(',', $sterms);
  3516. foreach ($sterms as $sterm) {
  3517. if (!$simulation) {
  3518. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  3519. add_specific_field_value(
  3520. $specific_field['id'],
  3521. $course_code,
  3522. TOOL_DOCUMENT,
  3523. $docid,
  3524. $sterm
  3525. );
  3526. }
  3527. }
  3528. }
  3529. }
  3530. // Add terms also to content to make terms findable by probabilistic search
  3531. $file_content = $all_specific_terms.' '.$file_content;
  3532. if (!$simulation) {
  3533. $ic_slide->addValue('content', $file_content);
  3534. $di->addChunk($ic_slide);
  3535. // Index and return search engine document id
  3536. $did = $di->index();
  3537. if ($did) {
  3538. // Save it to db
  3539. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  3540. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  3541. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  3542. $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid, $did);
  3543. Database::query($sql);
  3544. } else {
  3545. return false;
  3546. }
  3547. }
  3548. }
  3549. } else {
  3550. return false;
  3551. }
  3552. }
  3553. return true;
  3554. }
  3555. /**
  3556. * @return array
  3557. */
  3558. public static function get_web_odf_extension_list()
  3559. {
  3560. return ['ods', 'odt', 'odp'];
  3561. }
  3562. /**
  3563. * Set of extension allowed to use Jodconverter.
  3564. *
  3565. * @param $mode 'from'
  3566. * 'to'
  3567. * 'all'
  3568. * @param $format 'text'
  3569. * 'spreadsheet'
  3570. * 'presentation'
  3571. * 'drawing'
  3572. * 'all'
  3573. *
  3574. * @return array
  3575. */
  3576. public static function getJodconverterExtensionList($mode, $format)
  3577. {
  3578. $extensionList = [];
  3579. $extensionListFromText = [
  3580. 'odt',
  3581. 'sxw',
  3582. 'rtf',
  3583. 'doc',
  3584. 'docx',
  3585. 'wpd',
  3586. 'txt',
  3587. ];
  3588. $extensionListToText = [
  3589. 'pdf',
  3590. 'odt',
  3591. 'sxw',
  3592. 'rtf',
  3593. 'doc',
  3594. 'docx',
  3595. 'txt',
  3596. ];
  3597. $extensionListFromSpreadsheet = [
  3598. 'ods',
  3599. 'sxc',
  3600. 'xls',
  3601. 'xlsx',
  3602. 'csv',
  3603. 'tsv',
  3604. ];
  3605. $extensionListToSpreadsheet = [
  3606. 'pdf',
  3607. 'ods',
  3608. 'sxc',
  3609. 'xls',
  3610. 'xlsx',
  3611. 'csv',
  3612. 'tsv',
  3613. ];
  3614. $extensionListFromPresentation = [
  3615. 'odp',
  3616. 'sxi',
  3617. 'ppt',
  3618. 'pptx',
  3619. ];
  3620. $extensionListToPresentation = [
  3621. 'pdf',
  3622. 'swf',
  3623. 'odp',
  3624. 'sxi',
  3625. 'ppt',
  3626. 'pptx',
  3627. ];
  3628. $extensionListFromDrawing = ['odg'];
  3629. $extensionListToDrawing = ['svg', 'swf'];
  3630. if ($mode === 'from') {
  3631. if ($format === 'text') {
  3632. $extensionList = array_merge($extensionList, $extensionListFromText);
  3633. } elseif ($format === 'spreadsheet') {
  3634. $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
  3635. } elseif ($format === 'presentation') {
  3636. $extensionList = array_merge($extensionList, $extensionListFromPresentation);
  3637. } elseif ($format === 'drawing') {
  3638. $extensionList = array_merge($extensionList, $extensionListFromDrawing);
  3639. } elseif ($format === 'all') {
  3640. $extensionList = array_merge($extensionList, $extensionListFromText);
  3641. $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
  3642. $extensionList = array_merge($extensionList, $extensionListFromPresentation);
  3643. $extensionList = array_merge($extensionList, $extensionListFromDrawing);
  3644. }
  3645. } elseif ($mode === 'to') {
  3646. if ($format === 'text') {
  3647. $extensionList = array_merge($extensionList, $extensionListToText);
  3648. } elseif ($format === 'spreadsheet') {
  3649. $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
  3650. } elseif ($format === 'presentation') {
  3651. $extensionList = array_merge($extensionList, $extensionListToPresentation);
  3652. } elseif ($format === 'drawing') {
  3653. $extensionList = array_merge($extensionList, $extensionListToDrawing);
  3654. } elseif ($format === 'all') {
  3655. $extensionList = array_merge($extensionList, $extensionListToText);
  3656. $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
  3657. $extensionList = array_merge($extensionList, $extensionListToPresentation);
  3658. $extensionList = array_merge($extensionList, $extensionListToDrawing);
  3659. }
  3660. } elseif ($mode === 'all') {
  3661. if ($format === 'text') {
  3662. $extensionList = array_merge($extensionList, $extensionListFromText);
  3663. $extensionList = array_merge($extensionList, $extensionListToText);
  3664. } elseif ($format === 'spreadsheet') {
  3665. $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
  3666. $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
  3667. } elseif ($format === 'presentation') {
  3668. $extensionList = array_merge($extensionList, $extensionListFromPresentation);
  3669. $extensionList = array_merge($extensionList, $extensionListToPresentation);
  3670. } elseif ($format === 'drawing') {
  3671. $extensionList = array_merge($extensionList, $extensionListFromDrawing);
  3672. $extensionList = array_merge($extensionList, $extensionListToDrawing);
  3673. } elseif ($format === 'all') {
  3674. $extensionList = array_merge($extensionList, $extensionListFromText);
  3675. $extensionList = array_merge($extensionList, $extensionListToText);
  3676. $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
  3677. $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
  3678. $extensionList = array_merge($extensionList, $extensionListFromPresentation);
  3679. $extensionList = array_merge($extensionList, $extensionListToPresentation);
  3680. $extensionList = array_merge($extensionList, $extensionListFromDrawing);
  3681. $extensionList = array_merge($extensionList, $extensionListToDrawing);
  3682. }
  3683. }
  3684. return $extensionList;
  3685. }
  3686. /**
  3687. * Get Format type list by extension and mode.
  3688. *
  3689. * @param string $mode Mode to search format type list
  3690. *
  3691. * @example 'from'
  3692. * @example 'to'
  3693. *
  3694. * @param string $extension file extension to check file type
  3695. *
  3696. * @return array
  3697. */
  3698. public static function getFormatTypeListConvertor($mode = 'from', $extension)
  3699. {
  3700. $formatTypesList = [];
  3701. $formatTypes = ['text', 'spreadsheet', 'presentation', 'drawing'];
  3702. foreach ($formatTypes as $formatType) {
  3703. if (in_array($extension, self::getJodconverterExtensionList($mode, $formatType))) {
  3704. $formatTypesList[] = $formatType;
  3705. }
  3706. }
  3707. return $formatTypesList;
  3708. }
  3709. /**
  3710. * @param string $path
  3711. * @param bool $is_certificate_mode
  3712. *
  3713. * @return bool
  3714. */
  3715. public static function is_folder_to_avoid($path, $is_certificate_mode = false)
  3716. {
  3717. $foldersToAvoid = [
  3718. '/HotPotatoes_files',
  3719. '/certificates',
  3720. ];
  3721. $systemFolder = api_get_course_setting('show_system_folders');
  3722. if ($systemFolder == 1) {
  3723. $foldersToAvoid = [];
  3724. }
  3725. if (basename($path) == 'css') {
  3726. return true;
  3727. }
  3728. if ($is_certificate_mode == false) {
  3729. //Certificate results
  3730. if (strstr($path, 'certificates')) {
  3731. return true;
  3732. }
  3733. }
  3734. // Admin setting for Hide/Show the folders of all users
  3735. if (api_get_setting('show_users_folders') == 'false') {
  3736. $foldersToAvoid[] = '/shared_folder';
  3737. if (strstr($path, 'shared_folder_session_')) {
  3738. return true;
  3739. }
  3740. }
  3741. // Admin setting for Hide/Show Default folders to all users
  3742. if (api_get_setting('show_default_folders') == 'false') {
  3743. $foldersToAvoid[] = '/images';
  3744. $foldersToAvoid[] = '/flash';
  3745. $foldersToAvoid[] = '/audio';
  3746. $foldersToAvoid[] = '/video';
  3747. }
  3748. // Admin setting for Hide/Show chat history folder
  3749. if (api_get_setting('show_chat_folder') == 'false') {
  3750. $foldersToAvoid[] = '/chat_files';
  3751. }
  3752. if (is_array($foldersToAvoid)) {
  3753. return in_array($path, $foldersToAvoid);
  3754. } else {
  3755. return false;
  3756. }
  3757. }
  3758. /**
  3759. * @return array
  3760. */
  3761. public static function get_system_folders()
  3762. {
  3763. return [
  3764. '/certificates',
  3765. '/HotPotatoes_files',
  3766. '/chat_files',
  3767. '/images',
  3768. '/flash',
  3769. '/audio',
  3770. '/video',
  3771. '/shared_folder',
  3772. '/learning_path',
  3773. ];
  3774. }
  3775. /**
  3776. * @return array
  3777. */
  3778. public static function getProtectedFolderFromStudent()
  3779. {
  3780. return [
  3781. '/certificates',
  3782. '/HotPotatoes_files',
  3783. '/chat_files',
  3784. '/shared_folder',
  3785. '/learning_path',
  3786. ];
  3787. }
  3788. /**
  3789. * @param string $courseCode
  3790. *
  3791. * @return string 'visible' or 'invisible' string
  3792. */
  3793. public static function getDocumentDefaultVisibility($courseCode)
  3794. {
  3795. $settings = api_get_setting('tool_visible_by_default_at_creation');
  3796. $defaultVisibility = 'visible';
  3797. if (isset($settings['documents'])) {
  3798. $portalDefaultVisibility = 'invisible';
  3799. if ($settings['documents'] == 'true') {
  3800. $portalDefaultVisibility = 'visible';
  3801. }
  3802. $defaultVisibility = $portalDefaultVisibility;
  3803. }
  3804. if (api_get_setting('documents_default_visibility_defined_in_course') == 'true') {
  3805. $courseVisibility = api_get_course_setting('documents_default_visibility', $courseCode);
  3806. if (!empty($courseVisibility) && in_array($courseVisibility, ['visible', 'invisible'])) {
  3807. $defaultVisibility = $courseVisibility;
  3808. }
  3809. }
  3810. return $defaultVisibility;
  3811. }
  3812. /**
  3813. * @param array $courseInfo
  3814. * @param int $id doc id
  3815. * @param string $visibility visible/invisible
  3816. * @param int $userId
  3817. */
  3818. public static function updateVisibilityFromAllSessions($courseInfo, $id, $visibility, $userId)
  3819. {
  3820. $sessionList = SessionManager::get_session_by_course($courseInfo['real_id']);
  3821. if (!empty($sessionList)) {
  3822. foreach ($sessionList as $session) {
  3823. $sessionId = $session['id'];
  3824. api_item_property_update(
  3825. $courseInfo,
  3826. TOOL_DOCUMENT,
  3827. $id,
  3828. $visibility,
  3829. $userId,
  3830. null,
  3831. null,
  3832. null,
  3833. null,
  3834. $sessionId
  3835. );
  3836. }
  3837. }
  3838. }
  3839. /**
  3840. * @param string $filePath
  3841. * @param string $path
  3842. * @param array $courseInfo
  3843. * @param int $sessionId
  3844. * @param string $whatIfFileExists overwrite|rename
  3845. * @param int $userId
  3846. * @param int $groupId
  3847. * @param int $toUserId
  3848. * @param string $comment
  3849. *
  3850. * @return bool|path
  3851. */
  3852. public static function addFileToDocumentTool(
  3853. $filePath,
  3854. $path,
  3855. $courseInfo,
  3856. $sessionId,
  3857. $userId,
  3858. $whatIfFileExists = 'overwrite',
  3859. $groupId = null,
  3860. $toUserId = null,
  3861. $comment = null
  3862. ) {
  3863. if (!file_exists($filePath)) {
  3864. return false;
  3865. }
  3866. $fileInfo = pathinfo($filePath);
  3867. $file = [
  3868. 'name' => $fileInfo['basename'],
  3869. 'tmp_name' => $filePath,
  3870. 'size' => filesize($filePath),
  3871. 'from_file' => true,
  3872. ];
  3873. $course_dir = $courseInfo['path'].'/document';
  3874. $baseWorkDir = api_get_path(SYS_COURSE_PATH).$course_dir;
  3875. $filePath = handle_uploaded_document(
  3876. $courseInfo,
  3877. $file,
  3878. $baseWorkDir,
  3879. $path,
  3880. $userId,
  3881. $groupId,
  3882. $toUserId,
  3883. false,
  3884. $whatIfFileExists,
  3885. false,
  3886. false,
  3887. $comment,
  3888. $sessionId
  3889. );
  3890. if ($filePath) {
  3891. return self::get_document_id(
  3892. $courseInfo,
  3893. $filePath,
  3894. $sessionId
  3895. );
  3896. }
  3897. return false;
  3898. }
  3899. /**
  3900. * Converts wav to mp3 file.
  3901. * Requires the ffmpeg lib. In ubuntu: sudo apt-get install ffmpeg.
  3902. *
  3903. * @param string $wavFile
  3904. * @param bool $removeWavFileIfSuccess
  3905. *
  3906. * @return bool
  3907. */
  3908. public static function convertWavToMp3($wavFile, $removeWavFileIfSuccess = false)
  3909. {
  3910. if (file_exists($wavFile)) {
  3911. try {
  3912. $ffmpeg = \FFMpeg\FFMpeg::create();
  3913. $video = $ffmpeg->open($wavFile);
  3914. $mp3File = str_replace('wav', 'mp3', $wavFile);
  3915. $result = $video->save(new FFMpeg\Format\Audio\Mp3(), $mp3File);
  3916. if ($result && $removeWavFileIfSuccess) {
  3917. unlink($wavFile);
  3918. }
  3919. if (file_exists($mp3File)) {
  3920. return $mp3File;
  3921. }
  3922. } catch (Exception $e) {
  3923. error_log($e->getMessage());
  3924. error_log($e->getPrevious()->getMessage());
  3925. }
  3926. }
  3927. return false;
  3928. }
  3929. /**
  3930. * @param string $documentData wav document information
  3931. * @param array $courseInfo
  3932. * @param int $sessionId
  3933. * @param int $userId user that adds the document
  3934. * @param string $whatIfFileExists
  3935. * @param bool $deleteWavFile
  3936. *
  3937. * @return bool
  3938. */
  3939. public static function addAndConvertWavToMp3(
  3940. $documentData,
  3941. $courseInfo,
  3942. $sessionId,
  3943. $userId,
  3944. $whatIfFileExists = 'overwrite',
  3945. $deleteWavFile = false
  3946. ) {
  3947. if (empty($documentData)) {
  3948. return false;
  3949. }
  3950. if (isset($documentData['absolute_path']) &&
  3951. file_exists($documentData['absolute_path'])
  3952. ) {
  3953. $mp3FilePath = self::convertWavToMp3($documentData['absolute_path']);
  3954. if (!empty($mp3FilePath) && file_exists($mp3FilePath)) {
  3955. $documentId = self::addFileToDocumentTool(
  3956. $mp3FilePath,
  3957. dirname($documentData['path']),
  3958. $courseInfo,
  3959. $sessionId,
  3960. $userId,
  3961. $whatIfFileExists,
  3962. null,
  3963. null,
  3964. $documentData['comment']
  3965. );
  3966. if (!empty($documentId)) {
  3967. if ($deleteWavFile) {
  3968. $coursePath = $courseInfo['directory'].'/document';
  3969. $documentPath = api_get_path(SYS_COURSE_PATH).$coursePath;
  3970. self::delete_document(
  3971. $courseInfo,
  3972. null,
  3973. $documentPath,
  3974. $sessionId,
  3975. $documentData['id']
  3976. );
  3977. }
  3978. return $documentId;
  3979. }
  3980. }
  3981. }
  3982. return false;
  3983. }
  3984. /**
  3985. * Sets.
  3986. *
  3987. * @param string $file ($document_data['path'])
  3988. * @param string $file_url_sys
  3989. *
  3990. * @return string
  3991. */
  3992. public static function generateAudioTempFile($file, $file_url_sys)
  3993. {
  3994. //make temp audio
  3995. $temp_folder = api_get_path(SYS_ARCHIVE_PATH).'temp/audio';
  3996. if (!file_exists($temp_folder)) {
  3997. @mkdir($temp_folder, api_get_permissions_for_new_directories(), true);
  3998. }
  3999. //make htaccess with allow from all, and file index.html into temp/audio
  4000. $htaccess = api_get_path(SYS_ARCHIVE_PATH).'temp/audio/.htaccess';
  4001. if (!file_exists($htaccess)) {
  4002. $htaccess_content = "order deny,allow\r\nallow from all\r\nOptions -Indexes";
  4003. $fp = @fopen(api_get_path(SYS_ARCHIVE_PATH).'temp/audio/.htaccess', 'w');
  4004. if ($fp) {
  4005. fwrite($fp, $htaccess_content);
  4006. fclose($fp);
  4007. }
  4008. }
  4009. //encript temp name file
  4010. $name_crip = sha1(uniqid()); //encript
  4011. $findext = explode(".", $file);
  4012. $extension = $findext[count($findext) - 1];
  4013. $file_crip = $name_crip.'.'.$extension;
  4014. //copy file to temp/audio directory
  4015. $from_sys = $file_url_sys;
  4016. $to_sys = api_get_path(SYS_ARCHIVE_PATH).'temp/audio/'.$file_crip;
  4017. if (file_exists($from_sys)) {
  4018. copy($from_sys, $to_sys);
  4019. }
  4020. // get file from tmp directory
  4021. Session::write('temp_audio_nanogong', $to_sys);
  4022. return api_get_path(WEB_ARCHIVE_PATH).'temp/audio/'.$file_crip;
  4023. }
  4024. /**
  4025. * Erase temp nanogong audio.
  4026. */
  4027. public static function removeGeneratedAudioTempFile()
  4028. {
  4029. $tempAudio = Session::read('temp_audio_nanogong');
  4030. if (!empty(isset($tempAudio)) && is_file($tempAudio)) {
  4031. unlink($tempAudio);
  4032. Session::erase('temp_audio_nanogong');
  4033. }
  4034. }
  4035. /**
  4036. * Check if the path is used in this course.
  4037. *
  4038. * @param array $courseInfo
  4039. * @param string $path
  4040. *
  4041. * @return array
  4042. */
  4043. public static function getDocumentByPathInCourse($courseInfo, $path)
  4044. {
  4045. $table = Database::get_course_table(TABLE_DOCUMENT);
  4046. $path = Database::escape_string($path);
  4047. $courseId = $courseInfo['real_id'];
  4048. if (empty($courseId)) {
  4049. return false;
  4050. }
  4051. $sql = "SELECT * FROM $table WHERE c_id = $courseId AND path = '$path'";
  4052. $result = Database::query($sql);
  4053. return Database::store_result($result, 'ASSOC');
  4054. }
  4055. /**
  4056. * @param array $_course
  4057. *
  4058. * @return int
  4059. */
  4060. public static function createDefaultAudioFolder($_course)
  4061. {
  4062. if (!isset($_course['path'])) {
  4063. return false;
  4064. }
  4065. $audioId = null;
  4066. $path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  4067. if (!is_dir($path.'audio')) {
  4068. mkdir($path.'audio', api_get_permissions_for_new_directories());
  4069. $audioId = add_document($_course, '/audio', 'folder', 0, 'Audio');
  4070. api_item_property_update(
  4071. $_course,
  4072. TOOL_DOCUMENT,
  4073. $audioId,
  4074. 'FolderCreated',
  4075. api_get_user_id(),
  4076. null,
  4077. null,
  4078. null,
  4079. null,
  4080. api_get_session_id()
  4081. );
  4082. }
  4083. return $audioId;
  4084. }
  4085. /**
  4086. * Generate a default certificate for a courses.
  4087. *
  4088. * @todo move to certificate lib
  4089. *
  4090. * @global string $css CSS directory
  4091. * @global string $img_dir image directory
  4092. * @global string $default_course_dir Course directory
  4093. * @global string $js JS directory
  4094. *
  4095. * @param array $courseData The course info
  4096. * @param bool $fromBaseCourse
  4097. * @param int $sessionId
  4098. */
  4099. public static function generateDefaultCertificate(
  4100. $courseData,
  4101. $fromBaseCourse = false,
  4102. $sessionId = 0
  4103. ) {
  4104. if (empty($courseData)) {
  4105. return false;
  4106. }
  4107. global $css, $img_dir, $default_course_dir, $js;
  4108. $codePath = api_get_path(REL_CODE_PATH);
  4109. $dir = '/certificates';
  4110. $comment = null;
  4111. $title = get_lang('DefaultCertificate');
  4112. $fileName = api_replace_dangerous_char($title);
  4113. $filePath = api_get_path(SYS_COURSE_PATH)."{$courseData['directory']}/document$dir";
  4114. if (!is_dir($filePath)) {
  4115. mkdir($filePath, api_get_permissions_for_new_directories());
  4116. }
  4117. $fileFullPath = "$filePath/$fileName.html";
  4118. $fileType = 'file';
  4119. $templateContent = file_get_contents(api_get_path(SYS_CODE_PATH).'gradebook/certificate_template/template.html');
  4120. $search = ['{CSS}', '{IMG_DIR}', '{REL_CODE_PATH}', '{COURSE_DIR}'];
  4121. $replace = [$css.$js, $img_dir, $codePath, $default_course_dir];
  4122. $fileContent = str_replace($search, $replace, $templateContent);
  4123. $saveFilePath = "$dir/$fileName.html";
  4124. if ($fromBaseCourse) {
  4125. $defaultCertificateId = self::get_default_certificate_id(
  4126. $courseData['code'],
  4127. 0
  4128. );
  4129. if (!empty($defaultCertificateId)) {
  4130. // We have a certificate from the course base
  4131. $documentData = self::get_document_data_by_id(
  4132. $defaultCertificateId,
  4133. $courseData['code'],
  4134. false,
  4135. 0
  4136. );
  4137. if ($documentData) {
  4138. $fileContent = file_get_contents($documentData['absolute_path']);
  4139. }
  4140. }
  4141. }
  4142. if (file_exists($fileFullPath) === false) {
  4143. $result = file_put_contents($fileFullPath, $fileContent);
  4144. if ($result) {
  4145. $fileSize = filesize($fileFullPath);
  4146. $documentId = add_document(
  4147. $courseData,
  4148. $saveFilePath,
  4149. $fileType,
  4150. $fileSize,
  4151. $title,
  4152. $comment,
  4153. 0, //$readonly = 0,
  4154. true, //$save_visibility = true,
  4155. null, //$group_id = null,
  4156. $sessionId
  4157. );
  4158. api_item_property_update(
  4159. $courseData,
  4160. TOOL_DOCUMENT,
  4161. $documentId,
  4162. 'DocumentAdded',
  4163. api_get_user_id(),
  4164. null,
  4165. null,
  4166. null,
  4167. null,
  4168. $sessionId
  4169. );
  4170. $defaultCertificateId = self::get_default_certificate_id(
  4171. $courseData['code'],
  4172. $sessionId
  4173. );
  4174. if (!isset($defaultCertificateId)) {
  4175. self::attach_gradebook_certificate(
  4176. $courseData['code'],
  4177. $documentId,
  4178. $sessionId
  4179. );
  4180. }
  4181. }
  4182. }
  4183. }
  4184. /**
  4185. * Update the document name.
  4186. *
  4187. * @param int $documentId The document id
  4188. * @param string $newName The new name
  4189. */
  4190. public static function renameDocument($documentId, $newName)
  4191. {
  4192. $documentId = intval($documentId);
  4193. $newName = Database::escape_string($newName);
  4194. $docuentTable = Database::get_course_table(TABLE_DOCUMENT);
  4195. $values = [
  4196. 'title' => $newName,
  4197. ];
  4198. $whereConditions = [
  4199. 'id = ?' => $documentId,
  4200. ];
  4201. Database::update($docuentTable, $values, $whereConditions);
  4202. }
  4203. /**
  4204. * Get folder/file suffix.
  4205. *
  4206. * @param array $courseInfo
  4207. * @param int $sessionId
  4208. * @param int $groupId
  4209. *
  4210. * @return string
  4211. */
  4212. public static function getDocumentSuffix($courseInfo, $sessionId, $groupId)
  4213. {
  4214. // If no session or group, then no suffix.
  4215. if (empty($sessionId) && empty($groupId)) {
  4216. return '';
  4217. }
  4218. return '__'.intval($sessionId).'__'.intval($groupId);
  4219. }
  4220. /**
  4221. * Fix a document name adding session id and group id
  4222. * Turns picture.jpg -> picture__1__2.jpg
  4223. * Where 1 = session id and 2 group id
  4224. * Of session id and group id are empty then the function returns:
  4225. * picture.jpg -> picture.jpg.
  4226. *
  4227. * @param string $name folder or file name
  4228. * @param string $type 'folder' or 'file'
  4229. * @param array $courseInfo
  4230. * @param int $sessionId
  4231. * @param int $groupId
  4232. *
  4233. * @return string
  4234. */
  4235. public static function fixDocumentName($name, $type, $courseInfo, $sessionId, $groupId)
  4236. {
  4237. $suffix = self::getDocumentSuffix($courseInfo, $sessionId, $groupId);
  4238. switch ($type) {
  4239. case 'folder':
  4240. $name = $name.$suffix;
  4241. break;
  4242. case 'file':
  4243. $name = self::addSuffixToFileName($name, $suffix);
  4244. break;
  4245. }
  4246. return $name;
  4247. }
  4248. /**
  4249. * Add a suffix to a file Example:
  4250. * /folder/picture.jpg => to /folder/picture_this.jpg
  4251. * where "_this" is the suffix.
  4252. *
  4253. * @param string $name
  4254. * @param string $suffix
  4255. *
  4256. * @return string
  4257. */
  4258. public static function addSuffixToFileName($name, $suffix)
  4259. {
  4260. $extension = pathinfo($name, PATHINFO_EXTENSION);
  4261. $fileName = pathinfo($name, PATHINFO_FILENAME);
  4262. $dir = pathinfo($name, PATHINFO_DIRNAME);
  4263. if ($dir == '.') {
  4264. $dir = null;
  4265. }
  4266. if (!empty($dir) && $dir != '/') {
  4267. $dir = $dir.'/';
  4268. }
  4269. $name = $dir.$fileName.$suffix.'.'.$extension;
  4270. return $name;
  4271. }
  4272. /**
  4273. * Check if folder exist in the course base or in the session course.
  4274. *
  4275. * @param string $folder Example: /folder/folder2
  4276. * @param array $courseInfo
  4277. * @param int $sessionId
  4278. * @param int $groupId group.id
  4279. *
  4280. * @return bool
  4281. */
  4282. public static function folderExists(
  4283. $folder,
  4284. $courseInfo,
  4285. $sessionId,
  4286. $groupId
  4287. ) {
  4288. $courseId = $courseInfo['real_id'];
  4289. if (empty($courseId)) {
  4290. return false;
  4291. }
  4292. $sessionId = intval($sessionId);
  4293. $folderWithSuffix = self::fixDocumentName(
  4294. $folder,
  4295. 'folder',
  4296. $courseInfo,
  4297. $sessionId,
  4298. $groupId
  4299. );
  4300. $folder = Database::escape_string($folder);
  4301. $folderWithSuffix = Database::escape_string($folderWithSuffix);
  4302. // Check if pathname already exists inside document table
  4303. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  4304. $sql = "SELECT id, path FROM $tbl_document
  4305. WHERE
  4306. filetype = 'folder' AND
  4307. c_id = $courseId AND
  4308. (path = '$folder' OR path = '$folderWithSuffix') AND
  4309. (session_id = 0 OR session_id = $sessionId)
  4310. ";
  4311. $rs = Database::query($sql);
  4312. if (Database::num_rows($rs)) {
  4313. return true;
  4314. }
  4315. return false;
  4316. }
  4317. /**
  4318. * Check if file exist in the course base or in the session course.
  4319. *
  4320. * @param string $fileName Example: /folder/picture.jpg
  4321. * @param array $courseInfo
  4322. * @param int $sessionId
  4323. * @param int $groupId
  4324. *
  4325. * @return bool
  4326. */
  4327. public static function documentExists(
  4328. $fileName,
  4329. $courseInfo,
  4330. $sessionId,
  4331. $groupId
  4332. ) {
  4333. $courseId = $courseInfo['real_id'];
  4334. if (empty($courseId)) {
  4335. return false;
  4336. }
  4337. $sessionId = intval($sessionId);
  4338. $fileNameEscape = Database::escape_string($fileName);
  4339. $fileNameWithSuffix = self::fixDocumentName(
  4340. $fileName,
  4341. 'file',
  4342. $courseInfo,
  4343. $sessionId,
  4344. $groupId
  4345. );
  4346. $fileNameWithSuffix = Database::escape_string($fileNameWithSuffix);
  4347. // Check if pathname already exists inside document table
  4348. $table = Database::get_course_table(TABLE_DOCUMENT);
  4349. $sql = "SELECT id, path FROM $table
  4350. WHERE
  4351. filetype = 'file' AND
  4352. c_id = $courseId AND
  4353. (
  4354. path = '".$fileNameEscape."' OR
  4355. path = '$fileNameWithSuffix'
  4356. ) AND
  4357. (session_id = 0 OR session_id = $sessionId)
  4358. ";
  4359. $rs = Database::query($sql);
  4360. if (Database::num_rows($rs)) {
  4361. return true;
  4362. }
  4363. return false;
  4364. }
  4365. /**
  4366. * Undo the suffix applied to a file example:
  4367. * turns picture__1__1.jpg to picture.jpg.
  4368. *
  4369. * @param string $name
  4370. * @param int $courseId
  4371. * @param int $sessionId
  4372. * @param int $groupId
  4373. *
  4374. * @return string
  4375. */
  4376. public static function undoFixDocumentName(
  4377. $name,
  4378. $courseId,
  4379. $sessionId,
  4380. $groupId
  4381. ) {
  4382. if (empty($sessionId) && empty($groupId)) {
  4383. return $name;
  4384. }
  4385. $suffix = self::getDocumentSuffix(
  4386. ['real_id' => $courseId],
  4387. $sessionId,
  4388. $groupId
  4389. );
  4390. $name = str_replace($suffix, '', $name);
  4391. return $name;
  4392. }
  4393. /**
  4394. * @param string $path
  4395. * @param string $name
  4396. * @param array $courseInfo
  4397. * @param int $sessionId
  4398. * @param int $groupId
  4399. *
  4400. * @return string
  4401. */
  4402. public static function getUniqueFileName($path, $name, $courseInfo, $sessionId, $groupId)
  4403. {
  4404. $counter = 1;
  4405. $filePath = $path.$name;
  4406. $uniqueName = $name;
  4407. while ($documentExists = self::documentExists(
  4408. $filePath,
  4409. $courseInfo,
  4410. $sessionId,
  4411. $groupId
  4412. )) {
  4413. $uniqueName = self::addSuffixToFileName($name, '_'.$counter);
  4414. $filePath = $path.$uniqueName;
  4415. $counter++;
  4416. }
  4417. return $uniqueName;
  4418. }
  4419. /**
  4420. * Builds the form that enables the user to
  4421. * select a directory to browse/upload in.
  4422. *
  4423. * @param array An array containing the folders we want to be able to select
  4424. * @param string The current folder (path inside of the "document" directory, including the prefix "/")
  4425. * @param string Group directory, if empty, prevents documents to be uploaded
  4426. * (because group documents cannot be uploaded in root)
  4427. * @param bool Whether to change the renderer (this will add a template <span>
  4428. * to the QuickForm object displaying the form)
  4429. *
  4430. * @return string html form
  4431. */
  4432. public static function build_directory_selector(
  4433. $folders,
  4434. $document_id,
  4435. $group_dir = '',
  4436. $change_renderer = false,
  4437. &$form = null,
  4438. $selectName = 'id'
  4439. ) {
  4440. $doc_table = Database::get_course_table(TABLE_DOCUMENT);
  4441. $course_id = api_get_course_int_id();
  4442. $folder_titles = [];
  4443. if (is_array($folders)) {
  4444. $escaped_folders = [];
  4445. foreach ($folders as $key => &$val) {
  4446. $escaped_folders[$key] = Database::escape_string($val);
  4447. }
  4448. $folder_sql = implode("','", $escaped_folders);
  4449. $sql = "SELECT path, title
  4450. FROM $doc_table
  4451. WHERE
  4452. filetype = 'folder' AND
  4453. c_id = $course_id AND
  4454. path IN ('".$folder_sql."')";
  4455. $res = Database::query($sql);
  4456. $folder_titles = [];
  4457. while ($obj = Database::fetch_object($res)) {
  4458. $folder_titles[$obj->path] = $obj->title;
  4459. }
  4460. }
  4461. $attributes = [];
  4462. if (empty($form)) {
  4463. $form = new FormValidator('selector', 'GET', api_get_self().'?'.api_get_cidreq());
  4464. $attributes = ['onchange' => 'javascript: document.selector.submit();'];
  4465. }
  4466. $form->addElement('hidden', 'cidReq', api_get_course_id());
  4467. $form->addElement('hidden', 'id_session', api_get_session_id());
  4468. $form->addElement('hidden', 'gidReq', api_get_group_id());
  4469. $parent_select = $form->addSelect(
  4470. $selectName,
  4471. get_lang('CurrentDirectory'),
  4472. '',
  4473. $attributes
  4474. );
  4475. // Group documents cannot be uploaded in the root
  4476. if (empty($group_dir)) {
  4477. $parent_select->addOption(get_lang('Documents'), '/');
  4478. if (is_array($folders)) {
  4479. foreach ($folders as $folder_id => &$folder) {
  4480. $selected = ($document_id == $folder_id) ? ' selected="selected"' : '';
  4481. $path_parts = explode('/', $folder);
  4482. $folder_titles[$folder] = cut($folder_titles[$folder], 80);
  4483. $counter = count($path_parts) - 2;
  4484. if ($counter > 0) {
  4485. $label = str_repeat('&nbsp;&nbsp;&nbsp;', $counter).' &mdash; '.$folder_titles[$folder];
  4486. } else {
  4487. $label = ' &mdash; '.$folder_titles[$folder];
  4488. }
  4489. $parent_select->addOption($label, $folder_id);
  4490. if ($selected != '') {
  4491. $parent_select->setSelected($folder_id);
  4492. }
  4493. }
  4494. }
  4495. } else {
  4496. if (!empty($folders)) {
  4497. foreach ($folders as $folder_id => &$folder) {
  4498. $selected = ($document_id == $folder_id) ? ' selected="selected"' : '';
  4499. $label = $folder_titles[$folder];
  4500. if ($folder == $group_dir) {
  4501. $label = get_lang('Documents');
  4502. } else {
  4503. $path_parts = explode('/', str_replace($group_dir, '', $folder));
  4504. $label = cut($label, 80);
  4505. $label = str_repeat('&nbsp;&nbsp;&nbsp;', count($path_parts) - 2).' &mdash; '.$label;
  4506. }
  4507. $parent_select->addOption($label, $folder_id);
  4508. if ($selected != '') {
  4509. $parent_select->setSelected($folder_id);
  4510. }
  4511. }
  4512. }
  4513. }
  4514. $html = $form->toHtml();
  4515. return $html;
  4516. }
  4517. /**
  4518. * Create a html hyperlink depending on if it's a folder or a file.
  4519. *
  4520. * @param string $documentWebPath
  4521. * @param array $document_data
  4522. * @param bool $show_as_icon - if it is true, only a clickable icon will be shown
  4523. * @param int $visibility (1/0)
  4524. * @param int $counter
  4525. * @param int $size
  4526. * @param bool $isAllowedToEdit
  4527. * @param bool $isCertificateMode
  4528. *
  4529. * @return string url
  4530. */
  4531. public static function create_document_link(
  4532. $documentWebPath,
  4533. $document_data,
  4534. $show_as_icon = false,
  4535. $counter = null,
  4536. $visibility,
  4537. $size = 0,
  4538. $isAllowedToEdit = false,
  4539. $isCertificateMode = false
  4540. ) {
  4541. global $dbl_click_id;
  4542. $www = $documentWebPath;
  4543. $sessionId = api_get_session_id();
  4544. $courseParams = api_get_cidreq();
  4545. $webODFList = self::get_web_odf_extension_list();
  4546. // Get the title or the basename depending on what we're using
  4547. if ($document_data['title'] != '') {
  4548. $title = $document_data['title'];
  4549. } else {
  4550. $title = basename($document_data['path']);
  4551. }
  4552. $filetype = $document_data['filetype'];
  4553. $path = $document_data['path'];
  4554. $url_path = urlencode($document_data['path']);
  4555. // Add class="invisible" on invisible files
  4556. $visibility_class = $visibility == false ? ' class="muted"' : '';
  4557. $forcedownload_link = '';
  4558. $forcedownload_icon = '';
  4559. $prevent_multiple_click = '';
  4560. $force_download_html = '';
  4561. if (!$show_as_icon) {
  4562. // Build download link (icon)
  4563. $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'];
  4564. // Folder download or file download?
  4565. $forcedownload_icon = $filetype == 'folder' ? 'save_pack.png' : 'save.png';
  4566. // Prevent multiple clicks on zipped folder download
  4567. $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; }\"" : '';
  4568. }
  4569. $target = '_self';
  4570. $is_browser_viewable_file = false;
  4571. if ($filetype == 'file') {
  4572. // Check the extension
  4573. $ext = explode('.', $path);
  4574. $ext = strtolower($ext[sizeof($ext) - 1]);
  4575. // HTML-files an some other types are shown in a frameset by default.
  4576. $is_browser_viewable_file = self::isBrowserViewable($ext);
  4577. if ($is_browser_viewable_file) {
  4578. if ($ext == 'pdf' || in_array($ext, $webODFList)) {
  4579. $url = api_get_self().'?'.$courseParams.'&amp;action=download&amp;id='.$document_data['id'];
  4580. } else {
  4581. $url = 'showinframes.php?'.$courseParams.'&id='.$document_data['id'];
  4582. }
  4583. } else {
  4584. // url-encode for problematic characters (we may not call them dangerous characters...)
  4585. //$path = str_replace('%2F', '/', $url_path).'?'.$courseParams;
  4586. $url = $www.str_replace('%2F', '/', $url_path).'?'.$courseParams;
  4587. }
  4588. } else {
  4589. $url = api_get_self().'?'.$courseParams.'&id='.$document_data['id'];
  4590. }
  4591. if ($isCertificateMode) {
  4592. $url .= '&certificate=true&selectcat='.(isset($_GET['selectcat']) ? $_GET['selectcat'] : '');
  4593. }
  4594. // The little download icon
  4595. $tooltip_title = $title;
  4596. $tooltip_title_alt = $tooltip_title;
  4597. if ($filetype == 'link') {
  4598. $tooltip_title_alt = $title;
  4599. $url = $document_data['comment'].'" target="_blank';
  4600. }
  4601. if ($path == '/shared_folder') {
  4602. $tooltip_title_alt = get_lang('UserFolders');
  4603. } elseif (strstr($path, 'shared_folder_session_')) {
  4604. $tooltip_title_alt = get_lang('UserFolders').' ('.api_get_session_name(api_get_session_id()).')';
  4605. } elseif (strstr($tooltip_title, 'sf_user_')) {
  4606. $userinfo = api_get_user_info(substr($tooltip_title, 8));
  4607. $tooltip_title_alt = get_lang('UserFolder').' '.$userinfo['complete_name'];
  4608. } elseif ($path == '/chat_files') {
  4609. $tooltip_title_alt = get_lang('ChatFiles');
  4610. } elseif ($path == '/learning_path') {
  4611. $tooltip_title_alt = get_lang('LearningPaths');
  4612. } elseif ($path == '/video') {
  4613. $tooltip_title_alt = get_lang('Video');
  4614. } elseif ($path == '/audio') {
  4615. $tooltip_title_alt = get_lang('Audio');
  4616. } elseif ($path == '/flash') {
  4617. $tooltip_title_alt = get_lang('Flash');
  4618. } elseif ($path == '/images') {
  4619. $tooltip_title_alt = get_lang('Images');
  4620. } elseif ($path == '/images/gallery') {
  4621. $tooltip_title_alt = get_lang('DefaultCourseImages');
  4622. }
  4623. $copyToMyFiles = $open_in_new_window_link = '';
  4624. $curdirpath = isset($_GET['curdirpath']) ? Security::remove_XSS($_GET['curdirpath']) : null;
  4625. $send_to = null;
  4626. $checkExtension = $path;
  4627. $extension = pathinfo($path, PATHINFO_EXTENSION);
  4628. $document_data['file_extension'] = $extension;
  4629. if (!$show_as_icon) {
  4630. if ($filetype == 'folder') {
  4631. if ($isAllowedToEdit ||
  4632. api_is_platform_admin() ||
  4633. api_get_setting('students_download_folders') == 'true'
  4634. ) {
  4635. // filter: when I am into a shared folder, I can only show "my shared folder" for donwload
  4636. if (self::is_shared_folder($curdirpath, $sessionId)) {
  4637. if (preg_match('/shared_folder\/sf_user_'.api_get_user_id().'$/', urldecode($forcedownload_link)) ||
  4638. preg_match('/shared_folder_session_'.$sessionId.'\/sf_user_'.api_get_user_id().'$/', urldecode($forcedownload_link)) ||
  4639. $isAllowedToEdit || api_is_platform_admin()
  4640. ) {
  4641. $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.
  4642. Display::return_icon($forcedownload_icon, get_lang('Download'), [], ICON_SIZE_SMALL).'</a>';
  4643. }
  4644. } elseif (!preg_match('/shared_folder/', urldecode($forcedownload_link)) ||
  4645. $isAllowedToEdit ||
  4646. api_is_platform_admin()
  4647. ) {
  4648. $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.
  4649. Display::return_icon($forcedownload_icon, get_lang('Download'), [], ICON_SIZE_SMALL).'</a>';
  4650. }
  4651. }
  4652. } else {
  4653. $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.' download="'.$document_data['basename'].'">'.
  4654. Display::return_icon($forcedownload_icon, get_lang('Download'), [], ICON_SIZE_SMALL).'</a>';
  4655. }
  4656. // Copy files to user's myfiles
  4657. if (api_get_setting('allow_my_files') === 'true' &&
  4658. api_get_setting('users_copy_files') === 'true' && api_is_anonymous() === false
  4659. ) {
  4660. $copy_myfiles_link = $filetype == 'file' ? api_get_self().'?'.$courseParams.'&action=copytomyfiles&id='.$document_data['id'] : api_get_self().'?'.$courseParams;
  4661. if ($filetype == 'file') {
  4662. $copyToMyFiles = '<a href="'.$copy_myfiles_link.'" style="float:right"'.$prevent_multiple_click.'>'.
  4663. Display::return_icon('briefcase.png', get_lang('CopyToMyFiles'), [], ICON_SIZE_SMALL).'&nbsp;&nbsp;</a>';
  4664. if (api_get_setting('allow_my_files') === 'false') {
  4665. $copyToMyFiles = '';
  4666. }
  4667. }
  4668. }
  4669. $pdf_icon = '';
  4670. if (!$isAllowedToEdit &&
  4671. api_get_setting('students_export2pdf') == 'true' &&
  4672. $filetype == 'file' &&
  4673. in_array($extension, ['html', 'htm'])
  4674. ) {
  4675. $pdf_icon = ' <a style="float:right".'.$prevent_multiple_click.' href="'.api_get_self().'?'.$courseParams.'&action=export_to_pdf&id='.$document_data['id'].'&curdirpath='.$curdirpath.'">'.
  4676. Display::return_icon('pdf.png', get_lang('Export2PDF'), [], ICON_SIZE_SMALL).'</a> ';
  4677. }
  4678. if ($is_browser_viewable_file) {
  4679. $open_in_new_window_link = '<a href="'.$www.str_replace('%2F', '/', $url_path).'?'.$courseParams.'" style="float:right"'.$prevent_multiple_click.' target="_blank">'.
  4680. Display::return_icon('open_in_new_window.png', get_lang('OpenInANewWindow'), [], ICON_SIZE_SMALL).'&nbsp;&nbsp;</a>';
  4681. }
  4682. if ($filetype == 'file') {
  4683. // Sound preview
  4684. if (preg_match('/mp3$/i', urldecode($checkExtension)) ||
  4685. (preg_match('/wav$/i', urldecode($checkExtension))) ||
  4686. preg_match('/ogg$/i', urldecode($checkExtension))
  4687. ) {
  4688. return '<span style="float:left" '.$visibility_class.'>'.
  4689. $title.
  4690. '</span>'.$force_download_html.$send_to.$copyToMyFiles.$open_in_new_window_link.$pdf_icon;
  4691. } elseif (
  4692. // Show preview
  4693. preg_match('/swf$/i', urldecode($checkExtension)) ||
  4694. preg_match('/png$/i', urldecode($checkExtension)) ||
  4695. preg_match('/gif$/i', urldecode($checkExtension)) ||
  4696. preg_match('/jpg$/i', urldecode($checkExtension)) ||
  4697. preg_match('/jpeg$/i', urldecode($checkExtension)) ||
  4698. preg_match('/bmp$/i', urldecode($checkExtension)) ||
  4699. preg_match('/svg$/i', urldecode($checkExtension))
  4700. ) {
  4701. // Simpler version of showinframesmin.php with no headers
  4702. $url = 'show_content.php?'.$courseParams.'&id='.$document_data['id'];
  4703. $class = 'ajax';
  4704. if ($visibility == false) {
  4705. $class = "ajax text-muted";
  4706. }
  4707. return Display::url(
  4708. $title,
  4709. $url,
  4710. [
  4711. 'class' => $class,
  4712. 'title' => $tooltip_title_alt,
  4713. 'data-title' => $title,
  4714. 'style' => 'float:left;',
  4715. ]
  4716. )
  4717. .$force_download_html.$send_to.$copyToMyFiles
  4718. .$open_in_new_window_link.$pdf_icon;
  4719. } else {
  4720. // For a "PDF Download" of the file.
  4721. $pdfPreview = null;
  4722. if ($ext != 'pdf' && !in_array($ext, $webODFList)) {
  4723. $url = 'showinframes.php?'.$courseParams.'&id='.$document_data['id'];
  4724. } else {
  4725. $pdfPreview = Display::url(
  4726. Display::return_icon('preview.png', get_lang('Preview'), null, ICON_SIZE_SMALL),
  4727. api_get_path(WEB_CODE_PATH).'document/showinframes.php?'.$courseParams.'&id='.$document_data['id'],
  4728. ['style' => 'float:right']
  4729. );
  4730. }
  4731. // No plugin just the old and good showinframes.php page
  4732. return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" style="float:left" '.$visibility_class.' >'.$title.'</a>'.
  4733. $pdfPreview.$force_download_html.$send_to.$copyToMyFiles.$open_in_new_window_link.$pdf_icon;
  4734. }
  4735. } else {
  4736. return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.$title.'</a>'.
  4737. $force_download_html.$send_to.$copyToMyFiles.$open_in_new_window_link.$pdf_icon;
  4738. }
  4739. // end copy files to users myfiles
  4740. } else {
  4741. // Icon column
  4742. if (preg_match('/shared_folder/', urldecode($checkExtension)) &&
  4743. preg_match('/shared_folder$/', urldecode($checkExtension)) == false &&
  4744. preg_match('/shared_folder_session_'.$sessionId.'$/', urldecode($url)) == false
  4745. ) {
  4746. if ($filetype == 'file') {
  4747. //Sound preview
  4748. if (preg_match('/mp3$/i', urldecode($checkExtension)) ||
  4749. (preg_match('/wav$/i', urldecode($checkExtension))) ||
  4750. preg_match('/ogg$/i', urldecode($checkExtension))) {
  4751. $soundPreview = self::generateAudioPreview($documentWebPath, $document_data);
  4752. return $soundPreview;
  4753. } elseif (
  4754. // Show preview
  4755. preg_match('/swf$/i', urldecode($checkExtension)) ||
  4756. preg_match('/png$/i', urldecode($checkExtension)) ||
  4757. preg_match('/gif$/i', urldecode($checkExtension)) ||
  4758. preg_match('/jpg$/i', urldecode($checkExtension)) ||
  4759. preg_match('/jpeg$/i', urldecode($checkExtension)) ||
  4760. preg_match('/bmp$/i', urldecode($checkExtension)) ||
  4761. preg_match('/svg$/i', urldecode($checkExtension))
  4762. ) {
  4763. $url = 'showinframes.php?'.$courseParams.'&id='.$document_data['id'];
  4764. return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.
  4765. self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
  4766. Display::return_icon('shared.png', get_lang('ResourceShared'), []).
  4767. '</a>';
  4768. } else {
  4769. return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.
  4770. self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
  4771. Display::return_icon('shared.png', get_lang('ResourceShared'), []).
  4772. '</a>';
  4773. }
  4774. } else {
  4775. return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" target="'.$target.'"'.$visibility_class.' style="float:left">'.
  4776. self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
  4777. Display::return_icon('shared.png', get_lang('ResourceShared'), []).
  4778. '</a>';
  4779. }
  4780. } else {
  4781. if ($filetype == 'file') {
  4782. // Sound preview with jplayer
  4783. if (preg_match('/mp3$/i', urldecode($checkExtension)) ||
  4784. (preg_match('/wav$/i', urldecode($checkExtension))) ||
  4785. preg_match('/ogg$/i', urldecode($checkExtension))) {
  4786. $soundPreview = self::generateAudioPreview($documentWebPath, $document_data);
  4787. return $soundPreview;
  4788. } elseif (
  4789. //Show preview
  4790. preg_match('/html$/i', urldecode($checkExtension)) ||
  4791. preg_match('/htm$/i', urldecode($checkExtension)) ||
  4792. preg_match('/swf$/i', urldecode($checkExtension)) ||
  4793. preg_match('/png$/i', urldecode($checkExtension)) ||
  4794. preg_match('/gif$/i', urldecode($checkExtension)) ||
  4795. preg_match('/jpg$/i', urldecode($checkExtension)) ||
  4796. preg_match('/jpeg$/i', urldecode($checkExtension)) ||
  4797. preg_match('/bmp$/i', urldecode($checkExtension)) ||
  4798. preg_match('/svg$/i', urldecode($checkExtension))
  4799. ) {
  4800. $url = 'showinframes.php?'.$courseParams.'&id='.$document_data['id']; //without preview
  4801. return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.
  4802. self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
  4803. '</a>';
  4804. } else {
  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. }
  4809. } else {
  4810. return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" target="'.$target.'"'.$visibility_class.' style="float:left">'.
  4811. self::build_document_icon_tag($filetype, $path, $isAllowedToEdit).
  4812. '</a>';
  4813. }
  4814. }
  4815. }
  4816. }
  4817. /**
  4818. * Builds an img html tag for the file type.
  4819. *
  4820. * @param string $type (file/folder)
  4821. * @param string $path
  4822. * @param bool $isAllowedToEdit
  4823. *
  4824. * @return string img html tag
  4825. */
  4826. public static function build_document_icon_tag($type, $path, $isAllowedToEdit = null)
  4827. {
  4828. $basename = basename($path);
  4829. $sessionId = api_get_session_id();
  4830. if (is_null($isAllowedToEdit)) {
  4831. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4832. }
  4833. $user_image = false;
  4834. if ($type == 'file') {
  4835. $icon = choose_image($basename);
  4836. $basename = substr(strrchr($basename, '.'), 1);
  4837. } elseif ($type == 'link') {
  4838. $icon = 'clouddoc.png';
  4839. $basename = get_lang('CloudFileLink');
  4840. } else {
  4841. if ($path == '/shared_folder') {
  4842. $icon = 'folder_users.png';
  4843. if ($isAllowedToEdit) {
  4844. $basename = get_lang('HelpUsersFolder');
  4845. } else {
  4846. $basename = get_lang('UserFolders');
  4847. }
  4848. } elseif (strstr($basename, 'sf_user_')) {
  4849. $userInfo = api_get_user_info(substr($basename, 8));
  4850. $icon = $userInfo['avatar_small'];
  4851. $basename = get_lang('UserFolder').' '.$userInfo['complete_name'];
  4852. $user_image = true;
  4853. } elseif (strstr($path, 'shared_folder_session_')) {
  4854. $sessionName = api_get_session_name($sessionId);
  4855. if ($isAllowedToEdit) {
  4856. $basename = '***('.$sessionName.')*** '.get_lang('HelpUsersFolder');
  4857. } else {
  4858. $basename = get_lang('UserFolders').' ('.$sessionName.')';
  4859. }
  4860. $icon = 'folder_users.png';
  4861. } else {
  4862. $icon = 'folder_document.png';
  4863. if ($path == '/audio') {
  4864. $icon = 'folder_audio.png';
  4865. if ($isAllowedToEdit) {
  4866. $basename = get_lang('HelpDefaultDirDocuments');
  4867. } else {
  4868. $basename = get_lang('Audio');
  4869. }
  4870. } elseif ($path == '/flash') {
  4871. $icon = 'folder_flash.png';
  4872. if ($isAllowedToEdit) {
  4873. $basename = get_lang('HelpDefaultDirDocuments');
  4874. } else {
  4875. $basename = get_lang('Flash');
  4876. }
  4877. } elseif ($path == '/images') {
  4878. $icon = 'folder_images.png';
  4879. if ($isAllowedToEdit) {
  4880. $basename = get_lang('HelpDefaultDirDocuments');
  4881. } else {
  4882. $basename = get_lang('Images');
  4883. }
  4884. } elseif ($path == '/video') {
  4885. $icon = 'folder_video.png';
  4886. if ($isAllowedToEdit) {
  4887. $basename = get_lang('HelpDefaultDirDocuments');
  4888. } else {
  4889. $basename = get_lang('Video');
  4890. }
  4891. } elseif ($path == '/images/gallery') {
  4892. $icon = 'folder_gallery.png';
  4893. if ($isAllowedToEdit) {
  4894. $basename = get_lang('HelpDefaultDirDocuments');
  4895. } else {
  4896. $basename = get_lang('Gallery');
  4897. }
  4898. } elseif ($path == '/chat_files') {
  4899. $icon = 'folder_chat.png';
  4900. if ($isAllowedToEdit) {
  4901. $basename = get_lang('HelpFolderChat');
  4902. } else {
  4903. $basename = get_lang('ChatFiles');
  4904. }
  4905. } elseif ($path == '/learning_path') {
  4906. $icon = 'folder_learningpath.png';
  4907. if ($isAllowedToEdit) {
  4908. $basename = get_lang('HelpFolderLearningPaths');
  4909. } else {
  4910. $basename = get_lang('LearningPaths');
  4911. }
  4912. }
  4913. }
  4914. }
  4915. if ($user_image) {
  4916. return Display::img($icon, $basename, [], false);
  4917. }
  4918. return Display::return_icon($icon, $basename, [], ICON_SIZE_SMALL);
  4919. }
  4920. /**
  4921. * Creates the row of edit icons for a file/folder.
  4922. *
  4923. * @param array $document_data
  4924. * @param int $id
  4925. * @param bool $is_template
  4926. * @param int $is_read_only
  4927. * @param int $visibility (1/0)
  4928. *
  4929. * @return string html img tags with hyperlinks
  4930. */
  4931. public static function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0, $visibility)
  4932. {
  4933. $sessionId = api_get_session_id();
  4934. $courseParams = api_get_cidreq();
  4935. $document_id = $document_data['id'];
  4936. $type = $document_data['filetype'];
  4937. $is_read_only = $document_data['readonly'];
  4938. $path = $document_data['path'];
  4939. if ($type == 'link') {
  4940. $parent_id = self::get_document_id(
  4941. api_get_course_info(),
  4942. rtrim($path, '/'),
  4943. 0
  4944. );
  4945. } else {
  4946. $parent_id = self::get_document_id(
  4947. api_get_course_info(),
  4948. dirname($path),
  4949. 0
  4950. );
  4951. }
  4952. if (empty($parent_id) && !empty($sessionId)) {
  4953. $parent_id = self::get_document_id(
  4954. api_get_course_info(),
  4955. dirname($path),
  4956. $sessionId
  4957. );
  4958. }
  4959. $curdirpath = dirname($document_data['path']);
  4960. $is_certificate_mode = self::is_certificate_mode($path);
  4961. $curdirpath = urlencode($curdirpath);
  4962. $extension = pathinfo($path, PATHINFO_EXTENSION);
  4963. //@todo Implement remote support for converter
  4964. $usePpt2lp = api_get_setting('service_ppt2lp', 'active') == 'true' && api_get_setting('service_ppt2lp', 'host') == 'localhost';
  4965. $formatTypeList = self::getFormatTypeListConvertor('from', $extension);
  4966. $formatType = current($formatTypeList);
  4967. // If document is read only *or* we're in a session and the document
  4968. // is from a non-session context, hide the edition capabilities
  4969. $modify_icons = [];
  4970. $modify_icons[] = self::getButtonEdit($is_read_only, $document_data, $extension, $is_certificate_mode);
  4971. $modify_icons[] = self::getButtonMove($is_read_only, $document_data, $is_certificate_mode, $parent_id);
  4972. $modify_icons[] = self::getButtonVisibility(
  4973. $is_read_only,
  4974. $visibility,
  4975. $document_data,
  4976. $is_certificate_mode,
  4977. $parent_id
  4978. );
  4979. $modify_icons[] = self::getButtonDelete(
  4980. $is_read_only,
  4981. $document_data,
  4982. $is_certificate_mode,
  4983. $curdirpath,
  4984. $parent_id
  4985. );
  4986. if (!$is_read_only /* or ($session_id!=api_get_session_id()) */) {
  4987. // Add action to covert to PDF, will create a new document whit same filename but .pdf extension
  4988. // @TODO: add prompt to select a format target
  4989. if (!in_array($path, self::get_system_folders())) {
  4990. if ($usePpt2lp && $formatType) {
  4991. $modify_icons[] = Display::url(
  4992. Display::return_icon('convert.png', get_lang('Convert')),
  4993. '#',
  4994. ['class' => 'convertAction', 'data-documentId' => $document_id, 'data-formatType' => $formatType]
  4995. );
  4996. }
  4997. }
  4998. }
  4999. if ($type == 'file' && ($extension == 'html' || $extension == 'htm')) {
  5000. if ($is_template == 0) {
  5001. if ((isset($_GET['curdirpath']) && $_GET['curdirpath'] != '/certificates') || !isset($_GET['curdirpath'])) {
  5002. $modify_icons[] = Display::url(
  5003. Display::return_icon('wizard.png', get_lang('AddAsTemplate')),
  5004. api_get_self()."?$courseParams&curdirpath=$curdirpath&add_as_template=$id"
  5005. );
  5006. }
  5007. if ((isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates') || $is_certificate_mode) {//allow attach certificate to course
  5008. $visibility_icon_certificate = 'nocertificate';
  5009. if (self::get_default_certificate_id(api_get_course_id()) == $id) {
  5010. $visibility_icon_certificate = 'certificate';
  5011. $certificate = get_lang('DefaultCertificate');
  5012. $preview = get_lang('PreviewCertificate');
  5013. $is_preview = true;
  5014. } else {
  5015. $is_preview = false;
  5016. $certificate = get_lang('NoDefaultCertificate');
  5017. }
  5018. if (isset($_GET['selectcat'])) {
  5019. $modify_icons[] = Display::url(
  5020. Display::return_icon($visibility_icon_certificate.'.png', $certificate),
  5021. api_get_self()."?$courseParams&curdirpath=$curdirpath&selectcat=".intval($_GET['selectcat'])."&set_certificate=$id"
  5022. );
  5023. if ($is_preview) {
  5024. $modify_icons[] = Display::url(
  5025. Display::return_icon('preview_view.png', $preview),
  5026. api_get_self()."?$courseParams&curdirpath=$curdirpath&set_preview=$id"
  5027. );
  5028. }
  5029. }
  5030. }
  5031. } else {
  5032. $modify_icons[] = Display::url(
  5033. Display::return_icon('wizard_na.png', get_lang('RemoveAsTemplate')),
  5034. api_get_self()."?$courseParams&curdirpath=$curdirpath&remove_as_template=$id"
  5035. );
  5036. }
  5037. $modify_icons[] = Display::url(
  5038. Display::return_icon('pdf.png', get_lang('Export2PDF')),
  5039. api_get_self()."?$courseParams&action=export_to_pdf&id=$id&curdirpath=$curdirpath"
  5040. );
  5041. }
  5042. return implode(PHP_EOL, $modify_icons);
  5043. }
  5044. /**
  5045. * @param $folders
  5046. * @param $curdirpath
  5047. * @param $move_file
  5048. * @param string $group_dir
  5049. *
  5050. * @return string
  5051. */
  5052. public static function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir = '')
  5053. {
  5054. $form = new FormValidator('move_to', 'post', api_get_self().'?'.api_get_cidreq());
  5055. // Form title
  5056. $form->addHidden('move_file', $move_file);
  5057. $options = [];
  5058. // Group documents cannot be uploaded in the root
  5059. if ($group_dir == '') {
  5060. if ($curdirpath != '/') {
  5061. $options['/'] = get_lang('Documents');
  5062. }
  5063. if (is_array($folders)) {
  5064. foreach ($folders as &$folder) {
  5065. // Hide some folders
  5066. if ($folder == '/HotPotatoes_files' ||
  5067. $folder == '/certificates' ||
  5068. basename($folder) == 'css'
  5069. ) {
  5070. continue;
  5071. }
  5072. // Admin setting for Hide/Show the folders of all users
  5073. if (api_get_setting('show_users_folders') == 'false' &&
  5074. (strstr($folder, '/shared_folder') || strstr($folder, 'shared_folder_session_'))
  5075. ) {
  5076. continue;
  5077. }
  5078. // Admin setting for Hide/Show Default folders to all users
  5079. if (api_get_setting('show_default_folders') == 'false' &&
  5080. (
  5081. $folder == '/images' ||
  5082. $folder == '/flash' ||
  5083. $folder == '/audio' ||
  5084. $folder == '/video' ||
  5085. strstr($folder, '/images/gallery') ||
  5086. $folder == '/video/flv'
  5087. )
  5088. ) {
  5089. continue;
  5090. }
  5091. // Admin setting for Hide/Show chat history folder
  5092. if (api_get_setting('show_chat_folder') == 'false' &&
  5093. $folder == '/chat_files') {
  5094. continue;
  5095. }
  5096. // You cannot move a file to:
  5097. // 1. current directory
  5098. // 2. inside the folder you want to move
  5099. // 3. inside a subfolder of the folder you want to move
  5100. if (($curdirpath != $folder) &&
  5101. ($folder != $move_file) &&
  5102. (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')
  5103. ) {
  5104. // If document title is used, we have to display titles instead of real paths...
  5105. $path_displayed = self::get_titles_of_path($folder);
  5106. if (empty($path_displayed)) {
  5107. $path_displayed = get_lang('Untitled');
  5108. }
  5109. $options[$folder] = $path_displayed;
  5110. }
  5111. }
  5112. }
  5113. } else {
  5114. foreach ($folders as $folder) {
  5115. if (($curdirpath != $folder) &&
  5116. ($folder != $move_file) &&
  5117. (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')
  5118. ) {
  5119. // Cannot copy dir into his own subdir
  5120. $path_displayed = self::get_titles_of_path($folder);
  5121. $display_folder = substr($path_displayed, strlen($group_dir));
  5122. $display_folder = $display_folder == '' ? get_lang('Documents') : $display_folder;
  5123. $options[$folder] = $display_folder;
  5124. }
  5125. }
  5126. }
  5127. $form->addElement('select', 'move_to', get_lang('MoveTo'), $options);
  5128. $form->addButtonNext(get_lang('MoveElement'), 'move_file_submit');
  5129. return $form->returnForm();
  5130. }
  5131. /**
  5132. * Gets the path translated with title of docs and folders.
  5133. *
  5134. * @param string $path the real path
  5135. *
  5136. * @return the path which should be displayed
  5137. */
  5138. public static function get_titles_of_path($path)
  5139. {
  5140. global $tmp_folders_titles;
  5141. $course_id = api_get_course_int_id();
  5142. $nb_slashes = substr_count($path, '/');
  5143. $current_slash_pos = 0;
  5144. $path_displayed = '';
  5145. for ($i = 0; $i < $nb_slashes; $i++) {
  5146. // For each folder of the path, retrieve title.
  5147. $current_slash_pos = strpos($path, '/', $current_slash_pos + 1);
  5148. $tmp_path = substr($path, strpos($path, '/', 0), $current_slash_pos);
  5149. if (empty($tmp_path)) {
  5150. // If empty, then we are in the final part of the path
  5151. $tmp_path = $path;
  5152. }
  5153. if (!empty($tmp_folders_titles[$tmp_path])) {
  5154. // If this path has soon been stored here we don't need a new query
  5155. $path_displayed .= $tmp_folders_titles[$tmp_path];
  5156. } else {
  5157. $sql = 'SELECT title FROM '.Database::get_course_table(TABLE_DOCUMENT).'
  5158. WHERE c_id = '.$course_id.' AND path LIKE BINARY "'.$tmp_path.'"';
  5159. $rs = Database::query($sql);
  5160. $tmp_title = '/'.Database::result($rs, 0, 0);
  5161. $path_displayed .= $tmp_title;
  5162. $tmp_folders_titles[$tmp_path] = $tmp_title;
  5163. }
  5164. }
  5165. return $path_displayed;
  5166. }
  5167. /**
  5168. * Creates form that asks for the directory name.
  5169. *
  5170. * @return string html-output text for the form
  5171. */
  5172. public static function create_dir_form($dirId)
  5173. {
  5174. global $document_id;
  5175. $form = new FormValidator('create_dir_form', 'post', api_get_self().'?'.api_get_cidreq());
  5176. $form->addElement('hidden', 'create_dir', 1);
  5177. $form->addElement('hidden', 'dir_id', intval($document_id));
  5178. $form->addElement('hidden', 'id', intval($dirId));
  5179. $form->addElement('header', get_lang('CreateDir'));
  5180. $form->addText('dirname', get_lang('NewDir'), ['autofocus' => 'autofocus']);
  5181. $form->addButtonCreate(get_lang('CreateFolder'));
  5182. return $form->returnForm();
  5183. }
  5184. /**
  5185. * Checks whether the user is in shared folder.
  5186. *
  5187. * @param string $curdirpath
  5188. * @param int $sessionId
  5189. *
  5190. * @return bool Return true when user is into shared folder
  5191. */
  5192. public static function is_shared_folder($curdirpath, $sessionId)
  5193. {
  5194. $clean_curdirpath = Security::remove_XSS($curdirpath);
  5195. if ($clean_curdirpath == '/shared_folder') {
  5196. return true;
  5197. } elseif ($clean_curdirpath == '/shared_folder_session_'.$sessionId) {
  5198. return true;
  5199. } else {
  5200. return false;
  5201. }
  5202. }
  5203. /**
  5204. * Checks whether the user is into any user shared folder.
  5205. *
  5206. * @param string $path
  5207. * @param int $sessionId
  5208. *
  5209. * @return bool Return true when user is in any user shared folder
  5210. */
  5211. public static function is_any_user_shared_folder($path, $sessionId)
  5212. {
  5213. $clean_path = Security::remove_XSS($path);
  5214. if (strpos($clean_path, 'shared_folder/sf_user_')) {
  5215. return true;
  5216. } elseif (strpos($clean_path, 'shared_folder_session_'.$sessionId.'/sf_user_')) {
  5217. return true;
  5218. } else {
  5219. return false;
  5220. }
  5221. }
  5222. /**
  5223. * Create users shared folder for course.
  5224. *
  5225. * @param int $userId
  5226. * @param array $courseInfo
  5227. * @param int $sessionId
  5228. */
  5229. public static function createUserSharedFolder($userId, array $courseInfo, $sessionId = 0)
  5230. {
  5231. $documentDirectory = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/document';
  5232. $userInfo = api_get_user_info($userId);
  5233. if (!$sessionId) {
  5234. //Create shared folder. Necessary for recycled courses.
  5235. if (!file_exists($documentDirectory.'/shared_folder')) {
  5236. create_unexisting_directory(
  5237. $courseInfo,
  5238. $userId,
  5239. 0,
  5240. 0,
  5241. 0,
  5242. $documentDirectory,
  5243. '/shared_folder',
  5244. get_lang('UserFolders'),
  5245. 0,
  5246. false,
  5247. false
  5248. );
  5249. }
  5250. // Create dynamic user shared folder
  5251. if (!file_exists($documentDirectory.'/shared_folder/sf_user_'.$userId)) {
  5252. create_unexisting_directory(
  5253. $courseInfo,
  5254. $userId,
  5255. 0,
  5256. 0,
  5257. 0,
  5258. $documentDirectory,
  5259. '/shared_folder/sf_user_'.$userId,
  5260. $userInfo['complete_name'],
  5261. 1,
  5262. false,
  5263. false
  5264. );
  5265. }
  5266. return;
  5267. }
  5268. // Create shared folder session.
  5269. if (!file_exists($documentDirectory.'/shared_folder_session_'.$sessionId)) {
  5270. create_unexisting_directory(
  5271. $courseInfo,
  5272. api_get_user_id(),
  5273. $sessionId,
  5274. 0,
  5275. 0,
  5276. $documentDirectory,
  5277. '/shared_folder_session_'.$sessionId,
  5278. get_lang('UserFolders').' ('.api_get_session_name($sessionId).')',
  5279. 0,
  5280. false,
  5281. false
  5282. );
  5283. }
  5284. //Create dynamic user shared folder into a shared folder session
  5285. if (!file_exists($documentDirectory.'/shared_folder_session_'.$sessionId.'/sf_user_'.$userId)) {
  5286. create_unexisting_directory(
  5287. $courseInfo,
  5288. $userId,
  5289. $sessionId,
  5290. 0,
  5291. 0,
  5292. $documentDirectory,
  5293. '/shared_folder_session_'.$sessionId.'/sf_user_'.$userId,
  5294. $userInfo['complete_name'].'('.api_get_session_name($sessionId).')',
  5295. 1,
  5296. false,
  5297. false
  5298. );
  5299. }
  5300. }
  5301. /**
  5302. * Checks whether the user is into his shared folder or into a subfolder.
  5303. *
  5304. * @param int $user_id
  5305. * @param string $path
  5306. * @param int $sessionId
  5307. *
  5308. * @return bool Return true when user is in his user shared folder or into a subfolder
  5309. */
  5310. public static function is_my_shared_folder($user_id, $path, $sessionId)
  5311. {
  5312. $clean_path = Security::remove_XSS($path).'/';
  5313. //for security does not remove the last slash
  5314. $main_user_shared_folder = '/shared_folder\/sf_user_'.$user_id.'\//';
  5315. //for security does not remove the last slash
  5316. $main_user_shared_folder_session = '/shared_folder_session_'.$sessionId.'\/sf_user_'.$user_id.'\//';
  5317. if (preg_match($main_user_shared_folder, $clean_path)) {
  5318. return true;
  5319. } elseif (preg_match($main_user_shared_folder_session, $clean_path)) {
  5320. return true;
  5321. } else {
  5322. return false;
  5323. }
  5324. }
  5325. /**
  5326. * Check if the file name or folder searched exist.
  5327. *
  5328. * @return bool Return true when exist
  5329. */
  5330. public static function search_keyword($document_name, $keyword)
  5331. {
  5332. if (api_strripos($document_name, $keyword) !== false) {
  5333. return true;
  5334. } else {
  5335. return false;
  5336. }
  5337. }
  5338. /**
  5339. * Checks whether a document can be previewed by using the browser.
  5340. *
  5341. * @param string $file_extension the filename extension of the document (it must be in lower case)
  5342. *
  5343. * @return bool returns TRUE or FALSE
  5344. */
  5345. public static function isBrowserViewable($file_extension)
  5346. {
  5347. static $allowed_extensions = [
  5348. 'htm', 'html', 'xhtml',
  5349. 'gif', 'jpg', 'jpeg', 'png', 'tif', 'tiff',
  5350. 'pdf', 'svg', 'swf',
  5351. 'txt', 'log',
  5352. 'mp4', 'ogg', 'ogv', 'ogx', 'mpg', 'mpeg', 'mov', 'avi', 'webm', 'wmv',
  5353. 'mp3', 'oga', 'wav', 'au', 'wma', 'mid', 'kar',
  5354. ];
  5355. /*
  5356. //TODO: make a admin switch to strict mode
  5357. 1. global default $allowed_extensions
  5358. if (in_array($file_extension, $allowed_extensions)) { // Assignment + a logical check.
  5359. return true;
  5360. }
  5361. 2. check native support
  5362. 3. check plugins: quicktime, mediaplayer, vlc, acrobat, flash, java
  5363. */
  5364. if (!($result = in_array($file_extension, $allowed_extensions))) {
  5365. // Assignment + a logical check.
  5366. return false;
  5367. }
  5368. //check native support (Explorer, Opera, Firefox, Chrome, Safari)
  5369. if ($file_extension == "pdf") {
  5370. return api_browser_support('pdf');
  5371. } elseif ($file_extension == "mp3") {
  5372. return api_browser_support('mp3');
  5373. } elseif ($file_extension == "mp4") {
  5374. return api_browser_support('mp4');
  5375. } elseif ($file_extension == "ogg" || $file_extension == "ogx" || $file_extension == "ogv" || $file_extension == "oga") {
  5376. return api_browser_support('ogg');
  5377. } elseif ($file_extension == "svg") {
  5378. return api_browser_support('svg');
  5379. } elseif ($file_extension == "mpg" || $file_extension == "mpeg") {
  5380. return api_browser_support('mpg');
  5381. } elseif ($file_extension == "mov") {
  5382. return api_browser_support('mov');
  5383. } elseif ($file_extension == "wav") {
  5384. return api_browser_support('wav');
  5385. } elseif ($file_extension == "mid" || $file_extension == "kar") {
  5386. return api_browser_support('mid');
  5387. } elseif ($file_extension == "avi") {
  5388. return api_browser_support('avi');
  5389. } elseif ($file_extension == "wma") {
  5390. return api_browser_support('wma');
  5391. } elseif ($file_extension == "wmv") {
  5392. return api_browser_support('wmv');
  5393. } elseif ($file_extension == "tif" || $file_extension == "tiff") {
  5394. return api_browser_support('tif');
  5395. } elseif ($file_extension == "mov") {
  5396. return api_browser_support('mov');
  5397. } elseif ($file_extension == "au") {
  5398. return api_browser_support('au');
  5399. } elseif ($file_extension == "webm") {
  5400. return api_browser_support('webm');
  5401. }
  5402. return $result;
  5403. }
  5404. /**
  5405. * @param array $courseInfo
  5406. * @param int $sessionId
  5407. *
  5408. * @return array
  5409. */
  5410. public static function getDeletedDocuments($courseInfo, $sessionId = 0)
  5411. {
  5412. $table = Database::get_course_table(TABLE_DOCUMENT);
  5413. $courseId = $courseInfo['real_id'];
  5414. $sessionCondition = api_get_session_condition($sessionId);
  5415. $sql = "SELECT * FROM $table
  5416. WHERE
  5417. path LIKE '%DELETED%' AND
  5418. c_id = $courseId
  5419. $sessionCondition
  5420. ORDER BY path
  5421. ";
  5422. $result = Database::query($sql);
  5423. $files = [];
  5424. while ($document = Database::fetch_array($result, 'ASSOC')) {
  5425. $files[] = $document;
  5426. }
  5427. return $files;
  5428. }
  5429. /**
  5430. * @param int $id
  5431. * @param array $courseInfo
  5432. * @param int $sessionId
  5433. *
  5434. * @return array
  5435. */
  5436. public static function getDeletedDocument($id, $courseInfo, $sessionId = 0)
  5437. {
  5438. if (empty($courseInfo)) {
  5439. return false;
  5440. }
  5441. $table = Database::get_course_table(TABLE_DOCUMENT);
  5442. $courseId = $courseInfo['real_id'];
  5443. $sessionCondition = api_get_session_condition($sessionId);
  5444. $sql = "SELECT * FROM $table
  5445. WHERE
  5446. path LIKE '%DELETED%' AND
  5447. id = $id AND
  5448. c_id = $courseId
  5449. $sessionCondition
  5450. LIMIT 1
  5451. ";
  5452. $result = Database::query($sql);
  5453. if (Database::num_rows($result)) {
  5454. $result = Database::fetch_array($result, 'ASSOC');
  5455. return $result;
  5456. }
  5457. return [];
  5458. }
  5459. /**
  5460. * @param int $id
  5461. * @param array $courseInfo
  5462. * @param int $sessionId
  5463. *
  5464. * @return bool
  5465. */
  5466. public static function purgeDocument($id, $courseInfo, $sessionId = 0)
  5467. {
  5468. $document = self::getDeletedDocument($id, $courseInfo, $sessionId);
  5469. if (!empty($document)) {
  5470. $path = $document['path'];
  5471. $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/';
  5472. my_delete($coursePath.$path);
  5473. // Hard delete.
  5474. self::deleteDocumentFromDb($id, $courseInfo, $sessionId, true);
  5475. return true;
  5476. }
  5477. return false;
  5478. }
  5479. /**
  5480. * @param array $courseInfo
  5481. * @param int $sessionId
  5482. */
  5483. public static function purgeDocuments($courseInfo, $sessionId)
  5484. {
  5485. $files = self::getDeletedDocuments($courseInfo, $sessionId);
  5486. foreach ($files as $file) {
  5487. self::purgeDocument($file['id'], $courseInfo, $sessionId);
  5488. }
  5489. }
  5490. /**
  5491. * @param int $id
  5492. * @param array $courseInfo
  5493. * @param int $sessionId
  5494. */
  5495. public static function downloadDeletedDocument($id, $courseInfo, $sessionId)
  5496. {
  5497. $document = self::getDeletedDocument($id, $courseInfo, $sessionId);
  5498. if (!empty($document)) {
  5499. $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/';
  5500. if (Security::check_abs_path($coursePath.$document['path'], $coursePath)) {
  5501. self::file_send_for_download($coursePath.$document['path']);
  5502. exit;
  5503. }
  5504. }
  5505. }
  5506. /**
  5507. * @param array $courseInfo
  5508. * @param int $sessionId
  5509. *
  5510. * @return bool
  5511. */
  5512. public static function downloadAllDeletedDocument($courseInfo, $sessionId)
  5513. {
  5514. $files = self::getDeletedDocuments($courseInfo, $sessionId);
  5515. if (empty($files)) {
  5516. return false;
  5517. }
  5518. $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
  5519. // Creating a ZIP file.
  5520. $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
  5521. $zip = new PclZip($tempZipFile);
  5522. foreach ($files as $file) {
  5523. $zip->add(
  5524. $coursePath.$file['path'],
  5525. PCLZIP_OPT_REMOVE_PATH,
  5526. $coursePath
  5527. );
  5528. }
  5529. if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
  5530. self::file_send_for_download($tempZipFile, true);
  5531. @unlink($tempZipFile);
  5532. exit;
  5533. }
  5534. }
  5535. /**
  5536. * Delete documents from a session in a course.
  5537. *
  5538. * @param array $courseInfo
  5539. * @param int $sessionId
  5540. *
  5541. * @return bool
  5542. */
  5543. public static function deleteDocumentsFromSession($courseInfo, $sessionId)
  5544. {
  5545. if (empty($courseInfo)) {
  5546. return false;
  5547. }
  5548. if (empty($sessionId)) {
  5549. return false;
  5550. }
  5551. $itemPropertyTable = Database::get_course_table(TABLE_ITEM_PROPERTY);
  5552. $documentTable = Database::get_course_table(TABLE_DOCUMENT);
  5553. $conditionSession = api_get_session_condition($sessionId, true, false, 'd.session_id');
  5554. $courseId = $courseInfo['real_id'];
  5555. // get invisible folders
  5556. $sql = "SELECT DISTINCT d.id, path
  5557. FROM $itemPropertyTable i
  5558. INNER JOIN $documentTable d
  5559. ON (i.c_id = d.c_id)
  5560. WHERE
  5561. d.id = i.ref AND
  5562. i.tool = '".TOOL_DOCUMENT."'
  5563. $conditionSession AND
  5564. i.c_id = $courseId AND
  5565. d.c_id = $courseId ";
  5566. $result = Database::query($sql);
  5567. $documents = Database::store_result($result, 'ASSOC');
  5568. if ($documents) {
  5569. $course_dir = $courseInfo['directory'].'/document';
  5570. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  5571. $base_work_dir = $sys_course_path.$course_dir;
  5572. foreach ($documents as $document) {
  5573. $documentId = $document['id'];
  5574. self::delete_document(
  5575. $courseInfo,
  5576. null,
  5577. $base_work_dir,
  5578. $sessionId,
  5579. $documentId
  5580. );
  5581. }
  5582. }
  5583. $sql = "DELETE FROM $documentTable
  5584. WHERE c_id = $courseId AND session_id = $sessionId";
  5585. Database::query($sql);
  5586. $sql = "DELETE FROM $itemPropertyTable
  5587. WHERE c_id = $courseId AND session_id = $sessionId AND tool = '".TOOL_DOCUMENT."'";
  5588. Database::query($sql);
  5589. }
  5590. /**
  5591. * Update the file or directory path in the document db document table.
  5592. *
  5593. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  5594. *
  5595. * @param string $action - action type require : 'delete' or 'update'
  5596. * @param string $old_path - old path info stored to change
  5597. * @param string $new_path - new path info to substitute
  5598. *
  5599. * @desc Update the file or directory path in the document db document table
  5600. */
  5601. public static function updateDbInfo($action, $old_path, $new_path = '')
  5602. {
  5603. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  5604. $course_id = api_get_course_int_id();
  5605. $old_path = Database::escape_string($old_path);
  5606. switch ($action) {
  5607. case 'delete':
  5608. $query = "DELETE FROM $dbTable
  5609. WHERE
  5610. c_id = $course_id AND
  5611. (
  5612. path LIKE BINARY '".$old_path."' OR
  5613. path LIKE BINARY '".$old_path."/%'
  5614. )";
  5615. Database::query($query);
  5616. break;
  5617. case 'update':
  5618. if ($new_path[0] == '.') {
  5619. $new_path = substr($new_path, 1);
  5620. }
  5621. $new_path = str_replace('//', '/', $new_path);
  5622. // Attempt to update - tested & working for root dir
  5623. $new_path = Database::escape_string($new_path);
  5624. $query = "UPDATE $dbTable SET
  5625. path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
  5626. WHERE
  5627. c_id = $course_id AND
  5628. (path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%')";
  5629. Database::query($query);
  5630. break;
  5631. }
  5632. }
  5633. /**
  5634. * This function calculates the resized width and resized heigt
  5635. * according to the source and target widths
  5636. * and heights, height so that no distortions occur
  5637. * parameters.
  5638. *
  5639. * @param $image = the absolute path to the image
  5640. * @param $target_width = how large do you want your resized image
  5641. * @param $target_height = how large do you want your resized image
  5642. * @param $slideshow (default=0) =
  5643. * indicates weither we are generating images for a slideshow or not,
  5644. * this overrides the $_SESSION["image_resizing"] a bit so that a thumbnail
  5645. * view is also possible when you choose not to resize the source images
  5646. *
  5647. * @return array
  5648. */
  5649. public static function resizeImageSlideShow(
  5650. $image,
  5651. $target_width,
  5652. $target_height,
  5653. $slideshow = 0
  5654. ) {
  5655. // Modifications by Ivan Tcholakov, 04-MAY-2009.
  5656. $result = [];
  5657. $imageResize = Session::read('image_resizing');
  5658. if ($imageResize == 'resizing' || $slideshow == 1) {
  5659. $new_sizes = api_resize_image($image, $target_width, $target_height);
  5660. $result[] = $new_sizes['height'];
  5661. $result[] = $new_sizes['width'];
  5662. } else {
  5663. $size = api_getimagesize($image);
  5664. $result[] = $size['height'];
  5665. $result[] = $size['width'];
  5666. }
  5667. return $result;
  5668. }
  5669. /**
  5670. * Calculates the total size of a directory by adding the sizes (that
  5671. * are stored in the database) of all files & folders in this directory.
  5672. *
  5673. * @param string $path
  5674. * @param bool $can_see_invisible
  5675. *
  5676. * @return int Total size
  5677. */
  5678. public static function getTotalFolderSize($path, $can_see_invisible = false)
  5679. {
  5680. $table_itemproperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  5681. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  5682. $tool_document = TOOL_DOCUMENT;
  5683. $course_id = api_get_course_int_id();
  5684. $session_id = api_get_session_id();
  5685. $session_condition = api_get_session_condition(
  5686. $session_id,
  5687. true,
  5688. true,
  5689. 'props.session_id'
  5690. );
  5691. if (empty($course_id)) {
  5692. return 0;
  5693. }
  5694. $path = Database::escape_string($path);
  5695. $visibility_rule = ' props.visibility '.($can_see_invisible ? '<> 2' : '= 1');
  5696. $sql = "SELECT SUM(table1.size) FROM (
  5697. SELECT props.ref, size
  5698. FROM $table_itemproperty AS props
  5699. INNER JOIN $table_document AS docs
  5700. ON (docs.id = props.ref AND docs.c_id = props.c_id)
  5701. WHERE
  5702. docs.c_id = $course_id AND
  5703. docs.path LIKE '$path/%' AND
  5704. props.c_id = $course_id AND
  5705. props.tool = '$tool_document' AND
  5706. $visibility_rule
  5707. $session_condition
  5708. GROUP BY ref
  5709. ) as table1";
  5710. $result = Database::query($sql);
  5711. if ($result && Database::num_rows($result) != 0) {
  5712. $row = Database::fetch_row($result);
  5713. return $row[0] == null ? 0 : $row[0];
  5714. } else {
  5715. return 0;
  5716. }
  5717. }
  5718. /**
  5719. * Adds a cloud link to the database.
  5720. *
  5721. * @author - Aquilino Blanco Cores <aqblanco@gmail.com>
  5722. *
  5723. * @param array $_course
  5724. * @param string $path
  5725. * @param string $url
  5726. * @param string $name
  5727. *
  5728. * @return int id of document or 0 if already exists or there was a problem creating it
  5729. */
  5730. public static function addCloudLink($_course, $path, $url, $name)
  5731. {
  5732. $file_path = $path;
  5733. if (!self::cloudLinkExists($_course, $path, $url)) {
  5734. $doc_id = add_document($_course, $file_path, 'link', 0, $name, $url);
  5735. if ($doc_id) {
  5736. // Update document item_property
  5737. api_item_property_update(
  5738. $_course,
  5739. TOOL_DOCUMENT,
  5740. $doc_id,
  5741. 'DocumentAdded',
  5742. api_get_user_id(),
  5743. api_get_group_id(),
  5744. api_get_user_id(),
  5745. null,
  5746. null,
  5747. api_get_session_id()
  5748. );
  5749. }
  5750. // If the file is in a folder, we need to update all parent folders
  5751. item_property_update_on_folder($_course, $file_path, api_get_user_id());
  5752. return $doc_id;
  5753. } else {
  5754. return 0;
  5755. }
  5756. }
  5757. /**
  5758. * Deletes a cloud link from the database.
  5759. *
  5760. * @author - Aquilino Blanco Cores <aqblanco@gmail.com>
  5761. *
  5762. * @param array $courseInfo
  5763. * @param string $documentId
  5764. *
  5765. * @return bool true if success / false if an error occurred
  5766. */
  5767. public static function deleteCloudLink($courseInfo, $documentId)
  5768. {
  5769. if (empty($documentId) || empty($courseInfo)) {
  5770. return false;
  5771. }
  5772. $documentId = (int) $documentId;
  5773. $fileDeletedFromDb = false;
  5774. if (!empty($documentId)) {
  5775. self::deleteDocumentFromDb($documentId, $courseInfo, 0, true);
  5776. // checking
  5777. $table = Database::get_course_table(TABLE_DOCUMENT);
  5778. $courseId = $courseInfo['real_id'];
  5779. echo $sql = "SELECT * FROM $table WHERE id = $documentId AND c_id = $courseId";
  5780. $result = Database::query($sql);
  5781. $exists = Database::num_rows($result) > 0;
  5782. $fileDeletedFromDb = !$exists;
  5783. }
  5784. return $fileDeletedFromDb;
  5785. }
  5786. /**
  5787. * Gets the id of a cloud link with a given path.
  5788. *
  5789. * @author - Aquilino Blanco Cores <aqblanco@gmail.com>
  5790. *
  5791. * @param array $courseInfo
  5792. * @param string $path
  5793. * @param string $url
  5794. *
  5795. * @return int link's id / false if no link found
  5796. */
  5797. public static function getCloudLinkId($courseInfo, $path, $url)
  5798. {
  5799. $table = Database::get_course_table(TABLE_DOCUMENT);
  5800. if (empty($courseInfo)) {
  5801. return false;
  5802. }
  5803. $courseId = (int) $courseInfo['real_id'];
  5804. $path = Database::escape_string($path);
  5805. if (substr($path, -1) != '/') {
  5806. // Add final slash to path if not present
  5807. $path .= '/';
  5808. }
  5809. if (!empty($courseId) && !empty($path)) {
  5810. $sql = "SELECT id FROM $table
  5811. WHERE
  5812. c_id = $courseId AND
  5813. path LIKE BINARY '$path' AND
  5814. comment = '$url' AND
  5815. filetype = 'link'
  5816. LIMIT 1";
  5817. $result = Database::query($sql);
  5818. if ($result && Database::num_rows($result)) {
  5819. $row = Database::fetch_array($result);
  5820. return intval($row[0]);
  5821. }
  5822. }
  5823. return false;
  5824. }
  5825. /**
  5826. * Checks if a cloud link exists.
  5827. *
  5828. * @author - Aquilino Blanco Cores <aqblanco@gmail.com>
  5829. *
  5830. * @param array $courseInfo
  5831. * @param string $path
  5832. * @param string $url
  5833. *
  5834. * @return bool true if it exists false in other case
  5835. */
  5836. public static function cloudLinkExists($courseInfo, $path, $url)
  5837. {
  5838. $exists = self::getCloudLinkId($courseInfo, $path, $url);
  5839. return $exists;
  5840. }
  5841. /**
  5842. * Gets the wellformed URLs regular expression in order to use it on forms' verifications.
  5843. *
  5844. * @author Aquilino Blanco Cores <aqblanco@gmail.com>
  5845. *
  5846. * @return string the well formed URLs regular expressions string
  5847. */
  5848. public static function getWellFormedUrlRegex()
  5849. {
  5850. 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';
  5851. }
  5852. /**
  5853. * Gets the files hosting sites' whitelist.
  5854. *
  5855. * @author Aquilino Blanco Cores <aqblanco@gmail.com>
  5856. *
  5857. * @return array the sites list
  5858. */
  5859. public static function getFileHostingWhiteList()
  5860. {
  5861. return [
  5862. 'asuswebstorage.com',
  5863. 'dropbox.com',
  5864. 'dropboxusercontent.com',
  5865. 'fileserve.com',
  5866. 'drive.google.com',
  5867. 'docs.google.com',
  5868. 'icloud.com',
  5869. 'mediafire.com',
  5870. 'mega.nz',
  5871. 'onedrive.live.com',
  5872. 'slideshare.net',
  5873. 'scribd.com',
  5874. 'wetransfer.com',
  5875. 'box.com',
  5876. 'livefilestore.com', // OneDrive
  5877. ];
  5878. }
  5879. /**
  5880. * @param int $userId
  5881. *
  5882. * @return array Example [ 0 => ['code' => 'ABC', 'directory' => 'ABC0', 'path' => '/images/gallery/test.png', 'code_path' => 'ABC:/images/gallery/test.png'], 1 => ...]
  5883. */
  5884. public static function getAllDocumentsCreatedByUser($userId)
  5885. {
  5886. $tblItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  5887. $tblDocument = Database::get_course_table(TABLE_DOCUMENT);
  5888. $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  5889. $userId = (int) $userId;
  5890. $sql = "SELECT DISTINCT c.code, c.directory, docs.path
  5891. FROM $tblItemProperty AS last
  5892. INNER JOIN $tblDocument AS docs
  5893. ON (
  5894. docs.id = last.ref AND
  5895. docs.c_id = last.c_id AND
  5896. docs.filetype <> 'folder'
  5897. )
  5898. INNER JOIN $tblCourse as c
  5899. ON (
  5900. docs.c_id = c.id
  5901. )
  5902. WHERE
  5903. last.tool = '".TOOL_DOCUMENT."' AND
  5904. last.insert_user_id = $userId AND
  5905. docs.path NOT LIKE '%_DELETED_%'
  5906. ORDER BY c.directory, docs.path
  5907. ";
  5908. $result = Database::query($sql);
  5909. $list = [];
  5910. if (Database::num_rows($result) != 0) {
  5911. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5912. $row['code_path'] = $row['code'].':'.$row['path'];
  5913. $list[] = $row;
  5914. }
  5915. }
  5916. return $list;
  5917. }
  5918. /**
  5919. * Parse file information into a link.
  5920. *
  5921. * @param array $userInfo Current user info
  5922. * @param array $course_info
  5923. * @param int $session_id
  5924. * @param array $resource
  5925. * @param int $lp_id
  5926. * @param bool $add_move_button
  5927. * @param string $target
  5928. * @param string $overwrite_url
  5929. *
  5930. * @return string|null
  5931. */
  5932. private static function parseFile(
  5933. $userInfo,
  5934. $course_info,
  5935. $session_id,
  5936. $resource,
  5937. $lp_id,
  5938. $add_move_button,
  5939. $target,
  5940. $overwrite_url
  5941. ) {
  5942. $img_sys_path = api_get_path(SYS_CODE_PATH).'img/';
  5943. $web_code_path = api_get_path(WEB_CODE_PATH);
  5944. $documentId = $resource['id'];
  5945. $path = $resource['path'];
  5946. if (empty($path)) {
  5947. $num = 0;
  5948. } else {
  5949. $num = substr_count($path, '/') - 1;
  5950. }
  5951. // It's a file.
  5952. $icon = choose_image($path);
  5953. $position = strrpos($icon, '.');
  5954. $icon = substr($icon, 0, $position).'_small.gif';
  5955. $my_file_title = $resource['title'];
  5956. $visibility = $resource['visibility'];
  5957. // If title is empty we try to use the path
  5958. if (empty($my_file_title)) {
  5959. $my_file_title = basename($path);
  5960. }
  5961. // Show the "image name" not the filename of the image.
  5962. if ($lp_id) {
  5963. // LP URL
  5964. $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;
  5965. } else {
  5966. // Direct document URL
  5967. $url = $web_code_path.'document/document.php?cidReq='.$course_info['code'].'&id_session='.$session_id.'&id='.$documentId;
  5968. }
  5969. if (!empty($overwrite_url)) {
  5970. $overwrite_url = Security::remove_XSS($overwrite_url);
  5971. $url = $overwrite_url.'&cidReq='.$course_info['code'].'&id_session='.$session_id.'&document_id='.$documentId;
  5972. }
  5973. $img = Display::returnIconPath($icon);
  5974. if (!file_exists($img_sys_path.$icon)) {
  5975. $img = Display::returnIconPath('default_small.gif');
  5976. }
  5977. $link = Display::url(
  5978. '<img alt="" src="'.$img.'" title="" />&nbsp;'.$my_file_title,
  5979. $url,
  5980. ['target' => $target, 'class' => 'moved']
  5981. );
  5982. $directUrl = $web_code_path.'document/document.php?cidReq='.$course_info['code'].'&id_session='.$session_id.'&id='.$documentId;
  5983. $link .= '&nbsp;'.Display::url(
  5984. Display::return_icon('preview_view.png', get_lang('Preview')),
  5985. $directUrl,
  5986. ['target' => '_blank']
  5987. );
  5988. $visibilityClass = null;
  5989. if ($visibility == 0) {
  5990. $visibilityClass = ' text-muted ';
  5991. }
  5992. $return = null;
  5993. if ($lp_id == false) {
  5994. $return .= '<li class="doc_resource '.$visibilityClass.' " data_id="'.$documentId.'" data_type="document" title="'.$my_file_title.'" >';
  5995. } else {
  5996. $return .= '<li class="doc_resource lp_resource_element '.$visibilityClass.' " data_id="'.$documentId.'" data_type="document" title="'.$my_file_title.'" >';
  5997. }
  5998. $return .= '<div class="item_data" style="margin-left:'.($num * 5).'px;margin-right:5px;">';
  5999. if ($add_move_button) {
  6000. $return .= '<a class="moved" href="#">';
  6001. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  6002. $return .= '</a> ';
  6003. }
  6004. $return .= $link;
  6005. $sessionStar = api_get_session_image($resource['session_id'], $userInfo['status']);
  6006. $return .= $sessionStar;
  6007. $return .= '</div></li>';
  6008. return $return;
  6009. }
  6010. /**
  6011. * @param int $folderId
  6012. * @param array $resource
  6013. * @param int $lp_id
  6014. *
  6015. * @return string|null
  6016. */
  6017. private static function parseFolder($folderId, $resource, $lp_id)
  6018. {
  6019. $title = isset($resource['title']) ? $resource['title'] : null;
  6020. $path = isset($resource['path']) ? $resource['path'] : null;
  6021. if (empty($path)) {
  6022. $num = 0;
  6023. } else {
  6024. $num = substr_count($path, '/');
  6025. }
  6026. // It's a folder.
  6027. //hide some folders
  6028. if (in_array(
  6029. $path,
  6030. ['shared_folder', 'chat_files', 'HotPotatoes_files', 'css', 'certificates']
  6031. )) {
  6032. return null;
  6033. } elseif (preg_match('/_groupdocs/', $path)) {
  6034. return null;
  6035. } elseif (preg_match('/sf_user_/', $path)) {
  6036. return null;
  6037. } elseif (preg_match('/shared_folder_session_/', $path)) {
  6038. return null;
  6039. }
  6040. //$onclick = '';
  6041. // if in LP, hidden folder are displayed in grey
  6042. $folder_class_hidden = '';
  6043. if ($lp_id) {
  6044. if (isset($resource['visible']) && $resource['visible'] == 0) {
  6045. $folder_class_hidden = ' doc_folder_hidden'; // in base.css
  6046. }
  6047. }
  6048. $onclick = 'onclick="javascript: testResources(\'res_'.$resource['id'].'\',\'img_'.$resource['id'].'\')"';
  6049. $return = null;
  6050. if (empty($path)) {
  6051. $return = '<ul class="lp_resource">';
  6052. }
  6053. $return .= '<li class="doc_folder'.$folder_class_hidden.'" id="doc_id_'.$resource['id'].'" style="margin-left:'.($num * 18).'px; ">';
  6054. $image = Display::returnIconPath('nolines_plus.gif');
  6055. if (empty($path)) {
  6056. $image = Display::returnIconPath('nolines_minus.gif');
  6057. }
  6058. $return .= '<img style="cursor: pointer;" src="'.$image.'" align="absmiddle" id="img_'.$resource['id'].'" '.$onclick.'>';
  6059. $return .= Display::return_icon('lp_folder.gif').'&nbsp;';
  6060. $return .= '<span '.$onclick.' style="cursor: pointer;" >'.$title.'</span>';
  6061. $return .= '</li>';
  6062. if (empty($path)) {
  6063. if ($folderId == false) {
  6064. $return .= '<div id="res_'.$resource['id'].'" >';
  6065. } else {
  6066. $return .= '<div id="res_'.$resource['id'].'" style="display: none;" >';
  6067. }
  6068. }
  6069. return $return;
  6070. }
  6071. /**
  6072. * Get the button to edit document.
  6073. *
  6074. * @param bool $isReadOnly
  6075. * @param array $documentData
  6076. * @param string $extension
  6077. * @param bool $isCertificateMode
  6078. *
  6079. * @return string
  6080. */
  6081. private static function getButtonEdit($isReadOnly, array $documentData, $extension, $isCertificateMode)
  6082. {
  6083. $extension = strtolower($extension);
  6084. $iconEn = Display::return_icon('edit.png', get_lang('Modify'));
  6085. $iconDis = Display::return_icon('edit_na.png', get_lang('Modify'));
  6086. $courseParams = api_get_cidreq();
  6087. $webOdfExtensionList = self::get_web_odf_extension_list();
  6088. $path = $documentData['path'];
  6089. $document_id = $documentData['id'];
  6090. if ($isReadOnly) {
  6091. if (!api_is_course_admin() && !api_is_platform_admin()) {
  6092. return $iconDis;
  6093. }
  6094. if (
  6095. $extension == 'svg' && api_browser_support('svg') &&
  6096. api_get_setting('enabled_support_svg') == 'true'
  6097. ) {
  6098. return Display::url($iconEn, "edit_draw.php?$courseParams&id=$document_id");
  6099. }
  6100. if (
  6101. in_array($extension, $webOdfExtensionList) &&
  6102. api_get_configuration_value('enabled_support_odf') === true
  6103. ) {
  6104. return Display::url($iconEn, "edit_odf.php?$courseParams&id=$document_id");
  6105. }
  6106. if (
  6107. in_array($extension, ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'pxd']) &&
  6108. api_get_setting('enabled_support_pixlr') == 'true'
  6109. ) {
  6110. return Display::url($iconEn, "edit_paint.php?$courseParams&id=$document_id");
  6111. }
  6112. return Display::url($iconEn, "edit_document.php?$courseParams&id=$document_id");
  6113. }
  6114. if (in_array($path, self::get_system_folders())) {
  6115. return $iconDis;
  6116. }
  6117. if ($isCertificateMode) {
  6118. return Display::url($iconEn, "edit_document.php?$courseParams&id=$document_id&curdirpath=/certificates");
  6119. }
  6120. $sessionId = api_get_session_id();
  6121. if ($sessionId && $documentData['session_id'] != $sessionId) {
  6122. return $iconDis;
  6123. }
  6124. if (
  6125. $extension == 'svg' && api_browser_support('svg') &&
  6126. api_get_setting('enabled_support_svg') == 'true'
  6127. ) {
  6128. return Display::url($iconEn, "edit_draw.php?$courseParams&id=$document_id");
  6129. }
  6130. if (
  6131. in_array($extension, $webOdfExtensionList) &&
  6132. api_get_configuration_value('enabled_support_odf') === true
  6133. ) {
  6134. return Display::url($iconEn, "edit_odf.php?$courseParams&id=$document_id");
  6135. }
  6136. if (
  6137. in_array($extension, ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'pxd']) &&
  6138. api_get_setting('enabled_support_pixlr') == 'true'
  6139. ) {
  6140. return Display::url($iconEn, "edit_paint.php?$courseParams&id=$document_id");
  6141. }
  6142. return Display::url($iconEn, "edit_document.php?$courseParams&id=$document_id");
  6143. }
  6144. /**
  6145. * Get the button to move document.
  6146. *
  6147. * @param bool $isReadOnly
  6148. * @param array $documentData
  6149. * @param bool $isCertificateMode
  6150. * @param int $parentId
  6151. *
  6152. * @return string
  6153. */
  6154. private static function getButtonMove($isReadOnly, array $documentData, $isCertificateMode, $parentId)
  6155. {
  6156. $iconEn = Display::return_icon('move.png', get_lang('Move'));
  6157. $iconDis = Display::return_icon('move_na.png', get_lang('Move'));
  6158. if ($isReadOnly) {
  6159. return $iconDis;
  6160. }
  6161. $path = $documentData['path'];
  6162. $document_id = $documentData['id'];
  6163. $sessionId = api_get_session_id();
  6164. $courseParams = api_get_cidreq();
  6165. if ($isCertificateMode || in_array($path, self::get_system_folders())) {
  6166. return $iconDis;
  6167. }
  6168. if ($sessionId) {
  6169. if ($documentData['session_id'] != $sessionId) {
  6170. return $iconDis;
  6171. }
  6172. }
  6173. $urlMoveParams = http_build_query(['id' => $parentId, 'move' => $document_id]);
  6174. return Display::url(
  6175. $iconEn,
  6176. api_get_self()."?$courseParams&$urlMoveParams"
  6177. );
  6178. }
  6179. /**
  6180. * Get the button to set visibility to document.
  6181. *
  6182. * @param bool $isReadOnly
  6183. * @param int $visibility
  6184. * @param array $documentData
  6185. * @param bool $isCertificateMode
  6186. * @param int $parentId
  6187. *
  6188. * @return string|null
  6189. */
  6190. private static function getButtonVisibility(
  6191. $isReadOnly,
  6192. $visibility,
  6193. array $documentData,
  6194. $isCertificateMode,
  6195. $parentId
  6196. ) {
  6197. $visibility_icon = $visibility == 0 ? 'invisible' : 'visible';
  6198. $visibility_command = $visibility == 0 ? 'set_visible' : 'set_invisible';
  6199. $courseParams = api_get_cidreq();
  6200. if ($isReadOnly) {
  6201. if (api_is_allowed_to_edit() || api_is_platform_admin()) {
  6202. return Display::return_icon($visibility_icon.'.png', get_lang('VisibilityCannotBeChanged'));
  6203. }
  6204. return null;
  6205. }
  6206. if ($isCertificateMode) {
  6207. return Display::return_icon($visibility_icon.'.png', get_lang('VisibilityCannotBeChanged'));
  6208. }
  6209. if (api_is_allowed_to_edit() || api_is_platform_admin()) {
  6210. $tip_visibility = $visibility_icon == 'invisible' ? get_lang('Show') : get_lang('Hide');
  6211. return Display::url(
  6212. Display::return_icon($visibility_icon.'.png', $tip_visibility),
  6213. api_get_self()."?$courseParams&id=$parentId&$visibility_command={$documentData['id']}"
  6214. );
  6215. }
  6216. return null;
  6217. }
  6218. /**
  6219. * GEt the button to delete a document.
  6220. *
  6221. * @param bool $isReadOnly
  6222. * @param array $documentData
  6223. * @param bool $isCertificateMode
  6224. * @param string $curDirPath
  6225. * @param int $parentId
  6226. *
  6227. * @return string
  6228. */
  6229. private static function getButtonDelete(
  6230. $isReadOnly,
  6231. array $documentData,
  6232. $isCertificateMode,
  6233. $curDirPath,
  6234. $parentId
  6235. ) {
  6236. $iconEn = Display::return_icon('delete.png', get_lang('Delete'));
  6237. $iconDis = Display::return_icon('delete_na.png', get_lang('ThisFolderCannotBeDeleted'));
  6238. $path = $documentData['path'];
  6239. $id = $documentData['id'];
  6240. $courseParams = api_get_cidreq();
  6241. if ($isReadOnly) {
  6242. return $iconDis;
  6243. }
  6244. if (in_array($path, self::get_system_folders())) {
  6245. return $iconDis;
  6246. }
  6247. $titleToShow = addslashes(basename($documentData['title']));
  6248. $urlDeleteParams = http_build_query([
  6249. 'curdirpath' => $curDirPath,
  6250. 'action' => 'delete_item',
  6251. 'id' => $parentId,
  6252. 'deleteid' => $documentData['id'],
  6253. ]);
  6254. $btn = Display::url(
  6255. $iconEn,
  6256. '#',
  6257. [
  6258. 'data-item-title' => $titleToShow,
  6259. 'data-href' => api_get_self()."?$courseParams&$urlDeleteParams",
  6260. 'data-toggle' => 'modal',
  6261. 'data-target' => '#confirm-delete',
  6262. ]
  6263. );
  6264. if (
  6265. isset($_GET['curdirpath']) &&
  6266. $_GET['curdirpath'] == '/certificates' &&
  6267. self::get_default_certificate_id(api_get_course_id()) == $id
  6268. ) {
  6269. return $btn;
  6270. }
  6271. if ($isCertificateMode) {
  6272. return $btn;
  6273. }
  6274. $sessionId = api_get_session_id();
  6275. if ($sessionId) {
  6276. if ($documentData['session_id'] != $sessionId) {
  6277. return $iconDis;
  6278. }
  6279. }
  6280. return $btn;
  6281. }
  6282. }