api.lib.php 276 KB

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