api.lib.php 285 KB

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