main_api.lib.php 268 KB

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