api.lib.php 301 KB

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