document.lib.php 257 KB

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