api.lib.php 273 KB

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