api.lib.php 271 KB

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