api.lib.php 276 KB

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