api.lib.php 284 KB

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