api.lib.php 283 KB

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