api.lib.php 275 KB

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