api.lib.php 260 KB

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