main_api.lib.php 256 KB

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