api.lib.php 272 KB

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