api.lib.php 274 KB

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