api.lib.php 303 KB

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