api.lib.php 304 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\SettingsCurrent;
  4. use Chamilo\CourseBundle\Entity\CItemProperty;
  5. use Chamilo\UserBundle\Entity\User;
  6. use ChamiloSession as Session;
  7. use Symfony\Component\Finder\Finder;
  8. /**
  9. * This is a code library for Chamilo.
  10. * It is included by default in every Chamilo file (through including the global.inc.php)
  11. * This library is in process of being transferred to src/Chamilo/CoreBundle/Component/Utils/ChamiloApi.
  12. * Whenever a function is transferred to the ChamiloApi class, the places where it is used should include
  13. * the "use Chamilo\CoreBundle\Component\Utils\ChamiloApi;" statement.
  14. *
  15. * @package chamilo.library
  16. */
  17. // PHP version requirement.
  18. define('REQUIRED_PHP_VERSION', '5.6');
  19. define('REQUIRED_MIN_MEMORY_LIMIT', '128');
  20. define('REQUIRED_MIN_UPLOAD_MAX_FILESIZE', '10');
  21. define('REQUIRED_MIN_POST_MAX_SIZE', '10');
  22. // USER STATUS CONSTANTS
  23. /** global status of a user: student */
  24. define('STUDENT', 5);
  25. /** global status of a user: course manager */
  26. define('COURSEMANAGER', 1);
  27. /** global status of a user: session admin */
  28. define('SESSIONADMIN', 3);
  29. /** global status of a user: human ressource manager */
  30. define('DRH', 4);
  31. /** global status of a user: human ressource manager */
  32. define('ANONYMOUS', 6);
  33. /** global status of a user: low security, necessary for inserting data from
  34. * the teacher through HTMLPurifier */
  35. define('COURSEMANAGERLOWSECURITY', 10);
  36. // Soft user status
  37. define('PLATFORM_ADMIN', 11);
  38. define('SESSION_COURSE_COACH', 12);
  39. define('SESSION_GENERAL_COACH', 13);
  40. define('COURSE_STUDENT', 14); //student subscribed in a course
  41. define('SESSION_STUDENT', 15); //student subscribed in a session course
  42. define('COURSE_TUTOR', 16); // student is tutor of a course (NOT in session)
  43. define('STUDENT_BOSS', 17); // student is boss
  44. define('INVITEE', 20);
  45. define('HRM_REQUEST', 21); //HRM has request for vinculation with user
  46. // Table of status
  47. $_status_list[COURSEMANAGER] = 'teacher'; // 1
  48. $_status_list[SESSIONADMIN] = 'session_admin'; // 3
  49. $_status_list[DRH] = 'drh'; // 4
  50. $_status_list[STUDENT] = 'user'; // 5
  51. $_status_list[ANONYMOUS] = 'anonymous'; // 6
  52. $_status_list[INVITEE] = 'invited'; // 20
  53. // COURSE VISIBILITY CONSTANTS
  54. /** only visible for course admin */
  55. define('COURSE_VISIBILITY_CLOSED', 0);
  56. /** only visible for users registered in the course */
  57. define('COURSE_VISIBILITY_REGISTERED', 1);
  58. /** Open for all registered users on the platform */
  59. define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
  60. /** Open for the whole world */
  61. define('COURSE_VISIBILITY_OPEN_WORLD', 3);
  62. /** Invisible to all except admin */
  63. define('COURSE_VISIBILITY_HIDDEN', 4);
  64. define('COURSE_REQUEST_PENDING', 0);
  65. define('COURSE_REQUEST_ACCEPTED', 1);
  66. define('COURSE_REQUEST_REJECTED', 2);
  67. define('DELETE_ACTION_ENABLED', false);
  68. // EMAIL SENDING RECIPIENT CONSTANTS
  69. define('SEND_EMAIL_EVERYONE', 1);
  70. define('SEND_EMAIL_STUDENTS', 2);
  71. define('SEND_EMAIL_TEACHERS', 3);
  72. // SESSION VISIBILITY CONSTANTS
  73. define('SESSION_VISIBLE_READ_ONLY', 1);
  74. define('SESSION_VISIBLE', 2);
  75. define('SESSION_INVISIBLE', 3); // not available
  76. define('SESSION_AVAILABLE', 4);
  77. define('SESSION_LINK_TARGET', '_self');
  78. define('SUBSCRIBE_ALLOWED', 1);
  79. define('SUBSCRIBE_NOT_ALLOWED', 0);
  80. define('UNSUBSCRIBE_ALLOWED', 1);
  81. define('UNSUBSCRIBE_NOT_ALLOWED', 0);
  82. // SURVEY VISIBILITY CONSTANTS
  83. define('SURVEY_VISIBLE_TUTOR', 0);
  84. define('SURVEY_VISIBLE_TUTOR_STUDENT', 1);
  85. define('SURVEY_VISIBLE_PUBLIC', 2);
  86. // CONSTANTS defining all tools, using the english version
  87. /* When you add a new tool you must add it into function api_get_tools_lists() too */
  88. define('TOOL_DOCUMENT', 'document');
  89. define('TOOL_LP_FINAL_ITEM', 'final_item');
  90. define('TOOL_READOUT_TEXT', 'readout_text');
  91. define('TOOL_THUMBNAIL', 'thumbnail');
  92. define('TOOL_HOTPOTATOES', 'hotpotatoes');
  93. define('TOOL_CALENDAR_EVENT', 'calendar_event');
  94. define('TOOL_LINK', 'link');
  95. define('TOOL_LINK_CATEGORY', 'link_category');
  96. define('TOOL_COURSE_DESCRIPTION', 'course_description');
  97. define('TOOL_SEARCH', 'search');
  98. define('TOOL_LEARNPATH', 'learnpath');
  99. define('TOOL_LEARNPATH_CATEGORY', 'learnpath_category');
  100. define('TOOL_AGENDA', 'agenda');
  101. define('TOOL_ANNOUNCEMENT', 'announcement');
  102. define('TOOL_FORUM', 'forum');
  103. define('TOOL_FORUM_CATEGORY', 'forum_category');
  104. define('TOOL_FORUM_THREAD', 'forum_thread');
  105. define('TOOL_FORUM_POST', 'forum_post');
  106. define('TOOL_FORUM_ATTACH', 'forum_attachment');
  107. define('TOOL_FORUM_THREAD_QUALIFY', 'forum_thread_qualify');
  108. define('TOOL_THREAD', 'thread');
  109. define('TOOL_POST', 'post');
  110. define('TOOL_DROPBOX', 'dropbox');
  111. define('TOOL_QUIZ', 'quiz');
  112. define('TOOL_TEST_CATEGORY', 'test_category');
  113. define('TOOL_USER', 'user');
  114. define('TOOL_GROUP', 'group');
  115. define('TOOL_BLOGS', 'blog_management');
  116. define('TOOL_CHAT', 'chat');
  117. define('TOOL_STUDENTPUBLICATION', 'student_publication');
  118. define('TOOL_TRACKING', 'tracking');
  119. define('TOOL_HOMEPAGE_LINK', 'homepage_link');
  120. define('TOOL_COURSE_SETTING', 'course_setting');
  121. define('TOOL_BACKUP', 'backup');
  122. define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
  123. define('TOOL_RECYCLE_COURSE', 'recycle_course');
  124. define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
  125. define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
  126. define('TOOL_UPLOAD', 'file_upload');
  127. define('TOOL_COURSE_MAINTENANCE', 'course_maintenance');
  128. define('TOOL_SURVEY', 'survey');
  129. define('TOOL_WIKI', 'wiki');
  130. define('TOOL_GLOSSARY', 'glossary');
  131. define('TOOL_GRADEBOOK', 'gradebook');
  132. define('TOOL_NOTEBOOK', 'notebook');
  133. define('TOOL_ATTENDANCE', 'attendance');
  134. define('TOOL_COURSE_PROGRESS', 'course_progress');
  135. define('TOOL_PORTFOLIO', 'portfolio');
  136. define('TOOL_PLAGIARISM', 'compilatio');
  137. // CONSTANTS defining Chamilo interface sections
  138. define('SECTION_CAMPUS', 'mycampus');
  139. define('SECTION_COURSES', 'mycourses');
  140. define('SECTION_CATALOG', 'catalog');
  141. define('SECTION_MYPROFILE', 'myprofile');
  142. define('SECTION_MYAGENDA', 'myagenda');
  143. define('SECTION_COURSE_ADMIN', 'course_admin');
  144. define('SECTION_PLATFORM_ADMIN', 'platform_admin');
  145. define('SECTION_MYGRADEBOOK', 'mygradebook');
  146. define('SECTION_TRACKING', 'session_my_space');
  147. define('SECTION_SOCIAL', 'social-network');
  148. define('SECTION_DASHBOARD', 'dashboard');
  149. define('SECTION_REPORTS', 'reports');
  150. define('SECTION_GLOBAL', 'global');
  151. define('SECTION_INCLUDE', 'include');
  152. // CONSTANT name for local authentication source
  153. define('PLATFORM_AUTH_SOURCE', 'platform');
  154. define('CAS_AUTH_SOURCE', 'cas');
  155. define('LDAP_AUTH_SOURCE', 'extldap');
  156. // CONSTANT defining the default HotPotatoes files directory
  157. define('DIR_HOTPOTATOES', '/HotPotatoes_files');
  158. // event logs types
  159. define('LOG_COURSE_DELETE', 'course_deleted');
  160. define('LOG_COURSE_CREATE', 'course_created');
  161. // @todo replace 'soc_gr' with social_group
  162. define('LOG_GROUP_PORTAL_CREATED', 'soc_gr_created');
  163. define('LOG_GROUP_PORTAL_UPDATED', 'soc_gr_updated');
  164. define('LOG_GROUP_PORTAL_DELETED', 'soc_gr_deleted');
  165. define('LOG_GROUP_PORTAL_USER_DELETE_ALL', 'soc_gr_delete_users');
  166. define('LOG_GROUP_PORTAL_ID', 'soc_gr_portal_id');
  167. define('LOG_GROUP_PORTAL_REL_USER_ARRAY', 'soc_gr_user_array');
  168. define('LOG_GROUP_PORTAL_USER_SUBSCRIBED', 'soc_gr_u_subs');
  169. define('LOG_GROUP_PORTAL_USER_UNSUBSCRIBED', 'soc_gr_u_unsubs');
  170. define('LOG_GROUP_PORTAL_USER_UPDATE_ROLE', 'soc_gr_update_role');
  171. define('LOG_USER_DELETE', 'user_deleted');
  172. define('LOG_USER_CREATE', 'user_created');
  173. define('LOG_USER_ENABLE', 'user_enable');
  174. define('LOG_USER_DISABLE', 'user_disable');
  175. define('LOG_USER_ANONYMIZE', 'user_anonymized');
  176. define('LOG_USER_FIELD_CREATE', 'user_field_created');
  177. define('LOG_USER_FIELD_DELETE', 'user_field_deleted');
  178. define('LOG_SESSION_CREATE', 'session_created');
  179. define('LOG_SESSION_DELETE', 'session_deleted');
  180. define('LOG_SESSION_ADD_USER_COURSE', 'session_add_user_course');
  181. define('LOG_SESSION_DELETE_USER_COURSE', 'session_delete_user_course');
  182. define('LOG_SESSION_ADD_USER', 'session_add_user');
  183. define('LOG_SESSION_DELETE_USER', 'session_delete_user');
  184. define('LOG_SESSION_ADD_COURSE', 'session_add_course');
  185. define('LOG_SESSION_DELETE_COURSE', 'session_delete_course');
  186. define('LOG_SESSION_CATEGORY_CREATE', 'session_cat_created'); //changed in 1.9.8
  187. define('LOG_SESSION_CATEGORY_DELETE', 'session_cat_deleted'); //changed in 1.9.8
  188. define('LOG_CONFIGURATION_SETTINGS_CHANGE', 'settings_changed');
  189. define('LOG_PLATFORM_LANGUAGE_CHANGE', 'platform_lng_changed'); //changed in 1.9.8
  190. define('LOG_SUBSCRIBE_USER_TO_COURSE', 'user_subscribed');
  191. define('LOG_UNSUBSCRIBE_USER_FROM_COURSE', 'user_unsubscribed');
  192. define('LOG_ATTEMPTED_FORCED_LOGIN', 'attempted_forced_login');
  193. define('LOG_HOMEPAGE_CHANGED', 'homepage_changed');
  194. define('LOG_PROMOTION_CREATE', 'promotion_created');
  195. define('LOG_PROMOTION_DELETE', 'promotion_deleted');
  196. define('LOG_CAREER_CREATE', 'career_created');
  197. define('LOG_CAREER_DELETE', 'career_deleted');
  198. define('LOG_USER_PERSONAL_DOC_DELETED', 'user_doc_deleted');
  199. define('LOG_WIKI_ACCESS', 'wiki_page_view');
  200. // All results from an exercise
  201. define('LOG_EXERCISE_RESULT_DELETE', 'exe_result_deleted');
  202. // Logs only the one attempt
  203. define('LOG_EXERCISE_ATTEMPT_DELETE', 'exe_attempt_deleted');
  204. define('LOG_LP_ATTEMPT_DELETE', 'lp_attempt_deleted');
  205. define('LOG_QUESTION_RESULT_DELETE', 'qst_attempt_deleted');
  206. define('LOG_MY_FOLDER_CREATE', 'my_folder_created');
  207. define('LOG_MY_FOLDER_CHANGE', 'my_folder_changed');
  208. define('LOG_MY_FOLDER_DELETE', 'my_folder_deleted');
  209. define('LOG_MY_FOLDER_COPY', 'my_folder_copied');
  210. define('LOG_MY_FOLDER_CUT', 'my_folder_cut');
  211. define('LOG_MY_FOLDER_PASTE', 'my_folder_pasted');
  212. define('LOG_MY_FOLDER_UPLOAD', 'my_folder_uploaded');
  213. // Event logs data types (max 20 chars)
  214. define('LOG_COURSE_CODE', 'course_code');
  215. define('LOG_COURSE_ID', 'course_id');
  216. define('LOG_USER_ID', 'user_id');
  217. define('LOG_USER_OBJECT', 'user_object');
  218. define('LOG_USER_FIELD_VARIABLE', 'user_field_variable');
  219. define('LOG_SESSION_ID', 'session_id');
  220. define('LOG_QUESTION_ID', 'question_id');
  221. define('LOG_SESSION_CATEGORY_ID', 'session_category_id');
  222. define('LOG_CONFIGURATION_SETTINGS_CATEGORY', 'settings_category');
  223. define('LOG_CONFIGURATION_SETTINGS_VARIABLE', 'settings_variable');
  224. define('LOG_PLATFORM_LANGUAGE', 'default_platform_language');
  225. define('LOG_CAREER_ID', 'career_id');
  226. define('LOG_PROMOTION_ID', 'promotion_id');
  227. define('LOG_GRADEBOOK_LOCKED', 'gradebook_locked');
  228. define('LOG_GRADEBOOK_UNLOCKED', 'gradebook_unlocked');
  229. define('LOG_GRADEBOOK_ID', 'gradebook_id');
  230. define('LOG_WIKI_PAGE_ID', 'wiki_page_id');
  231. define('LOG_EXERCISE_ID', 'exercise_id');
  232. define('LOG_EXERCISE_AND_USER_ID', 'exercise_and_user_id');
  233. define('LOG_LP_ID', 'lp_id');
  234. define('LOG_EXERCISE_ATTEMPT_QUESTION_ID', 'exercise_a_q_id');
  235. define('LOG_EXERCISE_ATTEMPT', 'exe_id');
  236. define('LOG_WORK_DIR_DELETE', 'work_dir_delete');
  237. define('LOG_WORK_FILE_DELETE', 'work_file_delete');
  238. define('LOG_WORK_DATA', 'work_data_array');
  239. define('LOG_MY_FOLDER_PATH', 'path');
  240. define('LOG_MY_FOLDER_NEW_PATH', 'new_path');
  241. define('LOG_TERM_CONDITION_ACCEPTED', 'term_condition_accepted');
  242. define('LOG_USER_CONFIRMED_EMAIL', 'user_confirmed_email');
  243. define('LOG_USER_REMOVED_LEGAL_ACCEPT', 'user_removed_legal_accept');
  244. define('LOG_USER_DELETE_ACCOUNT_REQUEST', 'user_delete_account_request');
  245. define('LOG_QUESTION_CREATED', 'question_created');
  246. define('LOG_QUESTION_UPDATED', 'question_updated');
  247. define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.]/');
  248. //used when login_is_email setting is true
  249. define('USERNAME_PURIFIER_MAIL', '/[^0-9A-Za-z_\.@]/');
  250. define('USERNAME_PURIFIER_SHALLOW', '/\s/');
  251. // This constant is a result of Windows OS detection, it has a boolean value:
  252. // true whether the server runs on Windows OS, false otherwise.
  253. define('IS_WINDOWS_OS', api_is_windows_os());
  254. // Checks for installed optional php-extensions.
  255. // intl extension (from PECL), it is installed by default as of PHP 5.3.0.
  256. define('INTL_INSTALLED', function_exists('intl_get_error_code'));
  257. // iconv extension, for PHP5 on Windows it is installed by default.
  258. define('ICONV_INSTALLED', function_exists('iconv'));
  259. define('MBSTRING_INSTALLED', function_exists('mb_strlen')); // mbstring extension.
  260. // Patterns for processing paths. Examples.
  261. define('REPEATED_SLASHES_PURIFIER', '/\/{2,}/'); // $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  262. define('VALID_WEB_PATH', '/https?:\/\/[^\/]*(\/.*)?/i'); // $is_valid_path = preg_match(VALID_WEB_PATH, $path);
  263. // $new_path = preg_replace(VALID_WEB_SERVER_BASE, $new_base, $path);
  264. define('VALID_WEB_SERVER_BASE', '/https?:\/\/[^\/]*/i');
  265. // Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
  266. // basic (leaf elements)
  267. define('REL_CODE_PATH', 'REL_CODE_PATH');
  268. define('REL_COURSE_PATH', 'REL_COURSE_PATH');
  269. define('REL_HOME_PATH', 'REL_HOME_PATH');
  270. // Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
  271. define('WEB_PATH', 'WEB_PATH');
  272. define('WEB_APP_PATH', 'WEB_APP_PATH');
  273. define('SYS_PATH', 'SYS_PATH');
  274. define('SYS_APP_PATH', 'SYS_APP_PATH');
  275. define('SYS_UPLOAD_PATH', 'SYS_UPLOAD_PATH');
  276. define('WEB_UPLOAD_PATH', 'WEB_UPLOAD_PATH');
  277. define('REL_PATH', 'REL_PATH');
  278. define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
  279. define('SYS_COURSE_PATH', 'SYS_COURSE_PATH');
  280. define('WEB_CODE_PATH', 'WEB_CODE_PATH');
  281. define('SYS_CODE_PATH', 'SYS_CODE_PATH');
  282. define('SYS_LANG_PATH', 'SYS_LANG_PATH');
  283. define('WEB_IMG_PATH', 'WEB_IMG_PATH');
  284. define('WEB_CSS_PATH', 'WEB_CSS_PATH');
  285. define('WEB_PUBLIC_PATH', 'WEB_PUBLIC_PATH');
  286. define('SYS_CSS_PATH', 'SYS_CSS_PATH');
  287. define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
  288. define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
  289. define('WEB_PLUGIN_ASSET_PATH', 'WEB_PLUGIN_ASSET_PATH');
  290. define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
  291. define('WEB_ARCHIVE_PATH', 'WEB_ARCHIVE_PATH');
  292. define('SYS_INC_PATH', 'SYS_INC_PATH');
  293. define('LIBRARY_PATH', 'LIBRARY_PATH');
  294. define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
  295. define('WEB_LIBRARY_PATH', 'WEB_LIBRARY_PATH');
  296. define('WEB_LIBRARY_JS_PATH', 'WEB_LIBRARY_JS_PATH');
  297. define('WEB_AJAX_PATH', 'WEB_AJAX_PATH');
  298. define('SYS_TEST_PATH', 'SYS_TEST_PATH');
  299. define('WEB_TEMPLATE_PATH', 'WEB_TEMPLATE_PATH');
  300. define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
  301. define('SYS_PUBLIC_PATH', 'SYS_PUBLIC_PATH');
  302. define('SYS_HOME_PATH', 'SYS_HOME_PATH');
  303. define('WEB_HOME_PATH', 'WEB_HOME_PATH');
  304. define('WEB_FONTS_PATH', 'WEB_FONTS_PATH');
  305. define('SYS_FONTS_PATH', 'SYS_FONTS_PATH');
  306. define('SYS_DEFAULT_COURSE_DOCUMENT_PATH', 'SYS_DEFAULT_COURSE_DOCUMENT_PATH');
  307. define('REL_DEFAULT_COURSE_DOCUMENT_PATH', 'REL_DEFAULT_COURSE_DOCUMENT_PATH');
  308. define('WEB_DEFAULT_COURSE_DOCUMENT_PATH', 'WEB_DEFAULT_COURSE_DOCUMENT_PATH');
  309. // Relations type with Course manager
  310. define('COURSE_RELATION_TYPE_COURSE_MANAGER', 1);
  311. define('SESSION_RELATION_TYPE_COURSE_MANAGER', 1);
  312. // Relations type with Human resources manager
  313. define('COURSE_RELATION_TYPE_RRHH', 1);
  314. define('SESSION_RELATION_TYPE_RRHH', 1);
  315. //User image sizes
  316. define('USER_IMAGE_SIZE_ORIGINAL', 1);
  317. define('USER_IMAGE_SIZE_BIG', 2);
  318. define('USER_IMAGE_SIZE_MEDIUM', 3);
  319. define('USER_IMAGE_SIZE_SMALL', 4);
  320. // Relation type between users
  321. define('USER_UNKNOWN', 0);
  322. define('USER_RELATION_TYPE_UNKNOWN', 1);
  323. define('USER_RELATION_TYPE_PARENT', 2); // should be deprecated is useless
  324. define('USER_RELATION_TYPE_FRIEND', 3);
  325. define('USER_RELATION_TYPE_GOODFRIEND', 4); // should be deprecated is useless
  326. define('USER_RELATION_TYPE_ENEMY', 5); // should be deprecated is useless
  327. define('USER_RELATION_TYPE_DELETED', 6);
  328. define('USER_RELATION_TYPE_RRHH', 7);
  329. define('USER_RELATION_TYPE_BOSS', 8);
  330. define('USER_RELATION_TYPE_HRM_REQUEST', 9);
  331. // Gradebook link constants
  332. // Please do not change existing values, they are used in the database !
  333. define('GRADEBOOK_ITEM_LIMIT', 1000);
  334. define('LINK_EXERCISE', 1);
  335. define('LINK_DROPBOX', 2);
  336. define('LINK_STUDENTPUBLICATION', 3);
  337. define('LINK_LEARNPATH', 4);
  338. define('LINK_FORUM_THREAD', 5);
  339. //define('LINK_WORK',6);
  340. define('LINK_ATTENDANCE', 7);
  341. define('LINK_SURVEY', 8);
  342. define('LINK_HOTPOTATOES', 9);
  343. // Score display types constants
  344. define('SCORE_DIV', 1); // X / Y
  345. define('SCORE_PERCENT', 2); // XX %
  346. define('SCORE_DIV_PERCENT', 3); // X / Y (XX %)
  347. define('SCORE_AVERAGE', 4); // XX %
  348. define('SCORE_DECIMAL', 5); // 0.50 (X/Y)
  349. define('SCORE_BAR', 6); // Uses the Display::bar_progress function
  350. define('SCORE_SIMPLE', 7); // X
  351. define('SCORE_IGNORE_SPLIT', 8); // ??
  352. define('SCORE_DIV_PERCENT_WITH_CUSTOM', 9); // X / Y (XX %) - Good!
  353. define('SCORE_CUSTOM', 10); // Good!
  354. define('SCORE_DIV_SIMPLE_WITH_CUSTOM', 11); // X - Good!
  355. define('SCORE_DIV_SIMPLE_WITH_CUSTOM_LETTERS', 12); // X - Good!
  356. define('SCORE_ONLY_SCORE', 13); // X - Good!
  357. define('SCORE_NUMERIC', 14);
  358. define('SCORE_BOTH', 1);
  359. define('SCORE_ONLY_DEFAULT', 2);
  360. define('SCORE_ONLY_CUSTOM', 3);
  361. // From display.lib.php
  362. define('MAX_LENGTH_BREADCRUMB', 100);
  363. define('ICON_SIZE_ATOM', 8);
  364. define('ICON_SIZE_TINY', 16);
  365. define('ICON_SIZE_SMALL', 22);
  366. define('ICON_SIZE_MEDIUM', 32);
  367. define('ICON_SIZE_LARGE', 48);
  368. define('ICON_SIZE_BIG', 64);
  369. define('ICON_SIZE_HUGE', 128);
  370. define('SHOW_TEXT_NEAR_ICONS', false);
  371. // Session catalog
  372. define('CATALOG_COURSES', 0);
  373. define('CATALOG_SESSIONS', 1);
  374. define('CATALOG_COURSES_SESSIONS', 2);
  375. // Hook type events, pre-process and post-process.
  376. // All means to be executed for both hook event types
  377. define('HOOK_EVENT_TYPE_PRE', 0);
  378. define('HOOK_EVENT_TYPE_POST', 1);
  379. define('HOOK_EVENT_TYPE_ALL', 10);
  380. define('CAREER_STATUS_ACTIVE', 1);
  381. define('CAREER_STATUS_INACTIVE', 0);
  382. define('PROMOTION_STATUS_ACTIVE', 1);
  383. define('PROMOTION_STATUS_INACTIVE', 0);
  384. // Group permissions
  385. define('GROUP_PERMISSION_OPEN', '1');
  386. define('GROUP_PERMISSION_CLOSED', '2');
  387. // Group user permissions
  388. define('GROUP_USER_PERMISSION_ADMIN', '1'); // the admin of a group
  389. define('GROUP_USER_PERMISSION_READER', '2'); // a normal user
  390. define('GROUP_USER_PERMISSION_PENDING_INVITATION', '3'); // When an admin/moderator invites a user
  391. define('GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER', '4'); // an user joins a group
  392. define('GROUP_USER_PERMISSION_MODERATOR', '5'); // a moderator
  393. define('GROUP_USER_PERMISSION_ANONYMOUS', '6'); // an anonymous user
  394. define('GROUP_USER_PERMISSION_HRM', '7'); // a human resources manager
  395. define('GROUP_IMAGE_SIZE_ORIGINAL', 1);
  396. define('GROUP_IMAGE_SIZE_BIG', 2);
  397. define('GROUP_IMAGE_SIZE_MEDIUM', 3);
  398. define('GROUP_IMAGE_SIZE_SMALL', 4);
  399. define('GROUP_TITLE_LENGTH', 50);
  400. // Exercise
  401. // @todo move into a class
  402. define('ALL_ON_ONE_PAGE', 1);
  403. define('ONE_PER_PAGE', 2);
  404. define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback - show score and expected answers
  405. define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
  406. define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); // NoFeedback - Show score only
  407. define('EXERCISE_FEEDBACK_TYPE_POPUP', 3); // Popup BT#15827
  408. define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and expected answers
  409. define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
  410. define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
  411. define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
  412. define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT', 4);
  413. define('RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK', 5);
  414. define('RESULT_DISABLE_RANKING', 6);
  415. define('RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER', 7);
  416. define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING', 8);
  417. define('EXERCISE_MAX_NAME_SIZE', 80);
  418. // Question types (edit next array as well when adding values)
  419. // @todo move into a class
  420. define('UNIQUE_ANSWER', 1);
  421. define('MULTIPLE_ANSWER', 2);
  422. define('FILL_IN_BLANKS', 3);
  423. define('MATCHING', 4);
  424. define('FREE_ANSWER', 5);
  425. define('HOT_SPOT', 6);
  426. define('HOT_SPOT_ORDER', 7);
  427. define('HOT_SPOT_DELINEATION', 8);
  428. define('MULTIPLE_ANSWER_COMBINATION', 9);
  429. define('UNIQUE_ANSWER_NO_OPTION', 10);
  430. define('MULTIPLE_ANSWER_TRUE_FALSE', 11);
  431. define('MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE', 12);
  432. define('ORAL_EXPRESSION', 13);
  433. define('GLOBAL_MULTIPLE_ANSWER', 14);
  434. define('MEDIA_QUESTION', 15);
  435. define('CALCULATED_ANSWER', 16);
  436. define('UNIQUE_ANSWER_IMAGE', 17);
  437. define('DRAGGABLE', 18);
  438. define('MATCHING_DRAGGABLE', 19);
  439. define('ANNOTATION', 20);
  440. define('READING_COMPREHENSION', 21);
  441. define('MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY', 22);
  442. define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
  443. define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
  444. define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
  445. // Question selection type
  446. define('EX_Q_SELECTION_ORDERED', 1);
  447. define('EX_Q_SELECTION_RANDOM', 2);
  448. define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED', 3);
  449. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED', 4);
  450. define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM', 5);
  451. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM', 6);
  452. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED', 7);
  453. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED', 8);
  454. define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED', 9);
  455. define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM', 10);
  456. // Used to save the skill_rel_item table
  457. define('ITEM_TYPE_EXERCISE', 1);
  458. define('ITEM_TYPE_HOTPOTATOES', 2);
  459. define('ITEM_TYPE_LINK', 3);
  460. define('ITEM_TYPE_LEARNPATH', 4);
  461. define('ITEM_TYPE_GRADEBOOK', 5);
  462. define('ITEM_TYPE_STUDENT_PUBLICATION', 6);
  463. //define('ITEM_TYPE_FORUM', 7);
  464. define('ITEM_TYPE_ATTENDANCE', 8);
  465. define('ITEM_TYPE_SURVEY', 9);
  466. define('ITEM_TYPE_FORUM_THREAD', 10);
  467. // one big string with all question types, for the validator in pear/HTML/QuickForm/Rule/QuestionType
  468. define(
  469. 'QUESTION_TYPES',
  470. UNIQUE_ANSWER.':'.
  471. MULTIPLE_ANSWER.':'.
  472. FILL_IN_BLANKS.':'.
  473. MATCHING.':'.
  474. FREE_ANSWER.':'.
  475. HOT_SPOT.':'.
  476. HOT_SPOT_ORDER.':'.
  477. HOT_SPOT_DELINEATION.':'.
  478. MULTIPLE_ANSWER_COMBINATION.':'.
  479. UNIQUE_ANSWER_NO_OPTION.':'.
  480. MULTIPLE_ANSWER_TRUE_FALSE.':'.
  481. MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE.':'.
  482. ORAL_EXPRESSION.':'.
  483. GLOBAL_MULTIPLE_ANSWER.':'.
  484. MEDIA_QUESTION.':'.
  485. CALCULATED_ANSWER.':'.
  486. UNIQUE_ANSWER_IMAGE.':'.
  487. DRAGGABLE.':'.
  488. MATCHING_DRAGGABLE.':'.
  489. MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY.':'.
  490. ANNOTATION
  491. );
  492. //Some alias used in the QTI exports
  493. define('MCUA', 1);
  494. define('TF', 1);
  495. define('MCMA', 2);
  496. define('FIB', 3);
  497. // Skills
  498. define('SKILL_TYPE_REQUIREMENT', 'required');
  499. define('SKILL_TYPE_ACQUIRED', 'acquired');
  500. define('SKILL_TYPE_BOTH', 'both');
  501. // Message
  502. define('MESSAGE_STATUS_NEW', '0');
  503. define('MESSAGE_STATUS_UNREAD', '1');
  504. //2 ??
  505. define('MESSAGE_STATUS_DELETED', '3');
  506. define('MESSAGE_STATUS_OUTBOX', '4');
  507. define('MESSAGE_STATUS_INVITATION_PENDING', '5');
  508. define('MESSAGE_STATUS_INVITATION_ACCEPTED', '6');
  509. define('MESSAGE_STATUS_INVITATION_DENIED', '7');
  510. define('MESSAGE_STATUS_WALL', '8');
  511. define('MESSAGE_STATUS_WALL_DELETE', '9');
  512. define('MESSAGE_STATUS_WALL_POST', '10');
  513. define('MESSAGE_STATUS_CONVERSATION', '11');
  514. define('MESSAGE_STATUS_FORUM', '12');
  515. define('MESSAGE_STATUS_PROMOTED', '13');
  516. // Images
  517. define('IMAGE_WALL_SMALL_SIZE', 200);
  518. define('IMAGE_WALL_MEDIUM_SIZE', 500);
  519. define('IMAGE_WALL_BIG_SIZE', 2000);
  520. define('IMAGE_WALL_SMALL', 'small');
  521. define('IMAGE_WALL_MEDIUM', 'medium');
  522. define('IMAGE_WALL_BIG', 'big');
  523. // Social PLUGIN PLACES
  524. define('SOCIAL_LEFT_PLUGIN', 1);
  525. define('SOCIAL_CENTER_PLUGIN', 2);
  526. define('SOCIAL_RIGHT_PLUGIN', 3);
  527. define('CUT_GROUP_NAME', 50);
  528. /**
  529. * FormValidator Filter.
  530. */
  531. define('NO_HTML', 1);
  532. define('STUDENT_HTML', 2);
  533. define('TEACHER_HTML', 3);
  534. define('STUDENT_HTML_FULLPAGE', 4);
  535. define('TEACHER_HTML_FULLPAGE', 5);
  536. // Timeline
  537. define('TIMELINE_STATUS_ACTIVE', '1');
  538. define('TIMELINE_STATUS_INACTIVE', '2');
  539. // Event email template class
  540. define('EVENT_EMAIL_TEMPLATE_ACTIVE', 1);
  541. define('EVENT_EMAIL_TEMPLATE_INACTIVE', 0);
  542. // Course home
  543. define('SHORTCUTS_HORIZONTAL', 0);
  544. define('SHORTCUTS_VERTICAL', 1);
  545. // Image class
  546. define('IMAGE_PROCESSOR', 'gd'); // 'imagick' or 'gd' strings
  547. // Course copy
  548. define('FILE_SKIP', 1);
  549. define('FILE_RENAME', 2);
  550. define('FILE_OVERWRITE', 3);
  551. define('UTF8_CONVERT', false); //false by default
  552. define('DOCUMENT', 'file');
  553. define('FOLDER', 'folder');
  554. define('RESOURCE_ASSET', 'asset');
  555. define('RESOURCE_DOCUMENT', 'document');
  556. define('RESOURCE_GLOSSARY', 'glossary');
  557. define('RESOURCE_EVENT', 'calendar_event');
  558. define('RESOURCE_LINK', 'link');
  559. define('RESOURCE_COURSEDESCRIPTION', 'course_description');
  560. define('RESOURCE_LEARNPATH', 'learnpath');
  561. define('RESOURCE_LEARNPATH_CATEGORY', 'learnpath_category');
  562. define('RESOURCE_ANNOUNCEMENT', 'announcement');
  563. define('RESOURCE_FORUM', 'forum');
  564. define('RESOURCE_FORUMTOPIC', 'thread');
  565. define('RESOURCE_FORUMPOST', 'post');
  566. define('RESOURCE_QUIZ', 'quiz');
  567. define('RESOURCE_TEST_CATEGORY', 'test_category');
  568. define('RESOURCE_QUIZQUESTION', 'Exercise_Question');
  569. define('RESOURCE_TOOL_INTRO', 'Tool introduction');
  570. define('RESOURCE_LINKCATEGORY', 'Link_Category');
  571. define('RESOURCE_FORUMCATEGORY', 'Forum_Category');
  572. define('RESOURCE_SCORM', 'Scorm');
  573. define('RESOURCE_SURVEY', 'survey');
  574. define('RESOURCE_SURVEYQUESTION', 'survey_question');
  575. define('RESOURCE_SURVEYINVITATION', 'survey_invitation');
  576. define('RESOURCE_WIKI', 'wiki');
  577. define('RESOURCE_THEMATIC', 'thematic');
  578. define('RESOURCE_ATTENDANCE', 'attendance');
  579. define('RESOURCE_WORK', 'work');
  580. define('RESOURCE_SESSION_COURSE', 'session_course');
  581. define('RESOURCE_GRADEBOOK', 'gradebook');
  582. define('ADD_THEMATIC_PLAN', 6);
  583. // Max online users to show per page (whoisonline)
  584. define('MAX_ONLINE_USERS', 12);
  585. // Number of characters maximum to show in preview of course blog posts
  586. define('BLOG_MAX_PREVIEW_CHARS', 800);
  587. // HTML string to replace with a 'Read more...' link
  588. define('BLOG_PAGE_BREAK', '<div style="page-break-after: always"><span style="display: none;">&nbsp;</span></div>');
  589. // Make sure the CHAMILO_LOAD_WYSIWYG constant is defined
  590. // To remove CKeditor libs from HTML, set this constant to true before loading
  591. if (!defined('CHAMILO_LOAD_WYSIWYG')) {
  592. define('CHAMILO_LOAD_WYSIWYG', true);
  593. }
  594. /* Constants for course home */
  595. define('TOOL_PUBLIC', 'Public');
  596. define('TOOL_PUBLIC_BUT_HIDDEN', 'PublicButHide');
  597. define('TOOL_COURSE_ADMIN', 'courseAdmin');
  598. define('TOOL_PLATFORM_ADMIN', 'platformAdmin');
  599. define('TOOL_AUTHORING', 'toolauthoring');
  600. define('TOOL_INTERACTION', 'toolinteraction');
  601. define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
  602. define('TOOL_ADMIN', 'tooladmin');
  603. define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
  604. define('TOOL_DRH', 'tool_drh');
  605. define('TOOL_STUDENT_VIEW', 'toolstudentview');
  606. define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
  607. /**
  608. * Inclusion of internationalization libraries.
  609. */
  610. require_once __DIR__.'/internationalization.lib.php';
  611. /**
  612. * Returns a path to a certain resource within the Chamilo area, specifyed through a parameter.
  613. * Also, this function provides conversion between path types, in this case the input path points inside the Chamilo area too.
  614. *
  615. * See $_configuration['course_folder'] in the configuration.php to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters.
  616. *
  617. * @param string $path (optional) A path which type is to be converted. Also, it may be a defined constant for a path.
  618. * This parameter has meaning when $type parameter has one of the following values: TO_WEB, TO_SYS, TO_REL. Otherwise it is ignored.
  619. *
  620. * @return string the requested path or the converted path
  621. *
  622. *
  623. * Notes about the current behaviour model:
  624. * 1. Windows back-slashes are converted to slashes in the result.
  625. * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
  626. * a slash too, so an additional check about presence of leading system server base is implemented. For example, the function is
  627. * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
  628. * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
  629. * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
  630. * It has not been identified as needed yet.
  631. * 4. Also, resolving the meta-symbols "." and ".." within paths has not been implemented, it is to be identified as needed.
  632. *
  633. * For examples go to: *
  634. * See main/admin/system_status.php?section=paths
  635. *
  636. * Vchamilo changes : allow using an alternate configuration
  637. * to get vchamilo instance paths
  638. */
  639. function api_get_path($path = '', $configuration = [])
  640. {
  641. global $paths;
  642. // get proper configuration data if exists
  643. global $_configuration;
  644. $emptyConfigurationParam = false;
  645. if (empty($configuration)) {
  646. $configuration = (array) $_configuration;
  647. $emptyConfigurationParam = true;
  648. }
  649. $course_folder = 'courses/';
  650. static $root_web = '';
  651. $root_sys = $_configuration['root_sys'];
  652. // If no $root_web has been set so far *and* no custom config has been passed to the function
  653. // then re-use the previously-calculated (run-specific) $root_web and skip this complex calculation
  654. if (empty($root_web) || $emptyConfigurationParam === false || empty($configuration)) {
  655. // Resolve master hostname.
  656. if (!empty($configuration) && array_key_exists('root_web', $configuration)) {
  657. $root_web = $configuration['root_web'];
  658. } else {
  659. $root_web = '';
  660. // Try guess it from server.
  661. if (defined('SYSTEM_INSTALLATION') && SYSTEM_INSTALLATION) {
  662. if (($pos = strpos(($requested_page_rel = api_get_self()), 'main/install')) !== false) {
  663. $root_rel = substr($requested_page_rel, 0, $pos);
  664. // See http://www.mediawiki.org/wiki/Manual:$wgServer
  665. $server_protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
  666. $server_name =
  667. isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME']
  668. : (isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME']
  669. : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
  670. : (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR']
  671. : 'localhost')));
  672. if (isset($_SERVER['SERVER_PORT']) &&
  673. !strpos($server_name, ':') &&
  674. (($server_protocol == 'http' && $_SERVER['SERVER_PORT'] != 80) ||
  675. ($server_protocol == 'https' && $_SERVER['SERVER_PORT'] != 443))
  676. ) {
  677. $server_name .= ":".$_SERVER['SERVER_PORT'];
  678. }
  679. $root_web = $server_protocol.'://'.$server_name.$root_rel;
  680. $root_sys = str_replace('\\', '/', realpath(__DIR__.'/../../../')).'/';
  681. }
  682. // Here we give up, so we don't touch anything.
  683. }
  684. }
  685. }
  686. if (isset($configuration['multiple_access_urls']) &&
  687. $configuration['multiple_access_urls']
  688. ) {
  689. // To avoid that the api_get_access_url() function fails since global.inc.php also calls the api.lib.php.
  690. if (isset($configuration['access_url']) && !empty($configuration['access_url'])) {
  691. // We look into the DB the function api_get_access_url
  692. $urlInfo = api_get_access_url($configuration['access_url']);
  693. // Avoid default value
  694. $defaultValues = ['http://localhost/', 'https://localhost/'];
  695. if (!empty($urlInfo['url']) && !in_array($urlInfo['url'], $defaultValues)) {
  696. $root_web = $urlInfo['active'] == 1 ? $urlInfo['url'] : $configuration['root_web'];
  697. }
  698. }
  699. }
  700. $paths = [];
  701. // Initialise cache with default values.
  702. if (!array_key_exists($root_web, $paths)) {
  703. $paths[$root_web] = [
  704. WEB_PATH => '',
  705. SYS_PATH => '',
  706. REL_PATH => '',
  707. WEB_COURSE_PATH => '',
  708. SYS_COURSE_PATH => '',
  709. REL_COURSE_PATH => '',
  710. WEB_CODE_PATH => 'main/',
  711. SYS_CODE_PATH => 'main/',
  712. REL_CODE_PATH => '/main/',
  713. SYS_LANG_PATH => 'lang/',
  714. WEB_IMG_PATH => 'img/',
  715. WEB_CSS_PATH => 'web/css/',
  716. SYS_CSS_PATH => 'app/Resources/public/css/',
  717. SYS_PLUGIN_PATH => 'plugin/',
  718. WEB_PLUGIN_PATH => 'plugin/',
  719. WEB_PLUGIN_ASSET_PATH => 'public/plugins/',
  720. SYS_ARCHIVE_PATH => 'app/cache/',
  721. WEB_ARCHIVE_PATH => 'app/cache/',
  722. SYS_HOME_PATH => 'app/home/',
  723. WEB_HOME_PATH => 'app/home/',
  724. REL_HOME_PATH => 'app/home/',
  725. SYS_APP_PATH => 'app/',
  726. WEB_APP_PATH => 'app/',
  727. SYS_UPLOAD_PATH => 'app/upload/',
  728. SYS_INC_PATH => 'inc/',
  729. CONFIGURATION_PATH => 'app/config/',
  730. LIBRARY_PATH => 'inc/lib/',
  731. WEB_LIBRARY_PATH => 'inc/lib/',
  732. WEB_LIBRARY_JS_PATH => 'inc/lib/javascript/',
  733. WEB_AJAX_PATH => 'inc/ajax/',
  734. SYS_TEST_PATH => 'tests/',
  735. WEB_TEMPLATE_PATH => 'template/',
  736. SYS_TEMPLATE_PATH => 'template/',
  737. WEB_UPLOAD_PATH => 'app/upload/',
  738. WEB_PUBLIC_PATH => 'web/',
  739. SYS_PUBLIC_PATH => 'web/',
  740. WEB_FONTS_PATH => 'fonts/',
  741. SYS_FONTS_PATH => 'fonts/',
  742. ];
  743. }
  744. $isInitialized = [];
  745. $course_folder = isset($configuration['course_folder']) ? $configuration['course_folder'] : $course_folder;
  746. $root_rel = isset($configuration['url_append']) ? $configuration['url_append'] : '';
  747. if (!empty($root_rel)) {
  748. // Adds "/" to the root_rel
  749. $hasSlash = substr($configuration['url_append'], 0, 1);
  750. if ($hasSlash !== '/') {
  751. $root_rel = '/'.$root_rel;
  752. }
  753. }
  754. // Web server base and system server base.
  755. if (!array_key_exists($root_web, $isInitialized)) {
  756. // process absolute global roots
  757. if (!empty($configuration)) {
  758. $code_folder = 'main';
  759. } else {
  760. $code_folder = $paths[$root_web][REL_CODE_PATH];
  761. }
  762. // Support for the installation process.
  763. // Developers might use the function api_get_path() directly or indirectly (this is difficult to be traced), at the moment when
  764. // configuration has not been created yet. This is why this function should be upgraded to return correct results in this case.
  765. // Dealing with trailing slashes.
  766. $slashed_root_web = api_add_trailing_slash($root_web);
  767. $root_sys = api_add_trailing_slash($root_sys);
  768. $root_rel = api_add_trailing_slash($root_rel);
  769. $code_folder = api_add_trailing_slash($code_folder);
  770. $course_folder = api_add_trailing_slash($course_folder);
  771. // Initialization of a table that contains common-purpose paths.
  772. $paths[$root_web][REL_PATH] = $root_rel;
  773. $paths[$root_web][REL_COURSE_PATH] = $root_rel.$course_folder;
  774. $paths[$root_web][REL_CODE_PATH] = $root_rel.$code_folder;
  775. $paths[$root_web][REL_DEFAULT_COURSE_DOCUMENT_PATH] = $paths[$root_web][REL_PATH].'main/default_course_document/';
  776. $paths[$root_web][WEB_PATH] = $slashed_root_web;
  777. $paths[$root_web][WEB_CODE_PATH] = $paths[$root_web][WEB_PATH].$code_folder;
  778. $paths[$root_web][WEB_COURSE_PATH] = $paths[$root_web][WEB_PATH].$course_folder;
  779. $paths[$root_web][WEB_DEFAULT_COURSE_DOCUMENT_PATH] = $paths[$root_web][WEB_CODE_PATH].'default_course_document/';
  780. $paths[$root_web][WEB_APP_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_APP_PATH];
  781. $paths[$root_web][WEB_PLUGIN_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PLUGIN_PATH];
  782. $paths[$root_web][WEB_PLUGIN_ASSET_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PLUGIN_ASSET_PATH];
  783. $paths[$root_web][WEB_ARCHIVE_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_ARCHIVE_PATH];
  784. $paths[$root_web][WEB_CSS_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_CSS_PATH];
  785. $paths[$root_web][WEB_IMG_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_IMG_PATH];
  786. $paths[$root_web][WEB_LIBRARY_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_LIBRARY_PATH];
  787. $paths[$root_web][WEB_LIBRARY_JS_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_LIBRARY_JS_PATH];
  788. $paths[$root_web][WEB_AJAX_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_AJAX_PATH];
  789. $paths[$root_web][WEB_FONTS_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_FONTS_PATH];
  790. $paths[$root_web][WEB_TEMPLATE_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_TEMPLATE_PATH];
  791. $paths[$root_web][WEB_UPLOAD_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_UPLOAD_PATH];
  792. $paths[$root_web][WEB_PUBLIC_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PUBLIC_PATH];
  793. $paths[$root_web][WEB_HOME_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][REL_HOME_PATH];
  794. $paths[$root_web][SYS_PATH] = $root_sys;
  795. $paths[$root_web][SYS_CODE_PATH] = $root_sys.$code_folder;
  796. $paths[$root_web][SYS_TEST_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_TEST_PATH];
  797. $paths[$root_web][SYS_TEMPLATE_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_TEMPLATE_PATH];
  798. $paths[$root_web][SYS_PUBLIC_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_PUBLIC_PATH];
  799. $paths[$root_web][SYS_CSS_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_CSS_PATH];
  800. $paths[$root_web][SYS_FONTS_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_FONTS_PATH];
  801. $paths[$root_web][SYS_ARCHIVE_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_ARCHIVE_PATH];
  802. $paths[$root_web][SYS_APP_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_APP_PATH];
  803. $paths[$root_web][SYS_COURSE_PATH] = $paths[$root_web][SYS_APP_PATH].$course_folder;
  804. $paths[$root_web][SYS_UPLOAD_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_UPLOAD_PATH];
  805. $paths[$root_web][SYS_LANG_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_LANG_PATH];
  806. $paths[$root_web][SYS_HOME_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_HOME_PATH];
  807. $paths[$root_web][SYS_PLUGIN_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_PLUGIN_PATH];
  808. $paths[$root_web][SYS_INC_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_INC_PATH];
  809. $paths[$root_web][LIBRARY_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][LIBRARY_PATH];
  810. $paths[$root_web][CONFIGURATION_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][CONFIGURATION_PATH];
  811. global $virtualChamilo;
  812. if (!empty($virtualChamilo)) {
  813. $paths[$root_web][SYS_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_ARCHIVE_PATH]);
  814. $paths[$root_web][SYS_HOME_PATH] = api_add_trailing_slash($virtualChamilo[SYS_HOME_PATH]);
  815. $paths[$root_web][SYS_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_COURSE_PATH]);
  816. $paths[$root_web][SYS_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[SYS_UPLOAD_PATH]);
  817. $paths[$root_web][WEB_HOME_PATH] = api_add_trailing_slash($virtualChamilo[WEB_HOME_PATH]);
  818. $paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
  819. $paths[$root_web][WEB_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_ARCHIVE_PATH]);
  820. //$paths[$root_web][WEB_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_COURSE_PATH]);
  821. // WEB_UPLOAD_PATH should be handle by apache htaccess in the vhost
  822. // RewriteEngine On
  823. // RewriteRule /app/upload/(.*)$ http://localhost/other/upload/my-chamilo111-net/$1 [QSA,L]
  824. //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
  825. //$paths[$root_web][REL_PATH] = $virtualChamilo[REL_PATH];
  826. //$paths[$root_web][REL_COURSE_PATH] = $virtualChamilo[REL_COURSE_PATH];
  827. }
  828. $isInitialized[$root_web] = true;
  829. }
  830. $path = trim($path);
  831. // Retrieving a common-purpose path.
  832. if (isset($paths[$root_web][$path])) {
  833. return $paths[$root_web][$path];
  834. }
  835. // Second purification.
  836. // Replacing Windows back slashes.
  837. $path = str_replace('\\', '/', $path);
  838. // Query strings sometimes mighth wrongly appear in non-URLs.
  839. // Let us check remove them from all types of paths.
  840. if (($pos = strpos($path, '?')) !== false) {
  841. $path = substr($path, 0, $pos);
  842. }
  843. // Detection of the input path type. Conversion to semi-absolute type ( /chamilo/main/inc/.... ).
  844. if (preg_match(VALID_WEB_PATH, $path)) {
  845. // A special case: When a URL points to the document download script directly, without
  846. // mod-rewrite translation, we have to translate it into an "ordinary" web path.
  847. // For example:
  848. // http://localhost/chamilo/main/document/download.php?doc_url=/image.png&cDir=/
  849. // becomes
  850. // http://localhost/chamilo/courses/TEST/document/image.png
  851. // TEST is a course directory name, so called "system course code".
  852. if (strpos($path, 'download.php') !== false) { // Fast detection first.
  853. $path = urldecode($path);
  854. if (preg_match('/(.*)main\/document\/download.php\?doc_url=\/(.*)&cDir=\/(.*)?/', $path, $matches)) {
  855. $sys_course_code =
  856. isset($_SESSION['_course']['sysCode']) // User is inside a course?
  857. ? $_SESSION['_course']['sysCode'] // Yes, then use course's directory name.
  858. : '{SYS_COURSE_CODE}'; // No, then use a fake code, it may be processed later.
  859. $path = $matches[1].'courses/'.$sys_course_code.'/document/'.str_replace('//', '/', $matches[3].'/'.$matches[2]);
  860. }
  861. }
  862. // Replacement of the present web server base with a slash '/'.
  863. $path = preg_replace(VALID_WEB_SERVER_BASE, '/', $path);
  864. }
  865. // Path now is semi-absolute. It is convenient at this moment repeated slashes to be removed.
  866. $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  867. return $path;
  868. }
  869. /**
  870. * Gets a modified version of the path for the CDN, if defined in
  871. * configuration.php.
  872. *
  873. * @param string $web_path The path of the resource without CDN
  874. *
  875. * @return string The path of the resource converted to CDN
  876. *
  877. * @author Yannick Warnier <ywarnier@beeznst.org>
  878. */
  879. function api_get_cdn_path($web_path)
  880. {
  881. global $_configuration;
  882. if (!empty($_configuration['cdn_enable'])) {
  883. $web_root = api_get_path(WEB_PATH);
  884. $ext = substr($web_path, strrpos($web_path, '.'));
  885. if (isset($ext[2])) { // faster version of strlen to check if len>2
  886. // Check for CDN definitions
  887. if (!empty($ext)) {
  888. foreach ($_configuration['cdn'] as $host => $exts) {
  889. if (in_array($ext, $exts)) {
  890. //Use host as defined in $_configuration['cdn'], without
  891. // trailing slash
  892. return str_replace($web_root, $host.'/', $web_path);
  893. }
  894. }
  895. }
  896. }
  897. }
  898. return $web_path;
  899. }
  900. /**
  901. * @return bool Return true if CAS authentification is activated
  902. */
  903. function api_is_cas_activated()
  904. {
  905. return api_get_setting('cas_activate') == "true";
  906. }
  907. /**
  908. * @return bool Return true if LDAP authentification is activated
  909. */
  910. function api_is_ldap_activated()
  911. {
  912. global $extAuthSource;
  913. return is_array($extAuthSource[LDAP_AUTH_SOURCE]);
  914. }
  915. /**
  916. * @return bool Return true if Facebook authentification is activated
  917. */
  918. function api_is_facebook_auth_activated()
  919. {
  920. global $_configuration;
  921. return isset($_configuration['facebook_auth']) && $_configuration['facebook_auth'] == 1;
  922. }
  923. /**
  924. * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
  925. *
  926. * @param string $path the input path
  927. *
  928. * @return string returns the modified path
  929. */
  930. function api_add_trailing_slash($path)
  931. {
  932. return substr($path, -1) == '/' ? $path : $path.'/';
  933. }
  934. /**
  935. * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
  936. *
  937. * @param string $path the input path
  938. *
  939. * @return string returns the modified path
  940. */
  941. function api_remove_trailing_slash($path)
  942. {
  943. return substr($path, -1) == '/' ? substr($path, 0, -1) : $path;
  944. }
  945. /**
  946. * Checks the RFC 3986 syntax of a given URL.
  947. *
  948. * @param string $url the URL to be checked
  949. * @param bool $absolute whether the URL is absolute (beginning with a scheme such as "http:")
  950. *
  951. * @return string|false Returns the URL if it is valid, FALSE otherwise.
  952. * This function is an adaptation from the function valid_url(), Drupal CMS.
  953. *
  954. * @see http://drupal.org
  955. * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
  956. * @see http://bugs.php.net/51192
  957. */
  958. function api_valid_url($url, $absolute = false)
  959. {
  960. if ($absolute) {
  961. if (preg_match("
  962. /^ # Start at the beginning of the text
  963. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  964. (?: # Userinfo (optional) which is typically
  965. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  966. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  967. )?
  968. (?:
  969. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  970. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  971. )
  972. (?::[0-9]+)? # Server port number (optional)
  973. (?:[\/|\?]
  974. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  975. *)?
  976. $/xi", $url)) {
  977. return $url;
  978. }
  979. return false;
  980. } else {
  981. return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
  982. }
  983. }
  984. /**
  985. * Checks whether a given string looks roughly like an email address.
  986. *
  987. * @param string $address the e-mail address to be checked
  988. *
  989. * @return mixed returns the e-mail if it is valid, FALSE otherwise
  990. */
  991. function api_valid_email($address)
  992. {
  993. return filter_var($address, FILTER_VALIDATE_EMAIL);
  994. }
  995. /* PROTECTION FUNCTIONS
  996. Use these functions to protect your scripts. */
  997. /**
  998. * Function used to protect a course script.
  999. * The function blocks access when
  1000. * - there is no $_SESSION["_course"] defined; or
  1001. * - $is_allowed_in_course is set to false (this depends on the course
  1002. * visibility and user status).
  1003. *
  1004. * This is only the first proposal, test and improve!
  1005. *
  1006. * @param bool Option to print headers when displaying error message. Default: false
  1007. * @param bool whether session admins should be allowed or not
  1008. * @param bool $checkTool check if tool is available for users (user, group)
  1009. *
  1010. * @return bool True if the user has access to the current course or is out of a course context, false otherwise
  1011. *
  1012. * @todo replace global variable
  1013. *
  1014. * @author Roan Embrechts
  1015. */
  1016. function api_protect_course_script($print_headers = false, $allow_session_admins = false, $checkTool = '')
  1017. {
  1018. $course_info = api_get_course_info();
  1019. if (empty($course_info)) {
  1020. api_not_allowed($print_headers);
  1021. return false;
  1022. }
  1023. if (api_is_drh()) {
  1024. return true;
  1025. }
  1026. // Session admin has access to course
  1027. $sessionAccess = api_get_configuration_value('session_admins_access_all_content');
  1028. if ($sessionAccess) {
  1029. $allow_session_admins = true;
  1030. }
  1031. if (api_is_platform_admin($allow_session_admins)) {
  1032. return true;
  1033. }
  1034. $isAllowedInCourse = api_is_allowed_in_course();
  1035. $is_visible = false;
  1036. if (isset($course_info) && isset($course_info['visibility'])) {
  1037. switch ($course_info['visibility']) {
  1038. default:
  1039. case COURSE_VISIBILITY_CLOSED:
  1040. // Completely closed: the course is only accessible to the teachers. - 0
  1041. if (api_get_user_id() && !api_is_anonymous() && $isAllowedInCourse) {
  1042. $is_visible = true;
  1043. }
  1044. break;
  1045. case COURSE_VISIBILITY_REGISTERED:
  1046. // Private - access authorized to course members only - 1
  1047. if (api_get_user_id() && !api_is_anonymous() && $isAllowedInCourse) {
  1048. $is_visible = true;
  1049. }
  1050. break;
  1051. case COURSE_VISIBILITY_OPEN_PLATFORM:
  1052. // Open - access allowed for users registered on the platform - 2
  1053. if (api_get_user_id() && !api_is_anonymous() && $isAllowedInCourse) {
  1054. $is_visible = true;
  1055. }
  1056. break;
  1057. case COURSE_VISIBILITY_OPEN_WORLD:
  1058. //Open - access allowed for the whole world - 3
  1059. $is_visible = true;
  1060. break;
  1061. case COURSE_VISIBILITY_HIDDEN:
  1062. //Completely closed: the course is only accessible to the teachers. - 0
  1063. if (api_is_platform_admin()) {
  1064. $is_visible = true;
  1065. }
  1066. break;
  1067. }
  1068. //If password is set and user is not registered to the course then the course is not visible
  1069. if ($isAllowedInCourse == false &&
  1070. isset($course_info['registration_code']) &&
  1071. !empty($course_info['registration_code'])
  1072. ) {
  1073. $is_visible = false;
  1074. }
  1075. }
  1076. if (!empty($checkTool)) {
  1077. if (!api_is_allowed_to_edit(true, true, true)) {
  1078. $toolInfo = api_get_tool_information_by_name($checkTool);
  1079. if (!empty($toolInfo) && isset($toolInfo['visibility']) && $toolInfo['visibility'] == 0) {
  1080. api_not_allowed(true);
  1081. return false;
  1082. }
  1083. }
  1084. }
  1085. // Check session visibility
  1086. $session_id = api_get_session_id();
  1087. if (!empty($session_id)) {
  1088. // $isAllowedInCourse was set in local.inc.php
  1089. if (!$isAllowedInCourse) {
  1090. $is_visible = false;
  1091. }
  1092. }
  1093. if (!$is_visible) {
  1094. api_not_allowed($print_headers);
  1095. return false;
  1096. }
  1097. return true;
  1098. }
  1099. /**
  1100. * Function used to protect an admin script.
  1101. *
  1102. * The function blocks access when the user has no platform admin rights
  1103. * with an error message printed on default output
  1104. *
  1105. * @param bool Whether to allow session admins as well
  1106. * @param bool Whether to allow HR directors as well
  1107. * @param string An optional message (already passed through get_lang)
  1108. *
  1109. * @return bool True if user is allowed, false otherwise.
  1110. * The function also outputs an error message in case not allowed
  1111. *
  1112. * @author Roan Embrechts (original author)
  1113. */
  1114. function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false, $message = null)
  1115. {
  1116. if (!api_is_platform_admin($allow_sessions_admins, $allow_drh)) {
  1117. api_not_allowed(true, $message);
  1118. return false;
  1119. }
  1120. return true;
  1121. }
  1122. /**
  1123. * Function used to protect a teacher script.
  1124. * The function blocks access when the user has no teacher rights.
  1125. *
  1126. * @return bool True if the current user can access the script, false otherwise
  1127. *
  1128. * @author Yoselyn Castillo
  1129. */
  1130. function api_protect_teacher_script()
  1131. {
  1132. if (!api_is_allowed_to_edit()) {
  1133. api_not_allowed(true);
  1134. return false;
  1135. }
  1136. return true;
  1137. }
  1138. /**
  1139. * Function used to prevent anonymous users from accessing a script.
  1140. *
  1141. * @param bool|true $printHeaders
  1142. *
  1143. * @author Roan Embrechts
  1144. *
  1145. * @return bool
  1146. */
  1147. function api_block_anonymous_users($printHeaders = true)
  1148. {
  1149. $user = api_get_user_info();
  1150. if (!(isset($user['user_id']) && $user['user_id']) || api_is_anonymous($user['user_id'], true)) {
  1151. api_not_allowed($printHeaders);
  1152. return false;
  1153. }
  1154. return true;
  1155. }
  1156. /**
  1157. * Returns a rough evaluation of the browser's name and version based on very
  1158. * simple regexp.
  1159. *
  1160. * @return array with the navigator name and version ['name' => '...', 'version' => '...']
  1161. */
  1162. function api_get_navigator()
  1163. {
  1164. $navigator = 'Unknown';
  1165. $version = 0;
  1166. if (!isset($_SERVER['HTTP_USER_AGENT'])) {
  1167. return ['name' => 'Unknown', 'version' => '0.0.0'];
  1168. }
  1169. if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
  1170. $navigator = 'Opera';
  1171. list(, $version) = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
  1172. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Edge') !== false) {
  1173. $navigator = 'Edge';
  1174. list(, $version) = explode('Edge', $_SERVER['HTTP_USER_AGENT']);
  1175. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
  1176. $navigator = 'Internet Explorer';
  1177. list(, $version) = explode('MSIE ', $_SERVER['HTTP_USER_AGENT']);
  1178. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
  1179. $navigator = 'Chrome';
  1180. list(, $version) = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
  1181. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false) {
  1182. $navigator = 'Safari';
  1183. if (stripos($_SERVER['HTTP_USER_AGENT'], 'Version/') !== false) {
  1184. // If this Safari does have the "Version/" string in its user agent
  1185. // then use that as a version indicator rather than what's after
  1186. // "Safari/" which is rather a "build number" or something
  1187. list(, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  1188. } else {
  1189. list(, $version) = explode('Safari/', $_SERVER['HTTP_USER_AGENT']);
  1190. }
  1191. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== false) {
  1192. $navigator = 'Firefox';
  1193. list(, $version) = explode('Firefox', $_SERVER['HTTP_USER_AGENT']);
  1194. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') !== false) {
  1195. $navigator = 'Netscape';
  1196. if (stripos($_SERVER['HTTP_USER_AGENT'], 'Netscape/') !== false) {
  1197. list(, $version) = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
  1198. } else {
  1199. list(, $version) = explode('Navigator', $_SERVER['HTTP_USER_AGENT']);
  1200. }
  1201. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false) {
  1202. $navigator = 'Konqueror';
  1203. list(, $version) = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
  1204. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit') !== false) {
  1205. $navigator = 'AppleWebKit';
  1206. list(, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  1207. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false) {
  1208. $navigator = 'Mozilla';
  1209. list(, $version) = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
  1210. }
  1211. // Now cut extra stuff around (mostly *after*) the version number
  1212. $version = preg_replace('/^([\/\s])?([\d\.]+)?.*/', '\2', $version);
  1213. if (strpos($version, '.') === false) {
  1214. $version = number_format(doubleval($version), 1);
  1215. }
  1216. $return = ['name' => $navigator, 'version' => $version];
  1217. return $return;
  1218. }
  1219. /**
  1220. * @return true if user self registration is allowed, false otherwise
  1221. */
  1222. function api_is_self_registration_allowed()
  1223. {
  1224. return isset($GLOBALS['allowSelfReg']) ? $GLOBALS['allowSelfReg'] : false;
  1225. }
  1226. /**
  1227. * This function returns the id of the user which is stored in the $_user array.
  1228. *
  1229. * example: The function can be used to check if a user is logged in
  1230. * if (api_get_user_id())
  1231. *
  1232. * @return int the id of the current user, 0 if is empty
  1233. */
  1234. function api_get_user_id()
  1235. {
  1236. $userInfo = Session::read('_user');
  1237. if ($userInfo && isset($userInfo['user_id'])) {
  1238. return (int) $userInfo['user_id'];
  1239. }
  1240. return 0;
  1241. }
  1242. /**
  1243. * Gets the list of courses a specific user is subscribed to.
  1244. *
  1245. * @param int User ID
  1246. * @param bool $fetch_session Whether to get session courses or not - NOT YET IMPLEMENTED
  1247. *
  1248. * @return array Array of courses in the form [0]=>('code'=>xxx,'db'=>xxx,'dir'=>xxx,'status'=>d)
  1249. *
  1250. * @deprecated use CourseManager::get_courses_list_by_user_id()
  1251. */
  1252. function api_get_user_courses($userId, $fetch_session = true)
  1253. {
  1254. // Get out if not integer
  1255. if ($userId != strval(intval($userId))) {
  1256. return [];
  1257. }
  1258. $t_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1259. $t_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1260. $sql = "SELECT cc.id as real_id, cc.code code, cc.directory dir, cu.status status
  1261. FROM $t_course cc, $t_course_user cu
  1262. WHERE
  1263. cc.id = cu.c_id AND
  1264. cu.user_id = $userId AND
  1265. cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH;
  1266. $result = Database::query($sql);
  1267. if ($result === false) {
  1268. return [];
  1269. }
  1270. $courses = [];
  1271. while ($row = Database::fetch_array($result)) {
  1272. // we only need the database name of the course
  1273. $courses[] = $row;
  1274. }
  1275. return $courses;
  1276. }
  1277. /**
  1278. * Formats user information into a standard array
  1279. * This function should be only used inside api_get_user_info().
  1280. *
  1281. * @param array Non-standard user array
  1282. * @param bool $add_password
  1283. * @param bool $loadAvatars turn off to improve performance
  1284. *
  1285. * @return array Standard user array
  1286. */
  1287. function _api_format_user($user, $add_password = false, $loadAvatars = true)
  1288. {
  1289. $result = [];
  1290. $result['firstname'] = null;
  1291. $result['lastname'] = null;
  1292. if (isset($user['firstname']) && isset($user['lastname'])) { // with only lowercase
  1293. $result['firstname'] = $user['firstname'];
  1294. $result['lastname'] = $user['lastname'];
  1295. } elseif (isset($user['firstName']) && isset($user['lastName'])) { // with uppercase letters
  1296. $result['firstname'] = isset($user['firstName']) ? $user['firstName'] : null;
  1297. $result['lastname'] = isset($user['lastName']) ? $user['lastName'] : null;
  1298. }
  1299. if (isset($user['email'])) {
  1300. $result['mail'] = isset($user['email']) ? $user['email'] : null;
  1301. $result['email'] = isset($user['email']) ? $user['email'] : null;
  1302. } else {
  1303. $result['mail'] = isset($user['mail']) ? $user['mail'] : null;
  1304. $result['email'] = isset($user['mail']) ? $user['mail'] : null;
  1305. }
  1306. $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
  1307. $result['complete_name_with_username'] = $result['complete_name'];
  1308. if (!empty($user['username']) && !api_get_configuration_value('hide_username_with_complete_name')) {
  1309. $result['complete_name_with_username'] = $result['complete_name'].' ('.$user['username'].')';
  1310. }
  1311. $showEmail = api_get_setting('show_email_addresses') === 'true';
  1312. if (!empty($user['email'])) {
  1313. $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$user['email'].')';
  1314. if ($showEmail) {
  1315. $result['complete_name_with_email'] = $result['complete_name'].' ('.$user['email'].')';
  1316. }
  1317. } else {
  1318. $result['complete_name_with_email'] = $result['complete_name'];
  1319. $result['complete_name_with_email_forced'] = $result['complete_name'];
  1320. }
  1321. // Kept for historical reasons
  1322. $result['firstName'] = $result['firstname'];
  1323. $result['lastName'] = $result['lastname'];
  1324. $attributes = [
  1325. 'phone',
  1326. 'address',
  1327. 'picture_uri',
  1328. 'official_code',
  1329. 'status',
  1330. 'active',
  1331. 'auth_source',
  1332. 'username',
  1333. 'theme',
  1334. 'language',
  1335. 'creator_id',
  1336. 'registration_date',
  1337. 'hr_dept_id',
  1338. 'expiration_date',
  1339. 'last_login',
  1340. 'user_is_online',
  1341. ];
  1342. if (api_get_setting('extended_profile') === 'true') {
  1343. $attributes[] = 'competences';
  1344. $attributes[] = 'diplomas';
  1345. $attributes[] = 'teach';
  1346. $attributes[] = 'openarea';
  1347. }
  1348. foreach ($attributes as $attribute) {
  1349. $result[$attribute] = isset($user[$attribute]) ? $user[$attribute] : null;
  1350. }
  1351. $user_id = (int) $user['user_id'];
  1352. // Maintain the user_id index for backwards compatibility
  1353. $result['user_id'] = $result['id'] = $user_id;
  1354. $hasCertificates = Certificate::getCertificateByUser($user_id);
  1355. $result['has_certificates'] = 0;
  1356. if (!empty($hasCertificates)) {
  1357. $result['has_certificates'] = 1;
  1358. }
  1359. $result['icon_status'] = '';
  1360. $result['icon_status_medium'] = '';
  1361. $result['is_admin'] = UserManager::is_admin($user_id);
  1362. // Getting user avatar.
  1363. if ($loadAvatars) {
  1364. $result['avatar'] = '';
  1365. $result['avatar_no_query'] = '';
  1366. $result['avatar_small'] = '';
  1367. $result['avatar_medium'] = '';
  1368. if (!isset($user['avatar'])) {
  1369. $originalFile = UserManager::getUserPicture(
  1370. $user_id,
  1371. USER_IMAGE_SIZE_ORIGINAL,
  1372. null,
  1373. $result
  1374. );
  1375. $result['avatar'] = $originalFile;
  1376. $avatarString = explode('?', $result['avatar']);
  1377. $result['avatar_no_query'] = reset($avatarString);
  1378. } else {
  1379. $result['avatar'] = $user['avatar'];
  1380. $avatarString = explode('?', $user['avatar']);
  1381. $result['avatar_no_query'] = reset($avatarString);
  1382. }
  1383. if (!isset($user['avatar_small'])) {
  1384. $smallFile = UserManager::getUserPicture(
  1385. $user_id,
  1386. USER_IMAGE_SIZE_SMALL,
  1387. null,
  1388. $result
  1389. );
  1390. $result['avatar_small'] = $smallFile;
  1391. } else {
  1392. $result['avatar_small'] = $user['avatar_small'];
  1393. }
  1394. if (!isset($user['avatar_medium'])) {
  1395. $mediumFile = UserManager::getUserPicture(
  1396. $user_id,
  1397. USER_IMAGE_SIZE_MEDIUM,
  1398. null,
  1399. $result
  1400. );
  1401. $result['avatar_medium'] = $mediumFile;
  1402. } else {
  1403. $result['avatar_medium'] = $user['avatar_medium'];
  1404. }
  1405. $urlImg = api_get_path(WEB_IMG_PATH);
  1406. $iconStatus = '';
  1407. $iconStatusMedium = '';
  1408. switch ($result['status']) {
  1409. case STUDENT:
  1410. if ($result['has_certificates']) {
  1411. $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
  1412. } else {
  1413. $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
  1414. }
  1415. break;
  1416. case COURSEMANAGER:
  1417. if ($result['is_admin']) {
  1418. $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
  1419. } else {
  1420. $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
  1421. }
  1422. break;
  1423. case STUDENT_BOSS:
  1424. $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
  1425. break;
  1426. }
  1427. if (!empty($iconStatus)) {
  1428. $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
  1429. $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
  1430. }
  1431. $result['icon_status'] = $iconStatus;
  1432. $result['icon_status_medium'] = $iconStatusMedium;
  1433. }
  1434. if (isset($user['user_is_online'])) {
  1435. $result['user_is_online'] = $user['user_is_online'] == true ? 1 : 0;
  1436. }
  1437. if (isset($user['user_is_online_in_chat'])) {
  1438. $result['user_is_online_in_chat'] = (int) $user['user_is_online_in_chat'];
  1439. }
  1440. if ($add_password) {
  1441. $result['password'] = $user['password'];
  1442. }
  1443. if (isset($result['profile_completed'])) {
  1444. $result['profile_completed'] = $user['profile_completed'];
  1445. }
  1446. $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
  1447. // Send message link
  1448. $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
  1449. $result['complete_name_with_message_link'] = Display::url(
  1450. $result['complete_name_with_username'],
  1451. $sendMessage,
  1452. ['class' => 'ajax']
  1453. );
  1454. if (isset($user['extra'])) {
  1455. $result['extra'] = $user['extra'];
  1456. }
  1457. return $result;
  1458. }
  1459. /**
  1460. * Finds all the information about a user.
  1461. * If no parameter is passed you find all the information about the current user.
  1462. *
  1463. * @param int $user_id
  1464. * @param bool $checkIfUserOnline
  1465. * @param bool $showPassword
  1466. * @param bool $loadExtraData
  1467. * @param bool $loadOnlyVisibleExtraData Get the user extra fields that are visible
  1468. * @param bool $loadAvatars turn off to improve performance and if avatars are not needed
  1469. * @param bool $updateCache update apc cache if exists
  1470. *
  1471. * @return mixed $user_info user_id, lastname, firstname, username, email, etc or false on error
  1472. *
  1473. * @author Patrick Cool <patrick.cool@UGent.be>
  1474. * @author Julio Montoya
  1475. *
  1476. * @version 21 September 2004
  1477. */
  1478. function api_get_user_info(
  1479. $user_id = 0,
  1480. $checkIfUserOnline = false,
  1481. $showPassword = false,
  1482. $loadExtraData = false,
  1483. $loadOnlyVisibleExtraData = false,
  1484. $loadAvatars = true,
  1485. $updateCache = false
  1486. ) {
  1487. $apcVar = null;
  1488. $user = false;
  1489. $cacheAvailable = api_get_configuration_value('apc');
  1490. if (empty($user_id)) {
  1491. $userFromSession = Session::read('_user');
  1492. if (isset($userFromSession)) {
  1493. if ($cacheAvailable === true &&
  1494. (
  1495. empty($userFromSession['is_anonymous']) &&
  1496. (isset($userFromSession['status']) && $userFromSession['status'] != ANONYMOUS)
  1497. )
  1498. ) {
  1499. $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$userFromSession['user_id'];
  1500. if (apcu_exists($apcVar)) {
  1501. if ($updateCache) {
  1502. apcu_store($apcVar, $userFromSession, 60);
  1503. }
  1504. $user = apcu_fetch($apcVar);
  1505. } else {
  1506. $user = _api_format_user(
  1507. $userFromSession,
  1508. $showPassword,
  1509. $loadAvatars
  1510. );
  1511. apcu_store($apcVar, $user, 60);
  1512. }
  1513. } else {
  1514. $user = _api_format_user(
  1515. $userFromSession,
  1516. $showPassword,
  1517. $loadAvatars
  1518. );
  1519. }
  1520. return $user;
  1521. }
  1522. return false;
  1523. }
  1524. // Make sure user_id is safe
  1525. $user_id = (int) $user_id;
  1526. // Re-use user information if not stale and already stored in APCu
  1527. if ($cacheAvailable === true) {
  1528. $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$user_id;
  1529. if (apcu_exists($apcVar) && $updateCache == false && $checkIfUserOnline == false) {
  1530. $user = apcu_fetch($apcVar);
  1531. return $user;
  1532. }
  1533. }
  1534. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1535. WHERE id = $user_id";
  1536. $result = Database::query($sql);
  1537. if (Database::num_rows($result) > 0) {
  1538. $result_array = Database::fetch_array($result);
  1539. $result_array['user_is_online_in_chat'] = 0;
  1540. if ($checkIfUserOnline) {
  1541. $use_status_in_platform = user_is_online($user_id);
  1542. $result_array['user_is_online'] = $use_status_in_platform;
  1543. $user_online_in_chat = 0;
  1544. if ($use_status_in_platform) {
  1545. $user_status = UserManager::get_extra_user_data_by_field(
  1546. $user_id,
  1547. 'user_chat_status',
  1548. false,
  1549. true
  1550. );
  1551. if ((int) $user_status['user_chat_status'] == 1) {
  1552. $user_online_in_chat = 1;
  1553. }
  1554. }
  1555. $result_array['user_is_online_in_chat'] = $user_online_in_chat;
  1556. }
  1557. if ($loadExtraData) {
  1558. $fieldValue = new ExtraFieldValue('user');
  1559. $result_array['extra'] = $fieldValue->getAllValuesForAnItem(
  1560. $user_id,
  1561. $loadOnlyVisibleExtraData
  1562. );
  1563. }
  1564. $user = _api_format_user($result_array, $showPassword, $loadAvatars);
  1565. }
  1566. if ($cacheAvailable === true) {
  1567. apcu_store($apcVar, $user, 60);
  1568. }
  1569. return $user;
  1570. }
  1571. /**
  1572. * @param int $userId
  1573. *
  1574. * @return User
  1575. */
  1576. function api_get_user_entity($userId)
  1577. {
  1578. $userId = (int) $userId;
  1579. $repo = UserManager::getRepository();
  1580. /** @var User $user */
  1581. $user = $repo->find($userId);
  1582. return $user;
  1583. }
  1584. /**
  1585. * Finds all the information about a user from username instead of user id.
  1586. *
  1587. * @param string $username
  1588. *
  1589. * @return mixed $user_info array user_id, lastname, firstname, username, email or false on error
  1590. *
  1591. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  1592. */
  1593. function api_get_user_info_from_username($username = '')
  1594. {
  1595. if (empty($username)) {
  1596. return false;
  1597. }
  1598. $username = trim($username);
  1599. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1600. WHERE username='".Database::escape_string($username)."'";
  1601. $result = Database::query($sql);
  1602. if (Database::num_rows($result) > 0) {
  1603. $resultArray = Database::fetch_array($result);
  1604. return _api_format_user($resultArray);
  1605. }
  1606. return false;
  1607. }
  1608. /**
  1609. * Get first user with an email.
  1610. *
  1611. * @param string $email
  1612. *
  1613. * @return array|bool
  1614. */
  1615. function api_get_user_info_from_email($email = '')
  1616. {
  1617. if (empty($email)) {
  1618. return false;
  1619. }
  1620. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1621. WHERE email ='".Database::escape_string($email)."' LIMIT 1";
  1622. $result = Database::query($sql);
  1623. if (Database::num_rows($result) > 0) {
  1624. $resultArray = Database::fetch_array($result);
  1625. return _api_format_user($resultArray);
  1626. }
  1627. return false;
  1628. }
  1629. /**
  1630. * @return string
  1631. */
  1632. function api_get_course_id()
  1633. {
  1634. return Session::read('_cid', null);
  1635. }
  1636. /**
  1637. * Returns the current course id (integer).
  1638. *
  1639. * @param string $code Optional course code
  1640. *
  1641. * @return int
  1642. */
  1643. function api_get_course_int_id($code = null)
  1644. {
  1645. if (!empty($code)) {
  1646. $code = Database::escape_string($code);
  1647. $row = Database::select(
  1648. 'id',
  1649. Database::get_main_table(TABLE_MAIN_COURSE),
  1650. ['where' => ['code = ?' => [$code]]],
  1651. 'first'
  1652. );
  1653. if (is_array($row) && isset($row['id'])) {
  1654. return $row['id'];
  1655. } else {
  1656. return false;
  1657. }
  1658. }
  1659. return Session::read('_real_cid', 0);
  1660. }
  1661. /**
  1662. * Returns the current course directory.
  1663. *
  1664. * This function relies on api_get_course_info()
  1665. *
  1666. * @param string The course code - optional (takes it from session if not given)
  1667. *
  1668. * @return string The directory where the course is located inside the Chamilo "courses" directory
  1669. *
  1670. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  1671. */
  1672. function api_get_course_path($course_code = null)
  1673. {
  1674. $info = !empty($course_code) ? api_get_course_info($course_code) : api_get_course_info();
  1675. return $info['path'];
  1676. }
  1677. /**
  1678. * Gets a course setting from the current course_setting table. Try always using integer values.
  1679. *
  1680. * @param string $setting_name The name of the setting we want from the table
  1681. * @param string $course_code
  1682. *
  1683. * @return mixed The value of that setting in that table. Return -1 if not found.
  1684. */
  1685. function api_get_course_setting($setting_name, $course_code = null)
  1686. {
  1687. $course_info = api_get_course_info($course_code);
  1688. $table = Database::get_course_table(TABLE_COURSE_SETTING);
  1689. $setting_name = Database::escape_string($setting_name);
  1690. if (!empty($course_info['real_id']) && !empty($setting_name)) {
  1691. $sql = "SELECT value FROM $table
  1692. WHERE c_id = {$course_info['real_id']} AND variable = '$setting_name'";
  1693. $res = Database::query($sql);
  1694. if (Database::num_rows($res) > 0) {
  1695. $row = Database::fetch_array($res);
  1696. if ($setting_name === 'email_alert_manager_on_new_quiz') {
  1697. if (!is_null($row['value'])) {
  1698. $result = explode(',', $row['value']);
  1699. $row['value'] = $result;
  1700. }
  1701. }
  1702. return $row['value'];
  1703. }
  1704. }
  1705. return -1;
  1706. }
  1707. /**
  1708. * Gets an anonymous user ID.
  1709. *
  1710. * For some tools that need tracking, like the learnpath tool, it is necessary
  1711. * to have a usable user-id to enable some kind of tracking, even if not
  1712. * perfect. An anonymous ID is taken from the users table by looking for a
  1713. * status of "6" (anonymous).
  1714. *
  1715. * @return int User ID of the anonymous user, or O if no anonymous user found
  1716. */
  1717. function api_get_anonymous_id()
  1718. {
  1719. // Find if another anon is connected now
  1720. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1721. $tableU = Database::get_main_table(TABLE_MAIN_USER);
  1722. $ip = Database::escape_string(api_get_real_ip());
  1723. $max = (int) api_get_configuration_value('max_anonymous_users');
  1724. if ($max >= 2) {
  1725. $sql = "SELECT * FROM $table as TEL
  1726. JOIN $tableU as U
  1727. ON U.user_id = TEL.login_user_id
  1728. WHERE TEL.user_ip = '$ip'
  1729. AND U.status = ".ANONYMOUS."
  1730. AND U.user_id != 2 ";
  1731. $result = Database::query($sql);
  1732. if (empty(Database::num_rows($result))) {
  1733. $login = uniqid('anon_');
  1734. $anonList = UserManager::get_user_list(['status' => ANONYMOUS], ['registration_date ASC']);
  1735. if (count($anonList) >= $max) {
  1736. foreach ($anonList as $userToDelete) {
  1737. UserManager::delete_user($userToDelete['user_id']);
  1738. break;
  1739. }
  1740. }
  1741. $userId = UserManager::create_user(
  1742. $login,
  1743. 'anon',
  1744. ANONYMOUS,
  1745. ' anonymous@localhost',
  1746. $login,
  1747. $login
  1748. );
  1749. return $userId;
  1750. } else {
  1751. $row = Database::fetch_array($result, 'ASSOC');
  1752. return $row['user_id'];
  1753. }
  1754. }
  1755. $table = Database::get_main_table(TABLE_MAIN_USER);
  1756. $sql = "SELECT user_id
  1757. FROM $table
  1758. WHERE status = ".ANONYMOUS." ";
  1759. $res = Database::query($sql);
  1760. if (Database::num_rows($res) > 0) {
  1761. $row = Database::fetch_array($res, 'ASSOC');
  1762. return $row['user_id'];
  1763. }
  1764. // No anonymous user was found.
  1765. return 0;
  1766. }
  1767. /**
  1768. * @param string $courseCode
  1769. * @param int $sessionId
  1770. * @param int $groupId
  1771. *
  1772. * @return string
  1773. */
  1774. function api_get_cidreq_params($courseCode, $sessionId = 0, $groupId = 0)
  1775. {
  1776. $courseCode = !empty($courseCode) ? htmlspecialchars($courseCode) : '';
  1777. $sessionId = !empty($sessionId) ? (int) $sessionId : 0;
  1778. $groupId = !empty($groupId) ? (int) $groupId : 0;
  1779. $url = 'cidReq='.$courseCode;
  1780. $url .= '&id_session='.$sessionId;
  1781. $url .= '&gidReq='.$groupId;
  1782. return $url;
  1783. }
  1784. /**
  1785. * Returns the current course url part including session, group, and gradebook params.
  1786. *
  1787. * @param bool $addSessionId
  1788. * @param bool $addGroupId
  1789. * @param string $origin
  1790. *
  1791. * @return string Course & session references to add to a URL
  1792. */
  1793. function api_get_cidreq($addSessionId = true, $addGroupId = true, $origin = '')
  1794. {
  1795. $courseCode = api_get_course_id();
  1796. $url = empty($courseCode) ? '' : 'cidReq='.htmlspecialchars($courseCode);
  1797. $origin = empty($origin) ? api_get_origin() : Security::remove_XSS($origin);
  1798. if ($addSessionId) {
  1799. if (!empty($url)) {
  1800. $url .= api_get_session_id() == 0 ? '&id_session=0' : '&id_session='.api_get_session_id();
  1801. }
  1802. }
  1803. if ($addGroupId) {
  1804. if (!empty($url)) {
  1805. $url .= api_get_group_id() == 0 ? '&gidReq=0' : '&gidReq='.api_get_group_id();
  1806. }
  1807. }
  1808. if (!empty($url)) {
  1809. $url .= '&gradebook='.intval(api_is_in_gradebook());
  1810. $url .= '&origin='.$origin;
  1811. }
  1812. return $url;
  1813. }
  1814. /**
  1815. * Get if we visited a gradebook page.
  1816. *
  1817. * @return bool
  1818. */
  1819. function api_is_in_gradebook()
  1820. {
  1821. return Session::read('in_gradebook', false);
  1822. }
  1823. /**
  1824. * Set that we are in a page inside a gradebook.
  1825. */
  1826. function api_set_in_gradebook()
  1827. {
  1828. Session::write('in_gradebook', true);
  1829. }
  1830. /**
  1831. * Remove gradebook session.
  1832. */
  1833. function api_remove_in_gradebook()
  1834. {
  1835. Session::erase('in_gradebook');
  1836. }
  1837. /**
  1838. * Returns the current course info array see api_format_course_array()
  1839. * If the course_code is given, the returned array gives info about that
  1840. * particular course, if none given it gets the course info from the session.
  1841. *
  1842. * @param string $course_code
  1843. * @param bool $strict
  1844. *
  1845. * @return array
  1846. */
  1847. function api_get_course_info($course_code = null, $strict = false)
  1848. {
  1849. if (!empty($course_code)) {
  1850. $course_code = Database::escape_string($course_code);
  1851. $courseId = api_get_course_int_id($course_code);
  1852. if (empty($courseId)) {
  1853. return [];
  1854. }
  1855. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1856. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1857. $sql = "SELECT
  1858. course.*,
  1859. course_category.code faCode,
  1860. course_category.name faName
  1861. FROM $course_table
  1862. LEFT JOIN $course_cat_table
  1863. ON course.category_code = course_category.code
  1864. WHERE course.id = $courseId";
  1865. $result = Database::query($sql);
  1866. $courseInfo = [];
  1867. if (Database::num_rows($result) > 0) {
  1868. $data = Database::fetch_array($result);
  1869. $courseInfo = api_format_course_array($data);
  1870. }
  1871. return $courseInfo;
  1872. }
  1873. global $_course;
  1874. if ($_course == '-1') {
  1875. $_course = [];
  1876. }
  1877. return $_course;
  1878. }
  1879. /**
  1880. * @param int $courseId
  1881. *
  1882. * @return \Chamilo\CoreBundle\Entity\Course
  1883. */
  1884. function api_get_course_entity($courseId = 0)
  1885. {
  1886. if (empty($courseId)) {
  1887. $courseId = api_get_course_int_id();
  1888. }
  1889. return Database::getManager()->getRepository('ChamiloCoreBundle:Course')->find($courseId);
  1890. }
  1891. /**
  1892. * @param int $id
  1893. *
  1894. * @return \Chamilo\CoreBundle\Entity\Session
  1895. */
  1896. function api_get_session_entity($id = 0)
  1897. {
  1898. if (empty($id)) {
  1899. $id = api_get_session_id();
  1900. }
  1901. return Database::getManager()->getRepository('ChamiloCoreBundle:Session')->find($id);
  1902. }
  1903. /**
  1904. * Returns the current course info array.
  1905. * Now if the course_code is given, the returned array gives info about that
  1906. * particular course, not specially the current one.
  1907. *
  1908. * @param int $id Numeric ID of the course
  1909. *
  1910. * @return array The course info as an array formatted by api_format_course_array, including category.name
  1911. */
  1912. function api_get_course_info_by_id($id = null)
  1913. {
  1914. if (!empty($id)) {
  1915. $id = (int) $id;
  1916. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1917. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1918. $sql = "SELECT
  1919. course.*,
  1920. course_category.code faCode,
  1921. course_category.name faName
  1922. FROM $course_table
  1923. LEFT JOIN $course_cat_table
  1924. ON course.category_code = course_category.code
  1925. WHERE course.id = $id";
  1926. $result = Database::query($sql);
  1927. $_course = [];
  1928. if (Database::num_rows($result) > 0) {
  1929. $row = Database::fetch_array($result);
  1930. $_course = api_format_course_array($row);
  1931. }
  1932. return $_course;
  1933. }
  1934. global $_course;
  1935. if ($_course == '-1') {
  1936. $_course = [];
  1937. }
  1938. return $_course;
  1939. }
  1940. /**
  1941. * Reformat the course array (output by api_get_course_info()) in order, mostly,
  1942. * to switch from 'code' to 'id' in the array. This is a legacy feature and is
  1943. * now possibly causing massive confusion as a new "id" field has been added to
  1944. * the course table in 1.9.0.
  1945. *
  1946. * @param $course_data
  1947. *
  1948. * @return array
  1949. *
  1950. * @todo eradicate the false "id"=code field of the $_course array and use the int id
  1951. */
  1952. function api_format_course_array($course_data)
  1953. {
  1954. if (empty($course_data)) {
  1955. return [];
  1956. }
  1957. $_course = [];
  1958. $_course['id'] = $course_data['code'];
  1959. $_course['real_id'] = $course_data['id'];
  1960. // Added
  1961. $_course['code'] = $course_data['code'];
  1962. $_course['name'] = $course_data['title'];
  1963. $_course['title'] = $course_data['title'];
  1964. $_course['official_code'] = $course_data['visual_code'];
  1965. $_course['visual_code'] = $course_data['visual_code'];
  1966. $_course['sysCode'] = $course_data['code'];
  1967. $_course['path'] = $course_data['directory']; // Use as key in path.
  1968. $_course['directory'] = $course_data['directory'];
  1969. $_course['creation_date'] = $course_data['creation_date'];
  1970. $_course['titular'] = $course_data['tutor_name'];
  1971. $_course['language'] = $course_data['course_language'];
  1972. $_course['extLink']['url'] = $course_data['department_url'];
  1973. $_course['extLink']['name'] = $course_data['department_name'];
  1974. $_course['categoryCode'] = $course_data['faCode'];
  1975. $_course['categoryName'] = $course_data['faName'];
  1976. $_course['visibility'] = $course_data['visibility'];
  1977. $_course['subscribe_allowed'] = $course_data['subscribe'];
  1978. $_course['subscribe'] = $course_data['subscribe'];
  1979. $_course['unsubscribe'] = $course_data['unsubscribe'];
  1980. $_course['course_language'] = $course_data['course_language'];
  1981. $_course['activate_legal'] = isset($course_data['activate_legal']) ? $course_data['activate_legal'] : false;
  1982. $_course['legal'] = $course_data['legal'];
  1983. $_course['show_score'] = $course_data['show_score']; //used in the work tool
  1984. $_course['department_name'] = $course_data['department_name'];
  1985. $_course['department_url'] = $course_data['department_url'];
  1986. $courseSys = api_get_path(SYS_COURSE_PATH).$course_data['directory'];
  1987. $webCourseHome = api_get_path(WEB_COURSE_PATH).$course_data['directory'];
  1988. // Course password
  1989. $_course['registration_code'] = !empty($course_data['registration_code']) ? sha1($course_data['registration_code']) : null;
  1990. $_course['disk_quota'] = $course_data['disk_quota'];
  1991. $_course['course_public_url'] = $webCourseHome.'/index.php';
  1992. $_course['course_sys_path'] = $courseSys.'/';
  1993. if (array_key_exists('add_teachers_to_sessions_courses', $course_data)) {
  1994. $_course['add_teachers_to_sessions_courses'] = $course_data['add_teachers_to_sessions_courses'];
  1995. }
  1996. // Course image
  1997. $_course['course_image_source'] = '';
  1998. if (file_exists($courseSys.'/course-pic85x85.png')) {
  1999. $url_image = $webCourseHome.'/course-pic85x85.png';
  2000. $_course['course_image_source'] = $courseSys.'/course-pic85x85.png';
  2001. } else {
  2002. $url_image = Display::return_icon(
  2003. 'course.png',
  2004. null,
  2005. null,
  2006. ICON_SIZE_BIG,
  2007. null,
  2008. true,
  2009. false
  2010. );
  2011. }
  2012. $_course['course_image'] = $url_image;
  2013. // Course large image
  2014. $_course['course_image_large_source'] = '';
  2015. if (file_exists($courseSys.'/course-pic.png')) {
  2016. $url_image = $webCourseHome.'/course-pic.png';
  2017. $_course['course_image_large_source'] = $courseSys.'/course-pic.png';
  2018. } else {
  2019. $url_image = Display::return_icon(
  2020. 'session_default.png',
  2021. null,
  2022. null,
  2023. null,
  2024. null,
  2025. true,
  2026. true
  2027. );
  2028. }
  2029. $_course['course_image_large'] = $url_image;
  2030. return $_course;
  2031. }
  2032. /**
  2033. * Returns a difficult to guess password.
  2034. *
  2035. * @param int $length the length of the password
  2036. *
  2037. * @return string the generated password
  2038. */
  2039. function api_generate_password($length = 8)
  2040. {
  2041. if ($length < 2) {
  2042. $length = 2;
  2043. }
  2044. $charactersLowerCase = 'abcdefghijkmnopqrstuvwxyz';
  2045. $charactersUpperCase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  2046. $minNumbers = 2;
  2047. $length = $length - $minNumbers;
  2048. $minLowerCase = round($length / 2);
  2049. $minUpperCase = $length - $minLowerCase;
  2050. $password = '';
  2051. $passwordRequirements = api_get_configuration_value('password_requirements');
  2052. $factory = new RandomLib\Factory();
  2053. $generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
  2054. if (!empty($passwordRequirements)) {
  2055. $length = $passwordRequirements['min']['length'];
  2056. $minNumbers = $passwordRequirements['min']['numeric'];
  2057. $minLowerCase = $passwordRequirements['min']['lowercase'];
  2058. $minUpperCase = $passwordRequirements['min']['uppercase'];
  2059. $rest = $length - $minNumbers - $minLowerCase - $minUpperCase;
  2060. // Add the rest to fill the length requirement
  2061. if ($rest > 0) {
  2062. $password .= $generator->generateString($rest, $charactersLowerCase.$charactersUpperCase);
  2063. }
  2064. }
  2065. // Min digits default 2
  2066. for ($i = 0; $i < $minNumbers; $i++) {
  2067. $password .= $generator->generateInt(2, 9);
  2068. }
  2069. // Min lowercase
  2070. $password .= $generator->generateString($minLowerCase, $charactersLowerCase);
  2071. // Min uppercase
  2072. $password .= $generator->generateString($minUpperCase, $charactersUpperCase);
  2073. $password = str_shuffle($password);
  2074. return $password;
  2075. }
  2076. /**
  2077. * Checks a password to see wether it is OK to use.
  2078. *
  2079. * @param string $password
  2080. *
  2081. * @return bool if the password is acceptable, false otherwise
  2082. * Notes about what a password "OK to use" is:
  2083. * 1. The password should be at least 5 characters long.
  2084. * 2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
  2085. * 3. The password should contain at least 3 letters.
  2086. * 4. It should contain at least 2 digits.
  2087. * Settings will change if the configuration value is set: password_requirements
  2088. */
  2089. function api_check_password($password)
  2090. {
  2091. $passwordRequirements = Security::getPasswordRequirements();
  2092. $minLength = $passwordRequirements['min']['length'];
  2093. $minNumbers = $passwordRequirements['min']['numeric'];
  2094. // Optional
  2095. $minLowerCase = $passwordRequirements['min']['lowercase'];
  2096. $minUpperCase = $passwordRequirements['min']['uppercase'];
  2097. $minLetters = $minLowerCase + $minUpperCase;
  2098. $passwordLength = api_strlen($password);
  2099. $conditions = [
  2100. 'min_length' => $passwordLength >= $minLength,
  2101. ];
  2102. $digits = 0;
  2103. $lowerCase = 0;
  2104. $upperCase = 0;
  2105. for ($i = 0; $i < $passwordLength; $i++) {
  2106. $currentCharacterCode = api_ord(api_substr($password, $i, 1));
  2107. if ($currentCharacterCode >= 65 && $currentCharacterCode <= 90) {
  2108. $upperCase++;
  2109. }
  2110. if ($currentCharacterCode >= 97 && $currentCharacterCode <= 122) {
  2111. $lowerCase++;
  2112. }
  2113. if ($currentCharacterCode >= 48 && $currentCharacterCode <= 57) {
  2114. $digits++;
  2115. }
  2116. }
  2117. // Min number of digits
  2118. $conditions['min_numeric'] = $digits >= $minNumbers;
  2119. if (!empty($minUpperCase)) {
  2120. // Uppercase
  2121. $conditions['min_uppercase'] = $upperCase >= $minUpperCase;
  2122. }
  2123. if (!empty($minLowerCase)) {
  2124. // Lowercase
  2125. $conditions['min_lowercase'] = $upperCase >= $minLowerCase;
  2126. }
  2127. // Min letters
  2128. $letters = $upperCase + $lowerCase;
  2129. $conditions['min_letters'] = $letters >= $minLetters;
  2130. $isPasswordOk = true;
  2131. foreach ($conditions as $condition) {
  2132. if ($condition === false) {
  2133. $isPasswordOk = false;
  2134. break;
  2135. }
  2136. }
  2137. if ($isPasswordOk === false) {
  2138. $output = get_lang('NewPasswordRequirementsNotMatched').'<br />';
  2139. $output .= Security::getPasswordRequirementsToString($conditions);
  2140. Display::addFlash(Display::return_message($output, 'warning', false));
  2141. }
  2142. return $isPasswordOk;
  2143. }
  2144. /**
  2145. * Clears the user ID from the session if it was the anonymous user. Generally
  2146. * used on out-of-tools pages to remove a user ID that could otherwise be used
  2147. * in the wrong context.
  2148. * This function is to be used in conjunction with the api_set_anonymous()
  2149. * function to simulate the user existence in case of an anonymous visit.
  2150. *
  2151. * @param bool database check switch - passed to api_is_anonymous()
  2152. *
  2153. * @return bool true if succesfully unregistered, false if not anonymous
  2154. */
  2155. function api_clear_anonymous($db_check = false)
  2156. {
  2157. global $_user;
  2158. if (api_is_anonymous($_user['user_id'], $db_check)) {
  2159. unset($_user['user_id']);
  2160. Session::erase('_uid');
  2161. return true;
  2162. }
  2163. return false;
  2164. }
  2165. /**
  2166. * Returns the status string corresponding to the status code.
  2167. *
  2168. * @author Noel Dieschburg
  2169. *
  2170. * @param the int status code
  2171. *
  2172. * @return string
  2173. */
  2174. function get_status_from_code($status_code)
  2175. {
  2176. switch ($status_code) {
  2177. case STUDENT:
  2178. return get_lang('Student', '');
  2179. case COURSEMANAGER:
  2180. return get_lang('Teacher', '');
  2181. case SESSIONADMIN:
  2182. return get_lang('SessionsAdmin', '');
  2183. case DRH:
  2184. return get_lang('Drh', '');
  2185. }
  2186. }
  2187. /**
  2188. * Sets the current user as anonymous if it hasn't been identified yet. This
  2189. * function should be used inside a tool only. The function api_clear_anonymous()
  2190. * acts in the opposite direction by clearing the anonymous user's data every
  2191. * time we get on a course homepage or on a neutral page (index, admin, my space).
  2192. *
  2193. * @return bool true if set user as anonymous, false if user was already logged in or anonymous id could not be found
  2194. */
  2195. function api_set_anonymous()
  2196. {
  2197. global $_user;
  2198. if (!empty($_user['user_id'])) {
  2199. return false;
  2200. }
  2201. $user_id = api_get_anonymous_id();
  2202. if ($user_id == 0) {
  2203. return false;
  2204. }
  2205. if (isset($_user['is_anonymous'])) {
  2206. return false;
  2207. }
  2208. Session::erase('_user');
  2209. $_user['user_id'] = $user_id;
  2210. $_user['is_anonymous'] = true;
  2211. $GLOBALS['_user'] = $_user;
  2212. Session::write('_user', $_user);
  2213. return true;
  2214. }
  2215. /**
  2216. * Gets the current Chamilo (not PHP/cookie) session ID.
  2217. *
  2218. * @return int O if no active session, the session ID otherwise
  2219. */
  2220. function api_get_session_id()
  2221. {
  2222. return (int) Session::read('id_session', 0);
  2223. }
  2224. /**
  2225. * Gets the current Chamilo (not social network) group ID.
  2226. *
  2227. * @return int O if no active session, the session ID otherwise
  2228. */
  2229. function api_get_group_id()
  2230. {
  2231. return Session::read('_gid', 0);
  2232. }
  2233. /**
  2234. * Gets the current or given session name.
  2235. *
  2236. * @param int Session ID (optional)
  2237. *
  2238. * @return string The session name, or null if not found
  2239. */
  2240. function api_get_session_name($session_id = 0)
  2241. {
  2242. if (empty($session_id)) {
  2243. $session_id = api_get_session_id();
  2244. if (empty($session_id)) {
  2245. return null;
  2246. }
  2247. }
  2248. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  2249. $s = "SELECT name FROM $t WHERE id = ".(int) $session_id;
  2250. $r = Database::query($s);
  2251. $c = Database::num_rows($r);
  2252. if ($c > 0) {
  2253. //technically, there can be only one, but anyway we take the first
  2254. $rec = Database::fetch_array($r);
  2255. return $rec['name'];
  2256. }
  2257. return null;
  2258. }
  2259. /**
  2260. * Gets the session info by id.
  2261. *
  2262. * @param int $id Session ID
  2263. *
  2264. * @return array information of the session
  2265. */
  2266. function api_get_session_info($id)
  2267. {
  2268. return SessionManager::fetch($id);
  2269. }
  2270. /**
  2271. * Gets the session visibility by session id.
  2272. *
  2273. * @param int $session_id
  2274. * @param int $courseId
  2275. * @param bool $ignore_visibility_for_admins
  2276. *
  2277. * @return int
  2278. * 0 = session still available,
  2279. * SESSION_VISIBLE_READ_ONLY = 1,
  2280. * SESSION_VISIBLE = 2,
  2281. * SESSION_INVISIBLE = 3
  2282. */
  2283. function api_get_session_visibility(
  2284. $session_id,
  2285. $courseId = null,
  2286. $ignore_visibility_for_admins = true
  2287. ) {
  2288. if (api_is_platform_admin()) {
  2289. if ($ignore_visibility_for_admins) {
  2290. return SESSION_AVAILABLE;
  2291. }
  2292. }
  2293. $now = time();
  2294. if (empty($session_id)) {
  2295. return 0; // Means that the session is still available.
  2296. }
  2297. $session_id = (int) $session_id;
  2298. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2299. $result = Database::query("SELECT * FROM $tbl_session WHERE id = $session_id");
  2300. if (Database::num_rows($result) <= 0) {
  2301. return SESSION_INVISIBLE;
  2302. }
  2303. $row = Database::fetch_array($result, 'ASSOC');
  2304. $visibility = $original_visibility = $row['visibility'];
  2305. // I don't care the session visibility.
  2306. if (empty($row['access_start_date']) && empty($row['access_end_date'])) {
  2307. // Session duration per student.
  2308. if (isset($row['duration']) && !empty($row['duration'])) {
  2309. $duration = $row['duration'] * 24 * 60 * 60;
  2310. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser($session_id, api_get_user_id());
  2311. // If there is a session duration but there is no previous
  2312. // access by the user, then the session is still available
  2313. if (count($courseAccess) == 0) {
  2314. return SESSION_AVAILABLE;
  2315. }
  2316. $currentTime = time();
  2317. $firstAccess = isset($courseAccess['login_course_date'])
  2318. ? api_strtotime($courseAccess['login_course_date'], 'UTC')
  2319. : 0;
  2320. $userDurationData = SessionManager::getUserSession(
  2321. api_get_user_id(),
  2322. $session_id
  2323. );
  2324. $userDuration = isset($userDurationData['duration'])
  2325. ? (intval($userDurationData['duration']) * 24 * 60 * 60)
  2326. : 0;
  2327. $totalDuration = $firstAccess + $duration + $userDuration;
  2328. return $totalDuration > $currentTime ? SESSION_AVAILABLE : SESSION_VISIBLE_READ_ONLY;
  2329. }
  2330. return SESSION_AVAILABLE;
  2331. }
  2332. // If start date was set.
  2333. if (!empty($row['access_start_date'])) {
  2334. $visibility = $now > api_strtotime($row['access_start_date'], 'UTC') ? SESSION_AVAILABLE : SESSION_INVISIBLE;
  2335. }
  2336. // If the end date was set.
  2337. if (!empty($row['access_end_date'])) {
  2338. // Only if date_start said that it was ok
  2339. if ($visibility === SESSION_AVAILABLE) {
  2340. $visibility = $now < api_strtotime($row['access_end_date'], 'UTC')
  2341. ? SESSION_AVAILABLE // Date still available
  2342. : $row['visibility']; // Session ends
  2343. }
  2344. }
  2345. // If I'm a coach the visibility can change in my favor depending in the coach dates.
  2346. $isCoach = api_is_coach($session_id, $courseId);
  2347. if ($isCoach) {
  2348. // Test start date.
  2349. if (!empty($row['coach_access_start_date'])) {
  2350. $start = api_strtotime($row['coach_access_start_date'], 'UTC');
  2351. $visibility = $start < $now ? SESSION_AVAILABLE : SESSION_INVISIBLE;
  2352. }
  2353. // Test end date.
  2354. if (!empty($row['coach_access_end_date'])) {
  2355. if ($visibility === SESSION_AVAILABLE) {
  2356. $endDateCoach = api_strtotime($row['coach_access_end_date'], 'UTC');
  2357. $visibility = $endDateCoach >= $now ? SESSION_AVAILABLE : $row['visibility'];
  2358. }
  2359. }
  2360. }
  2361. return $visibility;
  2362. }
  2363. /**
  2364. * This function returns a (star) session icon if the session is not null and
  2365. * the user is not a student.
  2366. *
  2367. * @param int $sessionId
  2368. * @param int $statusId User status id - if 5 (student), will return empty
  2369. *
  2370. * @return string Session icon
  2371. */
  2372. function api_get_session_image($sessionId, $statusId)
  2373. {
  2374. $sessionId = (int) $sessionId;
  2375. $image = '';
  2376. if ($statusId != STUDENT) {
  2377. // Check whether is not a student
  2378. if ($sessionId > 0) {
  2379. $image = '&nbsp;&nbsp;'.Display::return_icon(
  2380. 'star.png',
  2381. get_lang('SessionSpecificResource'),
  2382. ['align' => 'absmiddle'],
  2383. ICON_SIZE_SMALL
  2384. );
  2385. }
  2386. }
  2387. return $image;
  2388. }
  2389. /**
  2390. * This function add an additional condition according to the session of the course.
  2391. *
  2392. * @param int $session_id session id
  2393. * @param bool $and optional, true if more than one condition false if the only condition in the query
  2394. * @param bool $with_base_content optional, true to accept content with session=0 as well,
  2395. * false for strict session condition
  2396. * @param string $session_field
  2397. *
  2398. * @return string condition of the session
  2399. */
  2400. function api_get_session_condition(
  2401. $session_id,
  2402. $and = true,
  2403. $with_base_content = false,
  2404. $session_field = 'session_id'
  2405. ) {
  2406. $session_id = (int) $session_id;
  2407. if (empty($session_field)) {
  2408. $session_field = 'session_id';
  2409. }
  2410. // Condition to show resources by session
  2411. $condition_add = $and ? ' AND ' : ' WHERE ';
  2412. if ($with_base_content) {
  2413. $condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0 OR $session_field IS NULL) ";
  2414. } else {
  2415. if (empty($session_id)) {
  2416. $condition_session = $condition_add." ($session_field = $session_id OR $session_field IS NULL)";
  2417. } else {
  2418. $condition_session = $condition_add." $session_field = $session_id ";
  2419. }
  2420. }
  2421. return $condition_session;
  2422. }
  2423. /**
  2424. * Returns the value of a setting from the web-adjustable admin config settings.
  2425. *
  2426. * WARNING true/false are stored as string, so when comparing you need to check e.g.
  2427. * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
  2428. * instead of
  2429. * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
  2430. *
  2431. * @param string $variable The variable name
  2432. * @param string $key The subkey (sub-variable) if any. Defaults to NULL
  2433. *
  2434. * @return string
  2435. *
  2436. * @author René Haentjens
  2437. * @author Bart Mollet
  2438. */
  2439. function api_get_setting($variable, $key = null)
  2440. {
  2441. global $_setting;
  2442. if ($variable == 'header_extra_content') {
  2443. $filename = api_get_home_path().'header_extra_content.txt';
  2444. if (file_exists($filename)) {
  2445. $value = file_get_contents($filename);
  2446. return $value;
  2447. } else {
  2448. return '';
  2449. }
  2450. }
  2451. if ($variable == 'footer_extra_content') {
  2452. $filename = api_get_home_path().'footer_extra_content.txt';
  2453. if (file_exists($filename)) {
  2454. $value = file_get_contents($filename);
  2455. return $value;
  2456. } else {
  2457. return '';
  2458. }
  2459. }
  2460. $value = null;
  2461. if (is_null($key)) {
  2462. $value = ((isset($_setting[$variable]) && $_setting[$variable] != '') ? $_setting[$variable] : null);
  2463. } else {
  2464. if (isset($_setting[$variable][$key])) {
  2465. $value = $_setting[$variable][$key];
  2466. }
  2467. }
  2468. return $value;
  2469. }
  2470. /**
  2471. * @param string $plugin
  2472. * @param string $variable
  2473. *
  2474. * @return string
  2475. */
  2476. function api_get_plugin_setting($plugin, $variable)
  2477. {
  2478. $variableName = $plugin.'_'.$variable;
  2479. $result = api_get_setting($variableName);
  2480. if (isset($result[$plugin])) {
  2481. $value = $result[$plugin];
  2482. $unserialized = UnserializeApi::unserialize('not_allowed_classes', $value, true);
  2483. if (false !== $unserialized) {
  2484. $value = $unserialized;
  2485. }
  2486. return $value;
  2487. }
  2488. return null;
  2489. }
  2490. /**
  2491. * Returns the value of a setting from the web-adjustable admin config settings.
  2492. */
  2493. function api_get_settings_params($params)
  2494. {
  2495. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2496. $result = Database::select('*', $table, ['where' => $params]);
  2497. return $result;
  2498. }
  2499. /**
  2500. * @param array $params example: [id = ? => '1']
  2501. *
  2502. * @return array
  2503. */
  2504. function api_get_settings_params_simple($params)
  2505. {
  2506. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2507. $result = Database::select('*', $table, ['where' => $params], 'one');
  2508. return $result;
  2509. }
  2510. /**
  2511. * Returns the value of a setting from the web-adjustable admin config settings.
  2512. */
  2513. function api_delete_settings_params($params)
  2514. {
  2515. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2516. $result = Database::delete($table, $params);
  2517. return $result;
  2518. }
  2519. /**
  2520. * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection.
  2521. *
  2522. * @return string Escaped version of $_SERVER['PHP_SELF']
  2523. */
  2524. function api_get_self()
  2525. {
  2526. return htmlentities($_SERVER['PHP_SELF']);
  2527. }
  2528. /* USER PERMISSIONS */
  2529. /**
  2530. * Checks whether current user is a platform administrator.
  2531. *
  2532. * @param bool $allowSessionAdmins Whether session admins should be considered admins or not
  2533. * @param bool $allowDrh Whether HR directors should be considered admins or not
  2534. *
  2535. * @return bool true if the user has platform admin rights,
  2536. * false otherwise
  2537. *
  2538. * @see usermanager::is_admin(user_id) for a user-id specific function
  2539. */
  2540. function api_is_platform_admin($allowSessionAdmins = false, $allowDrh = false)
  2541. {
  2542. $isAdmin = Session::read('is_platformAdmin');
  2543. if ($isAdmin) {
  2544. return true;
  2545. }
  2546. $user = api_get_user_info();
  2547. return
  2548. isset($user['status']) &&
  2549. (
  2550. ($allowSessionAdmins && $user['status'] == SESSIONADMIN) ||
  2551. ($allowDrh && $user['status'] == DRH)
  2552. );
  2553. }
  2554. /**
  2555. * Checks whether the user given as user id is in the admin table.
  2556. *
  2557. * @param int $user_id If none provided, will use current user
  2558. * @param int $url URL ID. If provided, also check if the user is active on given URL
  2559. *
  2560. * @return bool True if the user is admin, false otherwise
  2561. */
  2562. function api_is_platform_admin_by_id($user_id = null, $url = null)
  2563. {
  2564. $user_id = (int) $user_id;
  2565. if (empty($user_id)) {
  2566. $user_id = api_get_user_id();
  2567. }
  2568. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  2569. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  2570. $res = Database::query($sql);
  2571. $is_admin = Database::num_rows($res) === 1;
  2572. if (!$is_admin || !isset($url)) {
  2573. return $is_admin;
  2574. }
  2575. // We get here only if $url is set
  2576. $url = (int) $url;
  2577. $url_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2578. $sql = "SELECT * FROM $url_user_table
  2579. WHERE access_url_id = $url AND user_id = $user_id";
  2580. $res = Database::query($sql);
  2581. $result = Database::num_rows($res) === 1;
  2582. return $result;
  2583. }
  2584. /**
  2585. * Returns the user's numeric status ID from the users table.
  2586. *
  2587. * @param int $user_id If none provided, will use current user
  2588. *
  2589. * @return int User's status (1 for teacher, 5 for student, etc)
  2590. */
  2591. function api_get_user_status($user_id = null)
  2592. {
  2593. $user_id = (int) $user_id;
  2594. if (empty($user_id)) {
  2595. $user_id = api_get_user_id();
  2596. }
  2597. $table = Database::get_main_table(TABLE_MAIN_USER);
  2598. $sql = "SELECT status FROM $table WHERE user_id = $user_id ";
  2599. $result = Database::query($sql);
  2600. $status = null;
  2601. if (Database::num_rows($result)) {
  2602. $row = Database::fetch_array($result);
  2603. $status = $row['status'];
  2604. }
  2605. return $status;
  2606. }
  2607. /**
  2608. * Checks whether current user is allowed to create courses.
  2609. *
  2610. * @return bool true if the user has course creation rights,
  2611. * false otherwise
  2612. */
  2613. function api_is_allowed_to_create_course()
  2614. {
  2615. if (api_is_platform_admin()) {
  2616. return true;
  2617. }
  2618. // Teachers can only create courses
  2619. if (api_is_teacher()) {
  2620. if (api_get_setting('allow_users_to_create_courses') === 'true') {
  2621. return true;
  2622. } else {
  2623. return false;
  2624. }
  2625. }
  2626. return Session::read('is_allowedCreateCourse');
  2627. }
  2628. /**
  2629. * Checks whether the current user is a course administrator.
  2630. *
  2631. * @return bool True if current user is a course administrator
  2632. */
  2633. function api_is_course_admin()
  2634. {
  2635. if (api_is_platform_admin()) {
  2636. return true;
  2637. }
  2638. return Session::read('is_courseAdmin');
  2639. }
  2640. /**
  2641. * Checks whether the current user is a course coach
  2642. * Based on the presence of user in session.id_coach (session general coach).
  2643. *
  2644. * @return bool True if current user is a course coach
  2645. */
  2646. function api_is_session_general_coach()
  2647. {
  2648. return Session::read('is_session_general_coach');
  2649. }
  2650. /**
  2651. * Checks whether the current user is a course tutor
  2652. * Based on the presence of user in session_rel_course_rel_user.user_id with status = 2.
  2653. *
  2654. * @return bool True if current user is a course tutor
  2655. */
  2656. function api_is_course_tutor()
  2657. {
  2658. return Session::read('is_courseTutor');
  2659. }
  2660. /**
  2661. * @param int $user_id
  2662. * @param int $courseId
  2663. * @param int $session_id
  2664. *
  2665. * @return bool
  2666. */
  2667. function api_is_course_session_coach($user_id, $courseId, $session_id)
  2668. {
  2669. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2670. $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2671. $user_id = (int) $user_id;
  2672. $session_id = (int) $session_id;
  2673. $courseId = (int) $courseId;
  2674. $sql = "SELECT DISTINCT session.id
  2675. FROM $session_table
  2676. INNER JOIN $session_rel_course_rel_user_table session_rc_ru
  2677. ON session.id = session_rc_ru.session_id
  2678. WHERE
  2679. session_rc_ru.user_id = '".$user_id."' AND
  2680. session_rc_ru.c_id = '$courseId' AND
  2681. session_rc_ru.status = 2 AND
  2682. session_rc_ru.session_id = '$session_id'";
  2683. $result = Database::query($sql);
  2684. return Database::num_rows($result) > 0;
  2685. }
  2686. /**
  2687. * Checks whether the current user is a course or session coach.
  2688. *
  2689. * @param int $session_id
  2690. * @param int $courseId
  2691. * @param bool Check whether we are in student view and, if we are, return false
  2692. *
  2693. * @return bool True if current user is a course or session coach
  2694. */
  2695. function api_is_coach($session_id = 0, $courseId = null, $check_student_view = true)
  2696. {
  2697. $userId = api_get_user_id();
  2698. if (!empty($session_id)) {
  2699. $session_id = (int) $session_id;
  2700. } else {
  2701. $session_id = api_get_session_id();
  2702. }
  2703. // The student preview was on
  2704. if ($check_student_view && api_is_student_view_active()) {
  2705. return false;
  2706. }
  2707. if (!empty($courseId)) {
  2708. $courseId = (int) $courseId;
  2709. } else {
  2710. $courseId = api_get_course_int_id();
  2711. }
  2712. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2713. $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2714. $sessionIsCoach = [];
  2715. if (!empty($courseId)) {
  2716. $sql = "SELECT DISTINCT s.id, name, access_start_date, access_end_date
  2717. FROM $session_table s
  2718. INNER JOIN $session_rel_course_rel_user_table session_rc_ru
  2719. ON session_rc_ru.session_id = s.id AND session_rc_ru.user_id = '".$userId."'
  2720. WHERE
  2721. session_rc_ru.c_id = '$courseId' AND
  2722. session_rc_ru.status = 2 AND
  2723. session_rc_ru.session_id = '$session_id'";
  2724. $result = Database::query($sql);
  2725. $sessionIsCoach = Database::store_result($result);
  2726. }
  2727. if (!empty($session_id)) {
  2728. $sql = "SELECT DISTINCT id, name, access_start_date, access_end_date
  2729. FROM $session_table
  2730. WHERE session.id_coach = $userId AND id = $session_id
  2731. ORDER BY access_start_date, access_end_date, name";
  2732. $result = Database::query($sql);
  2733. if (!empty($sessionIsCoach)) {
  2734. $sessionIsCoach = array_merge(
  2735. $sessionIsCoach,
  2736. Database::store_result($result)
  2737. );
  2738. } else {
  2739. $sessionIsCoach = Database::store_result($result);
  2740. }
  2741. }
  2742. return count($sessionIsCoach) > 0;
  2743. }
  2744. /**
  2745. * Checks whether the current user is a session administrator.
  2746. *
  2747. * @return bool True if current user is a course administrator
  2748. */
  2749. function api_is_session_admin()
  2750. {
  2751. $user = api_get_user_info();
  2752. return isset($user['status']) && $user['status'] == SESSIONADMIN;
  2753. }
  2754. /**
  2755. * Checks whether the current user is a human resources manager.
  2756. *
  2757. * @return bool True if current user is a human resources manager
  2758. */
  2759. function api_is_drh()
  2760. {
  2761. $user = api_get_user_info();
  2762. return isset($user['status']) && $user['status'] == DRH;
  2763. }
  2764. /**
  2765. * Checks whether the current user is a student.
  2766. *
  2767. * @return bool True if current user is a human resources manager
  2768. */
  2769. function api_is_student()
  2770. {
  2771. $user = api_get_user_info();
  2772. return isset($user['status']) && $user['status'] == STUDENT;
  2773. }
  2774. /**
  2775. * Checks whether the current user has the status 'teacher'.
  2776. *
  2777. * @return bool True if current user is a human resources manager
  2778. */
  2779. function api_is_teacher()
  2780. {
  2781. $user = api_get_user_info();
  2782. return isset($user['status']) && $user['status'] == COURSEMANAGER;
  2783. }
  2784. /**
  2785. * Checks whether the current user is a invited user.
  2786. *
  2787. * @return bool
  2788. */
  2789. function api_is_invitee()
  2790. {
  2791. $user = api_get_user_info();
  2792. return isset($user['status']) && $user['status'] == INVITEE;
  2793. }
  2794. /**
  2795. * This function checks whether a session is assigned into a category.
  2796. *
  2797. * @param int - session id
  2798. * @param string - category name
  2799. *
  2800. * @return bool - true if is found, otherwise false
  2801. */
  2802. function api_is_session_in_category($session_id, $category_name)
  2803. {
  2804. $session_id = (int) $session_id;
  2805. $category_name = Database::escape_string($category_name);
  2806. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2807. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2808. $sql = "SELECT 1
  2809. FROM $tbl_session
  2810. WHERE $session_id IN (
  2811. SELECT s.id FROM $tbl_session s, $tbl_session_category sc
  2812. WHERE
  2813. s.session_category_id = sc.id AND
  2814. sc.name LIKE '%$category_name'
  2815. )";
  2816. $rs = Database::query($sql);
  2817. if (Database::num_rows($rs) > 0) {
  2818. return true;
  2819. } else {
  2820. return false;
  2821. }
  2822. }
  2823. /**
  2824. * Displays the title of a tool.
  2825. * Normal use: parameter is a string:
  2826. * api_display_tool_title("My Tool").
  2827. *
  2828. * Optionally, there can be a subtitle below
  2829. * the normal title, and / or a supra title above the normal title.
  2830. *
  2831. * e.g. supra title:
  2832. * group
  2833. * GROUP PROPERTIES
  2834. *
  2835. * e.g. subtitle:
  2836. * AGENDA
  2837. * calender & events tool
  2838. *
  2839. * @author Hugues Peeters <hugues.peeters@claroline.net>
  2840. *
  2841. * @param mixed $title_element - it could either be a string or an array
  2842. * containing 'supraTitle', 'mainTitle',
  2843. * 'subTitle'
  2844. */
  2845. function api_display_tool_title($title_element)
  2846. {
  2847. if (is_string($title_element)) {
  2848. $tit = $title_element;
  2849. unset($title_element);
  2850. $title_element['mainTitle'] = $tit;
  2851. }
  2852. echo '<h3>';
  2853. if (!empty($title_element['supraTitle'])) {
  2854. echo '<small>'.$title_element['supraTitle'].'</small><br />';
  2855. }
  2856. if (!empty($title_element['mainTitle'])) {
  2857. echo $title_element['mainTitle'];
  2858. }
  2859. if (!empty($title_element['subTitle'])) {
  2860. echo '<br /><small>'.$title_element['subTitle'].'</small>';
  2861. }
  2862. echo '</h3>';
  2863. }
  2864. /**
  2865. * Displays options for switching between student view and course manager view.
  2866. *
  2867. * Changes in version 1.2 (Patrick Cool)
  2868. * Student view switch now behaves as a real switch. It maintains its current state until the state
  2869. * is changed explicitly
  2870. *
  2871. * Changes in version 1.1 (Patrick Cool)
  2872. * student view now works correctly in subfolders of the document tool
  2873. * student view works correctly in the new links tool
  2874. *
  2875. * Example code for using this in your tools:
  2876. * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
  2877. * // display_tool_view_option($isStudentView);
  2878. * //}
  2879. * //and in later sections, use api_is_allowed_to_edit()
  2880. *
  2881. * @author Roan Embrechts
  2882. * @author Patrick Cool
  2883. * @author Julio Montoya, changes added in Chamilo
  2884. *
  2885. * @version 1.2
  2886. *
  2887. * @todo rewrite code so it is easier to understand
  2888. */
  2889. function api_display_tool_view_option()
  2890. {
  2891. if (api_get_setting('student_view_enabled') != 'true') {
  2892. return '';
  2893. }
  2894. $sourceurl = '';
  2895. $is_framed = false;
  2896. // Exceptions apply for all multi-frames pages
  2897. if (strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php') !== false) {
  2898. // The chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
  2899. return '';
  2900. }
  2901. // Uncomment to remove student view link from document view page
  2902. if (strpos($_SERVER['REQUEST_URI'], 'lp/lp_header.php') !== false) {
  2903. if (empty($_GET['lp_id'])) {
  2904. return '';
  2905. }
  2906. $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
  2907. $sourceurl = str_replace(
  2908. 'lp/lp_header.php',
  2909. 'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.($_SESSION['studentview'] == 'studentview' ? 'false' : 'true'),
  2910. $sourceurl
  2911. );
  2912. //showinframes doesn't handle student view anyway...
  2913. //return '';
  2914. $is_framed = true;
  2915. }
  2916. // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
  2917. if (!$is_framed) {
  2918. if (strpos($_SERVER['REQUEST_URI'], '?') === false) {
  2919. $sourceurl = api_get_self().'?'.api_get_cidreq();
  2920. } else {
  2921. $sourceurl = $_SERVER['REQUEST_URI'];
  2922. }
  2923. }
  2924. $output_string = '';
  2925. if (!empty($_SESSION['studentview'])) {
  2926. if ($_SESSION['studentview'] == 'studentview') {
  2927. // We have to remove the isStudentView=true from the $sourceurl
  2928. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2929. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2930. $output_string .= '<a class="btn btn-primary btn-sm" href="'.$sourceurl.'&isStudentView=false" target="_self">'.
  2931. Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToTeacherView').'</a>';
  2932. } elseif ($_SESSION['studentview'] == 'teacherview') {
  2933. // Switching to teacherview
  2934. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2935. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2936. $output_string .= '<a class="btn btn-default btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
  2937. Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToStudentView').'</a>';
  2938. }
  2939. } else {
  2940. $output_string .= '<a class="btn btn-default btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
  2941. Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToStudentView').'</a>';
  2942. }
  2943. $output_string = Security::remove_XSS($output_string);
  2944. $html = Display::tag('div', $output_string, ['class' => 'view-options']);
  2945. return $html;
  2946. }
  2947. // TODO: This is for the permission section.
  2948. /**
  2949. * Function that removes the need to directly use is_courseAdmin global in
  2950. * tool scripts. It returns true or false depending on the user's rights in
  2951. * this particular course.
  2952. * Optionally checking for tutor and coach roles here allows us to use the
  2953. * student_view feature altogether with these roles as well.
  2954. *
  2955. * @param bool Whether to check if the user has the tutor role
  2956. * @param bool Whether to check if the user has the coach role
  2957. * @param bool Whether to check if the user has the session coach role
  2958. * @param bool check the student view or not
  2959. *
  2960. * @author Roan Embrechts
  2961. * @author Patrick Cool
  2962. * @author Julio Montoya
  2963. *
  2964. * @version 1.1, February 2004
  2965. *
  2966. * @return bool true: the user has the rights to edit, false: he does not
  2967. */
  2968. function api_is_allowed_to_edit(
  2969. $tutor = false,
  2970. $coach = false,
  2971. $session_coach = false,
  2972. $check_student_view = true
  2973. ) {
  2974. $allowSessionAdminEdit = api_get_configuration_value('session_admins_edit_courses_content') === true;
  2975. // Admins can edit anything.
  2976. if (api_is_platform_admin($allowSessionAdminEdit)) {
  2977. //The student preview was on
  2978. if ($check_student_view && api_is_student_view_active()) {
  2979. return false;
  2980. } else {
  2981. return true;
  2982. }
  2983. }
  2984. $sessionId = api_get_session_id();
  2985. if ($sessionId && api_get_configuration_value('session_courses_read_only_mode')) {
  2986. $efv = new ExtraFieldValue('course');
  2987. $lockExrafieldField = $efv->get_values_by_handler_and_field_variable(
  2988. api_get_course_int_id(),
  2989. 'session_courses_read_only_mode'
  2990. );
  2991. if (!empty($lockExrafieldField['value'])) {
  2992. return false;
  2993. }
  2994. }
  2995. $is_allowed_coach_to_edit = api_is_coach(null, null, $check_student_view);
  2996. $session_visibility = api_get_session_visibility($sessionId);
  2997. $is_courseAdmin = api_is_course_admin();
  2998. if (!$is_courseAdmin && $tutor) {
  2999. // If we also want to check if the user is a tutor...
  3000. $is_courseAdmin = $is_courseAdmin || api_is_course_tutor();
  3001. }
  3002. if (!$is_courseAdmin && $coach) {
  3003. // If we also want to check if the user is a coach...';
  3004. // Check if session visibility is read only for coaches.
  3005. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  3006. $is_allowed_coach_to_edit = false;
  3007. }
  3008. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') {
  3009. // Check if coach is allowed to edit a course.
  3010. $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
  3011. }
  3012. }
  3013. if (!$is_courseAdmin && $session_coach) {
  3014. $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
  3015. }
  3016. // Check if the student_view is enabled, and if so, if it is activated.
  3017. if (api_get_setting('student_view_enabled') == 'true') {
  3018. if (!empty($sessionId)) {
  3019. // Check if session visibility is read only for coaches.
  3020. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  3021. $is_allowed_coach_to_edit = false;
  3022. }
  3023. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') {
  3024. // Check if coach is allowed to edit a course.
  3025. $is_allowed = $is_allowed_coach_to_edit;
  3026. } else {
  3027. $is_allowed = false;
  3028. }
  3029. if ($check_student_view) {
  3030. $is_allowed = $is_allowed && $_SESSION['studentview'] != 'studentview';
  3031. }
  3032. } else {
  3033. if ($check_student_view) {
  3034. $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview';
  3035. } else {
  3036. $is_allowed = $is_courseAdmin;
  3037. }
  3038. }
  3039. return $is_allowed;
  3040. } else {
  3041. return $is_courseAdmin;
  3042. }
  3043. }
  3044. /**
  3045. * Returns true if user is a course coach of at least one course in session.
  3046. *
  3047. * @param int $sessionId
  3048. *
  3049. * @return bool
  3050. */
  3051. function api_is_coach_of_course_in_session($sessionId)
  3052. {
  3053. if (api_is_platform_admin()) {
  3054. return true;
  3055. }
  3056. $userId = api_get_user_id();
  3057. $courseList = UserManager::get_courses_list_by_session(
  3058. $userId,
  3059. $sessionId
  3060. );
  3061. // Session visibility.
  3062. $visibility = api_get_session_visibility(
  3063. $sessionId,
  3064. null,
  3065. false
  3066. );
  3067. if ($visibility != SESSION_VISIBLE && !empty($courseList)) {
  3068. // Course Coach session visibility.
  3069. $blockedCourseCount = 0;
  3070. $closedVisibilityList = [
  3071. COURSE_VISIBILITY_CLOSED,
  3072. COURSE_VISIBILITY_HIDDEN,
  3073. ];
  3074. foreach ($courseList as $course) {
  3075. // Checking session visibility
  3076. $sessionCourseVisibility = api_get_session_visibility(
  3077. $sessionId,
  3078. $course['real_id']
  3079. );
  3080. $courseIsVisible = !in_array(
  3081. $course['visibility'],
  3082. $closedVisibilityList
  3083. );
  3084. if ($courseIsVisible === false || $sessionCourseVisibility == SESSION_INVISIBLE) {
  3085. $blockedCourseCount++;
  3086. }
  3087. }
  3088. // If all courses are blocked then no show in the list.
  3089. if ($blockedCourseCount === count($courseList)) {
  3090. $visibility = SESSION_INVISIBLE;
  3091. } else {
  3092. $visibility = SESSION_VISIBLE;
  3093. }
  3094. }
  3095. switch ($visibility) {
  3096. case SESSION_VISIBLE_READ_ONLY:
  3097. case SESSION_VISIBLE:
  3098. case SESSION_AVAILABLE:
  3099. return true;
  3100. break;
  3101. case SESSION_INVISIBLE:
  3102. return false;
  3103. }
  3104. return false;
  3105. }
  3106. /**
  3107. * Checks if a student can edit contents in a session depending
  3108. * on the session visibility.
  3109. *
  3110. * @param bool $tutor Whether to check if the user has the tutor role
  3111. * @param bool $coach Whether to check if the user has the coach role
  3112. *
  3113. * @return bool true: the user has the rights to edit, false: he does not
  3114. */
  3115. function api_is_allowed_to_session_edit($tutor = false, $coach = false)
  3116. {
  3117. if (api_is_allowed_to_edit($tutor, $coach)) {
  3118. // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
  3119. return true;
  3120. } else {
  3121. $sessionId = api_get_session_id();
  3122. if ($sessionId == 0) {
  3123. // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
  3124. return true;
  3125. } else {
  3126. // I'm in a session and I'm a student
  3127. // Get the session visibility
  3128. $session_visibility = api_get_session_visibility($sessionId);
  3129. // if 5 the session is still available
  3130. switch ($session_visibility) {
  3131. case SESSION_VISIBLE_READ_ONLY: // 1
  3132. return false;
  3133. case SESSION_VISIBLE: // 2
  3134. return true;
  3135. case SESSION_INVISIBLE: // 3
  3136. return false;
  3137. case SESSION_AVAILABLE: //5
  3138. return true;
  3139. }
  3140. }
  3141. }
  3142. }
  3143. /**
  3144. * Checks whether the user is allowed in a specific tool for a specific action.
  3145. *
  3146. * @param string $tool the tool we are checking if the user has a certain permission
  3147. * @param string $action the action we are checking (add, edit, delete, move, visibility)
  3148. *
  3149. * @return bool
  3150. *
  3151. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3152. * @author Julio Montoya
  3153. *
  3154. * @version 1.0
  3155. */
  3156. function api_is_allowed($tool, $action, $task_id = 0)
  3157. {
  3158. $_user = api_get_user_info();
  3159. $_course = api_get_course_info();
  3160. if (api_is_course_admin()) {
  3161. return true;
  3162. }
  3163. if (is_array($_course) and count($_course) > 0) {
  3164. require_once api_get_path(SYS_CODE_PATH).'permissions/permissions_functions.inc.php';
  3165. // Getting the permissions of this user.
  3166. if ($task_id == 0) {
  3167. $user_permissions = get_permissions('user', $_user['user_id']);
  3168. $_SESSION['total_permissions'][$_course['code']] = $user_permissions;
  3169. }
  3170. // Getting the permissions of the task.
  3171. if ($task_id != 0) {
  3172. $task_permissions = get_permissions('task', $task_id);
  3173. /* !!! */$_SESSION['total_permissions'][$_course['code']] = $task_permissions;
  3174. }
  3175. //print_r($_SESSION['total_permissions']);
  3176. // Getting the permissions of the groups of the user
  3177. //$groups_of_user = GroupManager::get_group_ids($_course['db_name'], $_user['user_id']);
  3178. //foreach($groups_of_user as $group)
  3179. // $this_group_permissions = get_permissions('group', $group);
  3180. // Getting the permissions of the courseroles of the user
  3181. $user_courserole_permissions = get_roles_permissions('user', $_user['user_id']);
  3182. // Getting the permissions of the platformroles of the user
  3183. //$user_platformrole_permissions = get_roles_permissions('user', $_user['user_id'], ', platform');
  3184. // Getting the permissions of the roles of the groups of the user
  3185. //foreach($groups_of_user as $group)
  3186. // $this_group_courserole_permissions = get_roles_permissions('group', $group);
  3187. // Getting the permissions of the platformroles of the groups of the user
  3188. //foreach($groups_of_user as $group)
  3189. // $this_group_platformrole_permissions = get_roles_permissions('group', $group, 'platform');
  3190. }
  3191. // If the permissions are limited, we have to map the extended ones to the limited ones.
  3192. if (api_get_setting('permissions') == 'limited') {
  3193. if ($action == 'Visibility') {
  3194. $action = 'Edit';
  3195. }
  3196. if ($action == 'Move') {
  3197. $action = 'Edit';
  3198. }
  3199. }
  3200. // The session that contains all the permissions already exists for this course
  3201. // so there is no need to requery everything.
  3202. //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]);
  3203. if (is_array($_SESSION['total_permissions'][$_course['code']][$tool])) {
  3204. if (in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool])) {
  3205. return true;
  3206. } else {
  3207. return false;
  3208. }
  3209. }
  3210. }
  3211. /**
  3212. * Tells whether this user is an anonymous user.
  3213. *
  3214. * @param int $user_id User ID (optional, will take session ID if not provided)
  3215. * @param bool $db_check Whether to check in the database (true) or simply in
  3216. * the session (false) to see if the current user is the anonymous user
  3217. *
  3218. * @return bool true if this user is anonymous, false otherwise
  3219. */
  3220. function api_is_anonymous($user_id = null, $db_check = false)
  3221. {
  3222. if (!isset($user_id)) {
  3223. $user_id = api_get_user_id();
  3224. }
  3225. if ($db_check) {
  3226. $info = api_get_user_info($user_id);
  3227. if ($info['status'] == ANONYMOUS) {
  3228. return true;
  3229. }
  3230. }
  3231. $_user = api_get_user_info();
  3232. if (isset($_user['status']) && $_user['status'] == ANONYMOUS) {
  3233. //if ($_user['user_id'] == 0) {
  3234. // In some cases, api_set_anonymous doesn't seem to be triggered in local.inc.php. Make sure it is.
  3235. // Occurs in agenda for admin links - YW
  3236. global $use_anonymous;
  3237. if (isset($use_anonymous) && $use_anonymous) {
  3238. api_set_anonymous();
  3239. }
  3240. return true;
  3241. }
  3242. return (isset($_user['is_anonymous']) && $_user['is_anonymous'] === true) || $_user === false;
  3243. }
  3244. /**
  3245. * Displays message "You are not allowed here..." and exits the entire script.
  3246. *
  3247. * @param bool $print_headers Whether or not to print headers (default = false -> does not print them)
  3248. * @param string $message
  3249. * @param int $responseCode
  3250. */
  3251. function api_not_allowed(
  3252. $print_headers = false,
  3253. $message = null,
  3254. $responseCode = 0
  3255. ) {
  3256. if (api_get_setting('sso_authentication') === 'true') {
  3257. global $osso;
  3258. if ($osso) {
  3259. $osso->logout();
  3260. }
  3261. }
  3262. $home_url = api_get_path(WEB_PATH);
  3263. $user_id = api_get_user_id();
  3264. $course = api_get_course_id();
  3265. global $this_section;
  3266. if (CustomPages::enabled() && !isset($user_id)) {
  3267. if (empty($user_id)) {
  3268. // Why the CustomPages::enabled() need to be to set the request_uri
  3269. $_SESSION['request_uri'] = $_SERVER['REQUEST_URI'];
  3270. }
  3271. CustomPages::display(CustomPages::INDEX_UNLOGGED);
  3272. }
  3273. $origin = api_get_origin();
  3274. $msg = null;
  3275. if (isset($message)) {
  3276. $msg = $message;
  3277. } else {
  3278. $msg = Display::return_message(
  3279. get_lang('NotAllowedClickBack').'
  3280. <script>function goBack(){window.history.back();}</script>',
  3281. 'error',
  3282. false
  3283. );
  3284. $msg .= '<p class="text-center">
  3285. <a onclick="goBack();" class="btn btn-default" href="'.$home_url.'">'.get_lang('GoBack').'</a>
  3286. </p>';
  3287. }
  3288. $msg = Display::div($msg, ['align' => 'center']);
  3289. $show_headers = 0;
  3290. if ($print_headers && $origin != 'learnpath') {
  3291. $show_headers = 1;
  3292. }
  3293. $tpl = new Template(null, $show_headers, $show_headers, false, true, false, true, $responseCode);
  3294. $tpl->assign('hide_login_link', 1);
  3295. $tpl->assign('content', $msg);
  3296. if (($user_id != 0 && !api_is_anonymous()) &&
  3297. (!isset($course) || $course == -1) &&
  3298. empty($_GET['cidReq'])
  3299. ) {
  3300. // if the access is not authorized and there is some login information
  3301. // but the cidReq is not found, assume we are missing course data and send the user
  3302. // to the user_portal
  3303. $tpl->display_one_col_template();
  3304. exit;
  3305. }
  3306. if (!empty($_SERVER['REQUEST_URI']) &&
  3307. (
  3308. !empty($_GET['cidReq']) ||
  3309. $this_section == SECTION_MYPROFILE ||
  3310. $this_section == SECTION_PLATFORM_ADMIN
  3311. )
  3312. ) {
  3313. $courseCode = api_get_course_id();
  3314. // Only display form and return to the previous URL if there was a course ID included
  3315. if ($user_id != 0 && !api_is_anonymous()) {
  3316. //if there is a user ID, then the user is not allowed but the session is still there. Say so and exit
  3317. $tpl->assign('content', $msg);
  3318. $tpl->display_one_col_template();
  3319. exit;
  3320. }
  3321. if (!is_null($courseCode)) {
  3322. api_set_firstpage_parameter($courseCode);
  3323. }
  3324. // If the user has no user ID, then his session has expired
  3325. $form = api_get_not_allowed_login_form();
  3326. // see same text in auth/gotocourse.php and main_api.lib.php function api_not_allowed (above)
  3327. $content = Display::return_message(get_lang('NotAllowed'), 'error', false);
  3328. if (!empty($courseCode)) {
  3329. $content .= '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>';
  3330. }
  3331. if (api_is_cas_activated()) {
  3332. $content .= Display::return_message(sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")), '', false);
  3333. $content .= Display::div(
  3334. "<br/><a href='".get_cas_direct_URL(api_get_course_id())."'>".sprintf(get_lang('LoginWithYourAccount'), api_get_setting("Institution"))."</a><br/><br/>",
  3335. ['align' => 'center']
  3336. );
  3337. $content .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
  3338. $content .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
  3339. $content .= "<div style='display:none;'>";
  3340. }
  3341. $content .= '<div class="well">';
  3342. $content .= $form->returnForm();
  3343. $content .= '</div>';
  3344. if (api_is_cas_activated()) {
  3345. $content .= "</div>";
  3346. }
  3347. if (!empty($courseCode)) {
  3348. $content .= '<hr/><p style="text-align:center"><a href="'.$home_url.'">'.
  3349. get_lang('ReturnToCourseHomepage').'</a></p>';
  3350. } else {
  3351. $content .= '<hr/><p style="text-align:center"><a href="'.$home_url.'">'.
  3352. get_lang('BackHome').'</a></p>';
  3353. }
  3354. $tpl->setLoginBodyClass();
  3355. $tpl->assign('content', $content);
  3356. $tpl->display_one_col_template();
  3357. exit;
  3358. }
  3359. if ($user_id != 0 && !api_is_anonymous()) {
  3360. $tpl->display_one_col_template();
  3361. exit;
  3362. }
  3363. $msg = null;
  3364. // The session is over and we were not in a course,
  3365. // or we try to get directly to a private course without being logged
  3366. $courseId = api_get_course_int_id();
  3367. if (!empty($courseId)) {
  3368. api_set_firstpage_parameter(api_get_course_id());
  3369. $tpl->setLoginBodyClass();
  3370. // see same text in auth/gotocourse.php and main_api.lib.php function api_not_allowed (bellow)
  3371. $msg = Display::return_message(get_lang('NotAllowed'), 'error', false);
  3372. $msg .= '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>';
  3373. $casEnabled = api_is_cas_activated();
  3374. if ($casEnabled) {
  3375. $msg .= Display::return_message(
  3376. sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")),
  3377. '',
  3378. false
  3379. );
  3380. $msg .= Display::div("<br/><a href='".get_cas_direct_URL(api_get_course_int_id())."'>".getCASLogoHTML()." ".sprintf(get_lang('LoginWithYourAccount'), api_get_setting("Institution"))."</a><br/><br/>", ['align' => 'center']);
  3381. $msg .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
  3382. $msg .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
  3383. $msg .= "<div style='display:none;'>";
  3384. }
  3385. $form = api_get_not_allowed_login_form();
  3386. $msg .= '<div class="well">';
  3387. $msg .= $form->returnForm();
  3388. $msg .= '</div>';
  3389. if ($casEnabled) {
  3390. $msg .= "</div>";
  3391. }
  3392. } else {
  3393. // we were not in a course, return to home page
  3394. $msg = Display::return_message(
  3395. get_lang('NotAllowed'),
  3396. 'error',
  3397. false
  3398. );
  3399. $msg .= '<p class="text-center">
  3400. <a class="btn btn-default" href="'.$home_url.'">'.get_lang('BackHome').'</a>
  3401. </p>';
  3402. if (!empty($message)) {
  3403. $msg = $message;
  3404. }
  3405. if (api_is_anonymous()) {
  3406. $form = api_get_not_allowed_login_form();
  3407. $msg .= '<div class="well">';
  3408. $msg .= $form->returnForm();
  3409. $msg .= '</div>';
  3410. }
  3411. }
  3412. $tpl->assign('content', $msg);
  3413. $tpl->display_one_col_template();
  3414. exit;
  3415. }
  3416. /**
  3417. * @return FormValidator
  3418. */
  3419. function api_get_not_allowed_login_form()
  3420. {
  3421. $action = api_get_self().'?'.Security::remove_XSS($_SERVER['QUERY_STRING']);
  3422. $action = str_replace('&amp;', '&', $action);
  3423. Session::write('redirect_after_not_allow_page', $action);
  3424. $action .= '&redirect_after_not_allow_page=1';
  3425. $form = new FormValidator(
  3426. 'formLogin',
  3427. 'post',
  3428. $action,
  3429. null,
  3430. ['class' => 'form-stacked']
  3431. );
  3432. $params = [
  3433. 'placeholder' => get_lang('UserName'),
  3434. 'class' => 'col-md-3',
  3435. ];
  3436. if (api_browser_support('autocapitalize')) {
  3437. $params['autocapitalize'] = 'none';
  3438. }
  3439. $form->addElement(
  3440. 'text',
  3441. 'login',
  3442. null,
  3443. $params
  3444. );
  3445. $form->addElement(
  3446. 'password',
  3447. 'password',
  3448. null,
  3449. ['placeholder' => get_lang('Password'), 'class' => 'col-md-3']
  3450. ); //new
  3451. $form->addButtonNext(get_lang('LoginEnter'), 'submitAuth');
  3452. return $form;
  3453. }
  3454. /**
  3455. * Gets a UNIX timestamp from a database (MySQL) datetime format string.
  3456. *
  3457. * @param $last_post_datetime standard output date in a sql query
  3458. *
  3459. * @return int timestamp
  3460. *
  3461. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>
  3462. *
  3463. * @version October 2003
  3464. * @desc convert sql date to unix timestamp
  3465. */
  3466. function convert_sql_date($last_post_datetime)
  3467. {
  3468. list($last_post_date, $last_post_time) = explode(' ', $last_post_datetime);
  3469. list($year, $month, $day) = explode('-', $last_post_date);
  3470. list($hour, $min, $sec) = explode(':', $last_post_time);
  3471. return mktime((int) $hour, (int) $min, (int) $sec, (int) $month, (int) $day, (int) $year);
  3472. }
  3473. /**
  3474. * Gets item visibility from the item_property table.
  3475. *
  3476. * Getting the visibility is done by getting the last updated visibility entry,
  3477. * using the largest session ID found if session 0 and another was found (meaning
  3478. * the only one that is actually from the session, in case there are results from
  3479. * session 0 *AND* session n).
  3480. *
  3481. * @param array $_course Course properties array (result of api_get_course_info())
  3482. * @param string $tool Tool (learnpath, document, etc)
  3483. * @param int $id The item ID in the given tool
  3484. * @param int $session The session ID (optional)
  3485. * @param int $user_id
  3486. * @param string $type
  3487. * @param string $group_id
  3488. *
  3489. * @return int -1 on error, 0 if invisible, 1 if visible
  3490. */
  3491. function api_get_item_visibility(
  3492. $_course,
  3493. $tool,
  3494. $id,
  3495. $session = 0,
  3496. $user_id = null,
  3497. $type = null,
  3498. $group_id = null
  3499. ) {
  3500. if (!is_array($_course) || count($_course) == 0 || empty($tool) || empty($id)) {
  3501. return -1;
  3502. }
  3503. $tool = Database::escape_string($tool);
  3504. $id = (int) $id;
  3505. $session = (int) $session;
  3506. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3507. $course_id = (int) $_course['real_id'];
  3508. $userCondition = '';
  3509. if (!empty($user_id)) {
  3510. $user_id = (int) $user_id;
  3511. $userCondition = " AND to_user_id = $user_id ";
  3512. }
  3513. $typeCondition = '';
  3514. if (!empty($type)) {
  3515. $type = Database::escape_string($type);
  3516. $typeCondition = " AND lastedit_type = '$type' ";
  3517. }
  3518. $groupCondition = '';
  3519. if (!empty($group_id)) {
  3520. $group_id = (int) $group_id;
  3521. $groupCondition = " AND to_group_id = '$group_id' ";
  3522. }
  3523. $sql = "SELECT visibility
  3524. FROM $TABLE_ITEMPROPERTY
  3525. WHERE
  3526. c_id = $course_id AND
  3527. tool = '$tool' AND
  3528. ref = $id AND
  3529. (session_id = $session OR session_id = 0 OR session_id IS NULL)
  3530. $userCondition $typeCondition $groupCondition
  3531. ORDER BY session_id DESC, lastedit_date DESC
  3532. LIMIT 1";
  3533. $res = Database::query($sql);
  3534. if ($res === false || Database::num_rows($res) == 0) {
  3535. return -1;
  3536. }
  3537. $row = Database::fetch_array($res);
  3538. return (int) $row['visibility'];
  3539. }
  3540. /**
  3541. * Delete a row in the c_item_property table.
  3542. *
  3543. * @param array $courseInfo
  3544. * @param string $tool
  3545. * @param int $itemId
  3546. * @param int $userId
  3547. * @param int $groupId group.iid
  3548. * @param int $sessionId
  3549. *
  3550. * @return false|null
  3551. */
  3552. function api_item_property_delete(
  3553. $courseInfo,
  3554. $tool,
  3555. $itemId,
  3556. $userId,
  3557. $groupId = 0,
  3558. $sessionId = 0
  3559. ) {
  3560. if (empty($courseInfo)) {
  3561. return false;
  3562. }
  3563. $courseId = (int) $courseInfo['real_id'];
  3564. if (empty($courseId) || empty($tool) || empty($itemId)) {
  3565. return false;
  3566. }
  3567. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3568. $tool = Database::escape_string($tool);
  3569. $itemId = intval($itemId);
  3570. $userId = intval($userId);
  3571. $groupId = intval($groupId);
  3572. $sessionId = intval($sessionId);
  3573. $groupCondition = " AND to_group_id = $groupId ";
  3574. if (empty($groupId)) {
  3575. $groupCondition = " AND (to_group_id is NULL OR to_group_id = 0) ";
  3576. }
  3577. $userCondition = " AND to_user_id = $userId ";
  3578. if (empty($userId)) {
  3579. $userCondition = " AND (to_user_id is NULL OR to_user_id = 0) ";
  3580. }
  3581. $sessionCondition = api_get_session_condition($sessionId, true, false, 'session_id');
  3582. $sql = "DELETE FROM $table
  3583. WHERE
  3584. c_id = $courseId AND
  3585. tool = '$tool' AND
  3586. ref = $itemId
  3587. $sessionCondition
  3588. $userCondition
  3589. $groupCondition
  3590. ";
  3591. Database::query($sql);
  3592. }
  3593. /**
  3594. * Updates or adds item properties to the Item_propetry table
  3595. * Tool and lastedit_type are language independant strings (langvars->get_lang!).
  3596. *
  3597. * @param array $_course array with course properties
  3598. * @param string $tool tool id, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3599. * @param int $item_id id of the item itself, linked to key of every tool ('id', ...)
  3600. * @param string $last_edit_type add or update action
  3601. * (1) message to be translated (in trad4all) : e.g. DocumentAdded, DocumentUpdated;
  3602. * (2) "delete"
  3603. * (3) "visible"
  3604. * (4) "invisible"
  3605. * @param int $user_id id of the editing/adding user
  3606. * @param array $groupInfo must include group.iid/group.od
  3607. * @param int $to_user_id id of the intended user (always has priority over $to_group_id !), only relevant for $type (1)
  3608. * @param string $start_visible 0000-00-00 00:00:00 format
  3609. * @param string $end_visible 0000-00-00 00:00:00 format
  3610. * @param int $session_id The session ID, if any, otherwise will default to 0
  3611. *
  3612. * @return bool false if update fails
  3613. *
  3614. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>, Ghent University
  3615. *
  3616. * @version January 2005
  3617. * @desc update the item_properties table (if entry not exists, insert) of the course
  3618. */
  3619. function api_item_property_update(
  3620. $_course,
  3621. $tool,
  3622. $item_id,
  3623. $last_edit_type,
  3624. $user_id,
  3625. $groupInfo = [],
  3626. $to_user_id = null,
  3627. $start_visible = '',
  3628. $end_visible = '',
  3629. $session_id = 0
  3630. ) {
  3631. if (empty($_course)) {
  3632. return false;
  3633. }
  3634. $course_id = $_course['real_id'];
  3635. if (empty($course_id)) {
  3636. return false;
  3637. }
  3638. $to_group_id = 0;
  3639. if (!empty($groupInfo) && isset($groupInfo['iid'])) {
  3640. $to_group_id = (int) $groupInfo['iid'];
  3641. }
  3642. $em = Database::getManager();
  3643. // Definition of variables.
  3644. $tool = Database::escape_string($tool);
  3645. $item_id = (int) $item_id;
  3646. $lastEditTypeNoFilter = $last_edit_type;
  3647. $last_edit_type = Database::escape_string($last_edit_type);
  3648. $user_id = (int) $user_id;
  3649. $startVisible = "NULL";
  3650. if (!empty($start_visible)) {
  3651. $start_visible = Database::escape_string($start_visible);
  3652. $startVisible = "'$start_visible'";
  3653. }
  3654. $endVisible = "NULL";
  3655. if (!empty($end_visible)) {
  3656. $end_visible = Database::escape_string($end_visible);
  3657. $endVisible = "'$end_visible'";
  3658. }
  3659. $to_filter = '';
  3660. $time = api_get_utc_datetime();
  3661. if (!empty($session_id)) {
  3662. $session_id = (int) $session_id;
  3663. } else {
  3664. $session_id = api_get_session_id();
  3665. }
  3666. // Definition of tables.
  3667. $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3668. if ($to_user_id <= 0) {
  3669. $to_user_id = null; // No to_user_id set
  3670. }
  3671. if (!is_null($to_user_id)) {
  3672. // $to_user_id has more priority than $to_group_id
  3673. $to_user_id = (int) $to_user_id;
  3674. $to_field = 'to_user_id';
  3675. $to_value = $to_user_id;
  3676. } else {
  3677. // $to_user_id is not set.
  3678. $to_field = 'to_group_id';
  3679. $to_value = $to_group_id;
  3680. }
  3681. $toValueCondition = empty($to_value) ? 'NULL' : "'$to_value'";
  3682. // Set filters for $to_user_id and $to_group_id, with priority for $to_user_id
  3683. $condition_session = " AND session_id = $session_id ";
  3684. if (empty($session_id)) {
  3685. $condition_session = ' AND (session_id = 0 OR session_id IS NULL) ';
  3686. }
  3687. $filter = " c_id = $course_id AND tool = '$tool' AND ref = $item_id $condition_session ";
  3688. // Check whether $to_user_id and $to_group_id are passed in the function call.
  3689. // If both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
  3690. if (is_null($to_user_id) && is_null($to_group_id)) {
  3691. $to_group_id = 0;
  3692. }
  3693. if (!is_null($to_user_id)) {
  3694. // Set filter to intended user.
  3695. $to_filter = " AND to_user_id = $to_user_id $condition_session";
  3696. } else {
  3697. // Set filter to intended group.
  3698. if (($to_group_id != 0) && $to_group_id == strval(intval($to_group_id))) {
  3699. $to_filter = " AND to_group_id = $to_group_id $condition_session";
  3700. }
  3701. }
  3702. // Adding filter if set.
  3703. $filter .= $to_filter;
  3704. // Update if possible
  3705. $set_type = '';
  3706. switch ($lastEditTypeNoFilter) {
  3707. case 'delete':
  3708. // delete = make item only visible for the platform admin.
  3709. $visibility = '2';
  3710. if (!empty($session_id)) {
  3711. // Check whether session id already exist into item_properties for updating visibility or add it.
  3712. $sql = "SELECT session_id FROM $tableItemProperty
  3713. WHERE
  3714. c_id = $course_id AND
  3715. tool = '$tool' AND
  3716. ref = $item_id AND
  3717. session_id = $session_id";
  3718. $rs = Database::query($sql);
  3719. if (Database::num_rows($rs) > 0) {
  3720. $sql = "UPDATE $tableItemProperty
  3721. SET lastedit_type = '".str_replace('_', '', ucwords($tool))."Deleted',
  3722. lastedit_date = '$time',
  3723. lastedit_user_id = $user_id,
  3724. visibility = $visibility,
  3725. session_id = $session_id $set_type
  3726. WHERE $filter";
  3727. $result = Database::query($sql);
  3728. } else {
  3729. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id)
  3730. VALUES ($course_id, '$tool',$item_id, '$time', $user_id, '$time', '$last_edit_type',$user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3731. $result = Database::query($sql);
  3732. $id = Database::insert_id();
  3733. if ($id) {
  3734. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3735. Database::query($sql);
  3736. }
  3737. }
  3738. } else {
  3739. $sql = "UPDATE $tableItemProperty
  3740. SET
  3741. lastedit_type='".str_replace('_', '', ucwords($tool))."Deleted',
  3742. lastedit_date='$time',
  3743. lastedit_user_id = $user_id,
  3744. visibility = $visibility $set_type
  3745. WHERE $filter";
  3746. $result = Database::query($sql);
  3747. }
  3748. break;
  3749. case 'visible': // Change item to visible.
  3750. $visibility = '1';
  3751. if (!empty($session_id)) {
  3752. // Check whether session id already exist into item_properties for updating visibility or add it.
  3753. $sql = "SELECT session_id FROM $tableItemProperty
  3754. WHERE
  3755. c_id = $course_id AND
  3756. tool = '$tool' AND
  3757. ref = $item_id AND
  3758. session_id = $session_id";
  3759. $rs = Database::query($sql);
  3760. if (Database::num_rows($rs) > 0) {
  3761. $sql = "UPDATE $tableItemProperty
  3762. SET
  3763. lastedit_type='".str_replace('_', '', ucwords($tool))."Visible',
  3764. lastedit_date='$time',
  3765. lastedit_user_id = $user_id,
  3766. visibility = $visibility,
  3767. session_id = $session_id $set_type
  3768. WHERE $filter";
  3769. $result = Database::query($sql);
  3770. } else {
  3771. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id)
  3772. VALUES ($course_id, '$tool', $item_id, '$time', $user_id, '$time', '$last_edit_type', $user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3773. $result = Database::query($sql);
  3774. $id = Database::insert_id();
  3775. if ($id) {
  3776. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3777. Database::query($sql);
  3778. }
  3779. }
  3780. } else {
  3781. $sql = "UPDATE $tableItemProperty
  3782. SET
  3783. lastedit_type='".str_replace('_', '', ucwords($tool))."Visible',
  3784. lastedit_date='$time',
  3785. lastedit_user_id = $user_id,
  3786. visibility = $visibility $set_type
  3787. WHERE $filter";
  3788. $result = Database::query($sql);
  3789. }
  3790. break;
  3791. case 'invisible': // Change item to invisible.
  3792. $visibility = '0';
  3793. if (!empty($session_id)) {
  3794. // Check whether session id already exist into item_properties for updating visibility or add it
  3795. $sql = "SELECT session_id FROM $tableItemProperty
  3796. WHERE
  3797. c_id = $course_id AND
  3798. tool = '$tool' AND
  3799. ref = $item_id AND
  3800. session_id = $session_id";
  3801. $rs = Database::query($sql);
  3802. if (Database::num_rows($rs) > 0) {
  3803. $sql = "UPDATE $tableItemProperty
  3804. SET
  3805. lastedit_type = '".str_replace('_', '', ucwords($tool))."Invisible',
  3806. lastedit_date = '$time',
  3807. lastedit_user_id = $user_id,
  3808. visibility = $visibility,
  3809. session_id = $session_id $set_type
  3810. WHERE $filter";
  3811. $result = Database::query($sql);
  3812. } else {
  3813. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, session_id)
  3814. VALUES ($course_id, '$tool', $item_id, '$time', $user_id, '$time', '$last_edit_type', $user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3815. $result = Database::query($sql);
  3816. $id = Database::insert_id();
  3817. if ($id) {
  3818. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3819. Database::query($sql);
  3820. }
  3821. }
  3822. } else {
  3823. $sql = "UPDATE $tableItemProperty
  3824. SET
  3825. lastedit_type = '".str_replace('_', '', ucwords($tool))."Invisible',
  3826. lastedit_date = '$time',
  3827. lastedit_user_id = $user_id,
  3828. visibility = $visibility $set_type
  3829. WHERE $filter";
  3830. $result = Database::query($sql);
  3831. }
  3832. break;
  3833. default: // The item will be added or updated.
  3834. $set_type = ", lastedit_type = '$last_edit_type' ";
  3835. $visibility = '1';
  3836. //$filter .= $to_filter; already added
  3837. $sql = "UPDATE $tableItemProperty
  3838. SET
  3839. lastedit_date = '$time',
  3840. lastedit_user_id = $user_id $set_type
  3841. WHERE $filter";
  3842. $result = Database::query($sql);
  3843. }
  3844. // Insert if no entries are found (can only happen in case of $last_edit_type switch is 'default').
  3845. if ($result == false || Database::affected_rows($result) == 0) {
  3846. $objCourse = $em->find('ChamiloCoreBundle:Course', intval($course_id));
  3847. $objTime = new DateTime('now', new DateTimeZone('UTC'));
  3848. $objUser = api_get_user_entity($user_id);
  3849. if (empty($objUser)) {
  3850. // Use anonymous
  3851. $user_id = api_get_anonymous_id();
  3852. $objUser = api_get_user_entity($user_id);
  3853. }
  3854. $objGroup = null;
  3855. if (!empty($to_group_id)) {
  3856. $objGroup = $em->find('ChamiloCourseBundle:CGroupInfo', $to_group_id);
  3857. }
  3858. $objToUser = api_get_user_entity($to_user_id);
  3859. $objSession = $em->find('ChamiloCoreBundle:Session', intval($session_id));
  3860. $startVisibleDate = !empty($start_visible) ? new DateTime($start_visible, new DateTimeZone('UTC')) : null;
  3861. $endVisibleDate = !empty($endVisibleDate) ? new DateTime($endVisibleDate, new DateTimeZone('UTC')) : null;
  3862. $cItemProperty = new CItemProperty($objCourse);
  3863. $cItemProperty
  3864. ->setTool($tool)
  3865. ->setRef($item_id)
  3866. ->setInsertDate($objTime)
  3867. ->setInsertUser($objUser)
  3868. ->setLasteditDate($objTime)
  3869. ->setLasteditType($last_edit_type)
  3870. ->setGroup($objGroup)
  3871. ->setToUser($objToUser)
  3872. ->setVisibility($visibility)
  3873. ->setStartVisible($startVisibleDate)
  3874. ->setEndVisible($endVisibleDate)
  3875. ->setSession($objSession);
  3876. $em->persist($cItemProperty);
  3877. $em->flush();
  3878. $id = $cItemProperty->getIid();
  3879. if ($id) {
  3880. $cItemProperty->setId($id);
  3881. $em->merge($cItemProperty);
  3882. $em->flush();
  3883. return false;
  3884. }
  3885. }
  3886. return true;
  3887. }
  3888. /**
  3889. * Gets item property by tool.
  3890. *
  3891. * @param string course code
  3892. * @param string tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3893. * @param int id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  3894. * @param int $session_id
  3895. * @param string $tool
  3896. * @param string $course_code
  3897. *
  3898. * @return array All fields from c_item_property (all rows found) or empty array
  3899. */
  3900. function api_get_item_property_by_tool($tool, $course_code, $session_id = null)
  3901. {
  3902. $course_info = api_get_course_info($course_code);
  3903. $tool = Database::escape_string($tool);
  3904. // Definition of tables.
  3905. $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3906. $session_id = (int) $session_id;
  3907. $session_condition = ' AND session_id = '.$session_id;
  3908. if (empty($session_id)) {
  3909. $session_condition = " AND (session_id = 0 OR session_id IS NULL) ";
  3910. }
  3911. $course_id = $course_info['real_id'];
  3912. $sql = "SELECT * FROM $item_property_table
  3913. WHERE
  3914. c_id = $course_id AND
  3915. tool = '$tool'
  3916. $session_condition ";
  3917. $rs = Database::query($sql);
  3918. $list = [];
  3919. if (Database::num_rows($rs) > 0) {
  3920. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  3921. $list[] = $row;
  3922. }
  3923. }
  3924. return $list;
  3925. }
  3926. /**
  3927. * Gets item property by tool and user.
  3928. *
  3929. * @param int $userId
  3930. * @param int $tool
  3931. * @param int $courseId
  3932. * @param int $session_id
  3933. *
  3934. * @return array
  3935. */
  3936. function api_get_item_property_list_by_tool_by_user(
  3937. $userId,
  3938. $tool,
  3939. $courseId,
  3940. $session_id = 0
  3941. ) {
  3942. $userId = intval($userId);
  3943. $tool = Database::escape_string($tool);
  3944. $session_id = intval($session_id);
  3945. $courseId = intval($courseId);
  3946. // Definition of tables.
  3947. $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3948. $session_condition = ' AND session_id = '.$session_id;
  3949. if (empty($session_id)) {
  3950. $session_condition = " AND (session_id = 0 OR session_id IS NULL) ";
  3951. }
  3952. $sql = "SELECT * FROM $item_property_table
  3953. WHERE
  3954. insert_user_id = $userId AND
  3955. c_id = $courseId AND
  3956. tool = '$tool'
  3957. $session_condition ";
  3958. $rs = Database::query($sql);
  3959. $list = [];
  3960. if (Database::num_rows($rs) > 0) {
  3961. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  3962. $list[] = $row;
  3963. }
  3964. }
  3965. return $list;
  3966. }
  3967. /**
  3968. * Gets item property id from tool of a course.
  3969. *
  3970. * @param string $course_code course code
  3971. * @param string $tool tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3972. * @param int $ref id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  3973. * @param int $sessionId Session ID (optional)
  3974. *
  3975. * @return int
  3976. */
  3977. function api_get_item_property_id($course_code, $tool, $ref, $sessionId = 0)
  3978. {
  3979. $course_info = api_get_course_info($course_code);
  3980. $tool = Database::escape_string($tool);
  3981. $ref = (int) $ref;
  3982. // Definition of tables.
  3983. $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3984. $course_id = $course_info['real_id'];
  3985. $sessionId = (int) $sessionId;
  3986. $sessionCondition = " AND session_id = $sessionId ";
  3987. if (empty($sessionId)) {
  3988. $sessionCondition = ' AND (session_id = 0 OR session_id IS NULL) ';
  3989. }
  3990. $sql = "SELECT id FROM $tableItemProperty
  3991. WHERE
  3992. c_id = $course_id AND
  3993. tool = '$tool' AND
  3994. ref = $ref
  3995. $sessionCondition";
  3996. $rs = Database::query($sql);
  3997. $item_property_id = '';
  3998. if (Database::num_rows($rs) > 0) {
  3999. $row = Database::fetch_array($rs);
  4000. $item_property_id = $row['id'];
  4001. }
  4002. return $item_property_id;
  4003. }
  4004. /**
  4005. * Inserts a record in the track_e_item_property table (No update).
  4006. *
  4007. * @param string $tool
  4008. * @param int $ref
  4009. * @param string $title
  4010. * @param string $content
  4011. * @param int $progress
  4012. *
  4013. * @return bool|int
  4014. */
  4015. function api_track_item_property_update($tool, $ref, $title, $content, $progress)
  4016. {
  4017. $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  4018. $course_id = api_get_course_int_id(); //numeric
  4019. $course_code = api_get_course_id(); //alphanumeric
  4020. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  4021. if (!empty($item_property_id)) {
  4022. $sql = "INSERT IGNORE INTO $tbl_stats_item_property SET
  4023. course_id = '$course_id',
  4024. item_property_id = '$item_property_id',
  4025. title = '".Database::escape_string($title)."',
  4026. content = '".Database::escape_string($content)."',
  4027. progress = '".intval($progress)."',
  4028. lastedit_date = '".api_get_utc_datetime()."',
  4029. lastedit_user_id = '".api_get_user_id()."',
  4030. session_id = '".api_get_session_id()."'";
  4031. $result = Database::query($sql);
  4032. $affected_rows = Database::affected_rows($result);
  4033. return $affected_rows;
  4034. }
  4035. return false;
  4036. }
  4037. /**
  4038. * @param string $tool
  4039. * @param int $ref
  4040. *
  4041. * @return array|resource
  4042. */
  4043. function api_get_track_item_property_history($tool, $ref)
  4044. {
  4045. $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  4046. $course_id = api_get_course_int_id(); //numeric
  4047. $course_code = api_get_course_id(); //alphanumeric
  4048. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  4049. $sql = "SELECT * FROM $tbl_stats_item_property
  4050. WHERE item_property_id = $item_property_id AND course_id = $course_id
  4051. ORDER BY lastedit_date DESC";
  4052. $result = Database::query($sql);
  4053. if ($result === false or $result === null) {
  4054. $result = [];
  4055. } else {
  4056. $result = Database::store_result($result, 'ASSOC');
  4057. }
  4058. return $result;
  4059. }
  4060. /**
  4061. * Gets item property data from tool of a course id.
  4062. *
  4063. * @param int $course_id
  4064. * @param string $tool tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  4065. * @param int $ref id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  4066. * @param int $session_id
  4067. * @param int $groupId
  4068. *
  4069. * @return array with all fields from c_item_property, empty array if not found or false if course could not be found
  4070. */
  4071. function api_get_item_property_info($course_id, $tool, $ref, $session_id = 0, $groupId = 0)
  4072. {
  4073. $courseInfo = api_get_course_info_by_id($course_id);
  4074. if (empty($courseInfo)) {
  4075. return false;
  4076. }
  4077. $tool = Database::escape_string($tool);
  4078. $course_id = $courseInfo['real_id'];
  4079. $ref = (int) $ref;
  4080. $session_id = (int) $session_id;
  4081. $sessionCondition = " session_id = $session_id";
  4082. if (empty($session_id)) {
  4083. $sessionCondition = ' (session_id = 0 OR session_id IS NULL) ';
  4084. }
  4085. // Definition of tables.
  4086. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  4087. $sql = "SELECT * FROM $table
  4088. WHERE
  4089. c_id = $course_id AND
  4090. tool = '$tool' AND
  4091. ref = $ref AND
  4092. $sessionCondition ";
  4093. if (!empty($groupId)) {
  4094. $groupId = (int) $groupId;
  4095. $sql .= " AND to_group_id = $groupId ";
  4096. }
  4097. $rs = Database::query($sql);
  4098. $row = [];
  4099. if (Database::num_rows($rs) > 0) {
  4100. $row = Database::fetch_array($rs, 'ASSOC');
  4101. }
  4102. return $row;
  4103. }
  4104. /**
  4105. * Displays a combo box so the user can select his/her preferred language.
  4106. *
  4107. * @param string The desired name= value for the select
  4108. * @param bool Whether we use the JQuery Chozen library or not
  4109. * (in some cases, like the indexing language picker, it can alter the presentation)
  4110. *
  4111. * @return string
  4112. */
  4113. function api_get_languages_combo($name = 'language')
  4114. {
  4115. $ret = '';
  4116. $platformLanguage = api_get_setting('platformLanguage');
  4117. // Retrieve a complete list of all the languages.
  4118. $language_list = api_get_languages();
  4119. if (count($language_list['name']) < 2) {
  4120. return $ret;
  4121. }
  4122. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  4123. if (isset($_SESSION['user_language_choice'])) {
  4124. $default = $_SESSION['user_language_choice'];
  4125. } else {
  4126. $default = $platformLanguage;
  4127. }
  4128. $languages = $language_list['name'];
  4129. $folder = $language_list['folder'];
  4130. $ret .= '<select name="'.$name.'" id="language_chosen" class="selectpicker form-control">';
  4131. foreach ($languages as $key => $value) {
  4132. if ($folder[$key] == $default) {
  4133. $selected = ' selected="selected"';
  4134. } else {
  4135. $selected = '';
  4136. }
  4137. $ret .= sprintf('<option value=%s" %s>%s</option>', $folder[$key], $selected, $value);
  4138. }
  4139. $ret .= '</select>';
  4140. return $ret;
  4141. }
  4142. /**
  4143. * Displays a form (drop down menu) so the user can select his/her preferred language.
  4144. * The form works with or without javascript.
  4145. *
  4146. * @param bool Hide form if only one language available (defaults to false = show the box anyway)
  4147. * @param bool $showAsButton
  4148. *
  4149. * @return string|null Display the box directly
  4150. */
  4151. function api_display_language_form($hide_if_no_choice = false, $showAsButton = false)
  4152. {
  4153. // Retrieve a complete list of all the languages.
  4154. $language_list = api_get_languages();
  4155. if (count($language_list['name']) <= 1 && $hide_if_no_choice) {
  4156. return; //don't show any form
  4157. }
  4158. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  4159. if (isset($_SESSION['user_language_choice'])) {
  4160. $user_selected_language = $_SESSION['user_language_choice'];
  4161. }
  4162. if (empty($user_selected_language)) {
  4163. $user_selected_language = api_get_setting('platformLanguage');
  4164. }
  4165. $currentLanguageId = api_get_language_id($user_selected_language);
  4166. $currentLanguageInfo = api_get_language_info($currentLanguageId);
  4167. $countryCode = languageToCountryIsoCode($currentLanguageInfo['isocode']);
  4168. $url = api_get_self();
  4169. if ($showAsButton) {
  4170. $html = '<div class="btn-group">
  4171. <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
  4172. <span class="flag-icon flag-icon-'.$countryCode.'"></span>
  4173. '.$currentLanguageInfo['original_name'].'
  4174. <span class="caret">
  4175. </span>
  4176. </button>';
  4177. } else {
  4178. $html = '
  4179. <a href="'.$url.'" class="dropdown-toggle" data-toggle="dropdown" role="button">
  4180. <span class="flag-icon flag-icon-'.$countryCode.'"></span>
  4181. '.$currentLanguageInfo['original_name'].'
  4182. <span class="caret"></span>
  4183. </a>
  4184. ';
  4185. }
  4186. $html .= '<ul class="dropdown-menu" role="menu">';
  4187. foreach ($language_list['all'] as $key => $data) {
  4188. $urlLink = $url.'?language='.$data['english_name'];
  4189. $html .= '<li><a href="'.$urlLink.'"><span class="flag-icon flag-icon-'.languageToCountryIsoCode($data['isocode']).'"></span> '.$data['original_name'].'</a></li>';
  4190. }
  4191. $html .= '</ul>';
  4192. if ($showAsButton) {
  4193. $html .= '</div>';
  4194. }
  4195. return $html;
  4196. }
  4197. /**
  4198. * @param string $languageIsoCode
  4199. *
  4200. * @return string
  4201. */
  4202. function languageToCountryIsoCode($languageIsoCode)
  4203. {
  4204. $allow = api_get_configuration_value('language_flags_by_country');
  4205. // @todo save in DB
  4206. switch ($languageIsoCode) {
  4207. case 'ko':
  4208. $country = 'kr';
  4209. break;
  4210. case 'ja':
  4211. $country = 'jp';
  4212. break;
  4213. case 'ca':
  4214. $country = 'es';
  4215. if ($allow) {
  4216. $country = 'catalan';
  4217. }
  4218. break;
  4219. case 'gl': // galego
  4220. $country = 'es';
  4221. if ($allow) {
  4222. $country = 'galician';
  4223. }
  4224. break;
  4225. case 'ka':
  4226. $country = 'ge';
  4227. break;
  4228. case 'sl':
  4229. $country = 'si';
  4230. break;
  4231. case 'eu': // Euskera
  4232. $country = 'es';
  4233. if ($allow) {
  4234. $country = 'basque';
  4235. }
  4236. break;
  4237. case 'cs':
  4238. $country = 'cz';
  4239. break;
  4240. case 'el':
  4241. $country = 'ae';
  4242. break;
  4243. case 'ar':
  4244. $country = 'ae';
  4245. break;
  4246. case 'en':
  4247. $country = 'gb';
  4248. break;
  4249. case 'he':
  4250. $country = 'il';
  4251. break;
  4252. case 'uk': // Ukraine
  4253. $country = 'ua';
  4254. break;
  4255. case 'da':
  4256. $country = 'dk';
  4257. break;
  4258. case 'pt-BR':
  4259. $country = 'br';
  4260. break;
  4261. case 'qu':
  4262. $country = 'pe';
  4263. break;
  4264. case 'sv':
  4265. $country = 'se';
  4266. break;
  4267. case 'zh-TW':
  4268. case 'zh':
  4269. $country = 'cn';
  4270. break;
  4271. default:
  4272. $country = $languageIsoCode;
  4273. break;
  4274. }
  4275. $country = strtolower($country);
  4276. return $country;
  4277. }
  4278. /**
  4279. * Returns a list of all the languages that are made available by the admin.
  4280. *
  4281. * @return array An array with all languages. Structure of the array is
  4282. * array['name'] = An array with the name of every language
  4283. * array['folder'] = An array with the corresponding names of the language-folders in the filesystem
  4284. */
  4285. function api_get_languages()
  4286. {
  4287. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  4288. $sql = "SELECT * FROM $tbl_language WHERE available='1'
  4289. ORDER BY original_name ASC";
  4290. $result = Database::query($sql);
  4291. $language_list = [];
  4292. while ($row = Database::fetch_array($result)) {
  4293. $language_list['name'][] = $row['original_name'];
  4294. $language_list['folder'][] = $row['dokeos_folder'];
  4295. $language_list['all'][] = $row;
  4296. }
  4297. return $language_list;
  4298. }
  4299. /**
  4300. * Returns a list of all the languages that are made available by the admin.
  4301. *
  4302. * @return array
  4303. */
  4304. function api_get_languages_to_array()
  4305. {
  4306. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  4307. $sql = "SELECT * FROM $tbl_language WHERE available='1' ORDER BY original_name ASC";
  4308. $result = Database::query($sql);
  4309. $languages = [];
  4310. while ($row = Database::fetch_array($result)) {
  4311. $languages[$row['dokeos_folder']] = $row['original_name'];
  4312. }
  4313. return $languages;
  4314. }
  4315. /**
  4316. * Returns the id (the database id) of a language.
  4317. *
  4318. * @param string language name (the corresponding name of the language-folder in the filesystem)
  4319. *
  4320. * @return int id of the language
  4321. */
  4322. function api_get_language_id($language)
  4323. {
  4324. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  4325. if (empty($language)) {
  4326. return null;
  4327. }
  4328. $language = Database::escape_string($language);
  4329. $sql = "SELECT id FROM $tbl_language
  4330. WHERE dokeos_folder = '$language' LIMIT 1";
  4331. $result = Database::query($sql);
  4332. $row = Database::fetch_array($result);
  4333. return $row['id'];
  4334. }
  4335. /**
  4336. * Gets language of the requested type for the current user. Types are :
  4337. * user_profil_lang : profile language of current user
  4338. * user_select_lang : language selected by user at login
  4339. * course_lang : language of the current course
  4340. * platform_lang : default platform language.
  4341. *
  4342. * @param string $lang_type
  4343. *
  4344. * @return string
  4345. */
  4346. function api_get_language_from_type($lang_type)
  4347. {
  4348. $return = false;
  4349. switch ($lang_type) {
  4350. case 'platform_lang':
  4351. $temp_lang = api_get_setting('platformLanguage');
  4352. if (!empty($temp_lang)) {
  4353. $return = $temp_lang;
  4354. }
  4355. break;
  4356. case 'user_profil_lang':
  4357. $_user = api_get_user_info();
  4358. if (isset($_user['language']) && !empty($_user['language'])) {
  4359. $return = $_user['language'];
  4360. }
  4361. break;
  4362. case 'user_selected_lang':
  4363. if (isset($_SESSION['user_language_choice']) && !empty($_SESSION['user_language_choice'])) {
  4364. $return = $_SESSION['user_language_choice'];
  4365. }
  4366. break;
  4367. case 'course_lang':
  4368. global $_course;
  4369. $cidReq = null;
  4370. if (empty($_course)) {
  4371. // Code modified because the local.inc.php file it's declarated after this work
  4372. // causing the function api_get_course_info() returns a null value
  4373. $cidReq = isset($_GET["cidReq"]) ? Database::escape_string($_GET["cidReq"]) : null;
  4374. $cDir = (!empty($_GET['cDir']) ? $_GET['cDir'] : null);
  4375. if (empty($cidReq) && !empty($cDir)) {
  4376. $c = CourseManager::getCourseCodeFromDirectory($cDir);
  4377. if ($c) {
  4378. $cidReq = $c;
  4379. }
  4380. }
  4381. }
  4382. $_course = api_get_course_info($cidReq);
  4383. if (isset($_course['language']) && !empty($_course['language'])) {
  4384. $return = $_course['language'];
  4385. $showCourseInUserLanguage = api_get_course_setting('show_course_in_user_language');
  4386. if ($showCourseInUserLanguage == 1) {
  4387. $userInfo = api_get_user_info();
  4388. if (isset($userInfo['language'])) {
  4389. $return = $userInfo['language'];
  4390. }
  4391. }
  4392. }
  4393. break;
  4394. default:
  4395. $return = false;
  4396. break;
  4397. }
  4398. return $return;
  4399. }
  4400. /**
  4401. * Get the language information by its id.
  4402. *
  4403. * @param int $languageId
  4404. *
  4405. * @throws Exception
  4406. *
  4407. * @return array
  4408. */
  4409. function api_get_language_info($languageId)
  4410. {
  4411. if (empty($languageId)) {
  4412. return [];
  4413. }
  4414. $language = Database::getManager()
  4415. ->find('ChamiloCoreBundle:Language', $languageId);
  4416. if (!$language) {
  4417. return [];
  4418. }
  4419. return [
  4420. 'id' => $language->getId(),
  4421. 'original_name' => $language->getOriginalName(),
  4422. 'english_name' => $language->getEnglishName(),
  4423. 'isocode' => $language->getIsocode(),
  4424. 'dokeos_folder' => $language->getDokeosFolder(),
  4425. 'available' => $language->getAvailable(),
  4426. 'parent_id' => $language->getParent() ? $language->getParent()->getId() : null,
  4427. ];
  4428. }
  4429. /**
  4430. * Returns the name of the visual (CSS) theme to be applied on the current page.
  4431. * The returned name depends on the platform, course or user -wide settings.
  4432. *
  4433. * @return string The visual theme's name, it is the name of a folder inside web/css/themes
  4434. */
  4435. function api_get_visual_theme()
  4436. {
  4437. static $visual_theme;
  4438. if (!isset($visual_theme)) {
  4439. // Get style directly from DB
  4440. $styleFromDatabase = api_get_settings_params_simple(
  4441. [
  4442. 'variable = ? AND access_url = ?' => [
  4443. 'stylesheets',
  4444. api_get_current_access_url_id(),
  4445. ],
  4446. ]
  4447. );
  4448. if ($styleFromDatabase) {
  4449. $platform_theme = $styleFromDatabase['selected_value'];
  4450. } else {
  4451. $platform_theme = api_get_setting('stylesheets');
  4452. }
  4453. // Platform's theme.
  4454. $visual_theme = $platform_theme;
  4455. if (api_get_setting('user_selected_theme') == 'true') {
  4456. $user_info = api_get_user_info();
  4457. if (isset($user_info['theme'])) {
  4458. $user_theme = $user_info['theme'];
  4459. if (!empty($user_theme)) {
  4460. $visual_theme = $user_theme;
  4461. // User's theme.
  4462. }
  4463. }
  4464. }
  4465. $course_id = api_get_course_id();
  4466. if (!empty($course_id)) {
  4467. if (api_get_setting('allow_course_theme') == 'true') {
  4468. $course_theme = api_get_course_setting('course_theme', $course_id);
  4469. if (!empty($course_theme) && $course_theme != -1) {
  4470. if (!empty($course_theme)) {
  4471. // Course's theme.
  4472. $visual_theme = $course_theme;
  4473. }
  4474. }
  4475. $allow_lp_theme = api_get_course_setting('allow_learning_path_theme');
  4476. if ($allow_lp_theme == 1) {
  4477. global $lp_theme_css, $lp_theme_config;
  4478. // These variables come from the file lp_controller.php.
  4479. if (!$lp_theme_config) {
  4480. if (!empty($lp_theme_css)) {
  4481. // LP's theme.
  4482. $visual_theme = $lp_theme_css;
  4483. }
  4484. }
  4485. }
  4486. }
  4487. }
  4488. if (empty($visual_theme)) {
  4489. $visual_theme = 'chamilo';
  4490. }
  4491. global $lp_theme_log;
  4492. if ($lp_theme_log) {
  4493. $visual_theme = $platform_theme;
  4494. }
  4495. }
  4496. return $visual_theme;
  4497. }
  4498. /**
  4499. * Returns a list of CSS themes currently available in the CSS folder
  4500. * The folder must have a default.css file.
  4501. *
  4502. * @param bool $getOnlyThemeFromVirtualInstance Used by the vchamilo plugin
  4503. *
  4504. * @return array list of themes directories from the css folder
  4505. * Note: Directory names (names of themes) in the file system should contain ASCII-characters only
  4506. */
  4507. function api_get_themes($getOnlyThemeFromVirtualInstance = false)
  4508. {
  4509. // This configuration value is set by the vchamilo plugin
  4510. $virtualTheme = api_get_configuration_value('virtual_css_theme_folder');
  4511. $readCssFolder = function ($dir) use ($virtualTheme) {
  4512. $finder = new Finder();
  4513. $themes = $finder->directories()->in($dir)->depth(0)->sortByName();
  4514. $list = [];
  4515. /** @var Symfony\Component\Finder\SplFileInfo $theme */
  4516. foreach ($themes as $theme) {
  4517. $folder = $theme->getFilename();
  4518. // A theme folder is consider if there's a default.css file
  4519. if (!file_exists($theme->getPathname().'/default.css')) {
  4520. continue;
  4521. }
  4522. $name = ucwords(str_replace('_', ' ', $folder));
  4523. if ($folder == $virtualTheme) {
  4524. continue;
  4525. }
  4526. $list[$folder] = $name;
  4527. }
  4528. return $list;
  4529. };
  4530. $dir = api_get_path(SYS_CSS_PATH).'themes/';
  4531. $list = $readCssFolder($dir);
  4532. if (!empty($virtualTheme)) {
  4533. $newList = $readCssFolder($dir.'/'.$virtualTheme);
  4534. if ($getOnlyThemeFromVirtualInstance) {
  4535. return $newList;
  4536. }
  4537. $list = $list + $newList;
  4538. asort($list);
  4539. }
  4540. return $list;
  4541. }
  4542. /**
  4543. * Find the largest sort value in a given user_course_category
  4544. * This function is used when we are moving a course to a different category
  4545. * and also when a user subscribes to courses (the new course is added at the end of the main category.
  4546. *
  4547. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  4548. *
  4549. * @param int $user_course_category the id of the user_course_category
  4550. * @param int $user_id
  4551. *
  4552. * @return int the value of the highest sort of the user_course_category
  4553. */
  4554. function api_max_sort_value($user_course_category, $user_id)
  4555. {
  4556. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4557. $sql = "SELECT max(sort) as max_sort FROM $tbl_course_user
  4558. WHERE
  4559. user_id='".intval($user_id)."' AND
  4560. relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
  4561. user_course_cat='".intval($user_course_category)."'";
  4562. $result_max = Database::query($sql);
  4563. if (Database::num_rows($result_max) == 1) {
  4564. $row_max = Database::fetch_array($result_max);
  4565. return $row_max['max_sort'];
  4566. }
  4567. return 0;
  4568. }
  4569. /**
  4570. * Transforms a number of seconds in hh:mm:ss format.
  4571. *
  4572. * @author Julian Prud'homme
  4573. *
  4574. * @param int the number of seconds
  4575. *
  4576. * @return string the formated time
  4577. */
  4578. function api_time_to_hms($seconds, $space = ':')
  4579. {
  4580. // $seconds = -1 means that we have wrong data in the db.
  4581. if ($seconds == -1) {
  4582. return
  4583. get_lang('Unknown').
  4584. Display::return_icon(
  4585. 'info2.gif',
  4586. get_lang('WrongDatasForTimeSpentOnThePlatform'),
  4587. ['align' => 'absmiddle', 'hspace' => '3px']
  4588. );
  4589. }
  4590. // How many hours ?
  4591. $hours = floor($seconds / 3600);
  4592. // How many minutes ?
  4593. $min = floor(($seconds - ($hours * 3600)) / 60);
  4594. // How many seconds
  4595. $sec = floor($seconds - ($hours * 3600) - ($min * 60));
  4596. if ($hours < 10) {
  4597. $hours = "0$hours";
  4598. }
  4599. if ($sec < 10) {
  4600. $sec = "0$sec";
  4601. }
  4602. if ($min < 10) {
  4603. $min = "0$min";
  4604. }
  4605. return $hours.$space.$min.$space.$sec;
  4606. }
  4607. /* FILE SYSTEM RELATED FUNCTIONS */
  4608. /**
  4609. * Returns the permissions to be assigned to every newly created directory by the web-server.
  4610. * The return value is based on the platform administrator's setting
  4611. * "Administration > Configuration settings > Security > Permissions for new directories".
  4612. *
  4613. * @return int returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value
  4614. */
  4615. function api_get_permissions_for_new_directories()
  4616. {
  4617. static $permissions;
  4618. if (!isset($permissions)) {
  4619. $permissions = trim(api_get_setting('permissions_for_new_directories'));
  4620. // The default value 0777 is according to that in the platform administration panel after fresh system installation.
  4621. $permissions = octdec(!empty($permissions) ? $permissions : '0777');
  4622. }
  4623. return $permissions;
  4624. }
  4625. /**
  4626. * Returns the permissions to be assigned to every newly created directory by the web-server.
  4627. * The return value is based on the platform administrator's setting
  4628. * "Administration > Configuration settings > Security > Permissions for new files".
  4629. *
  4630. * @return int returns the permissions in the format
  4631. * "Owner-Group-Others, Read-Write-Execute", as an integer value
  4632. */
  4633. function api_get_permissions_for_new_files()
  4634. {
  4635. static $permissions;
  4636. if (!isset($permissions)) {
  4637. $permissions = trim(api_get_setting('permissions_for_new_files'));
  4638. // The default value 0666 is according to that in the platform
  4639. // administration panel after fresh system installation.
  4640. $permissions = octdec(!empty($permissions) ? $permissions : '0666');
  4641. }
  4642. return $permissions;
  4643. }
  4644. /**
  4645. * Deletes a file, or a folder and its contents.
  4646. *
  4647. * @author Aidan Lister <aidan@php.net>
  4648. *
  4649. * @version 1.0.3
  4650. *
  4651. * @param string $dirname Directory to delete
  4652. * @param bool Deletes only the content or not
  4653. * @param bool $strict if one folder/file fails stop the loop
  4654. *
  4655. * @return bool Returns TRUE on success, FALSE on failure
  4656. *
  4657. * @see http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
  4658. *
  4659. * @author Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
  4660. * @author Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
  4661. */
  4662. function rmdirr($dirname, $delete_only_content_in_folder = false, $strict = false)
  4663. {
  4664. $res = true;
  4665. // A sanity check.
  4666. if (!file_exists($dirname)) {
  4667. return false;
  4668. }
  4669. $php_errormsg = '';
  4670. // Simple delete for a file.
  4671. if (is_file($dirname) || is_link($dirname)) {
  4672. $res = unlink($dirname);
  4673. if ($res === false) {
  4674. error_log(__FILE__.' line '.__LINE__.': '.((bool) ini_get('track_errors') ? $php_errormsg : 'Error not recorded because track_errors is off in your php.ini'), 0);
  4675. }
  4676. return $res;
  4677. }
  4678. // Loop through the folder.
  4679. $dir = dir($dirname);
  4680. // A sanity check.
  4681. $is_object_dir = is_object($dir);
  4682. if ($is_object_dir) {
  4683. while (false !== $entry = $dir->read()) {
  4684. // Skip pointers.
  4685. if ($entry == '.' || $entry == '..') {
  4686. continue;
  4687. }
  4688. // Recurse.
  4689. if ($strict) {
  4690. $result = rmdirr("$dirname/$entry");
  4691. if ($result == false) {
  4692. $res = false;
  4693. break;
  4694. }
  4695. } else {
  4696. rmdirr("$dirname/$entry");
  4697. }
  4698. }
  4699. }
  4700. // Clean up.
  4701. if ($is_object_dir) {
  4702. $dir->close();
  4703. }
  4704. if ($delete_only_content_in_folder == false) {
  4705. $res = rmdir($dirname);
  4706. if ($res === false) {
  4707. error_log(__FILE__.' line '.__LINE__.': '.((bool) ini_get('track_errors') ? $php_errormsg : 'error not recorded because track_errors is off in your php.ini'), 0);
  4708. }
  4709. }
  4710. return $res;
  4711. }
  4712. // TODO: This function is to be simplified. File access modes to be implemented.
  4713. /**
  4714. * function adapted from a php.net comment
  4715. * copy recursively a folder.
  4716. *
  4717. * @param the source folder
  4718. * @param the dest folder
  4719. * @param an array of excluded file_name (without extension)
  4720. * @param copied_files the returned array of copied files
  4721. * @param string $source
  4722. * @param string $dest
  4723. */
  4724. function copyr($source, $dest, $exclude = [], $copied_files = [])
  4725. {
  4726. if (empty($dest)) {
  4727. return false;
  4728. }
  4729. // Simple copy for a file
  4730. if (is_file($source)) {
  4731. $path_info = pathinfo($source);
  4732. if (!in_array($path_info['filename'], $exclude)) {
  4733. copy($source, $dest);
  4734. }
  4735. return true;
  4736. } elseif (!is_dir($source)) {
  4737. //then source is not a dir nor a file, return
  4738. return false;
  4739. }
  4740. // Make destination directory.
  4741. if (!is_dir($dest)) {
  4742. mkdir($dest, api_get_permissions_for_new_directories());
  4743. }
  4744. // Loop through the folder.
  4745. $dir = dir($source);
  4746. while (false !== $entry = $dir->read()) {
  4747. // Skip pointers
  4748. if ($entry == '.' || $entry == '..') {
  4749. continue;
  4750. }
  4751. // Deep copy directories.
  4752. if ($dest !== "$source/$entry") {
  4753. $files = copyr("$source/$entry", "$dest/$entry", $exclude, $copied_files);
  4754. }
  4755. }
  4756. // Clean up.
  4757. $dir->close();
  4758. return true;
  4759. }
  4760. /**
  4761. * @todo: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach.
  4762. * Documentation header to be added here.
  4763. *
  4764. * @param string $pathname
  4765. * @param string $base_path_document
  4766. * @param int $session_id
  4767. *
  4768. * @return mixed True if directory already exists, false if a file already exists at
  4769. * the destination and null if everything goes according to plan
  4770. */
  4771. function copy_folder_course_session(
  4772. $pathname,
  4773. $base_path_document,
  4774. $session_id,
  4775. $course_info,
  4776. $document,
  4777. $source_course_id
  4778. ) {
  4779. $table = Database::get_course_table(TABLE_DOCUMENT);
  4780. $session_id = intval($session_id);
  4781. $source_course_id = intval($source_course_id);
  4782. // Check whether directory already exists.
  4783. if (is_dir($pathname) || empty($pathname)) {
  4784. return true;
  4785. }
  4786. // Ensure that a file with the same name does not already exist.
  4787. if (is_file($pathname)) {
  4788. trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
  4789. return false;
  4790. }
  4791. $course_id = $course_info['real_id'];
  4792. $folders = explode(DIRECTORY_SEPARATOR, str_replace($base_path_document.DIRECTORY_SEPARATOR, '', $pathname));
  4793. $new_pathname = $base_path_document;
  4794. $path = '';
  4795. foreach ($folders as $folder) {
  4796. $new_pathname .= DIRECTORY_SEPARATOR.$folder;
  4797. $path .= DIRECTORY_SEPARATOR.$folder;
  4798. if (!file_exists($new_pathname)) {
  4799. $path = Database::escape_string($path);
  4800. $sql = "SELECT * FROM $table
  4801. WHERE
  4802. c_id = $source_course_id AND
  4803. path = '$path' AND
  4804. filetype = 'folder' AND
  4805. session_id = '$session_id'";
  4806. $rs1 = Database::query($sql);
  4807. $num_rows = Database::num_rows($rs1);
  4808. if ($num_rows == 0) {
  4809. mkdir($new_pathname, api_get_permissions_for_new_directories());
  4810. // Insert new folder with destination session_id.
  4811. $params = [
  4812. 'c_id' => $course_id,
  4813. 'path' => $path,
  4814. 'comment' => $document->comment,
  4815. 'title' => basename($new_pathname),
  4816. 'filetype' => 'folder',
  4817. 'size' => '0',
  4818. 'session_id' => $session_id,
  4819. ];
  4820. $document_id = Database::insert($table, $params);
  4821. if ($document_id) {
  4822. $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
  4823. Database::query($sql);
  4824. api_item_property_update(
  4825. $course_info,
  4826. TOOL_DOCUMENT,
  4827. $document_id,
  4828. 'FolderCreated',
  4829. api_get_user_id(),
  4830. 0,
  4831. 0,
  4832. null,
  4833. null,
  4834. $session_id
  4835. );
  4836. }
  4837. }
  4838. }
  4839. } // en foreach
  4840. }
  4841. // TODO: chmodr() is a better name. Some corrections are needed. Documentation header to be added here.
  4842. /**
  4843. * @param string $path
  4844. */
  4845. function api_chmod_R($path, $filemode)
  4846. {
  4847. if (!is_dir($path)) {
  4848. return chmod($path, $filemode);
  4849. }
  4850. $handler = opendir($path);
  4851. while ($file = readdir($handler)) {
  4852. if ($file != '.' && $file != '..') {
  4853. $fullpath = "$path/$file";
  4854. if (!is_dir($fullpath)) {
  4855. if (!chmod($fullpath, $filemode)) {
  4856. return false;
  4857. }
  4858. } else {
  4859. if (!api_chmod_R($fullpath, $filemode)) {
  4860. return false;
  4861. }
  4862. }
  4863. }
  4864. }
  4865. closedir($handler);
  4866. return chmod($path, $filemode);
  4867. }
  4868. // TODO: Where the following function has been copy/pased from? There is no information about author and license. Style, coding conventions...
  4869. /**
  4870. * Parse info file format. (e.g: file.info).
  4871. *
  4872. * Files should use an ini-like format to specify values.
  4873. * White-space generally doesn't matter, except inside values.
  4874. * e.g.
  4875. *
  4876. * @verbatim
  4877. * key = value
  4878. * key = "value"
  4879. * key = 'value'
  4880. * key = "multi-line
  4881. *
  4882. * value"
  4883. * key = 'multi-line
  4884. *
  4885. * value'
  4886. * key
  4887. * =
  4888. * 'value'
  4889. * @endverbatim
  4890. *
  4891. * Arrays are created using a GET-like syntax:
  4892. *
  4893. * @verbatim
  4894. * key[] = "numeric array"
  4895. * key[index] = "associative array"
  4896. * key[index][] = "nested numeric array"
  4897. * key[index][index] = "nested associative array"
  4898. * @endverbatim
  4899. *
  4900. * PHP constants are substituted in, but only when used as the entire value:
  4901. *
  4902. * Comments should start with a semi-colon at the beginning of a line.
  4903. *
  4904. * This function is NOT for placing arbitrary module-specific settings. Use
  4905. * variable_get() and variable_set() for that.
  4906. *
  4907. * Information stored in the module.info file:
  4908. * - name: The real name of the module for display purposes.
  4909. * - description: A brief description of the module.
  4910. * - dependencies: An array of shortnames of other modules this module depends on.
  4911. * - package: The name of the package of modules this module belongs to.
  4912. *
  4913. * Example of .info file:
  4914. * <code>
  4915. * @verbatim
  4916. * name = Forum
  4917. * description = Enables threaded discussions about general topics.
  4918. * dependencies[] = taxonomy
  4919. * dependencies[] = comment
  4920. * package = Core - optional
  4921. * version = VERSION
  4922. * @endverbatim
  4923. * </code>
  4924. *
  4925. * @param string $filename
  4926. * The file we are parsing. Accepts file with relative or absolute path.
  4927. *
  4928. * @return
  4929. * The info array
  4930. */
  4931. function api_parse_info_file($filename)
  4932. {
  4933. $info = [];
  4934. if (!file_exists($filename)) {
  4935. return $info;
  4936. }
  4937. $data = file_get_contents($filename);
  4938. if (preg_match_all('
  4939. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  4940. ((?:
  4941. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  4942. \[[^\[\]]*\] # unless they are balanced and not nested
  4943. )+?)
  4944. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  4945. (?:
  4946. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  4947. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  4948. ([^\r\n]*?) # Non-quoted string
  4949. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  4950. @msx', $data, $matches, PREG_SET_ORDER)) {
  4951. $key = $value1 = $value2 = $value3 = '';
  4952. foreach ($matches as $match) {
  4953. // Fetch the key and value string.
  4954. $i = 0;
  4955. foreach (['key', 'value1', 'value2', 'value3'] as $var) {
  4956. $$var = isset($match[++$i]) ? $match[$i] : '';
  4957. }
  4958. $value = stripslashes(substr($value1, 1, -1)).stripslashes(substr($value2, 1, -1)).$value3;
  4959. // Parse array syntax.
  4960. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  4961. $last = array_pop($keys);
  4962. $parent = &$info;
  4963. // Create nested arrays.
  4964. foreach ($keys as $key) {
  4965. if ($key == '') {
  4966. $key = count($parent);
  4967. }
  4968. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  4969. $parent[$key] = [];
  4970. }
  4971. $parent = &$parent[$key];
  4972. }
  4973. // Handle PHP constants.
  4974. if (defined($value)) {
  4975. $value = constant($value);
  4976. }
  4977. // Insert actual value.
  4978. if ($last == '') {
  4979. $last = count($parent);
  4980. }
  4981. $parent[$last] = $value;
  4982. }
  4983. }
  4984. return $info;
  4985. }
  4986. /**
  4987. * Gets Chamilo version from the configuration files.
  4988. *
  4989. * @return string A string of type "1.8.4", or an empty string if the version could not be found
  4990. */
  4991. function api_get_version()
  4992. {
  4993. return (string) api_get_configuration_value('system_version');
  4994. }
  4995. /**
  4996. * Gets the software name (the name/brand of the Chamilo-based customized system).
  4997. *
  4998. * @return string
  4999. */
  5000. function api_get_software_name()
  5001. {
  5002. $name = api_get_configuration_value('software_name');
  5003. if (!empty($name)) {
  5004. return $name;
  5005. } else {
  5006. return 'Chamilo';
  5007. }
  5008. }
  5009. /**
  5010. * Checks whether status given in parameter exists in the platform.
  5011. *
  5012. * @param mixed the status (can be either int either string)
  5013. *
  5014. * @return bool if the status exists, else returns false
  5015. */
  5016. function api_status_exists($status_asked)
  5017. {
  5018. global $_status_list;
  5019. return in_array($status_asked, $_status_list) ? true : isset($_status_list[$status_asked]);
  5020. }
  5021. /**
  5022. * Checks whether status given in parameter exists in the platform. The function
  5023. * returns the status ID or false if it does not exist, but given the fact there
  5024. * is no "0" status, the return value can be checked against
  5025. * if(api_status_key()) to know if it exists.
  5026. *
  5027. * @param mixed The status (can be either int or string)
  5028. *
  5029. * @return mixed Status ID if exists, false otherwise
  5030. */
  5031. function api_status_key($status)
  5032. {
  5033. global $_status_list;
  5034. return isset($_status_list[$status]) ? $status : array_search($status, $_status_list);
  5035. }
  5036. /**
  5037. * Gets the status langvars list.
  5038. *
  5039. * @return string[] the list of status with their translations
  5040. */
  5041. function api_get_status_langvars()
  5042. {
  5043. return [
  5044. COURSEMANAGER => get_lang('Teacher', ''),
  5045. SESSIONADMIN => get_lang('SessionsAdmin', ''),
  5046. DRH => get_lang('Drh', ''),
  5047. STUDENT => get_lang('Student', ''),
  5048. ANONYMOUS => get_lang('Anonymous', ''),
  5049. STUDENT_BOSS => get_lang('RoleStudentBoss', ''),
  5050. INVITEE => get_lang('Invited'),
  5051. ];
  5052. }
  5053. /**
  5054. * The function that retrieves all the possible settings for a certain config setting.
  5055. *
  5056. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  5057. */
  5058. function api_get_settings_options($var)
  5059. {
  5060. $table_settings_options = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  5061. $var = Database::escape_string($var);
  5062. $sql = "SELECT * FROM $table_settings_options
  5063. WHERE variable = '$var'
  5064. ORDER BY id";
  5065. $result = Database::query($sql);
  5066. $settings_options_array = [];
  5067. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5068. $settings_options_array[] = $row;
  5069. }
  5070. return $settings_options_array;
  5071. }
  5072. /**
  5073. * @param array $params
  5074. */
  5075. function api_set_setting_option($params)
  5076. {
  5077. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  5078. if (empty($params['id'])) {
  5079. Database::insert($table, $params);
  5080. } else {
  5081. Database::update($table, $params, ['id = ? ' => $params['id']]);
  5082. }
  5083. }
  5084. /**
  5085. * @param array $params
  5086. */
  5087. function api_set_setting_simple($params)
  5088. {
  5089. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  5090. $url_id = api_get_current_access_url_id();
  5091. if (empty($params['id'])) {
  5092. $params['access_url'] = $url_id;
  5093. Database::insert($table, $params);
  5094. } else {
  5095. Database::update($table, $params, ['id = ? ' => [$params['id']]]);
  5096. }
  5097. }
  5098. /**
  5099. * @param int $id
  5100. */
  5101. function api_delete_setting_option($id)
  5102. {
  5103. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  5104. if (!empty($id)) {
  5105. Database::delete($table, ['id = ? ' => $id]);
  5106. }
  5107. }
  5108. /**
  5109. * Sets a platform configuration setting to a given value.
  5110. *
  5111. * @param string The variable we want to update
  5112. * @param string The value we want to record
  5113. * @param string The sub-variable if any (in most cases, this will remain null)
  5114. * @param string The category if any (in most cases, this will remain null)
  5115. * @param int The access_url for which this parameter is valid
  5116. * @param string $cat
  5117. *
  5118. * @return bool|null
  5119. */
  5120. function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url = 1)
  5121. {
  5122. if (empty($var)) {
  5123. return false;
  5124. }
  5125. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  5126. $var = Database::escape_string($var);
  5127. $value = Database::escape_string($value);
  5128. $access_url = (int) $access_url;
  5129. if (empty($access_url)) {
  5130. $access_url = 1;
  5131. }
  5132. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  5133. if (!empty($subvar)) {
  5134. $subvar = Database::escape_string($subvar);
  5135. $select .= " AND subkey = '$subvar'";
  5136. }
  5137. if (!empty($cat)) {
  5138. $cat = Database::escape_string($cat);
  5139. $select .= " AND category = '$cat'";
  5140. }
  5141. if ($access_url > 1) {
  5142. $select .= " AND access_url = $access_url";
  5143. } else {
  5144. $select .= " AND access_url = 1 ";
  5145. }
  5146. $res = Database::query($select);
  5147. if (Database::num_rows($res) > 0) {
  5148. // Found item for this access_url.
  5149. $row = Database::fetch_array($res);
  5150. $sql = "UPDATE $t_settings SET selected_value = '$value'
  5151. WHERE id = ".$row['id'];
  5152. Database::query($sql);
  5153. } else {
  5154. // Item not found for this access_url, we have to check if it exist with access_url = 1
  5155. $select = "SELECT * FROM $t_settings
  5156. WHERE variable = '$var' AND access_url = 1 ";
  5157. // Just in case
  5158. if ($access_url == 1) {
  5159. if (!empty($subvar)) {
  5160. $select .= " AND subkey = '$subvar'";
  5161. }
  5162. if (!empty($cat)) {
  5163. $select .= " AND category = '$cat'";
  5164. }
  5165. $res = Database::query($select);
  5166. if (Database::num_rows($res) > 0) {
  5167. // We have a setting for access_url 1, but none for the current one, so create one.
  5168. $row = Database::fetch_array($res);
  5169. $insert = "INSERT INTO $t_settings (variable, subkey, type,category, selected_value, title, comment, scope, subkeytext, access_url)
  5170. VALUES
  5171. ('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
  5172. "'".$row['type']."','".$row['category']."',".
  5173. "'$value','".$row['title']."',".
  5174. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
  5175. "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url)";
  5176. Database::query($insert);
  5177. } else {
  5178. // Such a setting does not exist.
  5179. //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all', 0);
  5180. }
  5181. } else {
  5182. // Other access url.
  5183. if (!empty($subvar)) {
  5184. $select .= " AND subkey = '$subvar'";
  5185. }
  5186. if (!empty($cat)) {
  5187. $select .= " AND category = '$cat'";
  5188. }
  5189. $res = Database::query($select);
  5190. if (Database::num_rows($res) > 0) {
  5191. // We have a setting for access_url 1, but none for the current one, so create one.
  5192. $row = Database::fetch_array($res);
  5193. if ($row['access_url_changeable'] == 1) {
  5194. $insert = "INSERT INTO $t_settings (variable,subkey, type,category, selected_value,title, comment,scope, subkeytext,access_url, access_url_changeable) VALUES
  5195. ('".$row['variable']."',".
  5196. (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
  5197. "'".$row['type']."','".$row['category']."',".
  5198. "'$value','".$row['title']."',".
  5199. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".
  5200. (!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
  5201. "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url,".$row['access_url_changeable'].")";
  5202. Database::query($insert);
  5203. }
  5204. } else { // Such a setting does not exist.
  5205. //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all. The access_url is: '.$access_url.' ',0);
  5206. }
  5207. }
  5208. }
  5209. }
  5210. /**
  5211. * Sets a whole category of settings to one specific value.
  5212. *
  5213. * @param string Category
  5214. * @param string Value
  5215. * @param int Access URL. Optional. Defaults to 1
  5216. * @param array Optional array of filters on field type
  5217. * @param string $category
  5218. * @param string $value
  5219. *
  5220. * @return bool
  5221. */
  5222. function api_set_settings_category($category, $value = null, $access_url = 1, $fieldtype = [])
  5223. {
  5224. if (empty($category)) {
  5225. return false;
  5226. }
  5227. $category = Database::escape_string($category);
  5228. $t_s = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  5229. $access_url = (int) $access_url;
  5230. if (empty($access_url)) {
  5231. $access_url = 1;
  5232. }
  5233. if (isset($value)) {
  5234. $value = Database::escape_string($value);
  5235. $sql = "UPDATE $t_s SET selected_value = '$value'
  5236. WHERE category = '$category' AND access_url = $access_url";
  5237. if (is_array($fieldtype) && count($fieldtype) > 0) {
  5238. $sql .= " AND ( ";
  5239. $i = 0;
  5240. foreach ($fieldtype as $type) {
  5241. if ($i > 0) {
  5242. $sql .= ' OR ';
  5243. }
  5244. $type = Database::escape_string($type);
  5245. $sql .= " type='".$type."' ";
  5246. $i++;
  5247. }
  5248. $sql .= ")";
  5249. }
  5250. $res = Database::query($sql);
  5251. return $res !== false;
  5252. } else {
  5253. $sql = "UPDATE $t_s SET selected_value = NULL
  5254. WHERE category = '$category' AND access_url = $access_url";
  5255. if (is_array($fieldtype) && count($fieldtype) > 0) {
  5256. $sql .= " AND ( ";
  5257. $i = 0;
  5258. foreach ($fieldtype as $type) {
  5259. if ($i > 0) {
  5260. $sql .= ' OR ';
  5261. }
  5262. $type = Database::escape_string($type);
  5263. $sql .= " type='".$type."' ";
  5264. $i++;
  5265. }
  5266. $sql .= ")";
  5267. }
  5268. $res = Database::query($sql);
  5269. return $res !== false;
  5270. }
  5271. }
  5272. /**
  5273. * Gets all available access urls in an array (as in the database).
  5274. *
  5275. * @return array An array of database records
  5276. */
  5277. function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $direction = 'ASC')
  5278. {
  5279. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  5280. $from = (int) $from;
  5281. $to = (int) $to;
  5282. $order = Database::escape_string($order, null, false);
  5283. $direction = Database::escape_string($direction, null, false);
  5284. $sql = "SELECT id, url, description, active, created_by, tms
  5285. FROM $table
  5286. ORDER BY $order $direction
  5287. LIMIT $to OFFSET $from";
  5288. $res = Database::query($sql);
  5289. return Database::store_result($res);
  5290. }
  5291. /**
  5292. * Gets the access url info in an array.
  5293. *
  5294. * @param int $id Id of the access url
  5295. * @param bool $returnDefault Set to false if you want the real URL if URL 1 is still 'http://localhost/'
  5296. *
  5297. * @return array All the info (url, description, active, created_by, tms)
  5298. * from the access_url table
  5299. *
  5300. * @author Julio Montoya
  5301. */
  5302. function api_get_access_url($id, $returnDefault = true)
  5303. {
  5304. static $staticResult;
  5305. $id = (int) $id;
  5306. if (isset($staticResult[$id])) {
  5307. $result = $staticResult[$id];
  5308. } else {
  5309. // Calling the Database:: library dont work this is handmade.
  5310. $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  5311. $sql = "SELECT url, description, active, created_by, tms
  5312. FROM $table_access_url WHERE id = '$id' ";
  5313. $res = Database::query($sql);
  5314. $result = @Database::fetch_array($res);
  5315. $staticResult[$id] = $result;
  5316. }
  5317. // If the result url is 'http://localhost/' (the default) and the root_web
  5318. // (=current url) is different, and the $id is = 1 (which might mean
  5319. // api_get_current_access_url_id() returned 1 by default), then return the
  5320. // root_web setting instead of the current URL
  5321. // This is provided as an option to avoid breaking the storage of URL-specific
  5322. // homepages in home/localhost/
  5323. if ($id === 1 && $returnDefault === false) {
  5324. $currentUrl = api_get_current_access_url_id();
  5325. // only do this if we are on the main URL (=1), otherwise we could get
  5326. // information on another URL instead of the one asked as parameter
  5327. if ($currentUrl === 1) {
  5328. $rootWeb = api_get_path(WEB_PATH);
  5329. $default = 'http://localhost/';
  5330. if ($result['url'] === $default && $rootWeb != $default) {
  5331. $result['url'] = $rootWeb;
  5332. }
  5333. }
  5334. }
  5335. return $result;
  5336. }
  5337. /**
  5338. * Gets all the current settings for a specific access url.
  5339. *
  5340. * @param string The category, if any, that we want to get
  5341. * @param string Whether we want a simple list (display a category) or
  5342. * a grouped list (group by variable as in settings.php default). Values: 'list' or 'group'
  5343. * @param int Access URL's ID. Optional. Uses 1 by default, which is the unique URL
  5344. *
  5345. * @return array Array of database results for the current settings of the current access URL
  5346. */
  5347. function &api_get_settings($cat = null, $ordering = 'list', $access_url = 1, $url_changeable = 0)
  5348. {
  5349. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  5350. $access_url = (int) $access_url;
  5351. $where_condition = '';
  5352. if ($url_changeable == 1) {
  5353. $where_condition = " AND access_url_changeable= '1' ";
  5354. }
  5355. if (empty($access_url) || $access_url == -1) {
  5356. $access_url = 1;
  5357. }
  5358. $sql = "SELECT * FROM $table
  5359. WHERE access_url = $access_url $where_condition ";
  5360. if (!empty($cat)) {
  5361. $cat = Database::escape_string($cat);
  5362. $sql .= " AND category='$cat' ";
  5363. }
  5364. if ($ordering == 'group') {
  5365. $sql .= " ORDER BY id ASC";
  5366. } else {
  5367. $sql .= " ORDER BY 1,2 ASC";
  5368. }
  5369. $result = Database::query($sql);
  5370. if ($result === null) {
  5371. return [];
  5372. }
  5373. $result = Database::store_result($result, 'ASSOC');
  5374. return $result;
  5375. }
  5376. /**
  5377. * @param string $value The value we want to record
  5378. * @param string $variable The variable name we want to insert
  5379. * @param string $subKey The subkey for the variable we want to insert
  5380. * @param string $type The type for the variable we want to insert
  5381. * @param string $category The category for the variable we want to insert
  5382. * @param string $title The title
  5383. * @param string $comment The comment
  5384. * @param string $scope The scope
  5385. * @param string $subKeyText The subkey text
  5386. * @param int $accessUrlId The access_url for which this parameter is valid
  5387. * @param int $visibility The changeability of this setting for non-master urls
  5388. *
  5389. * @return int The setting ID
  5390. */
  5391. function api_add_setting(
  5392. $value,
  5393. $variable,
  5394. $subKey = '',
  5395. $type = 'textfield',
  5396. $category = '',
  5397. $title = '',
  5398. $comment = '',
  5399. $scope = '',
  5400. $subKeyText = '',
  5401. $accessUrlId = 1,
  5402. $visibility = 0
  5403. ) {
  5404. $em = Database::getManager();
  5405. $settingRepo = $em->getRepository('ChamiloCoreBundle:SettingsCurrent');
  5406. $accessUrlId = (int) $accessUrlId ?: 1;
  5407. if (is_array($value)) {
  5408. $value = serialize($value);
  5409. } else {
  5410. $value = trim($value);
  5411. }
  5412. $criteria = ['variable' => $variable, 'accessUrl' => $accessUrlId];
  5413. if (!empty($subKey)) {
  5414. $criteria['subkey'] = $subKey;
  5415. }
  5416. // Check if this variable doesn't exist already
  5417. /** @var SettingsCurrent $setting */
  5418. $setting = $settingRepo->findOneBy($criteria);
  5419. if ($setting) {
  5420. $setting->setSelectedValue($value);
  5421. $em->persist($setting);
  5422. $em->flush();
  5423. return $setting->getId();
  5424. }
  5425. // Item not found for this access_url, we have to check if the whole thing is missing
  5426. // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
  5427. $setting = new SettingsCurrent();
  5428. $setting
  5429. ->setVariable($variable)
  5430. ->setSelectedValue($value)
  5431. ->setType($type)
  5432. ->setCategory($category)
  5433. ->setSubkey($subKey)
  5434. ->setTitle($title)
  5435. ->setComment($comment)
  5436. ->setScope($scope)
  5437. ->setSubkeytext($subKeyText)
  5438. ->setAccessUrl($accessUrlId)
  5439. ->setAccessUrlChangeable($visibility);
  5440. $em->persist($setting);
  5441. $em->flush();
  5442. return $setting->getId();
  5443. }
  5444. /**
  5445. * Checks wether a user can or can't view the contents of a course.
  5446. *
  5447. * @deprecated use CourseManager::is_user_subscribed_in_course
  5448. *
  5449. * @param int $userid User id or NULL to get it from $_SESSION
  5450. * @param int $cid course id to check whether the user is allowed
  5451. *
  5452. * @return bool
  5453. */
  5454. function api_is_course_visible_for_user($userid = null, $cid = null)
  5455. {
  5456. if ($userid === null) {
  5457. $userid = api_get_user_id();
  5458. }
  5459. if (empty($userid) || strval(intval($userid)) != $userid) {
  5460. if (api_is_anonymous()) {
  5461. $userid = api_get_anonymous_id();
  5462. } else {
  5463. return false;
  5464. }
  5465. }
  5466. $cid = Database::escape_string($cid);
  5467. $courseInfo = api_get_course_info($cid);
  5468. $courseId = $courseInfo['real_id'];
  5469. $is_platformAdmin = api_is_platform_admin();
  5470. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  5471. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  5472. $sql = "SELECT
  5473. $course_table.category_code,
  5474. $course_table.visibility,
  5475. $course_table.code,
  5476. $course_cat_table.code
  5477. FROM $course_table
  5478. LEFT JOIN $course_cat_table
  5479. ON $course_table.category_code = $course_cat_table.code
  5480. WHERE
  5481. $course_table.code = '$cid'
  5482. LIMIT 1";
  5483. $result = Database::query($sql);
  5484. if (Database::num_rows($result) > 0) {
  5485. $visibility = Database::fetch_array($result);
  5486. $visibility = $visibility['visibility'];
  5487. } else {
  5488. $visibility = 0;
  5489. }
  5490. // Shortcut permissions in case the visibility is "open to the world".
  5491. if ($visibility === COURSE_VISIBILITY_OPEN_WORLD) {
  5492. return true;
  5493. }
  5494. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5495. $sql = "SELECT
  5496. is_tutor, status
  5497. FROM $tbl_course_user
  5498. WHERE
  5499. user_id = '$userid' AND
  5500. relation_type <> '".COURSE_RELATION_TYPE_RRHH."' AND
  5501. c_id = $courseId
  5502. LIMIT 1";
  5503. $result = Database::query($sql);
  5504. if (Database::num_rows($result) > 0) {
  5505. // This user has got a recorded state for this course.
  5506. $cuData = Database::fetch_array($result);
  5507. $is_courseMember = true;
  5508. $is_courseAdmin = ($cuData['status'] == 1);
  5509. }
  5510. if (!$is_courseAdmin) {
  5511. // This user has no status related to this course.
  5512. // Is it the session coach or the session admin?
  5513. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  5514. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5515. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5516. $sql = "SELECT
  5517. session.id_coach, session_admin_id, session.id
  5518. FROM
  5519. $tbl_session as session
  5520. INNER JOIN $tbl_session_course
  5521. ON session_rel_course.session_id = session.id
  5522. AND session_rel_course.c_id = '$courseId'
  5523. LIMIT 1";
  5524. $result = Database::query($sql);
  5525. $row = Database::store_result($result);
  5526. if ($row[0]['id_coach'] == $userid) {
  5527. $is_courseMember = true;
  5528. $is_courseAdmin = false;
  5529. } elseif ($row[0]['session_admin_id'] == $userid) {
  5530. $is_courseMember = false;
  5531. $is_courseAdmin = false;
  5532. } else {
  5533. // Check if the current user is the course coach.
  5534. $sql = "SELECT 1
  5535. FROM $tbl_session_course
  5536. WHERE session_rel_course.c_id = '$courseId'
  5537. AND session_rel_course.id_coach = '$userid'
  5538. LIMIT 1";
  5539. $result = Database::query($sql);
  5540. //if ($row = Database::fetch_array($result)) {
  5541. if (Database::num_rows($result) > 0) {
  5542. $is_courseMember = true;
  5543. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  5544. $sql = "SELECT status FROM $tbl_user
  5545. WHERE user_id = $userid
  5546. LIMIT 1";
  5547. $result = Database::query($sql);
  5548. if (Database::result($result, 0, 0) == 1) {
  5549. $is_courseAdmin = true;
  5550. } else {
  5551. $is_courseAdmin = false;
  5552. }
  5553. } else {
  5554. // Check if the user is a student is this session.
  5555. $sql = "SELECT id
  5556. FROM $tbl_session_course_user
  5557. WHERE
  5558. user_id = '$userid' AND
  5559. c_id = '$courseId'
  5560. LIMIT 1";
  5561. if (Database::num_rows($result) > 0) {
  5562. // This user haa got a recorded state for this course.
  5563. while ($row = Database::fetch_array($result)) {
  5564. $is_courseMember = true;
  5565. $is_courseAdmin = false;
  5566. }
  5567. }
  5568. }
  5569. }
  5570. }
  5571. switch ($visibility) {
  5572. case COURSE_VISIBILITY_OPEN_WORLD:
  5573. return true;
  5574. case COURSE_VISIBILITY_OPEN_PLATFORM:
  5575. return isset($userid);
  5576. case COURSE_VISIBILITY_REGISTERED:
  5577. case COURSE_VISIBILITY_CLOSED:
  5578. return $is_platformAdmin || $is_courseMember || $is_courseAdmin;
  5579. case COURSE_VISIBILITY_HIDDEN:
  5580. return $is_platformAdmin;
  5581. }
  5582. return false;
  5583. }
  5584. /**
  5585. * Returns whether an element (forum, message, survey ...) belongs to a session or not.
  5586. *
  5587. * @param string the tool of the element
  5588. * @param int the element id in database
  5589. * @param int the session_id to compare with element session id
  5590. *
  5591. * @return bool true if the element is in the session, false else
  5592. */
  5593. function api_is_element_in_the_session($tool, $element_id, $session_id = null)
  5594. {
  5595. if (is_null($session_id)) {
  5596. $session_id = api_get_session_id();
  5597. }
  5598. $element_id = (int) $element_id;
  5599. if (empty($element_id)) {
  5600. return false;
  5601. }
  5602. // Get information to build query depending of the tool.
  5603. switch ($tool) {
  5604. case TOOL_SURVEY:
  5605. $table_tool = Database::get_course_table(TABLE_SURVEY);
  5606. $key_field = 'survey_id';
  5607. break;
  5608. case TOOL_ANNOUNCEMENT:
  5609. $table_tool = Database::get_course_table(TABLE_ANNOUNCEMENT);
  5610. $key_field = 'id';
  5611. break;
  5612. case TOOL_AGENDA:
  5613. $table_tool = Database::get_course_table(TABLE_AGENDA);
  5614. $key_field = 'id';
  5615. break;
  5616. case TOOL_GROUP:
  5617. $table_tool = Database::get_course_table(TABLE_GROUP);
  5618. $key_field = 'id';
  5619. break;
  5620. default:
  5621. return false;
  5622. }
  5623. $course_id = api_get_course_int_id();
  5624. $sql = "SELECT session_id FROM $table_tool
  5625. WHERE c_id = $course_id AND $key_field = ".$element_id;
  5626. $rs = Database::query($sql);
  5627. if ($element_session_id = Database::result($rs, 0, 0)) {
  5628. if ($element_session_id == intval($session_id)) {
  5629. // The element belongs to the session.
  5630. return true;
  5631. }
  5632. }
  5633. return false;
  5634. }
  5635. /**
  5636. * Replaces "forbidden" characters in a filename string.
  5637. *
  5638. * @param string $filename
  5639. * @param bool $treat_spaces_as_hyphens
  5640. *
  5641. * @return string
  5642. */
  5643. function api_replace_dangerous_char($filename, $treat_spaces_as_hyphens = true)
  5644. {
  5645. // Some non-properly encoded file names can cause the whole file to be
  5646. // skipped when uploaded. Avoid this by detecting the encoding and
  5647. // converting to UTF-8, setting the source as ASCII (a reasonably
  5648. // limited characters set) if nothing could be found (BT#
  5649. $encoding = api_detect_encoding($filename);
  5650. if (empty($encoding)) {
  5651. $encoding = 'ASCII';
  5652. if (!api_is_valid_ascii($filename)) {
  5653. // try iconv and try non standard ASCII a.k.a CP437
  5654. // see BT#15022
  5655. if (function_exists('iconv')) {
  5656. $result = iconv('CP437', 'UTF-8', $filename);
  5657. if (api_is_valid_utf8($result)) {
  5658. $filename = $result;
  5659. $encoding = 'UTF-8';
  5660. }
  5661. }
  5662. }
  5663. }
  5664. $filename = api_to_system_encoding($filename, $encoding);
  5665. $url = URLify::filter(
  5666. $filename,
  5667. 250,
  5668. '',
  5669. true,
  5670. true,
  5671. false,
  5672. false,
  5673. $treat_spaces_as_hyphens
  5674. );
  5675. return $url;
  5676. }
  5677. /**
  5678. * Fixes the $_SERVER['REQUEST_URI'] that is empty in IIS6.
  5679. *
  5680. * @author Ivan Tcholakov, 28-JUN-2006.
  5681. */
  5682. function api_request_uri()
  5683. {
  5684. if (!empty($_SERVER['REQUEST_URI'])) {
  5685. return $_SERVER['REQUEST_URI'];
  5686. }
  5687. $uri = $_SERVER['SCRIPT_NAME'];
  5688. if (!empty($_SERVER['QUERY_STRING'])) {
  5689. $uri .= '?'.$_SERVER['QUERY_STRING'];
  5690. }
  5691. $_SERVER['REQUEST_URI'] = $uri;
  5692. return $uri;
  5693. }
  5694. /** Gets the current access_url id of the Chamilo Platform
  5695. * @author Julio Montoya <gugli100@gmail.com>
  5696. *
  5697. * @return int access_url_id of the current Chamilo Installation
  5698. */
  5699. function api_get_current_access_url_id()
  5700. {
  5701. $access_url_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  5702. $path = Database::escape_string(api_get_path(WEB_PATH));
  5703. $sql = "SELECT id FROM $access_url_table WHERE url = '".$path."'";
  5704. $result = Database::query($sql);
  5705. if (Database::num_rows($result) > 0) {
  5706. $access_url_id = Database::result($result, 0, 0);
  5707. if ($access_url_id === false) {
  5708. return -1;
  5709. }
  5710. return (int) $access_url_id;
  5711. }
  5712. //if the url in WEB_PATH was not found, it can only mean that there is
  5713. // either a configuration problem or the first URL has not been defined yet
  5714. // (by default it is http://localhost/). Thus the more sensible thing we can
  5715. // do is return 1 (the main URL) as the user cannot hack this value anyway
  5716. return 1;
  5717. }
  5718. /**
  5719. * Gets the registered urls from a given user id.
  5720. *
  5721. * @author Julio Montoya <gugli100@gmail.com>
  5722. *
  5723. * @return int user id
  5724. */
  5725. function api_get_access_url_from_user($user_id)
  5726. {
  5727. $user_id = (int) $user_id;
  5728. $table_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  5729. $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  5730. $sql = "SELECT access_url_id
  5731. FROM $table_url_rel_user url_rel_user
  5732. INNER JOIN $table_url u
  5733. ON (url_rel_user.access_url_id = u.id)
  5734. WHERE user_id = ".intval($user_id);
  5735. $result = Database::query($sql);
  5736. $list = [];
  5737. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5738. $list[] = $row['access_url_id'];
  5739. }
  5740. return $list;
  5741. }
  5742. /**
  5743. * Gets the status of a user in a course.
  5744. *
  5745. * @param int $user_id
  5746. * @param int $courseId
  5747. *
  5748. * @return int user status
  5749. */
  5750. function api_get_status_of_user_in_course($user_id, $courseId)
  5751. {
  5752. $tbl_rel_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5753. if (!empty($user_id) && !empty($courseId)) {
  5754. $user_id = intval($user_id);
  5755. $courseId = intval($courseId);
  5756. $sql = 'SELECT status
  5757. FROM '.$tbl_rel_course_user.'
  5758. WHERE user_id='.$user_id.' AND c_id = '.$courseId;
  5759. $result = Database::query($sql);
  5760. $row_status = Database::fetch_array($result, 'ASSOC');
  5761. return $row_status['status'];
  5762. } else {
  5763. return 0;
  5764. }
  5765. }
  5766. /**
  5767. * Checks whether the curent user is in a group or not.
  5768. *
  5769. * @param string The group id - optional (takes it from session if not given)
  5770. * @param string The course code - optional (no additional check by course if course code is not given)
  5771. *
  5772. * @return bool
  5773. *
  5774. * @author Ivan Tcholakov
  5775. */
  5776. function api_is_in_group($groupIdParam = null, $courseCodeParam = null)
  5777. {
  5778. if (!empty($courseCodeParam)) {
  5779. $courseCode = api_get_course_id();
  5780. if (!empty($courseCode)) {
  5781. if ($courseCodeParam != $courseCode) {
  5782. return false;
  5783. }
  5784. } else {
  5785. return false;
  5786. }
  5787. }
  5788. $groupId = api_get_group_id();
  5789. if (isset($groupId) && $groupId != '') {
  5790. if (!empty($groupIdParam)) {
  5791. return $groupIdParam == $groupId;
  5792. } else {
  5793. return true;
  5794. }
  5795. }
  5796. return false;
  5797. }
  5798. /**
  5799. * Checks whether a secret key is valid.
  5800. *
  5801. * @param string $original_key_secret - secret key from (webservice) client
  5802. * @param string $security_key - security key from Chamilo
  5803. *
  5804. * @return bool - true if secret key is valid, false otherwise
  5805. */
  5806. function api_is_valid_secret_key($original_key_secret, $security_key)
  5807. {
  5808. return $original_key_secret == sha1($security_key);
  5809. }
  5810. /**
  5811. * Checks whether a user is into course.
  5812. *
  5813. * @param int $course_id - the course id
  5814. * @param int $user_id - the user id
  5815. *
  5816. * @return bool
  5817. */
  5818. function api_is_user_of_course($course_id, $user_id)
  5819. {
  5820. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5821. $sql = 'SELECT user_id FROM '.$tbl_course_rel_user.'
  5822. WHERE
  5823. c_id ="'.intval($course_id).'" AND
  5824. user_id = "'.intval($user_id).'" AND
  5825. relation_type <> '.COURSE_RELATION_TYPE_RRHH.' ';
  5826. $result = Database::query($sql);
  5827. return Database::num_rows($result) == 1;
  5828. }
  5829. /**
  5830. * Checks whether the server's operating system is Windows (TM).
  5831. *
  5832. * @return bool - true if the operating system is Windows, false otherwise
  5833. */
  5834. function api_is_windows_os()
  5835. {
  5836. if (function_exists('php_uname')) {
  5837. // php_uname() exists as of PHP 4.0.2, according to the documentation.
  5838. // We expect that this function will always work for Chamilo 1.8.x.
  5839. $os = php_uname();
  5840. }
  5841. // The following methods are not needed, but let them stay, just in case.
  5842. elseif (isset($_ENV['OS'])) {
  5843. // Sometimes $_ENV['OS'] may not be present (bugs?)
  5844. $os = $_ENV['OS'];
  5845. } elseif (defined('PHP_OS')) {
  5846. // PHP_OS means on which OS PHP was compiled, this is why
  5847. // using PHP_OS is the last choice for detection.
  5848. $os = PHP_OS;
  5849. } else {
  5850. return false;
  5851. }
  5852. return strtolower(substr((string) $os, 0, 3)) == 'win';
  5853. }
  5854. /**
  5855. * This function informs whether the sent request is XMLHttpRequest.
  5856. */
  5857. function api_is_xml_http_request()
  5858. {
  5859. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
  5860. }
  5861. /**
  5862. * This wrapper function has been implemented for avoiding some known problems about the function getimagesize().
  5863. *
  5864. * @see http://php.net/manual/en/function.getimagesize.php
  5865. * @see http://www.dokeos.com/forum/viewtopic.php?t=12345
  5866. * @see http://www.dokeos.com/forum/viewtopic.php?t=16355
  5867. *
  5868. * @return int
  5869. */
  5870. function api_getimagesize($path)
  5871. {
  5872. $image = new Image($path);
  5873. return $image->get_image_size();
  5874. }
  5875. /**
  5876. * This function resizes an image, with preserving its proportions (or aspect ratio).
  5877. *
  5878. * @author Ivan Tcholakov, MAY-2009.
  5879. *
  5880. * @param int $image System path or URL of the image
  5881. * @param int $target_width Targeted width
  5882. * @param int $target_height Targeted height
  5883. *
  5884. * @return array Calculated new width and height
  5885. */
  5886. function api_resize_image($image, $target_width, $target_height)
  5887. {
  5888. $image_properties = api_getimagesize($image);
  5889. return api_calculate_image_size(
  5890. $image_properties['width'],
  5891. $image_properties['height'],
  5892. $target_width,
  5893. $target_height
  5894. );
  5895. }
  5896. /**
  5897. * This function calculates new image size, with preserving image's proportions (or aspect ratio).
  5898. *
  5899. * @author Ivan Tcholakov, MAY-2009.
  5900. * @author The initial idea has been taken from code by Patrick Cool, MAY-2004.
  5901. *
  5902. * @param int $image_width Initial width
  5903. * @param int $image_height Initial height
  5904. * @param int $target_width Targeted width
  5905. * @param int $target_height Targeted height
  5906. *
  5907. * @return array Calculated new width and height
  5908. */
  5909. function api_calculate_image_size(
  5910. $image_width,
  5911. $image_height,
  5912. $target_width,
  5913. $target_height
  5914. ) {
  5915. // Only maths is here.
  5916. $result = ['width' => $image_width, 'height' => $image_height];
  5917. if ($image_width <= 0 || $image_height <= 0) {
  5918. return $result;
  5919. }
  5920. $resize_factor_width = $target_width / $image_width;
  5921. $resize_factor_height = $target_height / $image_height;
  5922. $delta_width = $target_width - $image_width * $resize_factor_height;
  5923. $delta_height = $target_height - $image_height * $resize_factor_width;
  5924. if ($delta_width > $delta_height) {
  5925. $result['width'] = ceil($image_width * $resize_factor_height);
  5926. $result['height'] = ceil($image_height * $resize_factor_height);
  5927. } elseif ($delta_width < $delta_height) {
  5928. $result['width'] = ceil($image_width * $resize_factor_width);
  5929. $result['height'] = ceil($image_height * $resize_factor_width);
  5930. } else {
  5931. $result['width'] = ceil($target_width);
  5932. $result['height'] = ceil($target_height);
  5933. }
  5934. return $result;
  5935. }
  5936. /**
  5937. * Returns a list of Chamilo's tools or
  5938. * checks whether a given identificator is a valid Chamilo's tool.
  5939. *
  5940. * @author Isaac flores paz
  5941. *
  5942. * @param string The tool name to filter
  5943. *
  5944. * @return mixed Filtered string or array
  5945. */
  5946. function api_get_tools_lists($my_tool = null)
  5947. {
  5948. $tools_list = [
  5949. TOOL_DOCUMENT,
  5950. TOOL_THUMBNAIL,
  5951. TOOL_HOTPOTATOES,
  5952. TOOL_CALENDAR_EVENT,
  5953. TOOL_LINK,
  5954. TOOL_COURSE_DESCRIPTION,
  5955. TOOL_SEARCH,
  5956. TOOL_LEARNPATH,
  5957. TOOL_ANNOUNCEMENT,
  5958. TOOL_FORUM,
  5959. TOOL_THREAD,
  5960. TOOL_POST,
  5961. TOOL_DROPBOX,
  5962. TOOL_QUIZ,
  5963. TOOL_USER,
  5964. TOOL_GROUP,
  5965. TOOL_BLOGS,
  5966. TOOL_CHAT,
  5967. TOOL_STUDENTPUBLICATION,
  5968. TOOL_TRACKING,
  5969. TOOL_HOMEPAGE_LINK,
  5970. TOOL_COURSE_SETTING,
  5971. TOOL_BACKUP,
  5972. TOOL_COPY_COURSE_CONTENT,
  5973. TOOL_RECYCLE_COURSE,
  5974. TOOL_COURSE_HOMEPAGE,
  5975. TOOL_COURSE_RIGHTS_OVERVIEW,
  5976. TOOL_UPLOAD,
  5977. TOOL_COURSE_MAINTENANCE,
  5978. TOOL_SURVEY,
  5979. TOOL_WIKI,
  5980. TOOL_GLOSSARY,
  5981. TOOL_GRADEBOOK,
  5982. TOOL_NOTEBOOK,
  5983. TOOL_ATTENDANCE,
  5984. TOOL_COURSE_PROGRESS,
  5985. ];
  5986. if (empty($my_tool)) {
  5987. return $tools_list;
  5988. }
  5989. return in_array($my_tool, $tools_list) ? $my_tool : '';
  5990. }
  5991. /**
  5992. * Checks whether we already approved the last version term and condition.
  5993. *
  5994. * @param int user id
  5995. *
  5996. * @return bool true if we pass false otherwise
  5997. */
  5998. function api_check_term_condition($userId)
  5999. {
  6000. if (api_get_setting('allow_terms_conditions') === 'true') {
  6001. // Check if exists terms and conditions
  6002. if (LegalManager::count() == 0) {
  6003. return true;
  6004. }
  6005. $extraFieldValue = new ExtraFieldValue('user');
  6006. $data = $extraFieldValue->get_values_by_handler_and_field_variable(
  6007. $userId,
  6008. 'legal_accept'
  6009. );
  6010. if (!empty($data) && isset($data['value']) && !empty($data['value'])) {
  6011. $result = $data['value'];
  6012. $user_conditions = explode(':', $result);
  6013. $version = $user_conditions[0];
  6014. $langId = $user_conditions[1];
  6015. $realVersion = LegalManager::get_last_version($langId);
  6016. return $version >= $realVersion;
  6017. }
  6018. return false;
  6019. }
  6020. return false;
  6021. }
  6022. /**
  6023. * Gets all information of a tool into course.
  6024. *
  6025. * @param int The tool id
  6026. *
  6027. * @return array
  6028. */
  6029. function api_get_tool_information_by_name($name)
  6030. {
  6031. $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
  6032. $course_id = api_get_course_int_id();
  6033. $sql = "SELECT * FROM $t_tool
  6034. WHERE c_id = $course_id AND name = '".Database::escape_string($name)."' ";
  6035. $rs = Database::query($sql);
  6036. return Database::fetch_array($rs, 'ASSOC');
  6037. }
  6038. /**
  6039. * Function used to protect a "global" admin script.
  6040. * The function blocks access when the user has no global platform admin rights.
  6041. * Global admins are the admins that are registered in the main.admin table
  6042. * AND the users who have access to the "principal" portal.
  6043. * That means that there is a record in the main.access_url_rel_user table
  6044. * with his user id and the access_url_id=1.
  6045. *
  6046. * @author Julio Montoya
  6047. *
  6048. * @param int $user_id
  6049. *
  6050. * @return bool
  6051. */
  6052. function api_is_global_platform_admin($user_id = null)
  6053. {
  6054. $user_id = (int) $user_id;
  6055. if (empty($user_id)) {
  6056. $user_id = api_get_user_id();
  6057. }
  6058. if (api_is_platform_admin_by_id($user_id)) {
  6059. $urlList = api_get_access_url_from_user($user_id);
  6060. // The admin is registered in the first "main" site with access_url_id = 1
  6061. if (in_array(1, $urlList)) {
  6062. return true;
  6063. } else {
  6064. return false;
  6065. }
  6066. }
  6067. return false;
  6068. }
  6069. /**
  6070. * @param int $admin_id_to_check
  6071. * @param int $my_user_id
  6072. * @param bool $allow_session_admin
  6073. *
  6074. * @return bool
  6075. */
  6076. function api_global_admin_can_edit_admin(
  6077. $admin_id_to_check,
  6078. $my_user_id = null,
  6079. $allow_session_admin = false
  6080. ) {
  6081. if (empty($my_user_id)) {
  6082. $my_user_id = api_get_user_id();
  6083. }
  6084. $iam_a_global_admin = api_is_global_platform_admin($my_user_id);
  6085. $user_is_global_admin = api_is_global_platform_admin($admin_id_to_check);
  6086. if ($iam_a_global_admin) {
  6087. // Global admin can edit everything
  6088. return true;
  6089. } else {
  6090. // If i'm a simple admin
  6091. $is_platform_admin = api_is_platform_admin_by_id($my_user_id);
  6092. if ($allow_session_admin) {
  6093. $is_platform_admin = api_is_platform_admin_by_id($my_user_id) || (api_get_user_status($my_user_id) == SESSIONADMIN);
  6094. }
  6095. if ($is_platform_admin) {
  6096. if ($user_is_global_admin) {
  6097. return false;
  6098. } else {
  6099. return true;
  6100. }
  6101. } else {
  6102. return false;
  6103. }
  6104. }
  6105. }
  6106. /**
  6107. * @param int $admin_id_to_check
  6108. * @param int $my_user_id
  6109. * @param bool $allow_session_admin
  6110. *
  6111. * @return bool|null
  6112. */
  6113. function api_protect_super_admin($admin_id_to_check, $my_user_id = null, $allow_session_admin = false)
  6114. {
  6115. if (api_global_admin_can_edit_admin($admin_id_to_check, $my_user_id, $allow_session_admin)) {
  6116. return true;
  6117. } else {
  6118. api_not_allowed();
  6119. }
  6120. }
  6121. /**
  6122. * Function used to protect a global admin script.
  6123. * The function blocks access when the user has no global platform admin rights.
  6124. * See also the api_is_global_platform_admin() function wich defines who's a "global" admin.
  6125. *
  6126. * @author Julio Montoya
  6127. */
  6128. function api_protect_global_admin_script()
  6129. {
  6130. if (!api_is_global_platform_admin()) {
  6131. api_not_allowed();
  6132. return false;
  6133. }
  6134. return true;
  6135. }
  6136. /**
  6137. * Get active template.
  6138. *
  6139. * @param string theme type (optional: default)
  6140. * @param string path absolute(abs) or relative(rel) (optional:rel)
  6141. *
  6142. * @return string actived template path
  6143. */
  6144. function api_get_template($path_type = 'rel')
  6145. {
  6146. $path_types = ['rel', 'abs'];
  6147. $template_path = '';
  6148. if (in_array($path_type, $path_types)) {
  6149. if ($path_type == 'rel') {
  6150. $template_path = api_get_path(SYS_TEMPLATE_PATH);
  6151. } else {
  6152. $template_path = api_get_path(WEB_TEMPLATE_PATH);
  6153. }
  6154. }
  6155. $actived_theme = 'default';
  6156. if (api_get_setting('active_template')) {
  6157. $actived_theme = api_get_setting('active_template');
  6158. }
  6159. $actived_theme_path = $template_path.$actived_theme.DIRECTORY_SEPARATOR;
  6160. return $actived_theme_path;
  6161. }
  6162. /**
  6163. * Check browser support for specific file types or features
  6164. * This function checks if the user's browser supports a file format or given
  6165. * feature, or returns the current browser and major version when
  6166. * $format=check_browser. Only a limited number of formats and features are
  6167. * checked by this method. Make sure you check its definition first.
  6168. *
  6169. * @param string $format Can be a file format (extension like svg, webm, ...) or a feature (like autocapitalize, ...)
  6170. *
  6171. * @return bool or return text array if $format=check_browser
  6172. *
  6173. * @author Juan Carlos Raña Trabado
  6174. */
  6175. function api_browser_support($format = '')
  6176. {
  6177. $browser = new Browser();
  6178. $current_browser = $browser->getBrowser();
  6179. $a_versiontemp = explode('.', $browser->getVersion());
  6180. $current_majorver = $a_versiontemp[0];
  6181. static $result;
  6182. if (isset($result[$format])) {
  6183. return $result[$format];
  6184. }
  6185. // Native svg support
  6186. if ($format == 'svg') {
  6187. if (($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  6188. ($current_browser == 'Firefox' && $current_majorver > 1) ||
  6189. ($current_browser == 'Safari' && $current_majorver >= 4) ||
  6190. ($current_browser == 'Chrome' && $current_majorver >= 1) ||
  6191. ($current_browser == 'Opera' && $current_majorver >= 9)
  6192. ) {
  6193. $result[$format] = true;
  6194. return true;
  6195. } else {
  6196. $result[$format] = false;
  6197. return false;
  6198. }
  6199. } elseif ($format == 'pdf') {
  6200. // native pdf support
  6201. if ($current_browser == 'Chrome' && $current_majorver >= 6) {
  6202. $result[$format] = true;
  6203. return true;
  6204. } else {
  6205. $result[$format] = false;
  6206. return false;
  6207. }
  6208. } elseif ($format == 'tif' || $format == 'tiff') {
  6209. //native tif support
  6210. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  6211. $result[$format] = true;
  6212. return true;
  6213. } else {
  6214. $result[$format] = false;
  6215. return false;
  6216. }
  6217. } elseif ($format == 'ogg' || $format == 'ogx' || $format == 'ogv' || $format == 'oga') {
  6218. //native ogg, ogv,oga support
  6219. if (($current_browser == 'Firefox' && $current_majorver >= 3) ||
  6220. ($current_browser == 'Chrome' && $current_majorver >= 3) ||
  6221. ($current_browser == 'Opera' && $current_majorver >= 9)) {
  6222. $result[$format] = true;
  6223. return true;
  6224. } else {
  6225. $result[$format] = false;
  6226. return false;
  6227. }
  6228. } elseif ($format == 'mpg' || $format == 'mpeg') {
  6229. //native mpg support
  6230. if (($current_browser == 'Safari' && $current_majorver >= 5)) {
  6231. $result[$format] = true;
  6232. return true;
  6233. } else {
  6234. $result[$format] = false;
  6235. return false;
  6236. }
  6237. } elseif ($format == 'mp4') {
  6238. //native mp4 support (TODO: Android, iPhone)
  6239. if ($current_browser == 'Android' || $current_browser == 'iPhone') {
  6240. $result[$format] = true;
  6241. return true;
  6242. } else {
  6243. $result[$format] = false;
  6244. return false;
  6245. }
  6246. } elseif ($format == 'mov') {
  6247. //native mov support( TODO:check iPhone)
  6248. if ($current_browser == 'Safari' && $current_majorver >= 5 || $current_browser == 'iPhone') {
  6249. $result[$format] = true;
  6250. return true;
  6251. } else {
  6252. $result[$format] = false;
  6253. return false;
  6254. }
  6255. } elseif ($format == 'avi') {
  6256. //native avi support
  6257. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  6258. $result[$format] = true;
  6259. return true;
  6260. } else {
  6261. $result[$format] = false;
  6262. return false;
  6263. }
  6264. } elseif ($format == 'wmv') {
  6265. //native wmv support
  6266. if ($current_browser == 'Firefox' && $current_majorver >= 4) {
  6267. $result[$format] = true;
  6268. return true;
  6269. } else {
  6270. $result[$format] = false;
  6271. return false;
  6272. }
  6273. } elseif ($format == 'webm') {
  6274. //native webm support (TODO:check IE9, Chrome9, Android)
  6275. if (($current_browser == 'Firefox' && $current_majorver >= 4) ||
  6276. ($current_browser == 'Opera' && $current_majorver >= 9) ||
  6277. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  6278. ($current_browser == 'Chrome' && $current_majorver >= 9) ||
  6279. $current_browser == 'Android'
  6280. ) {
  6281. $result[$format] = true;
  6282. return true;
  6283. } else {
  6284. $result[$format] = false;
  6285. return false;
  6286. }
  6287. } elseif ($format == 'wav') {
  6288. //native wav support (only some codecs !)
  6289. if (($current_browser == 'Firefox' && $current_majorver >= 4) ||
  6290. ($current_browser == 'Safari' && $current_majorver >= 5) ||
  6291. ($current_browser == 'Opera' && $current_majorver >= 9) ||
  6292. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  6293. ($current_browser == 'Chrome' && $current_majorver > 9) ||
  6294. $current_browser == 'Android' ||
  6295. $current_browser == 'iPhone'
  6296. ) {
  6297. $result[$format] = true;
  6298. return true;
  6299. } else {
  6300. $result[$format] = false;
  6301. return false;
  6302. }
  6303. } elseif ($format == 'mid' || $format == 'kar') {
  6304. //native midi support (TODO:check Android)
  6305. if ($current_browser == 'Opera' && $current_majorver >= 9 || $current_browser == 'Android') {
  6306. $result[$format] = true;
  6307. return true;
  6308. } else {
  6309. $result[$format] = false;
  6310. return false;
  6311. }
  6312. } elseif ($format == 'wma') {
  6313. //native wma support
  6314. if ($current_browser == 'Firefox' && $current_majorver >= 4) {
  6315. $result[$format] = true;
  6316. return true;
  6317. } else {
  6318. $result[$format] = false;
  6319. return false;
  6320. }
  6321. } elseif ($format == 'au') {
  6322. //native au support
  6323. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  6324. $result[$format] = true;
  6325. return true;
  6326. } else {
  6327. $result[$format] = false;
  6328. return false;
  6329. }
  6330. } elseif ($format == 'mp3') {
  6331. //native mp3 support (TODO:check Android, iPhone)
  6332. if (($current_browser == 'Safari' && $current_majorver >= 5) ||
  6333. ($current_browser == 'Chrome' && $current_majorver >= 6) ||
  6334. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  6335. $current_browser == 'Android' ||
  6336. $current_browser == 'iPhone' ||
  6337. $current_browser == 'Firefox'
  6338. ) {
  6339. $result[$format] = true;
  6340. return true;
  6341. } else {
  6342. $result[$format] = false;
  6343. return false;
  6344. }
  6345. } elseif ($format == 'autocapitalize') {
  6346. // Help avoiding showing the autocapitalize option if the browser doesn't
  6347. // support it: this attribute is against the HTML5 standard
  6348. if ($current_browser == 'Safari' || $current_browser == 'iPhone') {
  6349. return true;
  6350. } else {
  6351. return false;
  6352. }
  6353. } elseif ($format == "check_browser") {
  6354. $array_check_browser = [$current_browser, $current_majorver];
  6355. return $array_check_browser;
  6356. } else {
  6357. $result[$format] = false;
  6358. return false;
  6359. }
  6360. }
  6361. /**
  6362. * This function checks if exist path and file browscap.ini
  6363. * In order for this to work, your browscap configuration setting in php.ini
  6364. * must point to the correct location of the browscap.ini file on your system
  6365. * http://php.net/manual/en/function.get-browser.php.
  6366. *
  6367. * @return bool
  6368. *
  6369. * @author Juan Carlos Raña Trabado
  6370. */
  6371. function api_check_browscap()
  6372. {
  6373. $setting = ini_get('browscap');
  6374. if ($setting) {
  6375. $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
  6376. if (strpos($setting, 'browscap.ini') && !empty($browser)) {
  6377. return true;
  6378. }
  6379. }
  6380. return false;
  6381. }
  6382. /**
  6383. * Returns the <script> HTML tag.
  6384. */
  6385. function api_get_js($file)
  6386. {
  6387. return '<script type="text/javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>'."\n";
  6388. }
  6389. /**
  6390. * Returns the <script> HTML tag.
  6391. *
  6392. * @return string
  6393. */
  6394. function api_get_asset($file)
  6395. {
  6396. return '<script type="text/javascript" src="'.api_get_path(WEB_PUBLIC_PATH).'assets/'.$file.'"></script>'."\n";
  6397. }
  6398. /**
  6399. * Returns the <script> HTML tag.
  6400. *
  6401. * @param string $file
  6402. * @param string $media
  6403. *
  6404. * @return string
  6405. */
  6406. function api_get_css_asset($file, $media = 'screen')
  6407. {
  6408. return '<link href="'.api_get_path(WEB_PUBLIC_PATH).'assets/'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
  6409. }
  6410. /**
  6411. * Returns the <link> HTML tag.
  6412. *
  6413. * @param string $file
  6414. * @param string $media
  6415. */
  6416. function api_get_css($file, $media = 'screen')
  6417. {
  6418. return '<link href="'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
  6419. }
  6420. /**
  6421. * Returns the js header to include the jquery library.
  6422. */
  6423. function api_get_jquery_js()
  6424. {
  6425. return api_get_asset('jquery/dist/jquery.min.js');
  6426. }
  6427. /**
  6428. * Returns the jquery path.
  6429. *
  6430. * @return string
  6431. */
  6432. function api_get_jquery_web_path()
  6433. {
  6434. return api_get_path(WEB_PUBLIC_PATH).'assets/jquery/dist/jquery.min.js';
  6435. }
  6436. /**
  6437. * @return string
  6438. */
  6439. function api_get_jquery_ui_js_web_path()
  6440. {
  6441. return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/jquery-ui.min.js';
  6442. }
  6443. /**
  6444. * @return string
  6445. */
  6446. function api_get_jquery_ui_css_web_path()
  6447. {
  6448. return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/themes/smoothness/jquery-ui.min.css';
  6449. }
  6450. /**
  6451. * Returns the jquery-ui library js headers.
  6452. *
  6453. * @param bool add the jqgrid library
  6454. *
  6455. * @return string html tags
  6456. */
  6457. function api_get_jquery_ui_js($include_jqgrid = false)
  6458. {
  6459. $libraries = [];
  6460. if ($include_jqgrid) {
  6461. $libraries[] = 'jqgrid';
  6462. }
  6463. return api_get_jquery_libraries_js($libraries);
  6464. }
  6465. function api_get_jqgrid_js()
  6466. {
  6467. return api_get_jquery_libraries_js(['jqgrid']);
  6468. }
  6469. /**
  6470. * Returns the jquery library js and css headers.
  6471. *
  6472. * @param array list of jquery libraries supported jquery-ui, jqgrid
  6473. * @param bool add the jquery library
  6474. *
  6475. * @return string html tags
  6476. */
  6477. function api_get_jquery_libraries_js($libraries)
  6478. {
  6479. $js = '';
  6480. $js_path = api_get_path(WEB_LIBRARY_PATH).'javascript/';
  6481. //jqgrid js and css
  6482. if (in_array('jqgrid', $libraries)) {
  6483. $languaje = 'en';
  6484. $platform_isocode = strtolower(api_get_language_isocode());
  6485. //languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  6486. $jqgrid_langs = [
  6487. 'bg', 'bg1251', 'cat', 'cn', 'cs', 'da', 'de', 'el', 'en', 'es', 'fa', 'fi', 'fr', 'gl', 'he', 'hu', 'is', 'it', 'ja', 'nl', 'no', 'pl', 'pt-br', 'pt', 'ro', 'ru', 'sk', 'sr', 'sv', 'tr', 'ua',
  6488. ];
  6489. if (in_array($platform_isocode, $jqgrid_langs)) {
  6490. $languaje = $platform_isocode;
  6491. }
  6492. //$js .= '<link rel="stylesheet" href="'.$js_path.'jqgrid/css/ui.jqgrid.css" type="text/css">';
  6493. $js .= api_get_css($js_path.'jqgrid/css/ui.jqgrid.css');
  6494. $js .= api_get_js('jqgrid/js/i18n/grid.locale-'.$languaje.'.js');
  6495. $js .= api_get_js('jqgrid/js/jquery.jqGrid.min.js');
  6496. }
  6497. //Document multiple upload funcionality
  6498. if (in_array('jquery-upload', $libraries)) {
  6499. $js .= api_get_asset('blueimp-load-image/js/load-image.all.min.js');
  6500. $js .= api_get_asset('blueimp-canvas-to-blob/js/canvas-to-blob.min.js');
  6501. $js .= api_get_asset('jquery-file-upload/js/jquery.iframe-transport.js');
  6502. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload.js');
  6503. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-process.js');
  6504. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-image.js');
  6505. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-audio.js');
  6506. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-video.js');
  6507. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-validate.js');
  6508. $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload.css');
  6509. $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload-ui.css');
  6510. }
  6511. // jquery datepicker
  6512. if (in_array('datepicker', $libraries)) {
  6513. $languaje = 'en-GB';
  6514. $platform_isocode = strtolower(api_get_language_isocode());
  6515. // languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  6516. $datapicker_langs = [
  6517. 'af', 'ar', 'ar-DZ', 'az', 'bg', 'bs', 'ca', 'cs', 'cy-GB', 'da', 'de', 'el', 'en-AU', 'en-GB', 'en-NZ', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr', 'fr-CH', 'gl', 'he', 'hi', 'hr', 'hu', 'hy', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'ko', 'lb', 'lt', 'lv', 'mk', 'ml', 'ms', 'nl', 'nl-BE', 'no', 'pl', 'pt', 'pt-BR', 'rm', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sr-SR', 'sv', 'ta', 'th', 'tj', 'tr', 'uk', 'vi', 'zh-CN', 'zh-HK', 'zh-TW',
  6518. ];
  6519. if (in_array($platform_isocode, $datapicker_langs)) {
  6520. $languaje = $platform_isocode;
  6521. }
  6522. $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
  6523. $script = '<script>
  6524. $(function(){
  6525. $.datepicker.setDefaults($.datepicker.regional["'.$languaje.'"]);
  6526. $.datepicker.regional["local"] = $.datepicker.regional["'.$languaje.'"];
  6527. });
  6528. </script>
  6529. ';
  6530. $js .= $script;
  6531. }
  6532. return $js;
  6533. }
  6534. /**
  6535. * Returns the URL to the course or session, removing the complexity of the URL
  6536. * building piece by piece.
  6537. *
  6538. * This function relies on api_get_course_info()
  6539. *
  6540. * @param string $courseCode The course code - optional (takes it from context if not given)
  6541. * @param int $sessionId The session ID - optional (takes it from context if not given)
  6542. * @param int $groupId The group ID - optional (takes it from context if not given)
  6543. *
  6544. * @return string The URL to a course, a session, or empty string if nothing works e.g. https://localhost/courses/ABC/index.php?session_id=3&gidReq=1
  6545. *
  6546. * @author Julio Montoya <gugli100@gmail.com>
  6547. */
  6548. function api_get_course_url($courseCode = null, $sessionId = null, $groupId = null)
  6549. {
  6550. $courseDirectory = '';
  6551. $url = '';
  6552. // If courseCode not set, get context or []
  6553. if (empty($courseCode)) {
  6554. $courseInfo = api_get_course_info();
  6555. } else {
  6556. $courseInfo = api_get_course_info($courseCode);
  6557. }
  6558. // If course defined, get directory, otherwise keep empty string
  6559. if (!empty($courseInfo['directory'])) {
  6560. $courseDirectory = $courseInfo['directory'];
  6561. }
  6562. // If sessionId not set, get context or 0
  6563. if (empty($sessionId)) {
  6564. $sessionId = api_get_session_id();
  6565. }
  6566. // If groupId not set, get context or 0
  6567. if (empty($groupId)) {
  6568. $groupId = api_get_group_id();
  6569. }
  6570. // Build the URL
  6571. if (!empty($courseDirectory)) {
  6572. // directory not empty, so we do have a course
  6573. $url = api_get_path(WEB_COURSE_PATH).$courseDirectory.'/index.php?id_session='.$sessionId.'&gidReq='.$groupId;
  6574. } elseif (!empty($sessionId) && api_get_configuration_value('remove_session_url') !== true) {
  6575. // if the course was unset and the session was set, send directly to the session
  6576. $url = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
  6577. }
  6578. // if not valid combination was found, return an empty string
  6579. return $url;
  6580. }
  6581. /**
  6582. * Check if the current portal has the $_configuration['multiple_access_urls'] parameter on.
  6583. *
  6584. * @return bool true if multi site is enabled
  6585. */
  6586. function api_get_multiple_access_url()
  6587. {
  6588. global $_configuration;
  6589. if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
  6590. return true;
  6591. }
  6592. return false;
  6593. }
  6594. /**
  6595. * @return bool
  6596. */
  6597. function api_is_multiple_url_enabled()
  6598. {
  6599. return api_get_multiple_access_url();
  6600. }
  6601. /**
  6602. * Returns a md5 unique id.
  6603. *
  6604. * @todo add more parameters
  6605. */
  6606. function api_get_unique_id()
  6607. {
  6608. $id = md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
  6609. return $id;
  6610. }
  6611. /**
  6612. * Get home path.
  6613. *
  6614. * @return string
  6615. */
  6616. function api_get_home_path()
  6617. {
  6618. // FIX : Start the routing determination from central path definition
  6619. $home = api_get_path(SYS_HOME_PATH);
  6620. if (api_get_multiple_access_url()) {
  6621. $access_url_id = api_get_current_access_url_id();
  6622. $url_info = api_get_access_url($access_url_id);
  6623. $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
  6624. $clean_url = api_replace_dangerous_char($url);
  6625. $clean_url = str_replace('/', '-', $clean_url);
  6626. $clean_url .= '/';
  6627. if ($clean_url != 'localhost/') {
  6628. // means that the multiple URL was not well configured we don't rename the $home variable
  6629. return "{$home}{$clean_url}";
  6630. }
  6631. }
  6632. return $home;
  6633. }
  6634. /**
  6635. * @param int Course id
  6636. * @param int tool id: TOOL_QUIZ, TOOL_FORUM, TOOL_STUDENTPUBLICATION, TOOL_LEARNPATH
  6637. * @param int the item id (tool id, exercise id, lp id)
  6638. *
  6639. * @return bool
  6640. */
  6641. function api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code = null)
  6642. {
  6643. if (api_is_platform_admin()) {
  6644. return false;
  6645. }
  6646. if (api_get_setting('gradebook_locking_enabled') == 'true') {
  6647. if (empty($course_code)) {
  6648. $course_code = api_get_course_id();
  6649. }
  6650. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
  6651. $item_id = intval($item_id);
  6652. $link_type = intval($link_type);
  6653. $course_code = Database::escape_string($course_code);
  6654. $sql = "SELECT locked FROM $table
  6655. WHERE locked = 1 AND ref_id = $item_id AND type = $link_type AND course_code = '$course_code' ";
  6656. $result = Database::query($sql);
  6657. if (Database::num_rows($result)) {
  6658. return true;
  6659. }
  6660. }
  6661. return false;
  6662. }
  6663. /**
  6664. * Blocks a page if the item was added in a gradebook.
  6665. *
  6666. * @param int exercise id, work id, thread id,
  6667. * @param int LINK_EXERCISE, LINK_STUDENTPUBLICATION, LINK_LEARNPATH LINK_FORUM_THREAD, LINK_ATTENDANCE
  6668. * see gradebook/lib/be/linkfactory
  6669. * @param string course code
  6670. *
  6671. * @return false|null
  6672. */
  6673. function api_block_course_item_locked_by_gradebook($item_id, $link_type, $course_code = null)
  6674. {
  6675. if (api_is_platform_admin()) {
  6676. return false;
  6677. }
  6678. if (api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code)) {
  6679. $message = Display::return_message(get_lang('ResourceLockedByGradebook'), 'warning');
  6680. api_not_allowed(true, $message);
  6681. }
  6682. }
  6683. /**
  6684. * Checks the PHP version installed is enough to run Chamilo.
  6685. *
  6686. * @param string Include path (used to load the error page)
  6687. */
  6688. function api_check_php_version($my_inc_path = null)
  6689. {
  6690. if (!function_exists('version_compare') || version_compare(phpversion(), REQUIRED_PHP_VERSION, '<')) {
  6691. $global_error_code = 1;
  6692. // Incorrect PHP version
  6693. $global_page = $my_inc_path.'global_error_message.inc.php';
  6694. if (file_exists($global_page)) {
  6695. require $global_page;
  6696. }
  6697. exit;
  6698. }
  6699. }
  6700. /**
  6701. * Checks whether the Archive directory is present and writeable. If not,
  6702. * prints a warning message.
  6703. */
  6704. function api_check_archive_dir()
  6705. {
  6706. if (is_dir(api_get_path(SYS_ARCHIVE_PATH)) && !is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
  6707. $message = Display::return_message(get_lang('ArchivesDirectoryNotWriteableContactAdmin'), 'warning');
  6708. api_not_allowed(true, $message);
  6709. }
  6710. }
  6711. /**
  6712. * Returns an array of global configuration settings which should be ignored
  6713. * when printing the configuration settings screens.
  6714. *
  6715. * @return array Array of strings, each identifying one of the excluded settings
  6716. */
  6717. function api_get_locked_settings()
  6718. {
  6719. return [
  6720. 'server_type',
  6721. 'permanently_remove_deleted_files',
  6722. 'account_valid_duration',
  6723. 'service_ppt2lp',
  6724. 'wcag_anysurfer_public_pages',
  6725. 'upload_extensions_list_type',
  6726. 'upload_extensions_blacklist',
  6727. 'upload_extensions_whitelist',
  6728. 'upload_extensions_skip',
  6729. 'upload_extensions_replace_by',
  6730. 'hide_dltt_markup',
  6731. 'split_users_upload_directory',
  6732. 'permissions_for_new_directories',
  6733. 'permissions_for_new_files',
  6734. 'platform_charset',
  6735. 'ldap_description',
  6736. 'cas_activate',
  6737. 'cas_server',
  6738. 'cas_server_uri',
  6739. 'cas_port',
  6740. 'cas_protocol',
  6741. 'cas_add_user_activate',
  6742. 'update_user_info_cas_with_ldap',
  6743. 'languagePriority1',
  6744. 'languagePriority2',
  6745. 'languagePriority3',
  6746. 'languagePriority4',
  6747. 'login_is_email',
  6748. 'chamilo_database_version',
  6749. ];
  6750. }
  6751. /**
  6752. * Checks if the user is corrently logged in. Returns the user ID if he is, or
  6753. * false if he isn't. If the user ID is given and is an integer, then the same
  6754. * ID is simply returned.
  6755. *
  6756. * @param int User ID
  6757. *
  6758. * @return bool Integer User ID is logged in, or false otherwise
  6759. */
  6760. function api_user_is_login($user_id = null)
  6761. {
  6762. $user_id = empty($user_id) ? api_get_user_id() : (int) $user_id;
  6763. return $user_id && !api_is_anonymous();
  6764. }
  6765. /**
  6766. * Guess the real ip for register in the database, even in reverse proxy cases.
  6767. * To be recognized, the IP has to be found in either $_SERVER['REMOTE_ADDR'] or
  6768. * in $_SERVER['HTTP_X_FORWARDED_FOR'], which is in common use with rproxies.
  6769. * Note: the result of this function is not SQL-safe. Please escape it before
  6770. * inserting in a database.
  6771. *
  6772. * @return string the user's real ip (unsafe - escape it before inserting to db)
  6773. *
  6774. * @author Jorge Frisancho Jibaja <jrfdeft@gmail.com>, USIL - Some changes to allow the use of real IP using reverse proxy
  6775. *
  6776. * @version CEV CHANGE 24APR2012
  6777. */
  6778. function api_get_real_ip()
  6779. {
  6780. $ip = trim($_SERVER['REMOTE_ADDR']);
  6781. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  6782. if (preg_match('/,/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  6783. @list($ip1, $ip2) = @explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  6784. } else {
  6785. $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
  6786. }
  6787. $ip = trim($ip1);
  6788. }
  6789. return $ip;
  6790. }
  6791. /**
  6792. * Checks whether an IP is included inside an IP range.
  6793. *
  6794. * @param string IP address
  6795. * @param string IP range
  6796. * @param string $ip
  6797. *
  6798. * @return bool True if IP is in the range, false otherwise
  6799. *
  6800. * @author claudiu at cnixs dot com on http://www.php.net/manual/fr/ref.network.php#55230
  6801. * @author Yannick Warnier for improvements and managment of multiple ranges
  6802. *
  6803. * @todo check for IPv6 support
  6804. */
  6805. function api_check_ip_in_range($ip, $range)
  6806. {
  6807. if (empty($ip) or empty($range)) {
  6808. return false;
  6809. }
  6810. $ip_ip = ip2long($ip);
  6811. // divide range param into array of elements
  6812. if (strpos($range, ',') !== false) {
  6813. $ranges = explode(',', $range);
  6814. } else {
  6815. $ranges = [$range];
  6816. }
  6817. foreach ($ranges as $range) {
  6818. $range = trim($range);
  6819. if (empty($range)) {
  6820. continue;
  6821. }
  6822. if (strpos($range, '/') === false) {
  6823. if (strcmp($ip, $range) === 0) {
  6824. return true; // there is a direct IP match, return OK
  6825. }
  6826. continue; //otherwise, get to the next range
  6827. }
  6828. // the range contains a "/", so analyse completely
  6829. list($net, $mask) = explode("/", $range);
  6830. $ip_net = ip2long($net);
  6831. // mask binary magic
  6832. $ip_mask = ~((1 << (32 - $mask)) - 1);
  6833. $ip_ip_net = $ip_ip & $ip_mask;
  6834. if ($ip_ip_net == $ip_net) {
  6835. return true;
  6836. }
  6837. }
  6838. return false;
  6839. }
  6840. function api_check_user_access_to_legal($course_visibility)
  6841. {
  6842. $course_visibility_list = [COURSE_VISIBILITY_OPEN_WORLD, COURSE_VISIBILITY_OPEN_PLATFORM];
  6843. return in_array($course_visibility, $course_visibility_list) || api_is_drh();
  6844. }
  6845. /**
  6846. * Checks if the global chat is enabled or not.
  6847. *
  6848. * @return bool
  6849. */
  6850. function api_is_global_chat_enabled()
  6851. {
  6852. return
  6853. !api_is_anonymous() &&
  6854. api_get_setting('allow_global_chat') === 'true' &&
  6855. api_get_setting('allow_social_tool') === 'true';
  6856. }
  6857. /**
  6858. * @todo Fix tool_visible_by_default_at_creation labels
  6859. *
  6860. * @param int $item_id
  6861. * @param int $tool_id
  6862. * @param int $group_id id
  6863. * @param array $courseInfo
  6864. * @param int $sessionId
  6865. * @param int $userId
  6866. */
  6867. function api_set_default_visibility(
  6868. $item_id,
  6869. $tool_id,
  6870. $group_id = 0,
  6871. $courseInfo = [],
  6872. $sessionId = 0,
  6873. $userId = 0
  6874. ) {
  6875. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  6876. $courseId = $courseInfo['real_id'];
  6877. $courseCode = $courseInfo['code'];
  6878. $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
  6879. $userId = empty($userId) ? api_get_user_id() : $userId;
  6880. // if group is null force group_id = 0, this force is needed to create a LP folder with group = 0
  6881. if (is_null($group_id)) {
  6882. $group_id = 0;
  6883. } else {
  6884. $group_id = empty($group_id) ? api_get_group_id() : $group_id;
  6885. }
  6886. $groupInfo = [];
  6887. if (!empty($group_id)) {
  6888. $groupInfo = GroupManager::get_group_properties($group_id);
  6889. }
  6890. $original_tool_id = $tool_id;
  6891. switch ($tool_id) {
  6892. case TOOL_LINK:
  6893. case TOOL_LINK_CATEGORY:
  6894. $tool_id = 'links';
  6895. break;
  6896. case TOOL_DOCUMENT:
  6897. $tool_id = 'documents';
  6898. break;
  6899. case TOOL_LEARNPATH:
  6900. $tool_id = 'learning';
  6901. break;
  6902. case TOOL_ANNOUNCEMENT:
  6903. $tool_id = 'announcements';
  6904. break;
  6905. case TOOL_FORUM:
  6906. case TOOL_FORUM_CATEGORY:
  6907. case TOOL_FORUM_THREAD:
  6908. $tool_id = 'forums';
  6909. break;
  6910. case TOOL_QUIZ:
  6911. $tool_id = 'quiz';
  6912. break;
  6913. }
  6914. $setting = api_get_setting('tool_visible_by_default_at_creation');
  6915. if (isset($setting[$tool_id])) {
  6916. $visibility = 'invisible';
  6917. if ($setting[$tool_id] == 'true') {
  6918. $visibility = 'visible';
  6919. }
  6920. // Read the portal and course default visibility
  6921. if ($tool_id == 'documents') {
  6922. $visibility = DocumentManager::getDocumentDefaultVisibility($courseCode);
  6923. }
  6924. api_item_property_update(
  6925. $courseInfo,
  6926. $original_tool_id,
  6927. $item_id,
  6928. $visibility,
  6929. $userId,
  6930. $groupInfo,
  6931. null,
  6932. null,
  6933. null,
  6934. $sessionId
  6935. );
  6936. // Fixes default visibility for tests
  6937. switch ($original_tool_id) {
  6938. case TOOL_QUIZ:
  6939. if (empty($sessionId)) {
  6940. $objExerciseTmp = new Exercise($courseId);
  6941. $objExerciseTmp->read($item_id);
  6942. if ($visibility == 'visible') {
  6943. $objExerciseTmp->enable();
  6944. $objExerciseTmp->save();
  6945. } else {
  6946. $objExerciseTmp->disable();
  6947. $objExerciseTmp->save();
  6948. }
  6949. }
  6950. break;
  6951. }
  6952. }
  6953. }
  6954. /**
  6955. * @return string
  6956. */
  6957. function api_get_security_key()
  6958. {
  6959. return api_get_configuration_value('security_key');
  6960. }
  6961. /**
  6962. * @param int $user_id
  6963. * @param int $courseId
  6964. * @param int $session_id
  6965. *
  6966. * @return array
  6967. */
  6968. function api_detect_user_roles($user_id, $courseId, $session_id = 0)
  6969. {
  6970. $user_roles = [];
  6971. $courseInfo = api_get_course_info_by_id($courseId);
  6972. $course_code = $courseInfo['code'];
  6973. $url_id = api_get_current_access_url_id();
  6974. if (api_is_platform_admin_by_id($user_id, $url_id)) {
  6975. $user_roles[] = PLATFORM_ADMIN;
  6976. }
  6977. /*if (api_is_drh()) {
  6978. $user_roles[] = DRH;
  6979. }*/
  6980. if (!empty($session_id)) {
  6981. if (SessionManager::user_is_general_coach($user_id, $session_id)) {
  6982. $user_roles[] = SESSION_GENERAL_COACH;
  6983. }
  6984. }
  6985. if (!empty($course_code)) {
  6986. if (empty($session_id)) {
  6987. if (CourseManager::is_course_teacher($user_id, $course_code)) {
  6988. $user_roles[] = COURSEMANAGER;
  6989. }
  6990. if (CourseManager::get_tutor_in_course_status($user_id, $courseInfo['real_id'])) {
  6991. $user_roles[] = COURSE_TUTOR;
  6992. }
  6993. if (CourseManager::is_user_subscribed_in_course($user_id, $course_code)) {
  6994. $user_roles[] = COURSE_STUDENT;
  6995. }
  6996. } else {
  6997. $user_status_in_session = SessionManager::get_user_status_in_course_session(
  6998. $user_id,
  6999. $courseId,
  7000. $session_id
  7001. );
  7002. if (!empty($user_status_in_session)) {
  7003. if ($user_status_in_session == 0) {
  7004. $user_roles[] = SESSION_STUDENT;
  7005. }
  7006. if ($user_status_in_session == 2) {
  7007. $user_roles[] = SESSION_COURSE_COACH;
  7008. }
  7009. }
  7010. /*if (api_is_course_session_coach($user_id, $course_code, $session_id)) {
  7011. $user_roles[] = SESSION_COURSE_COACH;
  7012. }*/
  7013. }
  7014. }
  7015. return $user_roles;
  7016. }
  7017. /**
  7018. * @param int $courseId
  7019. * @param int $session_id
  7020. *
  7021. * @return bool
  7022. */
  7023. function api_coach_can_edit_view_results($courseId = null, $session_id = null)
  7024. {
  7025. if (api_is_platform_admin()) {
  7026. return true;
  7027. }
  7028. $user_id = api_get_user_id();
  7029. if (empty($courseId)) {
  7030. $courseId = api_get_course_int_id();
  7031. }
  7032. if (empty($session_id)) {
  7033. $session_id = api_get_session_id();
  7034. }
  7035. $roles = api_detect_user_roles($user_id, $courseId, $session_id);
  7036. if (in_array(SESSION_COURSE_COACH, $roles)) {
  7037. //return api_get_setting('session_tutor_reports_visibility') == 'true';
  7038. return true;
  7039. } else {
  7040. if (in_array(COURSEMANAGER, $roles)) {
  7041. return true;
  7042. }
  7043. return false;
  7044. }
  7045. }
  7046. /**
  7047. * @param string $file
  7048. *
  7049. * @return string
  7050. */
  7051. function api_get_js_simple($file)
  7052. {
  7053. return '<script type="text/javascript" src="'.$file.'"></script>'."\n";
  7054. }
  7055. function api_set_settings_and_plugins()
  7056. {
  7057. global $_configuration;
  7058. $_setting = [];
  7059. $_plugins = [];
  7060. // access_url == 1 is the default chamilo location
  7061. $settings_by_access_list = [];
  7062. $access_url_id = api_get_current_access_url_id();
  7063. if ($access_url_id != 1) {
  7064. $url_info = api_get_access_url($_configuration['access_url']);
  7065. if ($url_info['active'] == 1) {
  7066. $settings_by_access = &api_get_settings(null, 'list', $_configuration['access_url'], 1);
  7067. foreach ($settings_by_access as &$row) {
  7068. if (empty($row['variable'])) {
  7069. $row['variable'] = 0;
  7070. }
  7071. if (empty($row['subkey'])) {
  7072. $row['subkey'] = 0;
  7073. }
  7074. if (empty($row['category'])) {
  7075. $row['category'] = 0;
  7076. }
  7077. $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
  7078. }
  7079. }
  7080. }
  7081. $result = api_get_settings(null, 'list', 1);
  7082. foreach ($result as &$row) {
  7083. if ($access_url_id != 1) {
  7084. if ($url_info['active'] == 1) {
  7085. $var = empty($row['variable']) ? 0 : $row['variable'];
  7086. $subkey = empty($row['subkey']) ? 0 : $row['subkey'];
  7087. $category = empty($row['category']) ? 0 : $row['category'];
  7088. }
  7089. if ($row['access_url_changeable'] == 1 && $url_info['active'] == 1) {
  7090. if (isset($settings_by_access_list[$var]) &&
  7091. $settings_by_access_list[$var][$subkey][$category]['selected_value'] != '') {
  7092. if ($row['subkey'] == null) {
  7093. $_setting[$row['variable']] = $settings_by_access_list[$var][$subkey][$category]['selected_value'];
  7094. } else {
  7095. $_setting[$row['variable']][$row['subkey']] = $settings_by_access_list[$var][$subkey][$category]['selected_value'];
  7096. }
  7097. } else {
  7098. if ($row['subkey'] == null) {
  7099. $_setting[$row['variable']] = $row['selected_value'];
  7100. } else {
  7101. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  7102. }
  7103. }
  7104. } else {
  7105. if ($row['subkey'] == null) {
  7106. $_setting[$row['variable']] = $row['selected_value'];
  7107. } else {
  7108. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  7109. }
  7110. }
  7111. } else {
  7112. if ($row['subkey'] == null) {
  7113. $_setting[$row['variable']] = $row['selected_value'];
  7114. } else {
  7115. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  7116. }
  7117. }
  7118. }
  7119. $result = api_get_settings('Plugins', 'list', $access_url_id);
  7120. $_plugins = [];
  7121. foreach ($result as &$row) {
  7122. $key = &$row['variable'];
  7123. if (is_string($_setting[$key])) {
  7124. $_setting[$key] = [];
  7125. }
  7126. $_setting[$key][] = $row['selected_value'];
  7127. $_plugins[$key][] = $row['selected_value'];
  7128. }
  7129. $_SESSION['_setting'] = $_setting;
  7130. $_SESSION['_plugins'] = $_plugins;
  7131. }
  7132. /**
  7133. * Modify default memory_limit and max_execution_time limits
  7134. * Needed when processing long tasks.
  7135. */
  7136. function api_set_more_memory_and_time_limits()
  7137. {
  7138. if (function_exists('ini_set')) {
  7139. api_set_memory_limit('256M');
  7140. ini_set('max_execution_time', 1800);
  7141. }
  7142. }
  7143. /**
  7144. * Tries to set memory limit, if authorized and new limit is higher than current.
  7145. *
  7146. * @param string $mem New memory limit
  7147. *
  7148. * @return bool True on success, false on failure or current is higher than suggested
  7149. * @assert (null) === false
  7150. * @assert (-1) === false
  7151. * @assert (0) === true
  7152. * @assert ('1G') === true
  7153. */
  7154. function api_set_memory_limit($mem)
  7155. {
  7156. //if ini_set() not available, this function is useless
  7157. if (!function_exists('ini_set') || is_null($mem) || $mem == -1) {
  7158. return false;
  7159. }
  7160. $memory_limit = ini_get('memory_limit');
  7161. if (api_get_bytes_memory_limit($mem) > api_get_bytes_memory_limit($memory_limit)) {
  7162. ini_set('memory_limit', $mem);
  7163. return true;
  7164. }
  7165. return false;
  7166. }
  7167. /**
  7168. * Gets memory limit in bytes.
  7169. *
  7170. * @param string The memory size (128M, 1G, 1000K, etc)
  7171. *
  7172. * @return int
  7173. * @assert (null) === false
  7174. * @assert ('1t') === 1099511627776
  7175. * @assert ('1g') === 1073741824
  7176. * @assert ('1m') === 1048576
  7177. * @assert ('100k') === 102400
  7178. */
  7179. function api_get_bytes_memory_limit($mem)
  7180. {
  7181. $size = strtolower(substr($mem, -1));
  7182. switch ($size) {
  7183. case 't':
  7184. $mem = intval(substr($mem, -1)) * 1024 * 1024 * 1024 * 1024;
  7185. break;
  7186. case 'g':
  7187. $mem = intval(substr($mem, 0, -1)) * 1024 * 1024 * 1024;
  7188. break;
  7189. case 'm':
  7190. $mem = intval(substr($mem, 0, -1)) * 1024 * 1024;
  7191. break;
  7192. case 'k':
  7193. $mem = intval(substr($mem, 0, -1)) * 1024;
  7194. break;
  7195. default:
  7196. // we assume it's integer only
  7197. $mem = intval($mem);
  7198. break;
  7199. }
  7200. return $mem;
  7201. }
  7202. /**
  7203. * Finds all the information about a user from username instead of user id.
  7204. *
  7205. * @param string $officialCode
  7206. *
  7207. * @return array $user_info user_id, lastname, firstname, username, email, ...
  7208. *
  7209. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  7210. */
  7211. function api_get_user_info_from_official_code($officialCode)
  7212. {
  7213. if (empty($officialCode)) {
  7214. return false;
  7215. }
  7216. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  7217. WHERE official_code ='".Database::escape_string($officialCode)."'";
  7218. $result = Database::query($sql);
  7219. if (Database::num_rows($result) > 0) {
  7220. $result_array = Database::fetch_array($result);
  7221. return _api_format_user($result_array);
  7222. }
  7223. return false;
  7224. }
  7225. /**
  7226. * @param string $usernameInputId
  7227. * @param string $passwordInputId
  7228. *
  7229. * @return string|null
  7230. */
  7231. function api_get_password_checker_js($usernameInputId, $passwordInputId)
  7232. {
  7233. $checkPass = api_get_setting('allow_strength_pass_checker');
  7234. $useStrengthPassChecker = $checkPass === 'true';
  7235. if ($useStrengthPassChecker === false) {
  7236. return null;
  7237. }
  7238. $translations = [
  7239. 'wordLength' => get_lang('PasswordIsTooShort'),
  7240. 'wordNotEmail' => get_lang('YourPasswordCannotBeTheSameAsYourEmail'),
  7241. 'wordSimilarToUsername' => get_lang('YourPasswordCannotContainYourUsername'),
  7242. 'wordTwoCharacterClasses' => get_lang('WordTwoCharacterClasses'),
  7243. 'wordRepetitions' => get_lang('TooManyRepetitions'),
  7244. 'wordSequences' => get_lang('YourPasswordContainsSequences'),
  7245. 'errorList' => get_lang('ErrorsFound'),
  7246. 'veryWeak' => get_lang('PasswordVeryWeak'),
  7247. 'weak' => get_lang('PasswordWeak'),
  7248. 'normal' => get_lang('PasswordNormal'),
  7249. 'medium' => get_lang('PasswordMedium'),
  7250. 'strong' => get_lang('PasswordStrong'),
  7251. 'veryStrong' => get_lang('PasswordVeryStrong'),
  7252. ];
  7253. $js = api_get_asset('pwstrength-bootstrap/dist/pwstrength-bootstrap.min.js');
  7254. $js .= "<script>
  7255. var errorMessages = {
  7256. password_to_short : \"".get_lang('PasswordIsTooShort')."\",
  7257. same_as_username : \"".get_lang('YourPasswordCannotBeTheSameAsYourUsername')."\"
  7258. };
  7259. $(function() {
  7260. var lang = ".json_encode($translations).";
  7261. var options = {
  7262. onLoad : function () {
  7263. //$('#messages').text('Start typing password');
  7264. },
  7265. onKeyUp: function (evt) {
  7266. $(evt.target).pwstrength('outputErrorList');
  7267. },
  7268. errorMessages : errorMessages,
  7269. viewports: {
  7270. progress: '#password_progress',
  7271. verdict: '#password-verdict',
  7272. errors: '#password-errors'
  7273. },
  7274. usernameField: '$usernameInputId'
  7275. };
  7276. options.i18n = {
  7277. t: function (key) {
  7278. var result = lang[key];
  7279. return result === key ? '' : result; // This assumes you return the
  7280. }
  7281. };
  7282. $('".$passwordInputId."').pwstrength(options);
  7283. });
  7284. </script>";
  7285. return $js;
  7286. }
  7287. /**
  7288. * create an user extra field called 'captcha_blocked_until_date'.
  7289. *
  7290. * @param string $username
  7291. *
  7292. * @return bool
  7293. */
  7294. function api_block_account_captcha($username)
  7295. {
  7296. $userInfo = api_get_user_info_from_username($username);
  7297. if (empty($userInfo)) {
  7298. return false;
  7299. }
  7300. $minutesToBlock = api_get_setting('captcha_time_to_block');
  7301. $time = time() + $minutesToBlock * 60;
  7302. UserManager::update_extra_field_value(
  7303. $userInfo['user_id'],
  7304. 'captcha_blocked_until_date',
  7305. api_get_utc_datetime($time)
  7306. );
  7307. return true;
  7308. }
  7309. /**
  7310. * @param string $username
  7311. *
  7312. * @return bool
  7313. */
  7314. function api_clean_account_captcha($username)
  7315. {
  7316. $userInfo = api_get_user_info_from_username($username);
  7317. if (empty($userInfo)) {
  7318. return false;
  7319. }
  7320. Session::erase('loginFailedCount');
  7321. UserManager::update_extra_field_value(
  7322. $userInfo['user_id'],
  7323. 'captcha_blocked_until_date',
  7324. null
  7325. );
  7326. return true;
  7327. }
  7328. /**
  7329. * @param string $username
  7330. *
  7331. * @return bool
  7332. */
  7333. function api_get_user_blocked_by_captcha($username)
  7334. {
  7335. $userInfo = api_get_user_info_from_username($username);
  7336. if (empty($userInfo)) {
  7337. return false;
  7338. }
  7339. $data = UserManager::get_extra_user_data_by_field(
  7340. $userInfo['user_id'],
  7341. 'captcha_blocked_until_date'
  7342. );
  7343. if (isset($data) && isset($data['captcha_blocked_until_date'])) {
  7344. return $data['captcha_blocked_until_date'];
  7345. }
  7346. return false;
  7347. }
  7348. /**
  7349. * Remove tags from HTML anf return the $in_number_char first non-HTML char
  7350. * Postfix the text with "..." if it has been truncated.
  7351. *
  7352. * @param string $text
  7353. * @param int $number
  7354. *
  7355. * @return string
  7356. *
  7357. * @author hubert borderiou
  7358. */
  7359. function api_get_short_text_from_html($text, $number)
  7360. {
  7361. // Delete script and style tags
  7362. $text = preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/is', "$1$3", $text);
  7363. $text = api_html_entity_decode($text);
  7364. $out_res = api_remove_tags_with_space($text, false);
  7365. $postfix = "...";
  7366. if (strlen($out_res) > $number) {
  7367. $out_res = substr($out_res, 0, $number).$postfix;
  7368. }
  7369. return $out_res;
  7370. }
  7371. /**
  7372. * Replace tags with a space in a text.
  7373. * If $in_double_quote_replace, replace " with '' (for HTML attribute purpose, for exemple).
  7374. *
  7375. * @return string
  7376. *
  7377. * @author hubert borderiou
  7378. */
  7379. function api_remove_tags_with_space($in_html, $in_double_quote_replace = true)
  7380. {
  7381. $out_res = $in_html;
  7382. if ($in_double_quote_replace) {
  7383. $out_res = str_replace('"', "''", $out_res);
  7384. }
  7385. // avoid text stuck together when tags are removed, adding a space after >
  7386. $out_res = str_replace(">", "> ", $out_res);
  7387. $out_res = strip_tags($out_res);
  7388. return $out_res;
  7389. }
  7390. /**
  7391. * If true, the drh can access all content (courses, users) inside a session.
  7392. *
  7393. * @return bool
  7394. */
  7395. function api_drh_can_access_all_session_content()
  7396. {
  7397. $value = api_get_setting('drh_can_access_all_session_content');
  7398. return $value === 'true';
  7399. }
  7400. /**
  7401. * @param string $tool
  7402. * @param string $setting
  7403. * @param int $defaultValue
  7404. *
  7405. * @return string
  7406. */
  7407. function api_get_default_tool_setting($tool, $setting, $defaultValue)
  7408. {
  7409. global $_configuration;
  7410. if (isset($_configuration[$tool]) &&
  7411. isset($_configuration[$tool]['default_settings']) &&
  7412. isset($_configuration[$tool]['default_settings'][$setting])
  7413. ) {
  7414. return $_configuration[$tool]['default_settings'][$setting];
  7415. }
  7416. return $defaultValue;
  7417. }
  7418. /**
  7419. * Checks if user can login as another user.
  7420. *
  7421. * @param int $loginAsUserId the user id to log in
  7422. * @param int $userId my user id
  7423. *
  7424. * @return bool
  7425. */
  7426. function api_can_login_as($loginAsUserId, $userId = null)
  7427. {
  7428. if (empty($userId)) {
  7429. $userId = api_get_user_id();
  7430. }
  7431. if ($loginAsUserId == $userId) {
  7432. return false;
  7433. }
  7434. if (empty($loginAsUserId)) {
  7435. return false;
  7436. }
  7437. if ($loginAsUserId != strval(intval($loginAsUserId))) {
  7438. return false;
  7439. }
  7440. // Check if the user to login is an admin
  7441. if (api_is_platform_admin_by_id($loginAsUserId)) {
  7442. // Only super admins can login to admin accounts
  7443. if (!api_global_admin_can_edit_admin($loginAsUserId)) {
  7444. return false;
  7445. }
  7446. }
  7447. $userInfo = api_get_user_info($loginAsUserId);
  7448. $isDrh = function () use ($loginAsUserId) {
  7449. if (api_is_drh()) {
  7450. if (api_drh_can_access_all_session_content()) {
  7451. $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
  7452. 'drh_all',
  7453. api_get_user_id()
  7454. );
  7455. $userList = [];
  7456. if (is_array($users)) {
  7457. foreach ($users as $user) {
  7458. $userList[] = $user['user_id'];
  7459. }
  7460. }
  7461. if (in_array($loginAsUserId, $userList)) {
  7462. return true;
  7463. }
  7464. } else {
  7465. if (api_is_drh() &&
  7466. UserManager::is_user_followed_by_drh($loginAsUserId, api_get_user_id())
  7467. ) {
  7468. return true;
  7469. }
  7470. }
  7471. }
  7472. return false;
  7473. };
  7474. $loginAsStatusForSessionAdmins = [STUDENT];
  7475. if (api_get_configuration_value('allow_session_admin_login_as_teacher')) {
  7476. $loginAsStatusForSessionAdmins[] = COURSEMANAGER;
  7477. }
  7478. return api_is_platform_admin() ||
  7479. (api_is_session_admin() && in_array($userInfo['status'], $loginAsStatusForSessionAdmins)) ||
  7480. $isDrh();
  7481. }
  7482. /**
  7483. * @return bool
  7484. */
  7485. function api_is_allowed_in_course()
  7486. {
  7487. if (api_is_platform_admin()) {
  7488. return true;
  7489. }
  7490. return Session::read('is_allowed_in_course');
  7491. }
  7492. /**
  7493. * Set the cookie to go directly to the course code $in_firstpage
  7494. * after login.
  7495. *
  7496. * @param string $value is the course code of the course to go
  7497. */
  7498. function api_set_firstpage_parameter($value)
  7499. {
  7500. setcookie('GotoCourse', $value);
  7501. }
  7502. /**
  7503. * Delete the cookie to go directly to the course code $in_firstpage
  7504. * after login.
  7505. */
  7506. function api_delete_firstpage_parameter()
  7507. {
  7508. setcookie('GotoCourse', '', time() - 3600);
  7509. }
  7510. /**
  7511. * @return bool if course_code for direct course access after login is set
  7512. */
  7513. function exist_firstpage_parameter()
  7514. {
  7515. return isset($_COOKIE['GotoCourse']) && $_COOKIE['GotoCourse'] != '';
  7516. }
  7517. /**
  7518. * @return return the course_code of the course where user login
  7519. */
  7520. function api_get_firstpage_parameter()
  7521. {
  7522. return $_COOKIE['GotoCourse'];
  7523. }
  7524. /**
  7525. * Return true on https install.
  7526. *
  7527. * @return bool
  7528. */
  7529. function api_is_https()
  7530. {
  7531. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  7532. $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_configuration['force_https_forwarded_proto'])
  7533. ) {
  7534. $isSecured = true;
  7535. } else {
  7536. if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  7537. $isSecured = true;
  7538. } else {
  7539. $isSecured = false;
  7540. // last chance
  7541. if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
  7542. $isSecured = true;
  7543. }
  7544. }
  7545. }
  7546. return $isSecured;
  7547. }
  7548. /**
  7549. * Return protocol (http or https).
  7550. *
  7551. * @return string
  7552. */
  7553. function api_get_protocol()
  7554. {
  7555. return api_is_https() ? 'https' : 'http';
  7556. }
  7557. /**
  7558. * Return a string where " are replaced with 2 '
  7559. * It is useful when you pass a PHP variable in a Javascript browser dialog
  7560. * e.g. : alert("<?php get_lang('Message') ?>");
  7561. * and message contains character ".
  7562. *
  7563. * @param string $in_text
  7564. *
  7565. * @return string
  7566. */
  7567. function convert_double_quote_to_single($in_text)
  7568. {
  7569. return api_preg_replace('/"/', "''", $in_text);
  7570. }
  7571. /**
  7572. * Get origin.
  7573. *
  7574. * @param string
  7575. *
  7576. * @return string
  7577. */
  7578. function api_get_origin()
  7579. {
  7580. $origin = isset($_REQUEST['origin']) ? Security::remove_XSS($_REQUEST['origin']) : '';
  7581. return $origin;
  7582. }
  7583. /**
  7584. * Warns an user that the portal reach certain limit.
  7585. *
  7586. * @param string $limitName
  7587. */
  7588. function api_warn_hosting_contact($limitName)
  7589. {
  7590. $hostingParams = api_get_configuration_value(1);
  7591. $email = null;
  7592. if (!empty($hostingParams)) {
  7593. if (isset($hostingParams['hosting_contact_mail'])) {
  7594. $email = $hostingParams['hosting_contact_mail'];
  7595. }
  7596. }
  7597. if (!empty($email)) {
  7598. $subject = get_lang('HostingWarningReached');
  7599. $body = get_lang('PortalName').': '.api_get_path(WEB_PATH)." \n ";
  7600. $body .= get_lang('PortalLimitType').': '.$limitName." \n ";
  7601. if (isset($hostingParams[$limitName])) {
  7602. $body .= get_lang('Value').': '.$hostingParams[$limitName];
  7603. }
  7604. api_mail_html(null, $email, $subject, $body);
  7605. }
  7606. }
  7607. /**
  7608. * Gets value of a variable from app/config/configuration.php
  7609. * Variables that are not set in the configuration.php file but set elsewhere:
  7610. * - virtual_css_theme_folder (vchamilo plugin)
  7611. * - access_url (global.inc.php)
  7612. * - apc/apc_prefix (global.inc.php).
  7613. *
  7614. * @param string $variable
  7615. *
  7616. * @return bool|mixed
  7617. */
  7618. function api_get_configuration_value($variable)
  7619. {
  7620. global $_configuration;
  7621. // Check the current url id, id = 1 by default
  7622. $urlId = isset($_configuration['access_url']) ? (int) $_configuration['access_url'] : 1;
  7623. $variable = trim($variable);
  7624. // Check if variable exists
  7625. if (isset($_configuration[$variable])) {
  7626. if (is_array($_configuration[$variable])) {
  7627. // Check if it exists for the sub portal
  7628. if (array_key_exists($urlId, $_configuration[$variable])) {
  7629. return $_configuration[$variable][$urlId];
  7630. } else {
  7631. // Try to found element with id = 1 (master portal)
  7632. if (array_key_exists(1, $_configuration[$variable])) {
  7633. return $_configuration[$variable][1];
  7634. }
  7635. }
  7636. }
  7637. return $_configuration[$variable];
  7638. }
  7639. return false;
  7640. }
  7641. /**
  7642. * Returns supported image extensions in the portal.
  7643. *
  7644. * @param bool $supportVectors Whether vector images should also be accepted or not
  7645. *
  7646. * @return array Supported image extensions in the portal
  7647. */
  7648. function api_get_supported_image_extensions($supportVectors = true)
  7649. {
  7650. // jpg can also be called jpeg, jpe, jfif and jif. See https://en.wikipedia.org/wiki/JPEG#JPEG_filename_extensions
  7651. $supportedImageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'jpe', 'jfif', 'jif'];
  7652. if ($supportVectors) {
  7653. array_push($supportedImageExtensions, 'svg');
  7654. }
  7655. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  7656. array_push($supportedImageExtensions, 'webp');
  7657. }
  7658. return $supportedImageExtensions;
  7659. }
  7660. /**
  7661. * This setting changes the registration status for the campus.
  7662. *
  7663. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  7664. *
  7665. * @version August 2006
  7666. *
  7667. * @param bool $listCampus Whether we authorize
  7668. *
  7669. * @todo the $_settings should be reloaded here. => write api function for this and use this in global.inc.php also.
  7670. */
  7671. function api_register_campus($listCampus = true)
  7672. {
  7673. $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  7674. $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
  7675. Database::query($sql);
  7676. if (!$listCampus) {
  7677. $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
  7678. Database::query($sql);
  7679. }
  7680. }
  7681. /**
  7682. * Checks whether current user is a student boss.
  7683. *
  7684. * @global array $_user
  7685. *
  7686. * @return bool
  7687. */
  7688. function api_is_student_boss()
  7689. {
  7690. $_user = api_get_user_info();
  7691. return isset($_user['status']) && $_user['status'] == STUDENT_BOSS;
  7692. }
  7693. /**
  7694. * Check whether the user type should be exclude.
  7695. * Such as invited or anonymous users.
  7696. *
  7697. * @param bool $checkDB Optional. Whether check the user status
  7698. * @param int $userId Options. The user id
  7699. *
  7700. * @return bool
  7701. */
  7702. function api_is_excluded_user_type($checkDB = false, $userId = 0)
  7703. {
  7704. if ($checkDB) {
  7705. $userId = empty($userId) ? api_get_user_id() : (int) $userId;
  7706. if ($userId == 0) {
  7707. return true;
  7708. }
  7709. $userInfo = api_get_user_info($userId);
  7710. switch ($userInfo['status']) {
  7711. case INVITEE:
  7712. case ANONYMOUS:
  7713. return true;
  7714. default:
  7715. return false;
  7716. }
  7717. }
  7718. $isInvited = api_is_invitee();
  7719. $isAnonymous = api_is_anonymous();
  7720. if ($isInvited || $isAnonymous) {
  7721. return true;
  7722. }
  7723. return false;
  7724. }
  7725. /**
  7726. * Get the user status to ignore in reports.
  7727. *
  7728. * @param string $format Optional. The result type (array or string)
  7729. *
  7730. * @return array|string
  7731. */
  7732. function api_get_users_status_ignored_in_reports($format = 'array')
  7733. {
  7734. $excludedTypes = [
  7735. INVITEE,
  7736. ANONYMOUS,
  7737. ];
  7738. if ($format == 'string') {
  7739. return implode(', ', $excludedTypes);
  7740. }
  7741. return $excludedTypes;
  7742. }
  7743. /**
  7744. * Set the Site Use Cookie Warning for 1 year.
  7745. */
  7746. function api_set_site_use_cookie_warning_cookie()
  7747. {
  7748. setcookie('ChamiloUsesCookies', 'ok', time() + 31556926);
  7749. }
  7750. /**
  7751. * Return true if the Site Use Cookie Warning Cookie warning exists.
  7752. *
  7753. * @return bool
  7754. */
  7755. function api_site_use_cookie_warning_cookie_exist()
  7756. {
  7757. return isset($_COOKIE['ChamiloUsesCookies']);
  7758. }
  7759. /**
  7760. * Given a number of seconds, format the time to show hours, minutes and seconds.
  7761. *
  7762. * @param int $time The time in seconds
  7763. * @param string $originFormat Optional. PHP o JS
  7764. *
  7765. * @return string (00h00'00")
  7766. */
  7767. function api_format_time($time, $originFormat = 'php')
  7768. {
  7769. $h = get_lang('h');
  7770. $hours = $time / 3600;
  7771. $mins = ($time % 3600) / 60;
  7772. $secs = ($time % 60);
  7773. if ($time < 0) {
  7774. $hours = 0;
  7775. $mins = 0;
  7776. $secs = 0;
  7777. }
  7778. if ($originFormat == 'js') {
  7779. $formattedTime = trim(sprintf("%02d : %02d : %02d", $hours, $mins, $secs));
  7780. } else {
  7781. $formattedTime = trim(sprintf("%02d$h%02d'%02d\"", $hours, $mins, $secs));
  7782. }
  7783. return $formattedTime;
  7784. }
  7785. /**
  7786. * Create a new empty directory with index.html file.
  7787. *
  7788. * @param string $name The new directory name
  7789. * @param string $parentDirectory Directory parent directory name
  7790. *
  7791. * @return bool Return true if the directory was create. Otherwise return false
  7792. */
  7793. function api_create_protected_dir($name, $parentDirectory)
  7794. {
  7795. $isCreated = false;
  7796. if (!is_writable($parentDirectory)) {
  7797. return false;
  7798. }
  7799. $fullPath = $parentDirectory.api_replace_dangerous_char($name);
  7800. if (mkdir($fullPath, api_get_permissions_for_new_directories(), true)) {
  7801. $fp = fopen($fullPath.'/index.html', 'w');
  7802. if ($fp) {
  7803. if (fwrite($fp, '<html><head></head><body></body></html>')) {
  7804. $isCreated = true;
  7805. }
  7806. }
  7807. fclose($fp);
  7808. }
  7809. return $isCreated;
  7810. }
  7811. /**
  7812. * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
  7813. * Sender name and email can be specified, if not specified
  7814. * name and email of the platform admin are used.
  7815. *
  7816. * @author Bert Vanderkimpen ICT&O UGent
  7817. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  7818. *
  7819. * @param string name of recipient
  7820. * @param string email of recipient
  7821. * @param string email subject
  7822. * @param string email body
  7823. * @param string sender name
  7824. * @param string sender e-mail
  7825. * @param array $extra_headers in form $headers = array($name => $value) to allow parsing
  7826. * @param array $data_file (path and filename)
  7827. * @param bool $embedded_image True for attaching a embedded file inside content html (optional)
  7828. * @param array $additionalParameters
  7829. * @param string $sendErrorTo If there's an error while sending the email, $sendErrorTo will receive a notification
  7830. *
  7831. * @return int true if mail was sent
  7832. *
  7833. * @see class.phpmailer.php
  7834. */
  7835. function api_mail_html(
  7836. $recipient_name,
  7837. $recipient_email,
  7838. $subject,
  7839. $message,
  7840. $senderName = '',
  7841. $senderEmail = '',
  7842. $extra_headers = [],
  7843. $data_file = [],
  7844. $embedded_image = false,
  7845. $additionalParameters = [],
  7846. $sendErrorTo = ''
  7847. ) {
  7848. global $platform_email;
  7849. $mail = new PHPMailer();
  7850. $mail->Mailer = $platform_email['SMTP_MAILER'];
  7851. $mail->Host = $platform_email['SMTP_HOST'];
  7852. $mail->Port = $platform_email['SMTP_PORT'];
  7853. $mail->CharSet = isset($platform_email['SMTP_CHARSET']) ? $platform_email['SMTP_CHARSET'] : 'UTF-8';
  7854. // Stay far below SMTP protocol 980 chars limit.
  7855. $mail->WordWrap = 200;
  7856. if ($platform_email['SMTP_AUTH']) {
  7857. $mail->SMTPAuth = 1;
  7858. $mail->Username = $platform_email['SMTP_USER'];
  7859. $mail->Password = $platform_email['SMTP_PASS'];
  7860. if (isset($platform_email['SMTP_SECURE'])) {
  7861. $mail->SMTPSecure = $platform_email['SMTP_SECURE'];
  7862. }
  7863. }
  7864. $mail->SMTPDebug = isset($platform_email['SMTP_DEBUG']) ? $platform_email['SMTP_DEBUG'] : 0;
  7865. // 5 = low, 1 = high
  7866. $mail->Priority = 3;
  7867. $mail->SMTPKeepAlive = true;
  7868. api_set_noreply_and_from_address_to_mailer(
  7869. $mail,
  7870. ['name' => $senderName, 'email' => $senderEmail],
  7871. !empty($extra_headers['reply_to']) ? $extra_headers['reply_to'] : []
  7872. );
  7873. if (!empty($sendErrorTo) && PHPMailer::ValidateAddress($sendErrorTo)) {
  7874. $mail->AddCustomHeader('Errors-To: '.$sendErrorTo);
  7875. }
  7876. unset($extra_headers['reply_to']);
  7877. $mail->Subject = $subject;
  7878. $mail->AltBody = strip_tags(
  7879. str_replace('<br />', "\n", api_html_entity_decode($message))
  7880. );
  7881. $list = api_get_configuration_value('send_all_emails_to');
  7882. if (!empty($list) && isset($list['emails'])) {
  7883. foreach ($list['emails'] as $email) {
  7884. $mail->AddAddress($email);
  7885. }
  7886. }
  7887. // Send embedded image.
  7888. if ($embedded_image) {
  7889. // Get all images html inside content.
  7890. preg_match_all("/<img\s+.*?src=[\"\']?([^\"\' >]*)[\"\']?[^>]*>/i", $message, $m);
  7891. // Prepare new tag images.
  7892. $new_images_html = [];
  7893. $i = 1;
  7894. if (!empty($m[1])) {
  7895. foreach ($m[1] as $image_path) {
  7896. $real_path = realpath($image_path);
  7897. $filename = basename($image_path);
  7898. $image_cid = $filename.'_'.$i;
  7899. $encoding = 'base64';
  7900. $image_type = mime_content_type($real_path);
  7901. $mail->AddEmbeddedImage(
  7902. $real_path,
  7903. $image_cid,
  7904. $filename,
  7905. $encoding,
  7906. $image_type
  7907. );
  7908. $new_images_html[] = '<img src="cid:'.$image_cid.'" />';
  7909. $i++;
  7910. }
  7911. }
  7912. // Replace origin image for new embedded image html.
  7913. $x = 0;
  7914. if (!empty($m[0])) {
  7915. foreach ($m[0] as $orig_img) {
  7916. $message = str_replace($orig_img, $new_images_html[$x], $message);
  7917. $x++;
  7918. }
  7919. }
  7920. }
  7921. $mailView = new Template(null, false, false, false, false, false, false);
  7922. $noReply = api_get_setting('noreply_email_address');
  7923. if (!empty($noReply)) {
  7924. $message .= '<br />'.get_lang('ThisIsAutomaticEmailNoReply');
  7925. }
  7926. $mailView->assign('content', $message);
  7927. if (isset($additionalParameters['link'])) {
  7928. $mailView->assign('link', $additionalParameters['link']);
  7929. }
  7930. $mailView->assign('mail_header_style', api_get_configuration_value('mail_header_style'));
  7931. $mailView->assign('mail_content_style', api_get_configuration_value('mail_content_style'));
  7932. $layout = $mailView->get_template('mail/mail.tpl');
  7933. $mail->Body = $mailView->fetch($layout);
  7934. // Attachment.
  7935. if (!empty($data_file)) {
  7936. foreach ($data_file as $file_attach) {
  7937. if (!empty($file_attach['path']) && !empty($file_attach['filename'])) {
  7938. $mail->AddAttachment($file_attach['path'], $file_attach['filename']);
  7939. }
  7940. }
  7941. }
  7942. // Only valid addresses are accepted.
  7943. if (is_array($recipient_email)) {
  7944. foreach ($recipient_email as $dest) {
  7945. if (api_valid_email($dest)) {
  7946. $mail->AddAddress($dest, $recipient_name);
  7947. }
  7948. }
  7949. } else {
  7950. if (api_valid_email($recipient_email)) {
  7951. $mail->AddAddress($recipient_email, $recipient_name);
  7952. } else {
  7953. return 0;
  7954. }
  7955. }
  7956. if (is_array($extra_headers) && count($extra_headers) > 0) {
  7957. foreach ($extra_headers as $key => $value) {
  7958. switch (strtolower($key)) {
  7959. case 'encoding':
  7960. case 'content-transfer-encoding':
  7961. $mail->Encoding = $value;
  7962. break;
  7963. case 'charset':
  7964. $mail->Charset = $value;
  7965. break;
  7966. case 'contenttype':
  7967. case 'content-type':
  7968. $mail->ContentType = $value;
  7969. break;
  7970. default:
  7971. $mail->AddCustomHeader($key.':'.$value);
  7972. break;
  7973. }
  7974. }
  7975. } else {
  7976. if (!empty($extra_headers)) {
  7977. $mail->AddCustomHeader($extra_headers);
  7978. }
  7979. }
  7980. // WordWrap the html body (phpMailer only fixes AltBody) FS#2988
  7981. $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap);
  7982. // Send the mail message.
  7983. if (!$mail->Send()) {
  7984. error_log('ERROR: mail not sent to '.$recipient_name.' ('.$recipient_email.') because of '.$mail->ErrorInfo.'<br />');
  7985. if ($mail->SMTPDebug) {
  7986. error_log(
  7987. "Connection details :: ".
  7988. "Protocol: ".$mail->Mailer.' :: '.
  7989. "Host/Port: ".$mail->Host.':'.$mail->Port.' :: '.
  7990. "Authent/Open: ".($mail->SMTPAuth ? 'Authent' : 'Open').' :: '.
  7991. ($mail->SMTPAuth ? " User/Pass: ".$mail->Username.':'.$mail->Password : '').' :: '.
  7992. "Sender: ".$mail->Sender
  7993. );
  7994. }
  7995. return 0;
  7996. }
  7997. if (!empty($additionalParameters)) {
  7998. $plugin = new AppPlugin();
  7999. $smsPlugin = $plugin->getSMSPluginLibrary();
  8000. if ($smsPlugin) {
  8001. $smsPlugin->send($additionalParameters);
  8002. }
  8003. }
  8004. // Clear all the addresses.
  8005. $mail->ClearAddresses();
  8006. // Clear all attachments
  8007. $mail->ClearAttachments();
  8008. return 1;
  8009. }
  8010. /**
  8011. * @param string $tool Possible values: GroupManager::GROUP_TOOL_*
  8012. * @param bool $showHeader
  8013. */
  8014. function api_protect_course_group($tool, $showHeader = true)
  8015. {
  8016. $groupId = api_get_group_id();
  8017. if (!empty($groupId)) {
  8018. if (api_is_platform_admin()) {
  8019. return true;
  8020. }
  8021. if (api_is_allowed_to_edit(false, true, true)) {
  8022. return true;
  8023. }
  8024. $userId = api_get_user_id();
  8025. $sessionId = api_get_session_id();
  8026. if (!empty($sessionId)) {
  8027. if (api_is_coach($sessionId, api_get_course_int_id())) {
  8028. return true;
  8029. }
  8030. if (api_is_drh()) {
  8031. if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
  8032. return true;
  8033. }
  8034. }
  8035. }
  8036. $groupInfo = GroupManager::get_group_properties($groupId);
  8037. // Group doesn't exists
  8038. if (empty($groupInfo)) {
  8039. api_not_allowed($showHeader);
  8040. }
  8041. // Check group access
  8042. $allow = GroupManager::user_has_access(
  8043. $userId,
  8044. $groupInfo['iid'],
  8045. $tool
  8046. );
  8047. if (!$allow) {
  8048. api_not_allowed($showHeader);
  8049. }
  8050. }
  8051. }
  8052. /**
  8053. * Check if a date is in a date range.
  8054. *
  8055. * @param datetime $startDate
  8056. * @param datetime $endDate
  8057. * @param datetime $currentDate
  8058. *
  8059. * @return bool true if date is in rage, false otherwise
  8060. */
  8061. function api_is_date_in_date_range($startDate, $endDate, $currentDate = null)
  8062. {
  8063. $startDate = strtotime(api_get_local_time($startDate));
  8064. $endDate = strtotime(api_get_local_time($endDate));
  8065. $currentDate = strtotime(api_get_local_time($currentDate));
  8066. if ($currentDate >= $startDate && $currentDate <= $endDate) {
  8067. return true;
  8068. }
  8069. return false;
  8070. }
  8071. /**
  8072. * Eliminate the duplicates of a multidimensional array by sending the key.
  8073. *
  8074. * @param array $array multidimensional array
  8075. * @param int $key key to find to compare
  8076. *
  8077. * @return array
  8078. */
  8079. function api_unique_multidim_array($array, $key)
  8080. {
  8081. $temp_array = [];
  8082. $i = 0;
  8083. $key_array = [];
  8084. foreach ($array as $val) {
  8085. if (!in_array($val[$key], $key_array)) {
  8086. $key_array[$i] = $val[$key];
  8087. $temp_array[$i] = $val;
  8088. }
  8089. $i++;
  8090. }
  8091. return $temp_array;
  8092. }
  8093. /**
  8094. * Limit the access to Session Admins when the limit_session_admin_role
  8095. * configuration variable is set to true.
  8096. */
  8097. function api_protect_limit_for_session_admin()
  8098. {
  8099. $limitAdmin = api_get_setting('limit_session_admin_role');
  8100. if (api_is_session_admin() && $limitAdmin === 'true') {
  8101. api_not_allowed(true);
  8102. }
  8103. }
  8104. /**
  8105. * Limits that a session admin has access to list users.
  8106. * When limit_session_admin_list_users configuration variable is set to true.
  8107. */
  8108. function api_protect_session_admin_list_users()
  8109. {
  8110. $limitAdmin = api_get_configuration_value('limit_session_admin_list_users');
  8111. if (api_is_session_admin() && true === $limitAdmin) {
  8112. api_not_allowed(true);
  8113. }
  8114. }
  8115. /**
  8116. * @return bool
  8117. */
  8118. function api_is_student_view_active()
  8119. {
  8120. $studentView = Session::read('studentview');
  8121. return $studentView == 'studentview';
  8122. }
  8123. /**
  8124. * Adds a file inside the upload/$type/id.
  8125. *
  8126. * @param string $type
  8127. * @param array $file
  8128. * @param int $itemId
  8129. * @param string $cropParameters
  8130. *
  8131. * @return array|bool
  8132. */
  8133. function api_upload_file($type, $file, $itemId, $cropParameters = '')
  8134. {
  8135. $upload = process_uploaded_file($file);
  8136. if ($upload) {
  8137. $name = api_replace_dangerous_char($file['name']);
  8138. // No "dangerous" files
  8139. $name = disable_dangerous_file($name);
  8140. $pathId = '/'.substr((string) $itemId, 0, 1).'/'.$itemId.'/';
  8141. $path = api_get_path(SYS_UPLOAD_PATH).$type.$pathId;
  8142. if (!is_dir($path)) {
  8143. mkdir($path, api_get_permissions_for_new_directories(), true);
  8144. }
  8145. $pathToSave = $path.$name;
  8146. $result = moveUploadedFile($file, $pathToSave);
  8147. if ($result) {
  8148. if (!empty($cropParameters)) {
  8149. $image = new Image($pathToSave);
  8150. $image->crop($cropParameters);
  8151. }
  8152. return ['path_to_save' => $pathId.$name];
  8153. }
  8154. return false;
  8155. }
  8156. }
  8157. /**
  8158. * @param string $type
  8159. * @param int $itemId
  8160. * @param string $file
  8161. *
  8162. * @return bool
  8163. */
  8164. function api_get_uploaded_web_url($type, $itemId, $file)
  8165. {
  8166. return api_get_uploaded_file($type, $itemId, $file, true);
  8167. }
  8168. /**
  8169. * @param string $type
  8170. * @param int $itemId
  8171. * @param string $file
  8172. * @param bool $getUrl
  8173. *
  8174. * @return bool
  8175. */
  8176. function api_get_uploaded_file($type, $itemId, $file, $getUrl = false)
  8177. {
  8178. $itemId = (int) $itemId;
  8179. $pathId = '/'.substr((string) $itemId, 0, 1).'/'.$itemId.'/';
  8180. $path = api_get_path(SYS_UPLOAD_PATH).$type.$pathId;
  8181. $file = basename($file);
  8182. $file = $path.'/'.$file;
  8183. if (Security::check_abs_path($file, $path) && is_file($file) && file_exists($file)) {
  8184. if ($getUrl) {
  8185. return str_replace(api_get_path(SYS_UPLOAD_PATH), api_get_path(WEB_UPLOAD_PATH), $file);
  8186. }
  8187. return $file;
  8188. }
  8189. return false;
  8190. }
  8191. /**
  8192. * @param string $type
  8193. * @param int $itemId
  8194. * @param string $file
  8195. * @param string $title
  8196. */
  8197. function api_download_uploaded_file($type, $itemId, $file, $title = '')
  8198. {
  8199. $file = api_get_uploaded_file($type, $itemId, $file);
  8200. if ($file) {
  8201. if (Security::check_abs_path($file, api_get_path(SYS_UPLOAD_PATH).$type)) {
  8202. DocumentManager::file_send_for_download($file, true, $title);
  8203. exit;
  8204. }
  8205. }
  8206. api_not_allowed(true);
  8207. }
  8208. /**
  8209. * @param string $type
  8210. * @param string $file
  8211. */
  8212. function api_remove_uploaded_file($type, $file)
  8213. {
  8214. $typePath = api_get_path(SYS_UPLOAD_PATH).$type;
  8215. $path = $typePath.'/'.$file;
  8216. if (Security::check_abs_path($path, $typePath) && file_exists($path) && is_file($path)) {
  8217. unlink($path);
  8218. }
  8219. }
  8220. /**
  8221. * @param string $type
  8222. * @param int $itemId
  8223. * @param string $file
  8224. *
  8225. * @return bool
  8226. */
  8227. function api_remove_uploaded_file_by_id($type, $itemId, $file)
  8228. {
  8229. $file = api_get_uploaded_file($type, $itemId, $file, false);
  8230. $typePath = api_get_path(SYS_UPLOAD_PATH).$type;
  8231. if (Security::check_abs_path($file, $typePath) && file_exists($file) && is_file($file)) {
  8232. unlink($file);
  8233. return true;
  8234. }
  8235. return false;
  8236. }
  8237. /**
  8238. * Converts string value to float value.
  8239. *
  8240. * 3.141516 => 3.141516
  8241. * 3,141516 => 3.141516
  8242. *
  8243. * @todo WIP
  8244. *
  8245. * @param string $number
  8246. *
  8247. * @return float
  8248. */
  8249. function api_float_val($number)
  8250. {
  8251. $number = (float) str_replace(',', '.', trim($number));
  8252. return $number;
  8253. }
  8254. /**
  8255. * Converts float values
  8256. * Example if $decimals = 2.
  8257. *
  8258. * 3.141516 => 3.14
  8259. * 3,141516 => 3,14
  8260. *
  8261. * @param string $number number in iso code
  8262. * @param int $decimals
  8263. * @param string $decimalSeparator
  8264. * @param string $thousandSeparator
  8265. *
  8266. * @return bool|string
  8267. */
  8268. function api_number_format($number, $decimals = 0, $decimalSeparator = '.', $thousandSeparator = ',')
  8269. {
  8270. $number = api_float_val($number);
  8271. return number_format($number, $decimals, $decimalSeparator, $thousandSeparator);
  8272. }
  8273. /**
  8274. * Set location url with a exit break by default.
  8275. *
  8276. * @param $url
  8277. * @param bool $exit
  8278. */
  8279. function location($url, $exit = true)
  8280. {
  8281. header('Location: '.$url);
  8282. if ($exit) {
  8283. exit;
  8284. }
  8285. }
  8286. /**
  8287. * @return string
  8288. */
  8289. function api_get_web_url()
  8290. {
  8291. if (api_get_setting('server_type') === 'test') {
  8292. return api_get_path(WEB_PATH).'web/app_dev.php/';
  8293. } else {
  8294. return api_get_path(WEB_PATH).'web/';
  8295. }
  8296. }
  8297. /**
  8298. * @param string $from
  8299. * @param string $to
  8300. *
  8301. * @return string
  8302. */
  8303. function api_get_relative_path($from, $to)
  8304. {
  8305. // some compatibility fixes for Windows paths
  8306. $from = is_dir($from) ? rtrim($from, '\/').'/' : $from;
  8307. $to = is_dir($to) ? rtrim($to, '\/').'/' : $to;
  8308. $from = str_replace('\\', '/', $from);
  8309. $to = str_replace('\\', '/', $to);
  8310. $from = explode('/', $from);
  8311. $to = explode('/', $to);
  8312. $relPath = $to;
  8313. foreach ($from as $depth => $dir) {
  8314. // find first non-matching dir
  8315. if ($dir === $to[$depth]) {
  8316. // ignore this directory
  8317. array_shift($relPath);
  8318. } else {
  8319. // get number of remaining dirs to $from
  8320. $remaining = count($from) - $depth;
  8321. if ($remaining > 1) {
  8322. // add traversals up to first matching dir
  8323. $padLength = (count($relPath) + $remaining - 1) * -1;
  8324. $relPath = array_pad($relPath, $padLength, '..');
  8325. break;
  8326. } else {
  8327. $relPath[0] = './'.$relPath[0];
  8328. }
  8329. }
  8330. }
  8331. return implode('/', $relPath);
  8332. }
  8333. /**
  8334. * Unserialize content using Brummann\Polyfill\Unserialize.
  8335. *
  8336. * @param string $type
  8337. * @param string $serialized
  8338. * @param bool $ignoreErrors. Optional.
  8339. *
  8340. * @return mixed
  8341. */
  8342. function api_unserialize_content($type, $serialized, $ignoreErrors = false)
  8343. {
  8344. switch ($type) {
  8345. case 'career':
  8346. case 'sequence_graph':
  8347. $allowedClasses = [Graph::class, VerticesMap::class, Vertices::class, Edges::class];
  8348. break;
  8349. case 'lp':
  8350. $allowedClasses = [
  8351. learnpath::class,
  8352. learnpathItem::class,
  8353. aicc::class,
  8354. aiccBlock::class,
  8355. aiccItem::class,
  8356. aiccObjective::class,
  8357. aiccResource::class,
  8358. scorm::class,
  8359. scormItem::class,
  8360. scormMetadata::class,
  8361. scormOrganization::class,
  8362. scormResource::class,
  8363. Link::class,
  8364. LpItem::class,
  8365. ];
  8366. break;
  8367. case 'course':
  8368. $allowedClasses = [
  8369. Course::class,
  8370. Announcement::class,
  8371. Attendance::class,
  8372. CalendarEvent::class,
  8373. CourseCopyLearnpath::class,
  8374. CourseCopyTestCategory::class,
  8375. CourseDescription::class,
  8376. CourseSession::class,
  8377. Document::class,
  8378. Forum::class,
  8379. ForumCategory::class,
  8380. ForumPost::class,
  8381. ForumTopic::class,
  8382. Glossary::class,
  8383. GradeBookBackup::class,
  8384. Link::class,
  8385. LinkCategory::class,
  8386. Quiz::class,
  8387. QuizQuestion::class,
  8388. QuizQuestionOption::class,
  8389. ScormDocument::class,
  8390. Survey::class,
  8391. SurveyInvitation::class,
  8392. SurveyQuestion::class,
  8393. Thematic::class,
  8394. ToolIntro::class,
  8395. Wiki::class,
  8396. Work::class,
  8397. stdClass::class,
  8398. ];
  8399. break;
  8400. case 'not_allowed_classes':
  8401. default:
  8402. $allowedClasses = false;
  8403. }
  8404. if ($ignoreErrors) {
  8405. return @Unserialize::unserialize(
  8406. $serialized,
  8407. ['allowed_classes' => $allowedClasses]
  8408. );
  8409. }
  8410. return Unserialize::unserialize(
  8411. $serialized,
  8412. ['allowed_classes' => $allowedClasses]
  8413. );
  8414. }
  8415. /**
  8416. * Set the From and ReplyTo properties to PHPMailer instance.
  8417. *
  8418. * @param PHPMailer $mailer
  8419. * @param array $sender
  8420. * @param array $replyToAddress
  8421. *
  8422. * @throws phpmailerException
  8423. */
  8424. function api_set_noreply_and_from_address_to_mailer(PHPMailer $mailer, array $sender, array $replyToAddress = [])
  8425. {
  8426. $platformEmail = $GLOBALS['platform_email'];
  8427. $noReplyAddress = api_get_setting('noreply_email_address');
  8428. $avoidReplyToAddress = false;
  8429. if (!empty($noReplyAddress)) {
  8430. $avoidReplyToAddress = api_get_configuration_value('mail_no_reply_avoid_reply_to');
  8431. }
  8432. $notification = new Notification();
  8433. // If the parameter is set don't use the admin.
  8434. $senderName = !empty($sender['name']) ? $sender['name'] : $notification->getDefaultPlatformSenderName();
  8435. $senderEmail = !empty($sender['email']) ? $sender['email'] : $notification->getDefaultPlatformSenderEmail();
  8436. // Send errors to the platform admin
  8437. $adminEmail = api_get_setting('emailAdministrator');
  8438. if (PHPMailer::ValidateAddress($adminEmail)) {
  8439. $mailer->AddCustomHeader('Errors-To: '.$adminEmail);
  8440. }
  8441. // Reply to first
  8442. if (!$avoidReplyToAddress) {
  8443. if (
  8444. !empty($replyToAddress) &&
  8445. isset($platformEmail['SMTP_UNIQUE_REPLY_TO']) && $platformEmail['SMTP_UNIQUE_REPLY_TO'] &&
  8446. PHPMailer::ValidateAddress($replyToAddress['mail'])
  8447. ) {
  8448. $mailer->AddReplyTo($replyToAddress['email'], $replyToAddress['name']);
  8449. $mailer->Sender = $replyToAddress['mail'];
  8450. }
  8451. }
  8452. //If the SMTP configuration only accept one sender
  8453. if (
  8454. isset($platformEmail['SMTP_UNIQUE_SENDER']) &&
  8455. $platformEmail['SMTP_UNIQUE_SENDER']
  8456. ) {
  8457. $senderName = $platformEmail['SMTP_FROM_NAME'];
  8458. $senderEmail = $platformEmail['SMTP_FROM_EMAIL'];
  8459. if (PHPMailer::ValidateAddress($senderEmail)) {
  8460. //force-set Sender to $senderEmail, otherwise SetFrom only does it if it is currently empty
  8461. $mailer->Sender = $senderEmail;
  8462. }
  8463. }
  8464. $mailer->SetFrom($senderEmail, $senderName, !$avoidReplyToAddress);
  8465. }
  8466. /**
  8467. * @param string $template
  8468. *
  8469. * @return string
  8470. */
  8471. function api_find_template($template)
  8472. {
  8473. return Template::findTemplateFilePath($template);
  8474. }
  8475. /**
  8476. * @return array
  8477. */
  8478. function api_get_language_list_for_flag()
  8479. {
  8480. $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  8481. $sql = "SELECT english_name, isocode FROM $table
  8482. ORDER BY original_name ASC";
  8483. static $languages = [];
  8484. if (empty($languages)) {
  8485. $result = Database::query($sql);
  8486. while ($row = Database::fetch_array($result)) {
  8487. $languages[$row['english_name']] = $row['isocode'];
  8488. }
  8489. $languages['english'] = 'gb';
  8490. }
  8491. return $languages;
  8492. }
  8493. /**
  8494. * @return string
  8495. */
  8496. function api_get_language_translate_html()
  8497. {
  8498. $translate = api_get_configuration_value('translate_html');
  8499. if (!$translate) {
  8500. return '';
  8501. }
  8502. $languageList = api_get_languages();
  8503. $hideAll = '';
  8504. foreach ($languageList['all'] as $language) {
  8505. $hideAll .= '
  8506. $("span:lang('.$language['isocode'].')").filter(
  8507. function(e, val) {
  8508. // Only find the spans if they have set the lang
  8509. if ($(this).attr("lang") == null) {
  8510. return false;
  8511. }
  8512. // Ignore ckeditor classes
  8513. return !this.className.match(/cke(.*)/);
  8514. }).hide();'."\n";
  8515. }
  8516. $userInfo = api_get_user_info();
  8517. $languageId = api_get_language_id($userInfo['language']);
  8518. $languageInfo = api_get_language_info($languageId);
  8519. $isoCode = 'en';
  8520. if (!empty($languageInfo)) {
  8521. $isoCode = $languageInfo['isocode'];
  8522. }
  8523. return '
  8524. $(function() {
  8525. '.$hideAll.'
  8526. var defaultLanguageFromUser = "'.$isoCode.'";
  8527. $("span:lang('.$isoCode.')").filter(
  8528. function() {
  8529. // Ignore ckeditor classes
  8530. return !this.className.match(/cke(.*)/);
  8531. }).show();
  8532. var defaultLanguage = "";
  8533. var langFromUserFound = false;
  8534. $(this).find("span").filter(
  8535. function() {
  8536. // Ignore ckeditor classes
  8537. return !this.className.match(/cke(.*)/);
  8538. }).each(function() {
  8539. defaultLanguage = $(this).attr("lang");
  8540. if (defaultLanguage) {
  8541. $(this).before().next("br").remove();
  8542. if (defaultLanguageFromUser == defaultLanguage) {
  8543. langFromUserFound = true;
  8544. }
  8545. }
  8546. });
  8547. // Show default language
  8548. if (langFromUserFound == false && defaultLanguage) {
  8549. $("span:lang("+defaultLanguage+")").filter(
  8550. function() {
  8551. // Ignore ckeditor classes
  8552. return !this.className.match(/cke(.*)/);
  8553. }).show();
  8554. }
  8555. });
  8556. ';
  8557. }