main_api.lib.php 257 KB

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