api.lib.php 277 KB

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