main_api.lib.php 257 KB

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