course.lib.php 241 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406
  1. <?php
  2. /* For licensing terms, see /license.txt*/
  3. use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
  4. use ChamiloSession as Session;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  7. /**
  8. * Class CourseManager
  9. *
  10. * This is the course library for Chamilo.
  11. *
  12. * All main course functions should be placed here.
  13. *
  14. * Many functions of this library deal with providing support for
  15. * virtual/linked/combined courses (this was already used in several universities
  16. * but not available in standard Chamilo).
  17. *
  18. * There are probably some places left with the wrong code.
  19. *
  20. * @package chamilo.library
  21. */
  22. class CourseManager
  23. {
  24. const MAX_COURSE_LENGTH_CODE = 40;
  25. /** This constant is used to show separate user names in the course
  26. * list (userportal), footer, etc */
  27. const USER_SEPARATOR = ' |';
  28. const COURSE_FIELD_TYPE_CHECKBOX = 10;
  29. public $columns = array();
  30. /**
  31. * Creates a course
  32. * @param array $params columns in the main.course table
  33. *
  34. * @return mixed false if the course was not created, array with the course info
  35. */
  36. public static function create_course($params, $authorId = 0)
  37. {
  38. global $_configuration;
  39. // Check portal limits
  40. $access_url_id = 1;
  41. if (api_get_multiple_access_url()) {
  42. $access_url_id = api_get_current_access_url_id();
  43. }
  44. $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
  45. if (isset($_configuration[$access_url_id]) && is_array($_configuration[$access_url_id])) {
  46. $return = self::checkCreateCourseAccessUrlParam(
  47. $_configuration,
  48. $access_url_id,
  49. 'hosting_limit_courses',
  50. 'PortalCoursesLimitReached'
  51. );
  52. if ($return != false) {
  53. return $return;
  54. }
  55. $return = self::checkCreateCourseAccessUrlParam(
  56. $_configuration,
  57. $access_url_id,
  58. 'hosting_limit_active_courses',
  59. 'PortalActiveCoursesLimitReached'
  60. );
  61. if ($return != false) {
  62. return $return;
  63. }
  64. }
  65. if (empty($params['title'])) {
  66. return false;
  67. }
  68. if (empty($params['wanted_code'])) {
  69. $params['wanted_code'] = $params['title'];
  70. // Check whether the requested course code has already been occupied.
  71. $substring = api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE);
  72. if ($substring === false || empty($substring)) {
  73. return false;
  74. } else {
  75. $params['wanted_code'] = self::generate_course_code($substring);
  76. }
  77. }
  78. // Create the course keys
  79. $keys = AddCourse::define_course_keys($params['wanted_code']);
  80. $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
  81. if (count($keys)) {
  82. $params['code'] = $keys['currentCourseCode'];
  83. $params['visual_code'] = $keys['currentCourseId'];
  84. $params['directory'] = $keys['currentCourseRepository'];
  85. $course_info = api_get_course_info($params['code']);
  86. if (empty($course_info)) {
  87. $course_id = AddCourse::register_course($params);
  88. $course_info = api_get_course_info_by_id($course_id);
  89. if (!empty($course_info)) {
  90. self::fillCourse($course_info, $params, $authorId);
  91. return $course_info;
  92. }
  93. }
  94. }
  95. return false;
  96. }
  97. /**
  98. * Returns all the information of a given course code
  99. * @param string $course_code , the course code
  100. * @return array with all the fields of the course table
  101. * @deprecated Use api_get_course_info() instead
  102. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  103. * @assert ('') === false
  104. */
  105. public static function get_course_information($course_code)
  106. {
  107. return Database::fetch_array(
  108. Database::query(
  109. "SELECT *, id as real_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  110. WHERE code='" . Database::escape_string($course_code)."'"), 'ASSOC'
  111. );
  112. }
  113. /**
  114. * Returns a list of courses. Should work with quickform syntax
  115. * @param integer $from Offset (from the 7th = '6'). Optional.
  116. * @param integer $howmany Number of results we want. Optional.
  117. * @param int $orderby The column we want to order it by. Optional, defaults to first column.
  118. * @param string $orderdirection The direction of the order (ASC or DESC). Optional, defaults to ASC.
  119. * @param int $visibility The visibility of the course, or all by default.
  120. * @param string $startwith If defined, only return results for which the course *title* begins with this string
  121. * @param string $urlId The Access URL ID, if using multiple URLs
  122. * @param bool $alsoSearchCode An extension option to indicate that we also want to search for course codes (not *only* titles)
  123. * @param array $conditionsLike
  124. * @return array
  125. */
  126. public static function get_courses_list(
  127. $from = 0,
  128. $howmany = 0,
  129. $orderby = 1,
  130. $orderdirection = 'ASC',
  131. $visibility = -1,
  132. $startwith = '',
  133. $urlId = null,
  134. $alsoSearchCode = false,
  135. $conditionsLike = array()
  136. ) {
  137. $sql = "SELECT course.* FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." course ";
  138. if (!empty($urlId)) {
  139. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  140. $sql .= " INNER JOIN $table url ON (url.c_id = course.id) ";
  141. }
  142. if (!empty($startwith)) {
  143. $sql .= "WHERE (title LIKE '".Database::escape_string($startwith)."%' ";
  144. if ($alsoSearchCode) {
  145. $sql .= "OR code LIKE '".Database::escape_string($startwith)."%' ";
  146. }
  147. $sql .= ') ';
  148. if ($visibility !== -1 && $visibility == strval(intval($visibility))) {
  149. $sql .= " AND visibility = $visibility ";
  150. }
  151. } else {
  152. $sql .= "WHERE 1 ";
  153. if ($visibility !== -1 && $visibility == strval(intval($visibility))) {
  154. $sql .= " AND visibility = $visibility ";
  155. }
  156. }
  157. if (!empty($urlId)) {
  158. $urlId = intval($urlId);
  159. $sql .= " AND access_url_id= $urlId";
  160. }
  161. $allowedFields = array(
  162. 'title',
  163. 'code'
  164. );
  165. if (count($conditionsLike) > 0) {
  166. $sql .= ' AND ';
  167. $temp_conditions = array();
  168. foreach ($conditionsLike as $field => $value) {
  169. if (!in_array($field, $allowedFields)) {
  170. continue;
  171. }
  172. $field = Database::escape_string($field);
  173. $value = Database::escape_string($value);
  174. $simple_like = false;
  175. if ($simple_like) {
  176. $temp_conditions[] = $field." LIKE '$value%'";
  177. } else {
  178. $temp_conditions[] = $field.' LIKE \'%'.$value.'%\'';
  179. }
  180. }
  181. $condition = ' AND ';
  182. if (!empty($temp_conditions)) {
  183. $sql .= implode(' '.$condition.' ', $temp_conditions);
  184. }
  185. }
  186. if (!empty($orderby)) {
  187. $sql .= " ORDER BY ".Database::escape_string($orderby)." ";
  188. } else {
  189. $sql .= " ORDER BY 1 ";
  190. }
  191. if (!in_array($orderdirection, array('ASC', 'DESC'))) {
  192. $sql .= 'ASC';
  193. } else {
  194. $sql .= ($orderdirection == 'ASC' ? 'ASC' : 'DESC');
  195. }
  196. if (!empty($howmany) && is_int($howmany) and $howmany > 0) {
  197. $sql .= ' LIMIT '.Database::escape_string($howmany);
  198. } else {
  199. $sql .= ' LIMIT 1000000'; //virtually no limit
  200. }
  201. if (!empty($from)) {
  202. $from = intval($from);
  203. $sql .= ' OFFSET '.intval($from);
  204. } else {
  205. $sql .= ' OFFSET 0';
  206. }
  207. $data = [];
  208. $res = Database::query($sql);
  209. if (Database::num_rows($res) > 0) {
  210. while ($row = Database::fetch_array($res, 'ASSOC')) {
  211. $data[] = $row;
  212. }
  213. }
  214. return $data;
  215. }
  216. /**
  217. * Returns the status of a user in a course, which is COURSEMANAGER or STUDENT.
  218. * @param int $userId
  219. * @param int $courseId
  220. *
  221. * @return int|bool the status of the user in that course (or false if the user is not in that course)
  222. */
  223. public static function getUserInCourseStatus($userId, $courseId)
  224. {
  225. $courseId = (int) $courseId;
  226. if (empty($courseId)) {
  227. return false;
  228. }
  229. $result = Database::fetch_array(
  230. Database::query(
  231. "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  232. WHERE
  233. c_id = $courseId AND
  234. user_id = ".intval($userId)
  235. )
  236. );
  237. return $result['status'];
  238. }
  239. /**
  240. * @param int $userId
  241. * @param int $courseId
  242. *
  243. * @return mixed
  244. */
  245. public static function getUserCourseInfo($userId, $courseId)
  246. {
  247. $result = Database::fetch_array(
  248. Database::query("
  249. SELECT * FROM " . Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  250. WHERE
  251. c_id = '" . intval($courseId)."' AND
  252. user_id = " . intval($userId)
  253. )
  254. );
  255. return $result;
  256. }
  257. /**
  258. * @param int $userId
  259. * @param int $courseId
  260. * @param bool $isTutor
  261. *
  262. * @return bool
  263. */
  264. public static function updateUserCourseTutor($userId, $courseId, $isTutor)
  265. {
  266. $table = Database::escape_string(TABLE_MAIN_COURSE_USER);
  267. $courseId = intval($courseId);
  268. $isTutor = intval($isTutor);
  269. $sql = "UPDATE $table SET is_tutor = '".$isTutor."'
  270. WHERE
  271. user_id = '".$userId."' AND
  272. c_id = '".$courseId."'";
  273. $result = Database::query($sql);
  274. if (Database::affected_rows($result) > 0) {
  275. return true;
  276. } else {
  277. return false;
  278. }
  279. }
  280. /**
  281. * @param int $user_id
  282. * @param int $courseId
  283. *
  284. * @return mixed
  285. */
  286. public static function get_tutor_in_course_status($user_id, $courseId)
  287. {
  288. $result = Database::fetch_array(
  289. Database::query("
  290. SELECT is_tutor
  291. FROM " . Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  292. WHERE
  293. c_id = '" . Database::escape_string($courseId)."' AND
  294. user_id = " . intval($user_id)
  295. )
  296. );
  297. return $result['is_tutor'];
  298. }
  299. /**
  300. * Unsubscribe one or more users from a course
  301. *
  302. * @param mixed user_id or an array with user ids
  303. * @param string course code
  304. * @param int session id
  305. * @assert ('', '') === false
  306. *
  307. */
  308. public static function unsubscribe_user($user_id, $course_code, $session_id = 0)
  309. {
  310. if (!is_array($user_id)) {
  311. $user_id = array($user_id);
  312. }
  313. if (count($user_id) == 0) {
  314. return;
  315. }
  316. if (!empty($session_id)) {
  317. $session_id = intval($session_id);
  318. } else {
  319. $session_id = api_get_session_id();
  320. }
  321. $user_list = array();
  322. // Cleaning the $user_id variable
  323. if (is_array($user_id)) {
  324. $new_user_id_list = array();
  325. foreach ($user_id as $my_user_id) {
  326. $new_user_id_list[] = intval($my_user_id);
  327. }
  328. $new_user_id_list = array_filter($new_user_id_list);
  329. $user_list = $new_user_id_list;
  330. $user_ids = implode(',', $new_user_id_list);
  331. } else {
  332. $user_ids = intval($user_id);
  333. $user_list[] = $user_id;
  334. }
  335. $course_info = api_get_course_info($course_code);
  336. $course_id = $course_info['real_id'];
  337. // Unsubscribe user from all groups in the course.
  338. $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  339. WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
  340. Database::query($sql);
  341. $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  342. WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
  343. Database::query($sql);
  344. // Erase user student publications (works) in the course - by André Boivin
  345. if (!empty($user_list)) {
  346. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  347. foreach ($user_list as $userId) {
  348. // Getting all work from user
  349. $workList = getWorkPerUser($userId);
  350. if (!empty($workList)) {
  351. foreach ($workList as $work) {
  352. $work = $work['work'];
  353. // Getting user results
  354. if (!empty($work->user_results)) {
  355. foreach ($work->user_results as $workSent) {
  356. deleteWorkItem($workSent['id'], $course_info);
  357. }
  358. }
  359. }
  360. }
  361. }
  362. }
  363. // Unsubscribe user from all blogs in the course.
  364. Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_REL_USER)." WHERE c_id = $course_id AND user_id IN (".$user_ids.")");
  365. Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)." WHERE c_id = $course_id AND user_id IN (".$user_ids.")");
  366. // Deleting users in forum_notification and mailqueue course tables
  367. $sql = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_NOTIFICATION)."
  368. WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
  369. Database::query($sql);
  370. $sql = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_MAIL_QUEUE)."
  371. WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
  372. Database::query($sql);
  373. // Unsubscribe user from the course.
  374. if (!empty($session_id)) {
  375. // Delete in table session_rel_course_rel_user
  376. $sql = "DELETE FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  377. WHERE
  378. session_id ='" . $session_id."' AND
  379. c_id = '" . $course_id."' AND
  380. user_id IN ($user_ids)";
  381. Database::query($sql);
  382. foreach ($user_list as $uid) {
  383. // check if a user is register in the session with other course
  384. $sql = "SELECT user_id FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  385. WHERE session_id='$session_id' AND user_id='$uid'";
  386. $rs = Database::query($sql);
  387. if (Database::num_rows($rs) == 0) {
  388. // Delete in table session_rel_user
  389. $sql = "DELETE FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  390. WHERE
  391. session_id ='" . $session_id."' AND
  392. user_id = '$uid' AND
  393. relation_type<>".SESSION_RELATION_TYPE_RRHH."";
  394. Database::query($sql);
  395. }
  396. }
  397. // Update the table session
  398. $sql = "SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  399. WHERE session_id = '" . $session_id."' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
  400. $row = Database::fetch_array(Database::query($sql));
  401. $count = $row[0];
  402. // number of users by session
  403. $sql = "UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION)." SET nbr_users = '$count'
  404. WHERE id = '".$session_id."'";
  405. Database::query($sql);
  406. // Update the table session_rel_course
  407. $sql = "SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  408. WHERE session_id = '$session_id' AND c_id = '$course_id' AND status<>2";
  409. $row = Database::fetch_array(@Database::query($sql));
  410. $count = $row[0];
  411. // number of users by session and course
  412. $sql = "UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE)."
  413. SET nbr_users = '$count'
  414. WHERE session_id = '$session_id' AND c_id = '$course_id'";
  415. Database::query($sql);
  416. Event::addEvent(
  417. LOG_UNSUBSCRIBE_USER_FROM_COURSE,
  418. LOG_COURSE_CODE,
  419. $course_code,
  420. api_get_utc_datetime(),
  421. $user_id,
  422. $course_id,
  423. $session_id
  424. );
  425. } else {
  426. $sql = "DELETE FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  427. WHERE
  428. user_id IN (" . $user_ids.") AND
  429. relation_type<>" . COURSE_RELATION_TYPE_RRHH." AND
  430. c_id = '" . $course_id."'";
  431. Database::query($sql);
  432. // add event to system log
  433. $user_id = api_get_user_id();
  434. Event::addEvent(
  435. LOG_UNSUBSCRIBE_USER_FROM_COURSE,
  436. LOG_COURSE_CODE,
  437. $course_code,
  438. api_get_utc_datetime(),
  439. $user_id,
  440. $course_id
  441. );
  442. foreach ($user_list as $userId) {
  443. $userInfo = api_get_user_info($userId);
  444. Event::addEvent(
  445. LOG_UNSUBSCRIBE_USER_FROM_COURSE,
  446. LOG_USER_OBJECT,
  447. $userInfo,
  448. api_get_utc_datetime(),
  449. $user_id,
  450. $course_id
  451. );
  452. }
  453. }
  454. }
  455. /**
  456. * Subscribe a user to a course. No checks are performed here to see if
  457. * course subscription is allowed.
  458. * @param int $user_id
  459. * @param string $course_code
  460. * @param int $status (STUDENT, COURSEMANAGER, COURSE_ADMIN, NORMAL_COURSE_MEMBER)
  461. * @param int $session_id
  462. * @param int $userCourseCategoryId
  463. *
  464. * @return bool True on success, false on failure
  465. * @see add_user_to_course
  466. * @assert ('', '') === false
  467. */
  468. public static function subscribe_user(
  469. $user_id,
  470. $course_code,
  471. $status = STUDENT,
  472. $session_id = 0,
  473. $userCourseCategoryId = 0
  474. ) {
  475. if ($user_id != strval(intval($user_id))) {
  476. return false; //detected possible SQL injection
  477. }
  478. $course_code = Database::escape_string($course_code);
  479. $courseInfo = api_get_course_info($course_code);
  480. $courseId = $courseInfo['real_id'];
  481. $courseCode = $courseInfo['code'];
  482. $userCourseCategoryId = intval($userCourseCategoryId);
  483. if (empty($user_id) || empty($course_code)) {
  484. return false;
  485. }
  486. if (!empty($session_id)) {
  487. $session_id = intval($session_id);
  488. } else {
  489. $session_id = api_get_session_id();
  490. }
  491. $status = ($status == STUDENT || $status == COURSEMANAGER) ? $status : STUDENT;
  492. // A preliminary check whether the user has bben already registered on the platform.
  493. $sql = "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  494. WHERE user_id = '$user_id' ";
  495. if (Database::num_rows(Database::query($sql)) == 0) {
  496. return false; // The user has not been registered to the platform.
  497. }
  498. // Check whether the user has not been already subscribed to the course.
  499. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  500. WHERE
  501. user_id = '$user_id' AND
  502. relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
  503. c_id = $courseId
  504. ";
  505. if (empty($session_id)) {
  506. if (Database::num_rows(Database::query($sql)) > 0) {
  507. // The user has been already subscribed to the course.
  508. return false;
  509. }
  510. }
  511. if (!empty($session_id)) {
  512. SessionManager::subscribe_users_to_session_course(array($user_id), $session_id, $courseCode);
  513. // Add event to the system log
  514. Event::addEvent(
  515. LOG_SUBSCRIBE_USER_TO_COURSE,
  516. LOG_COURSE_CODE,
  517. $course_code,
  518. api_get_utc_datetime(),
  519. api_get_user_id(),
  520. $courseId,
  521. $session_id
  522. );
  523. $user_info = api_get_user_info($user_id);
  524. Event::addEvent(
  525. LOG_SUBSCRIBE_USER_TO_COURSE,
  526. LOG_USER_OBJECT,
  527. $user_info,
  528. api_get_utc_datetime(),
  529. api_get_user_id(),
  530. $courseId,
  531. $session_id
  532. );
  533. } else {
  534. self::add_user_to_course(
  535. $user_id,
  536. $courseCode,
  537. $status,
  538. $userCourseCategoryId
  539. );
  540. // Add event to the system log
  541. Event::addEvent(
  542. LOG_SUBSCRIBE_USER_TO_COURSE,
  543. LOG_COURSE_CODE,
  544. $course_code,
  545. api_get_utc_datetime(),
  546. api_get_user_id(),
  547. $courseId
  548. );
  549. $user_info = api_get_user_info($user_id);
  550. Event::addEvent(
  551. LOG_SUBSCRIBE_USER_TO_COURSE,
  552. LOG_USER_OBJECT,
  553. $user_info,
  554. api_get_utc_datetime(),
  555. api_get_user_id(),
  556. $courseId
  557. );
  558. }
  559. return true;
  560. }
  561. /**
  562. * Get the course id based on the original id and field name in the
  563. * extra fields. Returns 0 if course was not found
  564. *
  565. * @param string $original_course_id_value
  566. * @param string $original_course_id_name
  567. * @return int Course id
  568. *
  569. * @assert ('', '') === false
  570. */
  571. public static function get_course_code_from_original_id($original_course_id_value, $original_course_id_name)
  572. {
  573. $t_cfv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  574. $table_field = Database::get_main_table(TABLE_EXTRA_FIELD);
  575. $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
  576. $original_course_id_value = Database::escape_string($original_course_id_value);
  577. $original_course_id_name = Database::escape_string($original_course_id_name);
  578. $sql = "SELECT item_id
  579. FROM $table_field cf
  580. INNER JOIN $t_cfv cfv
  581. ON cfv.field_id=cf.id
  582. WHERE
  583. variable = '$original_course_id_name' AND
  584. value = '$original_course_id_value' AND
  585. cf.extra_field_type = $extraFieldType
  586. ";
  587. $res = Database::query($sql);
  588. $row = Database::fetch_object($res);
  589. if ($row) {
  590. return $row->item_id;
  591. } else {
  592. return 0;
  593. }
  594. }
  595. /**
  596. * Gets the course code from the course id. Returns null if course id was not found
  597. *
  598. * @param int $id Course id
  599. * @return string Course code
  600. * @assert ('') === false
  601. */
  602. public static function get_course_code_from_course_id($id)
  603. {
  604. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  605. $id = intval($id);
  606. $sql = "SELECT code FROM $table WHERE id = '$id' ";
  607. $res = Database::query($sql);
  608. $row = Database::fetch_object($res);
  609. if ($row) {
  610. return $row->code;
  611. } else {
  612. return null;
  613. }
  614. }
  615. /**
  616. * Subscribe a user $user_id to a course defined by $courseCode.
  617. * @author Hugues Peeters
  618. * @author Roan Embrechts
  619. *
  620. * @param int $user_id the id of the user
  621. * @param string $courseCode the course code
  622. * @param int $status (optional) The user's status in the course
  623. * @param int $userCourseCategoryId
  624. * @param int The user category in which this subscription will be classified
  625. *
  626. * @return false|string true if subscription succeeds, boolean false otherwise.
  627. * @assert ('', '') === false
  628. */
  629. public static function add_user_to_course(
  630. $user_id,
  631. $courseCode,
  632. $status = STUDENT,
  633. $userCourseCategoryId = 0
  634. ) {
  635. $debug = false;
  636. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  637. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  638. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  639. $status = ($status == STUDENT || $status == COURSEMANAGER) ? $status : STUDENT;
  640. if (empty($user_id) || empty($courseCode) || ($user_id != strval(intval($user_id)))) {
  641. return false;
  642. }
  643. $courseCode = Database::escape_string($courseCode);
  644. $courseInfo = api_get_course_info($courseCode);
  645. $courseId = $courseInfo['real_id'];
  646. // Check in advance whether the user has already been registered on the platform.
  647. $sql = "SELECT status FROM ".$user_table." WHERE user_id = $user_id ";
  648. if (Database::num_rows(Database::query($sql)) == 0) {
  649. if ($debug) {
  650. error_log('The user has not been registered to the platform');
  651. }
  652. return false; // The user has not been registered to the platform.
  653. }
  654. // Check whether the user has already been subscribed to this course.
  655. $sql = "SELECT * FROM $course_user_table
  656. WHERE
  657. user_id = $user_id AND
  658. relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
  659. c_id = $courseId";
  660. if (Database::num_rows(Database::query($sql)) > 0) {
  661. if ($debug) {
  662. error_log('The user has been already subscribed to the course');
  663. }
  664. return false; // The user has been subscribed to the course.
  665. }
  666. if (!api_is_course_admin()) {
  667. // Check in advance whether subscription is allowed or not for this course.
  668. $sql = "SELECT code, visibility FROM $course_table
  669. WHERE id = $courseId AND subscribe = '".SUBSCRIBE_NOT_ALLOWED."'";
  670. if (Database::num_rows(Database::query($sql)) > 0) {
  671. if ($debug) {
  672. error_log('Subscription is not allowed for this course');
  673. }
  674. return false; // Subscription is not allowed for this course.
  675. }
  676. }
  677. // Ok, subscribe the user.
  678. $max_sort = api_max_sort_value('0', $user_id);
  679. $params = [
  680. 'c_id' => $courseId,
  681. 'user_id' => $user_id,
  682. 'status' => $status,
  683. 'sort' => $max_sort + 1,
  684. 'relation_type' => 0,
  685. 'user_course_cat' => (int) $userCourseCategoryId
  686. ];
  687. $insertId = Database::insert($course_user_table, $params);
  688. return $insertId;
  689. }
  690. /**
  691. * Add the user $userId visibility to the course $courseCode in the catalogue.
  692. * @author David Nos (https://github.com/dnos)
  693. *
  694. * @param int $userId the id of the user
  695. * @param string $courseCode the course code
  696. * @param int $visible (optional) The course visibility in the catalogue to the user (1=visible, 0=invisible)
  697. *
  698. * @return boolean true if added succesfully, false otherwise.
  699. */
  700. public static function addUserVisibilityToCourseInCatalogue($userId, $courseCode, $visible = 1)
  701. {
  702. $debug = false;
  703. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  704. $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
  705. if (empty($userId) || empty($courseCode) || ($userId != strval(intval($userId)))) {
  706. return false;
  707. }
  708. $courseCode = Database::escape_string($courseCode);
  709. $courseInfo = api_get_course_info($courseCode);
  710. $courseId = $courseInfo['real_id'];
  711. // Check in advance whether the user has already been registered on the platform.
  712. $sql = "SELECT status FROM ".$userTable." WHERE user_id = $userId ";
  713. if (Database::num_rows(Database::query($sql)) == 0) {
  714. if ($debug) {
  715. error_log('The user has not been registered to the platform');
  716. }
  717. return false; // The user has not been registered to the platform.
  718. }
  719. // Check whether the user has already been registered to the course visibility in the catalogue.
  720. $sql = "SELECT * FROM $courseUserTable
  721. WHERE
  722. user_id = $userId AND
  723. visible = ".$visible." AND
  724. c_id = $courseId";
  725. if (Database::num_rows(Database::query($sql)) > 0) {
  726. if ($debug) {
  727. error_log('The user has been already registered to the course visibility in the catalogue');
  728. }
  729. return true; // The visibility of the user to the course in the catalogue does already exist.
  730. }
  731. // Register the user visibility to course in catalogue.
  732. $params = [
  733. 'user_id' => $userId,
  734. 'c_id' => $courseId,
  735. 'visible' => $visible
  736. ];
  737. $insertId = Database::insert($courseUserTable, $params);
  738. return $insertId;
  739. }
  740. /**
  741. * Remove the user $userId visibility to the course $courseCode in the catalogue.
  742. * @author David Nos (https://github.com/dnos)
  743. *
  744. * @param int $userId the id of the user
  745. * @param string $courseCode the course code
  746. * @param int $visible (optional) The course visibility in the catalogue to the user (1=visible, 0=invisible)
  747. *
  748. * @return boolean true if removed succesfully or register not found, false otherwise.
  749. */
  750. public static function removeUserVisibilityToCourseInCatalogue($userId, $courseCode, $visible = 1)
  751. {
  752. $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
  753. if (empty($userId) || empty($courseCode) || ($userId != strval(intval($userId)))) {
  754. return false;
  755. }
  756. $courseCode = Database::escape_string($courseCode);
  757. $courseInfo = api_get_course_info($courseCode);
  758. $courseId = $courseInfo['real_id'];
  759. // Check whether the user has already been registered to the course visibility in the catalogue.
  760. $sql = "SELECT * FROM $courseUserTable
  761. WHERE
  762. user_id = $userId AND
  763. visible = ".$visible." AND
  764. c_id = $courseId";
  765. if (Database::num_rows(Database::query($sql)) > 0) {
  766. $cond = array(
  767. 'user_id = ? AND c_id = ? AND visible = ? ' => array(
  768. $userId,
  769. $courseId,
  770. $visible
  771. )
  772. );
  773. return Database::delete($courseUserTable, $cond);
  774. } else {
  775. return true; // Register does not exist
  776. }
  777. }
  778. /**
  779. * @return boolean if there already are one or more courses
  780. * with the same code OR visual_code (visualcode), false otherwise
  781. */
  782. public static function course_code_exists($wanted_course_code)
  783. {
  784. $wanted_course_code = Database::escape_string($wanted_course_code);
  785. $sql = "SELECT COUNT(*) as number
  786. FROM " . Database::get_main_table(TABLE_MAIN_COURSE)."
  787. WHERE code = '$wanted_course_code' OR visual_code = '$wanted_course_code'";
  788. $result = Database::fetch_array(Database::query($sql));
  789. return $result['number'] > 0;
  790. }
  791. /**
  792. * Get course list as coach
  793. *
  794. * @param int $user_id
  795. * @param bool $include_courses_in_sessions
  796. * @return array Course list
  797. *
  798. **/
  799. public static function get_course_list_as_coach($user_id, $include_courses_in_sessions = false)
  800. {
  801. // 1. Getting courses as teacher (No session)
  802. $courses_temp = self::get_course_list_of_user_as_course_admin($user_id);
  803. $courseList = array();
  804. if (!empty($courses_temp)) {
  805. foreach ($courses_temp as $course_item) {
  806. $courseList[0][$course_item['code']] = $course_item['code'];
  807. }
  808. }
  809. //2. Include courses in sessions
  810. if ($include_courses_in_sessions) {
  811. $sessions = Tracking::get_sessions_coached_by_user($user_id);
  812. if (!empty($sessions)) {
  813. foreach ($sessions as $session_item) {
  814. $courses = Tracking:: get_courses_followed_by_coach($user_id, $session_item['id']);
  815. if (is_array($courses)) {
  816. foreach ($courses as $course_item) {
  817. $courseList[$session_item['id']][$course_item] = $course_item;
  818. }
  819. }
  820. }
  821. }
  822. }
  823. return $courseList;
  824. }
  825. /**
  826. * @param int $user_id
  827. * @param bool $include_sessions
  828. * @return array
  829. */
  830. public static function get_user_list_from_courses_as_coach($user_id, $include_sessions = true)
  831. {
  832. $students_in_courses = array();
  833. $sessions = self::get_course_list_as_coach($user_id, true);
  834. if (!empty($sessions)) {
  835. foreach ($sessions as $session_id => $courses) {
  836. if (!$include_sessions) {
  837. if (!empty($session_id)) {
  838. continue;
  839. }
  840. }
  841. if (empty($session_id)) {
  842. foreach ($courses as $course_code) {
  843. $students_in_course = self::get_user_list_from_course_code($course_code);
  844. foreach ($students_in_course as $user_item) {
  845. //Only students
  846. if ($user_item['status_rel'] == STUDENT) {
  847. $students_in_courses[$user_item['user_id']] = $user_item['user_id'];
  848. }
  849. }
  850. }
  851. } else {
  852. $students_in_course = SessionManager::get_users_by_session($session_id, '0');
  853. if (is_array($students_in_course)) {
  854. foreach ($students_in_course as $user_item) {
  855. $students_in_courses[$user_item['user_id']] = $user_item['user_id'];
  856. }
  857. }
  858. }
  859. }
  860. }
  861. $students = Tracking:: get_student_followed_by_coach($user_id);
  862. if (!empty($students_in_courses)) {
  863. if (!empty($students)) {
  864. $students = array_merge($students, $students_in_courses);
  865. } else {
  866. $students = $students_in_courses;
  867. }
  868. }
  869. if (!empty($students)) {
  870. $students = array_unique($students);
  871. }
  872. return $students;
  873. }
  874. /**
  875. * @param int $user_id
  876. * @param string $startsWith Optional
  877. * @return array An array with the course info of all the courses (real and virtual)
  878. * of which the current user is course admin.
  879. */
  880. public static function get_course_list_of_user_as_course_admin($user_id, $startsWith = null)
  881. {
  882. if ($user_id != strval(intval($user_id))) {
  883. return array();
  884. }
  885. // Definitions database tables and variables
  886. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  887. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  888. $user_id = intval($user_id);
  889. $data = array();
  890. $sql = "SELECT
  891. course.code,
  892. course.title,
  893. course.id,
  894. course.id as real_id,
  895. course.category_code
  896. FROM $tbl_course_user as course_rel_user
  897. INNER JOIN $tbl_course as course
  898. ON course.id = course_rel_user.c_id
  899. WHERE
  900. course_rel_user.user_id='$user_id' AND
  901. course_rel_user.status='1'
  902. ";
  903. if (api_get_multiple_access_url()) {
  904. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  905. $access_url_id = api_get_current_access_url_id();
  906. if ($access_url_id != -1) {
  907. $sql = "
  908. SELECT
  909. course.code,
  910. course.title,
  911. course.id,
  912. course.id as real_id
  913. FROM $tbl_course_user as course_rel_user
  914. INNER JOIN $tbl_course as course
  915. ON course.id = course_rel_user.c_id
  916. INNER JOIN $tbl_course_rel_access_url course_rel_url
  917. ON (course_rel_url.c_id = course.id)
  918. WHERE
  919. access_url_id = $access_url_id AND
  920. course_rel_user.user_id = '$user_id' AND
  921. course_rel_user.status = '1'
  922. ";
  923. }
  924. }
  925. if (!empty($startsWith)) {
  926. $startsWith = Database::escape_string($startsWith);
  927. $sql .= " AND (course.title LIKE '$startsWith%' OR course.code LIKE '$startsWith%')";
  928. }
  929. $sql .= ' ORDER BY course.title';
  930. $result_nb_cours = Database::query($sql);
  931. if (Database::num_rows($result_nb_cours) > 0) {
  932. while ($row = Database::fetch_array($result_nb_cours, 'ASSOC')) {
  933. $data[$row['id']] = $row;
  934. }
  935. }
  936. return $data;
  937. }
  938. /**
  939. * @param int $userId
  940. * @param array $courseInfo
  941. * @return boolean|null
  942. */
  943. public static function isUserSubscribedInCourseAsDrh($userId, $courseInfo)
  944. {
  945. $userId = intval($userId);
  946. if (!api_is_drh()) {
  947. return false;
  948. }
  949. if (empty($courseInfo) || empty($userId)) {
  950. return false;
  951. }
  952. $courseId = intval($courseInfo['real_id']);
  953. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  954. $sql = "SELECT * FROM $table
  955. WHERE
  956. user_id = $userId AND
  957. relation_type = ".COURSE_RELATION_TYPE_RRHH." AND
  958. c_id = $courseId";
  959. $result = Database::fetch_array(Database::query($sql));
  960. if (!empty($result)) {
  961. // The user has been registered in this course.
  962. return true;
  963. }
  964. }
  965. /**
  966. * Check if user is subscribed inside a course
  967. * @param int $user_id
  968. * @param string $course_code , if this parameter is null, it'll check for all courses
  969. * @param bool $in_a_session True for checking inside sessions too, by default is not checked
  970. * @return bool $session_id true if the user is registered in the course, false otherwise
  971. */
  972. public static function is_user_subscribed_in_course(
  973. $user_id,
  974. $course_code = null,
  975. $in_a_session = false,
  976. $session_id = null
  977. ) {
  978. $user_id = intval($user_id);
  979. if (empty($session_id)) {
  980. $session_id = api_get_session_id();
  981. } else {
  982. $session_id = intval($session_id);
  983. }
  984. $condition_course = '';
  985. if (isset($course_code)) {
  986. $courseInfo = api_get_course_info($course_code);
  987. if (empty($courseInfo)) {
  988. return false;
  989. }
  990. $courseId = $courseInfo['real_id'];
  991. $condition_course = ' AND c_id = '.$courseId;
  992. }
  993. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  994. WHERE
  995. user_id = $user_id AND
  996. relation_type<>".COURSE_RELATION_TYPE_RRHH."
  997. $condition_course ";
  998. $result = Database::fetch_array(Database::query($sql));
  999. if (!empty($result)) {
  1000. // The user has been registered in this course.
  1001. return true;
  1002. }
  1003. if (!$in_a_session) {
  1004. // The user has not been registered in this course.
  1005. return false;
  1006. }
  1007. $tableSessionCourseUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1008. $sql = 'SELECT 1 FROM '.$tableSessionCourseUser.
  1009. ' WHERE user_id = '.$user_id.' '.$condition_course;
  1010. if (Database::num_rows(Database::query($sql)) > 0) {
  1011. return true;
  1012. }
  1013. $sql = 'SELECT 1 FROM '.$tableSessionCourseUser.
  1014. ' WHERE user_id = '.$user_id.' AND status=2 '.$condition_course;
  1015. if (Database::num_rows(Database::query($sql)) > 0) {
  1016. return true;
  1017. }
  1018. $sql = 'SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION).
  1019. ' WHERE id = '.$session_id.' AND id_coach='.$user_id;
  1020. if (Database::num_rows(Database::query($sql)) > 0) {
  1021. return true;
  1022. }
  1023. return false;
  1024. }
  1025. /**
  1026. * Is the user a teacher in the given course?
  1027. *
  1028. * @param integer $user_id , the id (int) of the user
  1029. * @param $course_code , the course code
  1030. *
  1031. * @return boolean if the user is a teacher in the course, false otherwise
  1032. */
  1033. public static function is_course_teacher($user_id, $course_code)
  1034. {
  1035. if ($user_id != strval(intval($user_id))) {
  1036. return false;
  1037. }
  1038. $courseInfo = api_get_course_info($course_code);
  1039. $courseId = $courseInfo['real_id'];
  1040. $result = Database::query(
  1041. 'SELECT status FROM '.Database::get_main_table(TABLE_MAIN_COURSE_USER).
  1042. ' WHERE c_id = '.$courseId.' AND user_id = '.$user_id.''
  1043. );
  1044. if (Database::num_rows($result) > 0) {
  1045. return Database::result($result, 0, 'status') == 1;
  1046. }
  1047. return false;
  1048. }
  1049. /**
  1050. * Is the user subscribed in the real course or linked courses?
  1051. *
  1052. * @param int the id of the user
  1053. * @param int $courseId
  1054. * @deprecated linked_courses definition doesn't exists
  1055. * @return boolean if the user is registered in the real course or linked courses, false otherwise
  1056. */
  1057. public static function is_user_subscribed_in_real_or_linked_course($user_id, $courseId, $session_id = '')
  1058. {
  1059. if ($user_id != strval(intval($user_id))) {
  1060. return false;
  1061. }
  1062. $courseId = intval($courseId);
  1063. if ($session_id == '') {
  1064. $result = Database::fetch_array(
  1065. Database::query(
  1066. "SELECT *
  1067. FROM " . Database::get_main_table(TABLE_MAIN_COURSE)." course
  1068. LEFT JOIN " . Database::get_main_table(TABLE_MAIN_COURSE_USER)." course_user
  1069. ON course.id = course_user.c_id
  1070. WHERE
  1071. course_user.user_id = '$user_id' AND
  1072. course_user.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
  1073. ( course.id = '$courseId')"
  1074. )
  1075. );
  1076. return !empty($result);
  1077. }
  1078. $session_id = intval($session_id);
  1079. // From here we trust session id.
  1080. // Is he/she subscribed to the session's course?
  1081. // A user?
  1082. if (Database::num_rows(Database::query("SELECT user_id
  1083. FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  1084. WHERE session_id='" . $session_id."'
  1085. AND user_id ='$user_id'"))
  1086. ) {
  1087. return true;
  1088. }
  1089. // A course coach?
  1090. if (Database::num_rows(Database::query("SELECT user_id
  1091. FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  1092. WHERE session_id='" . $session_id."'
  1093. AND user_id = '$user_id' AND status = 2
  1094. AND c_id ='$courseId'"))
  1095. ) {
  1096. return true;
  1097. }
  1098. // A session coach?
  1099. if (Database::num_rows(Database::query("SELECT id_coach
  1100. FROM " . Database::get_main_table(TABLE_MAIN_SESSION)." AS session
  1101. WHERE session.id='" . $session_id."'
  1102. AND id_coach='$user_id'"))
  1103. ) {
  1104. return true;
  1105. }
  1106. return false;
  1107. }
  1108. /**
  1109. * Return user info array of all users registered in a course
  1110. * This only returns the users that are registered in this actual course, not linked courses.
  1111. * @param string $course_code
  1112. * @param int $session_id
  1113. * @param string $limit
  1114. * @param string $order_by the field to order the users by.
  1115. * Valid values are 'lastname', 'firstname', 'username', 'email', 'official_code' OR a part of a SQL statement
  1116. * that starts with ORDER BY ...
  1117. * @param integer|null $filter_by_status if using the session_id: 0 or 2 (student, coach),
  1118. * if using session_id = 0 STUDENT or COURSEMANAGER
  1119. * @param boolean|null $return_count
  1120. * @param bool $add_reports
  1121. * @param bool $resumed_report
  1122. * @param array $extra_field
  1123. * @param array $courseCodeList
  1124. * @param array $userIdList
  1125. * @param string $filterByActive
  1126. * @param array $sessionIdList
  1127. * @return array|int
  1128. */
  1129. public static function get_user_list_from_course_code(
  1130. $course_code = null,
  1131. $session_id = 0,
  1132. $limit = null,
  1133. $order_by = null,
  1134. $filter_by_status = null,
  1135. $return_count = null,
  1136. $add_reports = false,
  1137. $resumed_report = false,
  1138. $extra_field = array(),
  1139. $courseCodeList = array(),
  1140. $userIdList = array(),
  1141. $filterByActive = null,
  1142. $sessionIdList = array()
  1143. ) {
  1144. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1145. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  1146. $session_id = intval($session_id);
  1147. $course_code = Database::escape_string($course_code);
  1148. $courseInfo = api_get_course_info($course_code);
  1149. $courseId = 0;
  1150. if (!empty($courseInfo)) {
  1151. $courseId = $courseInfo['real_id'];
  1152. }
  1153. $where = array();
  1154. if (empty($order_by)) {
  1155. $order_by = 'user.lastname, user.firstname';
  1156. if (api_is_western_name_order()) {
  1157. $order_by = 'user.firstname, user.lastname';
  1158. }
  1159. }
  1160. // if the $order_by does not contain 'ORDER BY'
  1161. // we have to check if it is a valid field that can be sorted on
  1162. if (!strstr($order_by, 'ORDER BY')) {
  1163. if (!empty($order_by)) {
  1164. $order_by = 'ORDER BY '.$order_by;
  1165. } else {
  1166. $order_by = '';
  1167. }
  1168. }
  1169. $filter_by_status_condition = null;
  1170. if (!empty($session_id) || !empty($sessionIdList)) {
  1171. $sql = 'SELECT DISTINCT
  1172. user.user_id,
  1173. user.email,
  1174. session_course_user.status as status_session,
  1175. session_id,
  1176. user.*,
  1177. course.*,
  1178. session.name as session_name
  1179. ';
  1180. if ($return_count) {
  1181. $sql = " SELECT COUNT(user.user_id) as count";
  1182. }
  1183. $sessionCondition = " session_course_user.session_id = $session_id";
  1184. if (!empty($sessionIdList)) {
  1185. $sessionIdListTostring = implode("','", array_map('intval', $sessionIdList));
  1186. $sessionCondition = " session_course_user.session_id IN ('$sessionIdListTostring') ";
  1187. }
  1188. $courseCondition = " course.id = $courseId";
  1189. if (!empty($courseCodeList)) {
  1190. $courseCodeListForSession = array_map(array('Database', 'escape_string'), $courseCodeList);
  1191. $courseCodeListForSession = implode('","', $courseCodeListForSession);
  1192. $courseCondition = ' course.code IN ("'.$courseCodeListForSession.'") ';
  1193. }
  1194. $sql .= ' FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
  1195. $sql .= " LEFT JOIN ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." as session_course_user
  1196. ON
  1197. user.id = session_course_user.user_id AND
  1198. $sessionCondition
  1199. INNER JOIN $course_table course
  1200. ON session_course_user.c_id = course.id AND
  1201. $courseCondition
  1202. INNER JOIN $sessionTable session
  1203. ON session_course_user.session_id = session.id
  1204. ";
  1205. $where[] = ' session_course_user.c_id IS NOT NULL ';
  1206. // 2 = coach
  1207. // 0 = student
  1208. if (isset($filter_by_status)) {
  1209. $filter_by_status = intval($filter_by_status);
  1210. $filter_by_status_condition = " session_course_user.status = $filter_by_status AND ";
  1211. }
  1212. } else {
  1213. if ($return_count) {
  1214. $sql = " SELECT COUNT(*) as count";
  1215. } else {
  1216. if (empty($course_code)) {
  1217. $sql = 'SELECT DISTINCT
  1218. course.title,
  1219. course.code,
  1220. course_rel_user.status as status_rel,
  1221. user.id as user_id,
  1222. user.email,
  1223. course_rel_user.is_tutor,
  1224. user.* ';
  1225. } else {
  1226. $sql = 'SELECT DISTINCT
  1227. course_rel_user.status as status_rel,
  1228. user.id as user_id,
  1229. user.email,
  1230. course_rel_user.is_tutor,
  1231. user.* ';
  1232. }
  1233. }
  1234. $sql .= ' FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user '
  1235. . ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_COURSE_USER).' as course_rel_user
  1236. ON
  1237. user.id = course_rel_user.user_id AND
  1238. course_rel_user.relation_type <> ' . COURSE_RELATION_TYPE_RRHH.' '
  1239. . " INNER JOIN $course_table course ON course_rel_user.c_id = course.id ";
  1240. if (!empty($course_code)) {
  1241. $sql .= ' AND course_rel_user.c_id = "'.$courseId.'"';
  1242. }
  1243. $where[] = ' course_rel_user.c_id IS NOT NULL ';
  1244. if (isset($filter_by_status) && is_numeric($filter_by_status)) {
  1245. $filter_by_status = intval($filter_by_status);
  1246. $filter_by_status_condition = " course_rel_user.status = $filter_by_status AND ";
  1247. }
  1248. }
  1249. $multiple_access_url = api_get_multiple_access_url();
  1250. if ($multiple_access_url) {
  1251. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au
  1252. ON (au.user_id = user.id) ';
  1253. }
  1254. $extraFieldWasAdded = false;
  1255. if ($return_count && $resumed_report) {
  1256. foreach ($extra_field as $extraField) {
  1257. $extraFieldInfo = UserManager::get_extra_field_information_by_name($extraField);
  1258. if (!empty($extraFieldInfo)) {
  1259. $fieldValuesTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  1260. $sql .= ' LEFT JOIN '.$fieldValuesTable.' as ufv
  1261. ON (
  1262. user.id = ufv.item_id AND
  1263. (field_id = '.$extraFieldInfo['id'].' OR field_id IS NULL)
  1264. )';
  1265. $extraFieldWasAdded = true;
  1266. }
  1267. }
  1268. }
  1269. $sql .= ' WHERE '.$filter_by_status_condition.' '.implode(' OR ', $where);
  1270. if ($multiple_access_url) {
  1271. $current_access_url_id = api_get_current_access_url_id();
  1272. $sql .= " AND (access_url_id = $current_access_url_id ) ";
  1273. }
  1274. if ($return_count && $resumed_report && $extraFieldWasAdded) {
  1275. $sql .= ' AND field_id IS NOT NULL GROUP BY value ';
  1276. }
  1277. if (!empty($courseCodeList)) {
  1278. $courseCodeList = array_map(array('Database', 'escape_string'), $courseCodeList);
  1279. $courseCodeList = implode('","', $courseCodeList);
  1280. if (empty($sessionIdList)) {
  1281. $sql .= ' AND course.code IN ("'.$courseCodeList.'")';
  1282. }
  1283. }
  1284. if (!empty($userIdList)) {
  1285. $userIdList = array_map('intval', $userIdList);
  1286. $userIdList = implode('","', $userIdList);
  1287. $sql .= ' AND user.id IN ("'.$userIdList.'")';
  1288. }
  1289. if (isset($filterByActive)) {
  1290. $filterByActive = intval($filterByActive);
  1291. $sql .= ' AND user.active = '.$filterByActive;
  1292. }
  1293. $sql .= ' '.$order_by.' '.$limit;
  1294. $rs = Database::query($sql);
  1295. $users = array();
  1296. $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
  1297. $counter = 1;
  1298. $count_rows = Database::num_rows($rs);
  1299. if ($return_count && $resumed_report) {
  1300. return $count_rows;
  1301. }
  1302. $table_user_field_value = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  1303. $tableExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
  1304. if ($count_rows) {
  1305. while ($user = Database::fetch_array($rs)) {
  1306. if ($return_count) {
  1307. return $user['count'];
  1308. }
  1309. $report_info = array();
  1310. $user_info = $user;
  1311. $user_info['status'] = $user['status'];
  1312. if (isset($user['is_tutor'])) {
  1313. $user_info['is_tutor'] = $user['is_tutor'];
  1314. }
  1315. if (!empty($session_id)) {
  1316. $user_info['status_session'] = $user['status_session'];
  1317. }
  1318. $sessionId = isset($user['session_id']) ? $user['session_id'] : 0;
  1319. $course_code = isset($user['code']) ? $user['code'] : null;
  1320. if ($add_reports) {
  1321. if ($resumed_report) {
  1322. $extra = array();
  1323. if (!empty($extra_fields)) {
  1324. foreach ($extra_fields as $extra) {
  1325. if (in_array($extra['1'], $extra_field)) {
  1326. $user_data = UserManager::get_extra_user_data_by_field(
  1327. $user['user_id'],
  1328. $extra['1']
  1329. );
  1330. break;
  1331. }
  1332. }
  1333. }
  1334. $row_key = '-1';
  1335. $name = '-';
  1336. if (!empty($extra)) {
  1337. if (!empty($user_data[$extra['1']])) {
  1338. $row_key = $user_data[$extra['1']];
  1339. $name = $user_data[$extra['1']];
  1340. $users[$row_key]['extra_'.$extra['1']] = $name;
  1341. }
  1342. }
  1343. $users[$row_key]['training_hours'] += Tracking::get_time_spent_on_the_course(
  1344. $user['user_id'],
  1345. $courseId,
  1346. $sessionId
  1347. );
  1348. $users[$row_key]['count_users'] += $counter;
  1349. $registered_users_with_extra_field = self::getCountRegisteredUsersWithCourseExtraField(
  1350. $name,
  1351. $tableExtraField,
  1352. $table_user_field_value
  1353. );
  1354. $users[$row_key]['count_users_registered'] = $registered_users_with_extra_field;
  1355. $users[$row_key]['average_hours_per_user'] = $users[$row_key]['training_hours'] / $users[$row_key]['count_users'];
  1356. $category = Category:: load(
  1357. null,
  1358. null,
  1359. $course_code,
  1360. null,
  1361. null,
  1362. $sessionId
  1363. );
  1364. if (!isset($users[$row_key]['count_certificates'])) {
  1365. $users[$row_key]['count_certificates'] = 0;
  1366. }
  1367. if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
  1368. $users[$row_key]['count_certificates']++;
  1369. }
  1370. foreach ($extra_fields as $extra) {
  1371. if ($extra['1'] == 'ruc') {
  1372. continue;
  1373. }
  1374. if (!isset($users[$row_key][$extra['1']])) {
  1375. $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
  1376. if (!empty($user_data[$extra['1']])) {
  1377. $users[$row_key][$extra['1']] = $user_data[$extra['1']];
  1378. }
  1379. }
  1380. }
  1381. } else {
  1382. $sessionName = !empty($sessionId) ? ' - '.$user['session_name'] : '';
  1383. $report_info['course'] = $user['title'].$sessionName;
  1384. $report_info['user'] = api_get_person_name($user['firstname'], $user['lastname']);
  1385. $report_info['email'] = $user['email'];
  1386. $report_info['time'] = api_time_to_hms(
  1387. Tracking::get_time_spent_on_the_course(
  1388. $user['user_id'],
  1389. $courseId,
  1390. $sessionId
  1391. )
  1392. );
  1393. $category = Category:: load(
  1394. null,
  1395. null,
  1396. $course_code,
  1397. null,
  1398. null,
  1399. $sessionId
  1400. );
  1401. $report_info['certificate'] = Display::label(get_lang('No'));
  1402. if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
  1403. $report_info['certificate'] = Display::label(get_lang('Yes'), 'success');
  1404. }
  1405. $progress = intval(
  1406. Tracking::get_avg_student_progress(
  1407. $user['user_id'],
  1408. $course_code,
  1409. array(),
  1410. $sessionId
  1411. )
  1412. );
  1413. $report_info['progress_100'] = $progress == 100 ? Display::label(get_lang('Yes'), 'success') : Display::label(get_lang('No'));
  1414. $report_info['progress'] = $progress."%";
  1415. foreach ($extra_fields as $extra) {
  1416. $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
  1417. $report_info[$extra['1']] = $user_data[$extra['1']];
  1418. }
  1419. $report_info['user_id'] = $user['user_id'];
  1420. $users[] = $report_info;
  1421. }
  1422. } else {
  1423. $users[$user['user_id']] = $user_info;
  1424. }
  1425. }
  1426. }
  1427. return $users;
  1428. }
  1429. /**
  1430. * @param bool $resumed_report
  1431. * @param array $extra_field
  1432. * @param array $courseCodeList
  1433. * @param array $userIdList
  1434. * @param array $sessionIdList
  1435. * @return array|int
  1436. */
  1437. public static function get_count_user_list_from_course_code(
  1438. $resumed_report = false,
  1439. $extra_field = array(),
  1440. $courseCodeList = array(),
  1441. $userIdList = array(),
  1442. $sessionIdList = array()
  1443. ) {
  1444. return self::get_user_list_from_course_code(
  1445. null,
  1446. 0,
  1447. null,
  1448. null,
  1449. null,
  1450. true,
  1451. false,
  1452. $resumed_report,
  1453. $extra_field,
  1454. $courseCodeList,
  1455. $userIdList,
  1456. null,
  1457. $sessionIdList
  1458. );
  1459. }
  1460. /**
  1461. * Gets subscribed users in a course or in a course/session
  1462. *
  1463. * @param string $course_code
  1464. * @param int $session_id
  1465. * @return int
  1466. */
  1467. public static function get_users_count_in_course(
  1468. $course_code,
  1469. $session_id = 0,
  1470. $status = null
  1471. ) {
  1472. // variable initialisation
  1473. $session_id = intval($session_id);
  1474. $course_code = Database::escape_string($course_code);
  1475. $courseInfo = api_get_course_info($course_code);
  1476. $courseId = $courseInfo['real_id'];
  1477. $sql = 'SELECT DISTINCT count(user.id) as count
  1478. FROM ' . Database::get_main_table(TABLE_MAIN_USER).' as user ';
  1479. $where = array();
  1480. if (!empty($session_id)) {
  1481. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' as session_course_user
  1482. ON
  1483. user.user_id = session_course_user.user_id AND
  1484. session_course_user.c_id = "' . $courseId.'" AND
  1485. session_course_user.session_id = ' . $session_id;
  1486. $where[] = ' session_course_user.c_id IS NOT NULL ';
  1487. } else {
  1488. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_COURSE_USER).' as course_rel_user
  1489. ON
  1490. user.user_id = course_rel_user.user_id AND
  1491. course_rel_user.relation_type<>' . COURSE_RELATION_TYPE_RRHH.' AND
  1492. course_rel_user.c_id = ' . $courseId;
  1493. $where[] = ' course_rel_user.c_id IS NOT NULL ';
  1494. }
  1495. $multiple_access_url = api_get_multiple_access_url();
  1496. if ($multiple_access_url) {
  1497. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au
  1498. ON (au.user_id = user.user_id) ';
  1499. }
  1500. $sql .= ' WHERE '.implode(' OR ', $where);
  1501. if ($multiple_access_url) {
  1502. $current_access_url_id = api_get_current_access_url_id();
  1503. $sql .= " AND (access_url_id = $current_access_url_id ) ";
  1504. }
  1505. $rs = Database::query($sql);
  1506. $count = 0;
  1507. if (Database::num_rows($rs)) {
  1508. $user = Database::fetch_array($rs);
  1509. $count = $user['count'];
  1510. }
  1511. return $count;
  1512. }
  1513. /**
  1514. * Get a list of coaches of a course and a session
  1515. * @param string $course_code
  1516. * @param int $session_id
  1517. * @param bool $addGeneralCoach
  1518. * @return array List of users
  1519. */
  1520. public static function get_coach_list_from_course_code($course_code, $session_id, $addGeneralCoach = true)
  1521. {
  1522. if (empty($course_code) || empty($session_id)) {
  1523. return array();
  1524. }
  1525. $course_code = Database::escape_string($course_code);
  1526. $courseInfo = api_get_course_info($course_code);
  1527. $courseId = $courseInfo['real_id'];
  1528. $session_id = intval($session_id);
  1529. $users = array();
  1530. // We get the coach for the given course in a given session.
  1531. $sql = 'SELECT user_id FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
  1532. ' WHERE session_id ="'.$session_id.'" AND c_id="'.$courseId.'" AND status = 2';
  1533. $rs = Database::query($sql);
  1534. while ($user = Database::fetch_array($rs)) {
  1535. $userInfo = api_get_user_info($user['user_id']);
  1536. if ($userInfo) {
  1537. $users[$user['user_id']] = $userInfo;
  1538. }
  1539. }
  1540. if ($addGeneralCoach) {
  1541. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  1542. // We get the session coach.
  1543. $sql = 'SELECT id_coach FROM '.$table.' WHERE id='.$session_id;
  1544. $rs = Database::query($sql);
  1545. $session_id_coach = Database::result($rs, 0, 'id_coach');
  1546. $userInfo = api_get_user_info($session_id_coach);
  1547. if ($userInfo) {
  1548. $users[$session_id_coach] = $userInfo;
  1549. }
  1550. }
  1551. return $users;
  1552. }
  1553. /**
  1554. * Return user info array of all users registered in a course
  1555. * This only returns the users that are registered in this actual course, not linked courses.
  1556. *
  1557. * @param string $course_code
  1558. * @param boolean $with_session
  1559. * @param integer $session_id
  1560. * @param string $date_from
  1561. * @param string $date_to
  1562. * @param boolean $includeInvitedUsers Whether include the invited users
  1563. * @param int $groupId
  1564. * @return array with user id
  1565. */
  1566. public static function get_student_list_from_course_code(
  1567. $course_code,
  1568. $with_session = false,
  1569. $session_id = 0,
  1570. $date_from = null,
  1571. $date_to = null,
  1572. $includeInvitedUsers = true,
  1573. $groupId = 0
  1574. ) {
  1575. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  1576. $session_id = intval($session_id);
  1577. $course_code = Database::escape_string($course_code);
  1578. $courseInfo = api_get_course_info($course_code);
  1579. $courseId = $courseInfo['real_id'];
  1580. $students = array();
  1581. if ($session_id == 0) {
  1582. if (empty($groupId)) {
  1583. // students directly subscribed to the course
  1584. $sql = "SELECT *
  1585. FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
  1586. INNER JOIN $userTable u
  1587. ON cu.user_id = u.user_id
  1588. WHERE c_id = '$courseId' AND cu.status = ".STUDENT;
  1589. if (!$includeInvitedUsers) {
  1590. $sql .= " AND u.status != ".INVITEE;
  1591. }
  1592. $rs = Database::query($sql);
  1593. while ($student = Database::fetch_array($rs)) {
  1594. $students[$student['user_id']] = $student;
  1595. }
  1596. } else {
  1597. $students = GroupManager::get_users(
  1598. $groupId,
  1599. false,
  1600. null,
  1601. null,
  1602. false,
  1603. $courseInfo['real_id']
  1604. );
  1605. $students = array_flip($students);
  1606. }
  1607. }
  1608. // students subscribed to the course through a session
  1609. if ($with_session) {
  1610. $joinSession = "";
  1611. //Session creation date
  1612. if (!empty($date_from) && !empty($date_to)) {
  1613. $joinSession = "INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)." s";
  1614. }
  1615. $sql_query = "SELECT *
  1616. FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." scu
  1617. $joinSession
  1618. INNER JOIN $userTable u ON scu.user_id = u.user_id
  1619. WHERE scu.c_id = '$courseId' AND scu.status <> 2";
  1620. if (!empty($date_from) && !empty($date_to)) {
  1621. $date_from = Database::escape_string($date_from);
  1622. $date_to = Database::escape_string($date_to);
  1623. $sql_query .= " AND s.access_start_date >= '$date_from' AND s.access_end_date <= '$date_to'";
  1624. }
  1625. if ($session_id != 0) {
  1626. $sql_query .= ' AND scu.session_id = '.$session_id;
  1627. }
  1628. if (!$includeInvitedUsers) {
  1629. $sql_query .= " AND u.status != ".INVITEE;
  1630. }
  1631. $rs = Database::query($sql_query);
  1632. while ($student = Database::fetch_array($rs)) {
  1633. $students[$student['user_id']] = $student;
  1634. }
  1635. }
  1636. return $students;
  1637. }
  1638. /**
  1639. * Return user info array of all teacher-users registered in a course
  1640. * This only returns the users that are registered in this actual course, not linked courses.
  1641. *
  1642. * @param string $course_code
  1643. * @return array with user id
  1644. */
  1645. public static function get_teacher_list_from_course_code($course_code)
  1646. {
  1647. $courseInfo = api_get_course_info($course_code);
  1648. $courseId = $courseInfo['real_id'];
  1649. if (empty($courseId)) {
  1650. return false;
  1651. }
  1652. $sql = "SELECT DISTINCT
  1653. u.id as user_id,
  1654. u.lastname,
  1655. u.firstname,
  1656. u.email,
  1657. u.username,
  1658. u.status
  1659. FROM " . Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
  1660. INNER JOIN " . Database::get_main_table(TABLE_MAIN_USER)." u
  1661. ON (cu.user_id = u.id)
  1662. WHERE
  1663. cu.c_id = $courseId AND
  1664. cu.status = 1 ";
  1665. $rs = Database::query($sql);
  1666. $teachers = array();
  1667. while ($teacher = Database::fetch_array($rs)) {
  1668. $teachers[$teacher['user_id']] = $teacher;
  1669. }
  1670. return $teachers;
  1671. }
  1672. /**
  1673. * Return user info array of all teacher-users registered in a course
  1674. * This only returns the users that are registered in this actual course, not linked courses.
  1675. *
  1676. * @param int $courseId
  1677. * @param bool $loadAvatars
  1678. *
  1679. * @return array with user id
  1680. */
  1681. public static function getTeachersFromCourse($courseId, $loadAvatars = true)
  1682. {
  1683. $courseId = (int) $courseId;
  1684. if (empty($courseId)) {
  1685. return false;
  1686. }
  1687. $sql = "SELECT DISTINCT
  1688. u.id as user_id,
  1689. u.lastname,
  1690. u.firstname,
  1691. u.email,
  1692. u.username,
  1693. u.status
  1694. FROM " . Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
  1695. INNER JOIN " . Database::get_main_table(TABLE_MAIN_USER)." u
  1696. ON (cu.user_id = u.id)
  1697. WHERE
  1698. cu.c_id = $courseId AND
  1699. cu.status = 1 ";
  1700. $rs = Database::query($sql);
  1701. $listTeachers = array();
  1702. $teachers = array();
  1703. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup';
  1704. while ($teacher = Database::fetch_array($rs)) {
  1705. $teachers['id'] = $teacher['user_id'];
  1706. $teachers['lastname'] = $teacher['lastname'];
  1707. $teachers['firstname'] = $teacher['firstname'];
  1708. $teachers['email'] = $teacher['email'];
  1709. $teachers['username'] = $teacher['username'];
  1710. $teachers['status'] = $teacher['status'];
  1711. $teachers['avatar'] = '';
  1712. if ($loadAvatars) {
  1713. $userPicture = UserManager::getUserPicture($teacher['user_id'], USER_IMAGE_SIZE_SMALL);
  1714. $teachers['avatar'] = $userPicture;
  1715. }
  1716. $teachers['url'] = $url.'&user_id='.$teacher['user_id'];
  1717. $listTeachers[] = $teachers;
  1718. }
  1719. return $listTeachers;
  1720. }
  1721. /**
  1722. * Returns a string list of teachers assigned to the given course
  1723. * @param string $course_code
  1724. * @param string $separator between teachers names
  1725. * @param bool $add_link_to_profile Whether to add a link to the teacher's profile
  1726. * @return string List of teachers teaching the course
  1727. */
  1728. public static function get_teacher_list_from_course_code_to_string(
  1729. $course_code,
  1730. $separator = self::USER_SEPARATOR,
  1731. $add_link_to_profile = false,
  1732. $orderList = false
  1733. ) {
  1734. $teacher_list = self::get_teacher_list_from_course_code($course_code);
  1735. $html = '';
  1736. $list = array();
  1737. if (!empty($teacher_list)) {
  1738. foreach ($teacher_list as $teacher) {
  1739. $teacher_name = api_get_person_name(
  1740. $teacher['firstname'],
  1741. $teacher['lastname']
  1742. );
  1743. if ($add_link_to_profile) {
  1744. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$teacher['user_id'];
  1745. $teacher_name = Display::url(
  1746. $teacher_name,
  1747. $url,
  1748. [
  1749. 'class' => 'ajax',
  1750. 'data-title' => $teacher_name
  1751. ]
  1752. );
  1753. }
  1754. $list[] = $teacher_name;
  1755. }
  1756. if (!empty($list)) {
  1757. if ($orderList === true) {
  1758. $html .= '<ul class="user-teacher">';
  1759. foreach ($list as $teacher) {
  1760. $html .= Display::tag('li', Display::return_icon('teacher.png', $teacher, null, ICON_SIZE_TINY).' '.$teacher);
  1761. }
  1762. $html .= '</ul>';
  1763. } else {
  1764. $html .= array_to_string($list, $separator);
  1765. }
  1766. }
  1767. }
  1768. return $html;
  1769. }
  1770. /**
  1771. * This function returns information about coachs from a course in session
  1772. * @param int $session_id
  1773. * @param int $courseId
  1774. *
  1775. * @return array containing user_id, lastname, firstname, username
  1776. */
  1777. public static function get_coachs_from_course($session_id = 0, $courseId = 0)
  1778. {
  1779. if (!empty($session_id)) {
  1780. $session_id = intval($session_id);
  1781. } else {
  1782. $session_id = api_get_session_id();
  1783. }
  1784. if (!empty($courseId)) {
  1785. $courseId = intval($courseId);
  1786. } else {
  1787. $courseId = api_get_course_int_id();
  1788. }
  1789. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1790. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1791. $sql = "SELECT DISTINCT
  1792. u.user_id,
  1793. u.lastname,
  1794. u.firstname,
  1795. u.username
  1796. FROM $tbl_user u
  1797. INNER JOIN $tbl_session_course_user scu
  1798. ON (u.user_id = scu.user_id)
  1799. WHERE
  1800. scu.session_id = '$session_id' AND
  1801. scu.c_id = '$courseId' AND
  1802. scu.status = 2";
  1803. $rs = Database::query($sql);
  1804. $coaches = array();
  1805. if (Database::num_rows($rs) > 0) {
  1806. while ($row = Database::fetch_array($rs)) {
  1807. $completeName = api_get_person_name($row['firstname'], $row['lastname']);
  1808. $coaches[] = $row + ['full_name' => $completeName];
  1809. }
  1810. }
  1811. return $coaches;
  1812. }
  1813. /**
  1814. * @param int $session_id
  1815. * @param int $courseId
  1816. * @param string $separator
  1817. * @param bool $add_link_to_profile
  1818. * @return string
  1819. */
  1820. public static function get_coachs_from_course_to_string(
  1821. $session_id = 0,
  1822. $courseId = 0,
  1823. $separator = self::USER_SEPARATOR,
  1824. $add_link_to_profile = false,
  1825. $orderList = false
  1826. ) {
  1827. $coachList = self::get_coachs_from_course($session_id, $courseId);
  1828. $course_coachs = array();
  1829. if (!empty($coachList)) {
  1830. foreach ($coachList as $coach_course) {
  1831. $coach_name = $coach_course['full_name'];
  1832. if ($add_link_to_profile) {
  1833. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$coach_course['user_id'];
  1834. $coach_name = Display::url(
  1835. $coach_name,
  1836. $url,
  1837. [
  1838. 'class' => 'ajax',
  1839. 'data-title' => $coach_name
  1840. ]
  1841. );
  1842. }
  1843. $course_coachs[] = $coach_name;
  1844. }
  1845. }
  1846. $html = '';
  1847. if (!empty($course_coachs)) {
  1848. if ($orderList === true) {
  1849. $html .= '<ul class="user-coachs">';
  1850. foreach ($course_coachs as $coachs) {
  1851. $html .= Display::tag(
  1852. 'li',
  1853. Display::return_icon('teacher.png', $coachs, null, ICON_SIZE_TINY).' '.$coachs
  1854. );
  1855. }
  1856. $html .= '</ul>';
  1857. } else {
  1858. $html = array_to_string($course_coachs, $separator);
  1859. }
  1860. }
  1861. return $html;
  1862. }
  1863. /**
  1864. * Return user info array of all users registered in the specified course
  1865. * this includes the users of the course itself and the users of all linked courses.
  1866. *
  1867. * @param string $course_code
  1868. * @param bool $with_sessions
  1869. * @param int $session_id
  1870. * @return array with user info
  1871. */
  1872. public static function get_real_and_linked_user_list($course_code, $with_sessions = true, $session_id = 0)
  1873. {
  1874. $list = array();
  1875. $userList = self::get_user_list_from_course_code($course_code, $session_id);
  1876. foreach ($userList as $user) {
  1877. $list[] = $user;
  1878. }
  1879. return $list;
  1880. }
  1881. /**
  1882. * Get the list of groups from the course
  1883. * @param string $course_code
  1884. * @param int $session_id Session ID (optional)
  1885. * @param integer $in_get_empty_group get empty groups (optional)
  1886. * @return array List of groups info
  1887. */
  1888. public static function get_group_list_of_course($course_code, $session_id = 0, $in_get_empty_group = 0)
  1889. {
  1890. $course_info = api_get_course_info($course_code);
  1891. if (empty($course_info)) {
  1892. return array();
  1893. }
  1894. $course_id = $course_info['real_id'];
  1895. if (empty($course_id)) {
  1896. return array();
  1897. }
  1898. $group_list = array();
  1899. $session_id != 0 ? $session_condition = ' WHERE g.session_id IN(1,'.intval($session_id).')' : $session_condition = ' WHERE g.session_id = 0';
  1900. if ($in_get_empty_group == 0) {
  1901. // get only groups that are not empty
  1902. $sql = "SELECT DISTINCT g.id, g.iid, g.name
  1903. FROM " . Database::get_course_table(TABLE_GROUP)." AS g
  1904. INNER JOIN " . Database::get_course_table(TABLE_GROUP_USER)." gu
  1905. ON (g.id = gu.group_id AND g.c_id = $course_id AND gu.c_id = $course_id)
  1906. $session_condition
  1907. ORDER BY g.name";
  1908. } else {
  1909. // get all groups even if they are empty
  1910. $sql = "SELECT g.id, g.name, g.iid
  1911. FROM " . Database::get_course_table(TABLE_GROUP)." AS g
  1912. $session_condition
  1913. AND c_id = $course_id";
  1914. }
  1915. $result = Database::query($sql);
  1916. while ($group_data = Database::fetch_array($result)) {
  1917. $group_data['userNb'] = GroupManager::number_of_students($group_data['id'], $course_id);
  1918. $group_list[$group_data['id']] = $group_data;
  1919. }
  1920. return $group_list;
  1921. }
  1922. /**
  1923. * Delete a course
  1924. * This function deletes a whole course-area from the platform. When the
  1925. * given course is a virtual course, the database and directory will not be
  1926. * deleted.
  1927. * When the given course is a real course, also all virtual courses refering
  1928. * to the given course will be deleted.
  1929. * Considering the fact that we remove all traces of the course in the main
  1930. * database, it makes sense to remove all tracking as well (if stats databases exist)
  1931. * so that a new course created with this code would not use the remains of an older
  1932. * course.
  1933. *
  1934. * @param string The code of the course to delete
  1935. * @param string $code
  1936. * @todo When deleting a virtual course: unsubscribe users from that virtual
  1937. * course from the groups in the real course if they are not subscribed in
  1938. * that real course.
  1939. * @todo Remove globals
  1940. */
  1941. public static function delete_course($code)
  1942. {
  1943. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1944. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1945. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1946. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1947. $table_course_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
  1948. $table_course_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1949. $table_course_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1950. $table_course_rel_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1951. $table_stats_hotpots = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  1952. $table_stats_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1953. $table_stats_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1954. $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  1955. $table_stats_lastaccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  1956. $table_stats_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1957. $table_stats_online = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  1958. $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  1959. $table_stats_downloads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  1960. $table_stats_links = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  1961. $table_stats_uploads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
  1962. $codeFiltered = Database::escape_string($code);
  1963. $sql = "SELECT * FROM $table_course WHERE code='".$codeFiltered."'";
  1964. $res = Database::query($sql);
  1965. if (Database::num_rows($res) == 0) {
  1966. return;
  1967. }
  1968. $sql = "SELECT * FROM $table_course
  1969. WHERE code = '".$codeFiltered."'";
  1970. $res = Database::query($sql);
  1971. $course = Database::fetch_array($res);
  1972. $courseId = $course['id'];
  1973. $count = 0;
  1974. if (api_is_multiple_url_enabled()) {
  1975. $url_id = 1;
  1976. if (api_get_current_access_url_id() != -1) {
  1977. $url_id = api_get_current_access_url_id();
  1978. }
  1979. UrlManager::delete_url_rel_course($courseId, $url_id);
  1980. $count = UrlManager::getCountUrlRelCourse($courseId);
  1981. }
  1982. if ($count == 0) {
  1983. self::create_database_dump($code);
  1984. $course_tables = AddCourse::get_course_tables();
  1985. // Cleaning group categories
  1986. $groupCategories = GroupManager::get_categories($course['code']);
  1987. if (!empty($groupCategories)) {
  1988. foreach ($groupCategories as $category) {
  1989. GroupManager::delete_category($category['id'], $course['code']);
  1990. }
  1991. }
  1992. // Cleaning groups
  1993. $groups = GroupManager::get_groups($courseId);
  1994. if (!empty($groups)) {
  1995. foreach ($groups as $group) {
  1996. GroupManager::delete_groups($group, $course['code']);
  1997. }
  1998. }
  1999. // Cleaning c_x tables
  2000. if (!empty($courseId)) {
  2001. foreach ($course_tables as $table) {
  2002. $table = Database::get_course_table($table);
  2003. $sql = "DELETE FROM $table WHERE c_id = $courseId ";
  2004. Database::query($sql);
  2005. }
  2006. }
  2007. $course_dir = api_get_path(SYS_COURSE_PATH).$course['directory'];
  2008. $archive_dir = api_get_path(SYS_ARCHIVE_PATH).$course['directory'].'_'.time();
  2009. if (is_dir($course_dir)) {
  2010. rename($course_dir, $archive_dir);
  2011. }
  2012. // Unsubscribe all users from the course
  2013. $sql = "DELETE FROM $table_course_user WHERE c_id='".$courseId."'";
  2014. Database::query($sql);
  2015. // Delete the course from the sessions tables
  2016. $sql = "DELETE FROM $table_session_course WHERE c_id='".$courseId."'";
  2017. Database::query($sql);
  2018. $sql = "DELETE FROM $table_session_course_user WHERE c_id='".$courseId."'";
  2019. Database::query($sql);
  2020. // Delete from Course - URL
  2021. $sql = "DELETE FROM $table_course_rel_url WHERE c_id = '".$courseId."'";
  2022. Database::query($sql);
  2023. $sql = 'SELECT survey_id FROM '.$table_course_survey.' WHERE course_code="'.$codeFiltered.'"';
  2024. $result_surveys = Database::query($sql);
  2025. while ($surveys = Database::fetch_array($result_surveys)) {
  2026. $survey_id = $surveys[0];
  2027. $sql = 'DELETE FROM '.$table_course_survey_question.' WHERE survey_id="'.$survey_id.'"';
  2028. Database::query($sql);
  2029. $sql = 'DELETE FROM '.$table_course_survey_question_option.' WHERE survey_id="'.$survey_id.'"';
  2030. Database::query($sql);
  2031. $sql = 'DELETE FROM '.$table_course_survey.' WHERE survey_id="'.$survey_id.'"';
  2032. Database::query($sql);
  2033. }
  2034. // Delete the course from the stats tables
  2035. $sql = "DELETE FROM $table_stats_hotpots WHERE c_id = $courseId";
  2036. Database::query($sql);
  2037. $sql = "DELETE FROM $table_stats_attempt WHERE c_id = $courseId";
  2038. Database::query($sql);
  2039. $sql = "DELETE FROM $table_stats_exercises WHERE c_id = $courseId";
  2040. Database::query($sql);
  2041. $sql = "DELETE FROM $table_stats_access WHERE c_id = $courseId";
  2042. Database::query($sql);
  2043. $sql = "DELETE FROM $table_stats_lastaccess WHERE c_id = $courseId";
  2044. Database::query($sql);
  2045. $sql = "DELETE FROM $table_stats_course_access WHERE c_id = $courseId";
  2046. Database::query($sql);
  2047. $sql = "DELETE FROM $table_stats_online WHERE c_id = $courseId";
  2048. Database::query($sql);
  2049. // Do not delete rows from track_e_default as these include course
  2050. // creation and other important things that do not take much space
  2051. // but give information on the course history
  2052. //$sql = "DELETE FROM $table_stats_default WHERE c_id = $courseId";
  2053. //Database::query($sql);
  2054. $sql = "DELETE FROM $table_stats_downloads WHERE c_id = $courseId";
  2055. Database::query($sql);
  2056. $sql = "DELETE FROM $table_stats_links WHERE c_id = $courseId";
  2057. Database::query($sql);
  2058. $sql = "DELETE FROM $table_stats_uploads WHERE c_id = $courseId";
  2059. Database::query($sql);
  2060. // Update ticket
  2061. $table = Database::get_main_table(TABLE_TICKET_TICKET);
  2062. $sql = "UPDATE $table SET course_id = NULL WHERE course_id = $courseId";
  2063. Database::query($sql);
  2064. // Class
  2065. $table = Database::get_main_table(TABLE_USERGROUP_REL_COURSE);
  2066. $sql = "DELETE FROM $table
  2067. WHERE course_id = $courseId";
  2068. Database::query($sql);
  2069. // Skills
  2070. $table = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
  2071. $argumentation = Database::escape_string(sprintf(get_lang('SkillFromCourseXDeletedSinceThen'), $course['code']));
  2072. $sql = "UPDATE $table SET course_id = NULL, session_id = NULL, argumentation = '$argumentation' WHERE course_id = $courseId";
  2073. Database::query($sql);
  2074. // Delete the course from the database
  2075. $sql = "DELETE FROM $table_course WHERE code = '".$codeFiltered."'";
  2076. Database::query($sql);
  2077. // delete extra course fields
  2078. $extraFieldValues = new ExtraFieldValue('course');
  2079. $extraFieldValues->deleteValuesByItem($courseId);
  2080. // Add event to system log
  2081. $user_id = api_get_user_id();
  2082. Event::addEvent(
  2083. LOG_COURSE_DELETE,
  2084. LOG_COURSE_CODE,
  2085. $code,
  2086. api_get_utc_datetime(),
  2087. $user_id,
  2088. $courseId
  2089. );
  2090. }
  2091. }
  2092. /**
  2093. * Creates a file called mysql_dump.sql in the course folder
  2094. * @param string $course_code The code of the course
  2095. * @todo Implementation for single database
  2096. */
  2097. public static function create_database_dump($course_code)
  2098. {
  2099. $sql_dump = '';
  2100. $course_code = Database::escape_string($course_code);
  2101. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2102. $sql = "SELECT * FROM $table_course WHERE code = '$course_code'";
  2103. $res = Database::query($sql);
  2104. $course = Database::fetch_array($res);
  2105. $course_tables = AddCourse::get_course_tables();
  2106. if (!empty($course['id'])) {
  2107. //Cleaning c_x tables
  2108. foreach ($course_tables as $table) {
  2109. $table = Database::get_course_table($table);
  2110. $sql = "SELECT * FROM $table WHERE c_id = {$course['id']} ";
  2111. $res_table = Database::query($sql);
  2112. while ($row = Database::fetch_array($res_table, 'ASSOC')) {
  2113. $row_to_save = array();
  2114. foreach ($row as $key => $value) {
  2115. $row_to_save[$key] = $key."='".Database::escape_string($row[$key])."'";
  2116. }
  2117. $sql_dump .= "\nINSERT INTO $table SET ".implode(', ', $row_to_save).';';
  2118. }
  2119. }
  2120. }
  2121. if (is_dir(api_get_path(SYS_COURSE_PATH).$course['directory'])) {
  2122. $file_name = api_get_path(SYS_COURSE_PATH).$course['directory'].'/mysql_dump.sql';
  2123. $handle = fopen($file_name, 'a+');
  2124. if ($handle !== false) {
  2125. fwrite($handle, $sql_dump);
  2126. fclose($handle);
  2127. } else {
  2128. //TODO trigger exception in a try-catch
  2129. }
  2130. }
  2131. }
  2132. /**
  2133. * Sort courses for a specific user ??
  2134. * @param int User ID
  2135. * @param string Course code
  2136. * @param integer $user_id
  2137. * @return int Minimum course order
  2138. * @todo Review documentation
  2139. */
  2140. public static function userCourseSort($user_id, $course_code)
  2141. {
  2142. if ($user_id != strval(intval($user_id))) {
  2143. return false;
  2144. }
  2145. $course_code = Database::escape_string($course_code);
  2146. $TABLECOURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  2147. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2148. $course_title = Database::result(Database::query('SELECT title FROM '.$TABLECOURSE.' WHERE code="'.$course_code.'"'),
  2149. 0, 0);
  2150. $sql = 'SELECT course.code as code, course.title as title, cu.sort as sort
  2151. FROM ' . $TABLECOURSUSER.' as cu, '.$TABLECOURSE.' as course
  2152. WHERE course.id = cu.c_id AND user_id = "' . $user_id.'" AND
  2153. cu.relation_type<>' . COURSE_RELATION_TYPE_RRHH.' AND
  2154. user_course_cat = 0
  2155. ORDER BY cu.sort';
  2156. $result = Database::query($sql);
  2157. $course_title_precedent = '';
  2158. $counter = 0;
  2159. $course_found = false;
  2160. $course_sort = 1;
  2161. if (Database::num_rows($result) > 0) {
  2162. while ($courses = Database::fetch_array($result)) {
  2163. if ($course_title_precedent == '') {
  2164. $course_title_precedent = $courses['title'];
  2165. }
  2166. if (api_strcasecmp($course_title_precedent, $course_title) < 0) {
  2167. $course_found = true;
  2168. $course_sort = $courses['sort'];
  2169. if ($counter == 0) {
  2170. $sql = 'UPDATE '.$TABLECOURSUSER.'
  2171. SET sort = sort+1
  2172. WHERE
  2173. user_id= "' . $user_id.'" AND
  2174. relation_type<>' . COURSE_RELATION_TYPE_RRHH.'
  2175. AND user_course_cat="0"
  2176. AND sort > "' . $course_sort.'"';
  2177. $course_sort++;
  2178. } else {
  2179. $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1
  2180. WHERE
  2181. user_id= "' . $user_id.'" AND
  2182. relation_type<>' . COURSE_RELATION_TYPE_RRHH.' AND
  2183. user_course_cat="0" AND
  2184. sort >= "' . $course_sort.'"';
  2185. }
  2186. Database::query($sql);
  2187. break;
  2188. } else {
  2189. $course_title_precedent = $courses['title'];
  2190. }
  2191. $counter++;
  2192. }
  2193. // We must register the course in the beginning of the list
  2194. if (!$course_found) {
  2195. $course_sort = Database::result(Database::query('SELECT min(sort) as min_sort FROM '.$TABLECOURSUSER.' WHERE user_id="'.$user_id.'" AND user_course_cat="0"'),
  2196. 0, 0);
  2197. Database::query('UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id= "'.$user_id.'" AND user_course_cat="0"');
  2198. }
  2199. }
  2200. return $course_sort;
  2201. }
  2202. /**
  2203. * check if course exists
  2204. * @param string $course_code
  2205. * @return integer if exists, false else
  2206. */
  2207. public static function course_exists($course_code)
  2208. {
  2209. $sql = 'SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_COURSE).'
  2210. WHERE code="' . Database::escape_string($course_code).'"';
  2211. return Database::num_rows(Database::query($sql));
  2212. }
  2213. /**
  2214. * Send an email to tutor after the auth-suscription of a student in your course
  2215. * @author Carlos Vargas <carlos.vargas@dokeos.com>, Dokeos Latino
  2216. * @param int $user_id the id of the user
  2217. * @param string $courseId the course code
  2218. * @param bool $send_to_tutor_also
  2219. * @return false|null we return the message that is displayed when the action is successful
  2220. */
  2221. public static function email_to_tutor($user_id, $courseId, $send_to_tutor_also = false)
  2222. {
  2223. if ($user_id != strval(intval($user_id))) {
  2224. return false;
  2225. }
  2226. $courseId = intval($courseId);
  2227. $information = api_get_course_info_by_id($courseId);
  2228. $course_code = $information['code'];
  2229. $student = api_get_user_info($user_id);
  2230. $name_course = $information['title'];
  2231. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  2232. WHERE c_id ='" . $courseId."'";
  2233. // TODO: Ivan: This is a mistake, please, have a look at it. Intention here is diffcult to be guessed.
  2234. //if ($send_to_tutor_also = true)
  2235. // Proposed change:
  2236. if ($send_to_tutor_also) {
  2237. $sql .= " AND is_tutor=1";
  2238. } else {
  2239. $sql .= " AND status=1";
  2240. }
  2241. $result = Database::query($sql);
  2242. while ($row = Database::fetch_array($result)) {
  2243. $tutor = api_get_user_info($row['user_id']);
  2244. $emailto = $tutor['email'];
  2245. $emailsubject = get_lang('NewUserInTheCourse').': '.$name_course;
  2246. $emailbody = get_lang('Dear').': '.api_get_person_name($tutor['firstname'], $tutor['lastname'])."\n";
  2247. $emailbody .= get_lang('MessageNewUserInTheCourse').': '.$name_course."\n";
  2248. $emailbody .= get_lang('UserName').': '.$student['username']."\n";
  2249. if (api_is_western_name_order()) {
  2250. $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
  2251. $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
  2252. } else {
  2253. $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
  2254. $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
  2255. }
  2256. $emailbody .= get_lang('Email').': <a href="mailto:'.$student['email'].'">'.$student['email']."</a>\n\n";
  2257. $recipient_name = api_get_person_name($tutor['firstname'], $tutor['lastname'], null,
  2258. PERSON_NAME_EMAIL_ADDRESS);
  2259. $sender_name = api_get_person_name(api_get_setting('administratorName'),
  2260. api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  2261. $email_admin = api_get_setting('emailAdministrator');
  2262. $additionalParameters = array(
  2263. 'smsType' => SmsPlugin::NEW_USER_SUBSCRIBED_COURSE,
  2264. 'userId' => $tutor['user_id'],
  2265. 'userUsername' => $student['username'],
  2266. 'courseCode' => $course_code
  2267. );
  2268. api_mail_html(
  2269. $recipient_name,
  2270. $emailto,
  2271. $emailsubject,
  2272. $emailbody,
  2273. $sender_name,
  2274. $email_admin,
  2275. null,
  2276. null,
  2277. null,
  2278. $additionalParameters
  2279. );
  2280. }
  2281. }
  2282. /**
  2283. * @return array
  2284. */
  2285. public static function get_special_course_list()
  2286. {
  2287. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2288. $tbl_course_field = Database::get_main_table(TABLE_EXTRA_FIELD);
  2289. $tbl_course_field_value = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2290. //we filter the courses from the URL
  2291. $join_access_url = $where_access_url = '';
  2292. if (api_get_multiple_access_url()) {
  2293. $access_url_id = api_get_current_access_url_id();
  2294. if ($access_url_id != -1) {
  2295. $tbl_url_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2296. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course
  2297. ON url_rel_course.c_id = tcfv.item_id ";
  2298. $where_access_url = " AND access_url_id = $access_url_id ";
  2299. }
  2300. }
  2301. $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
  2302. // get course list auto-register
  2303. $sql = "SELECT DISTINCT(c.id)
  2304. FROM $tbl_course_field_value tcfv
  2305. INNER JOIN $tbl_course_field tcf
  2306. ON tcfv.field_id = tcf.id $join_access_url
  2307. INNER JOIN $courseTable c
  2308. ON (c.id = tcfv.item_id)
  2309. WHERE
  2310. tcf.extra_field_type = $extraFieldType AND
  2311. tcf.variable = 'special_course' AND
  2312. tcfv.value = 1 $where_access_url";
  2313. $result = Database::query($sql);
  2314. $courseList = array();
  2315. if (Database::num_rows($result) > 0) {
  2316. while ($row = Database::fetch_array($result)) {
  2317. $courseList[] = $row['id'];
  2318. }
  2319. }
  2320. return $courseList;
  2321. }
  2322. /**
  2323. * Get the course codes that have been restricted in the catalogue, and if byUserId is set
  2324. * then the courses that the user is allowed or not to see in catalogue
  2325. *
  2326. * @param boolean $allowed Either if the courses have some users that are or are not allowed to see in catalogue
  2327. * @param boolean $byUserId if the courses are or are not allowed to see to the user
  2328. * @return array Course codes allowed or not to see in catalogue by some user or the user
  2329. */
  2330. public static function getCatalogueCourseList($allowed = true, $byUserId = -1)
  2331. {
  2332. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2333. $tblCourseRelUserCatalogue = Database::get_main_table(TABLE_MAIN_COURSE_CATALOGUE_USER);
  2334. $visibility = $allowed ? 1 : 0;
  2335. // Restriction by user id
  2336. $currentUserRestriction = "";
  2337. if ($byUserId > 0) {
  2338. $byUserId = (int) $byUserId;
  2339. $currentUserRestriction = " AND tcruc.user_id = $byUserId ";
  2340. }
  2341. //we filter the courses from the URL
  2342. $joinAccessUrl = '';
  2343. $whereAccessUrl = '';
  2344. if (api_get_multiple_access_url()) {
  2345. $accessUrlId = api_get_current_access_url_id();
  2346. if ($accessUrlId != -1) {
  2347. $tblUrlCourse = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2348. $joinAccessUrl = "LEFT JOIN $tblUrlCourse url_rel_course
  2349. ON url_rel_course.c_id = c.id ";
  2350. $whereAccessUrl = " AND access_url_id = $accessUrlId ";
  2351. }
  2352. }
  2353. // get course list auto-register
  2354. $sql = "SELECT DISTINCT(c.code)
  2355. FROM $tblCourseRelUserCatalogue tcruc
  2356. INNER JOIN $courseTable c
  2357. ON (c.id = tcruc.c_id) $joinAccessUrl
  2358. WHERE tcruc.visible = $visibility $currentUserRestriction $whereAccessUrl";
  2359. $result = Database::query($sql);
  2360. $courseList = array();
  2361. if (Database::num_rows($result) > 0) {
  2362. while ($resultRow = Database::fetch_array($result)) {
  2363. $courseList[] = $resultRow['code'];
  2364. }
  2365. }
  2366. return $courseList;
  2367. }
  2368. /**
  2369. * Get list of courses for a given user
  2370. *
  2371. * @param int $user_id
  2372. * @param boolean $include_sessions Whether to include courses from session or not
  2373. * @param boolean $adminGetsAllCourses If the user is platform admin,
  2374. * whether he gets all the courses or just his. Note: This does *not* include all sessions
  2375. * @param bool $loadSpecialCourses
  2376. * @param array $skipCourseList List of course ids to skip
  2377. * @return array List of codes and db name
  2378. * @author isaac flores paz
  2379. */
  2380. public static function get_courses_list_by_user_id(
  2381. $user_id,
  2382. $include_sessions = false,
  2383. $adminGetsAllCourses = false,
  2384. $loadSpecialCourses = true,
  2385. $skipCourseList = []
  2386. ) {
  2387. $user_id = intval($user_id);
  2388. $urlId = api_get_current_access_url_id();
  2389. $course_list = array();
  2390. $codes = array();
  2391. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2392. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2393. $tbl_user_course_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2394. $tableCourseUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2395. if ($adminGetsAllCourses && UserManager::is_admin($user_id)) {
  2396. // get the whole courses list
  2397. $sql = "SELECT DISTINCT(course.code), course.id as real_id
  2398. FROM $tbl_course course
  2399. INNER JOIN $tableCourseUrl url
  2400. ON (course.id = url.c_id)
  2401. WHERE url.access_url_id = $urlId
  2402. ";
  2403. } else {
  2404. $withSpecialCourses = $withoutSpecialCourses = '';
  2405. if ($loadSpecialCourses) {
  2406. $specialCourseList = self::get_special_course_list();
  2407. if (!empty($specialCourseList)) {
  2408. $specialCourseToString = '"'.implode(
  2409. '","',
  2410. $specialCourseList
  2411. ).'"';
  2412. $withSpecialCourses = ' AND course.id IN ('.$specialCourseToString.')';
  2413. $withoutSpecialCourses = ' AND course.id NOT IN ('.$specialCourseToString.')';
  2414. }
  2415. if (!empty($withSpecialCourses)) {
  2416. $sql = "SELECT DISTINCT(course.code), course.id as real_id
  2417. FROM $tbl_course_user course_rel_user
  2418. LEFT JOIN $tbl_course course
  2419. ON course.id = course_rel_user.c_id
  2420. LEFT JOIN $tbl_user_course_category user_course_category
  2421. ON course_rel_user.user_course_cat = user_course_category.id
  2422. INNER JOIN $tableCourseUrl url
  2423. ON (course.id = url.c_id)
  2424. WHERE url.access_url_id = $urlId $withSpecialCourses
  2425. GROUP BY course.code
  2426. ORDER BY user_course_category.sort, course.title, course_rel_user.sort ASC
  2427. ";
  2428. $rs_special_course = Database::query($sql);
  2429. if (Database::num_rows($rs_special_course) > 0) {
  2430. while ($result_row = Database::fetch_array(
  2431. $rs_special_course
  2432. )) {
  2433. $result_row['special_course'] = 1;
  2434. $course_list[] = $result_row;
  2435. $codes[] = $result_row['real_id'];
  2436. }
  2437. }
  2438. }
  2439. }
  2440. // get course list not auto-register. Use Distinct to avoid multiple
  2441. // entries when a course is assigned to a HRD (DRH) as watcher
  2442. $sql = "SELECT DISTINCT(course.code), course.id as real_id
  2443. FROM $tbl_course course
  2444. INNER JOIN $tbl_course_user cru
  2445. ON (course.id = cru.c_id)
  2446. INNER JOIN $tableCourseUrl url
  2447. ON (course.id = url.c_id)
  2448. WHERE
  2449. url.access_url_id = $urlId AND
  2450. cru.user_id = '$user_id'
  2451. $withoutSpecialCourses
  2452. ORDER BY course.title
  2453. ";
  2454. }
  2455. $result = Database::query($sql);
  2456. if (Database::num_rows($result)) {
  2457. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2458. if (!empty($skipCourseList)) {
  2459. if (in_array($row['real_id'], $skipCourseList)) {
  2460. continue;
  2461. }
  2462. }
  2463. $course_list[] = $row;
  2464. $codes[] = $row['real_id'];
  2465. }
  2466. }
  2467. if ($include_sessions === true) {
  2468. $sql = "SELECT DISTINCT(c.code), c.id as real_id
  2469. FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." s,
  2470. $tbl_course c
  2471. WHERE user_id = $user_id AND s.c_id = c.id";
  2472. $r = Database::query($sql);
  2473. while ($row = Database::fetch_array($r, 'ASSOC')) {
  2474. if (!empty($skipCourseList)) {
  2475. if (in_array($row['real_id'], $skipCourseList)) {
  2476. continue;
  2477. }
  2478. }
  2479. if (!in_array($row['real_id'], $codes)) {
  2480. $course_list[] = $row;
  2481. }
  2482. }
  2483. }
  2484. return $course_list;
  2485. }
  2486. /**
  2487. * Get course ID from a given course directory name
  2488. * @param string $path Course directory (without any slash)
  2489. *
  2490. * @return string Course code, or false if not found
  2491. */
  2492. public static function get_course_id_from_path($path)
  2493. {
  2494. $path = Database::escape_string(str_replace('.', '', str_replace('/', '', $path)));
  2495. $res = Database::query("SELECT code FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  2496. WHERE directory LIKE BINARY '$path'");
  2497. if ($res === false) {
  2498. return false;
  2499. }
  2500. if (Database::num_rows($res) != 1) {
  2501. return false;
  2502. }
  2503. $row = Database::fetch_array($res);
  2504. return $row['code'];
  2505. }
  2506. /**
  2507. * Get course code(s) from visual code
  2508. * @deprecated
  2509. * @param string Visual code
  2510. * @return array List of codes for the given visual code
  2511. */
  2512. public static function get_courses_info_from_visual_code($code)
  2513. {
  2514. $result = array();
  2515. $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  2516. WHERE visual_code = '" . Database::escape_string($code)."'");
  2517. while ($virtual_course = Database::fetch_array($sql_result)) {
  2518. $result[] = $virtual_course;
  2519. }
  2520. return $result;
  2521. }
  2522. /**
  2523. * Get emails of tutors to course
  2524. * @param int $courseId
  2525. * @return array List of emails of tutors to course
  2526. *
  2527. * @author Carlos Vargas <carlos.vargas@dokeos.com>, Dokeos Latino
  2528. * */
  2529. public static function get_emails_of_tutors_to_course($courseId)
  2530. {
  2531. $list = array();
  2532. $res = Database::query("SELECT user_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  2533. WHERE c_id ='" . intval($courseId)."' AND status=1");
  2534. while ($list_users = Database::fetch_array($res)) {
  2535. $result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  2536. WHERE user_id=" . $list_users['user_id']);
  2537. while ($row_user = Database::fetch_array($result)) {
  2538. $name_teacher = api_get_person_name($row_user['firstname'], $row_user['lastname']);
  2539. $list[] = array($row_user['email'] => $name_teacher);
  2540. }
  2541. }
  2542. return $list;
  2543. }
  2544. /**
  2545. * Get coaches emails by session
  2546. * @param int session id
  2547. * @param int $courseId
  2548. * @param integer $session_id
  2549. * @return array array(email => name_tutor) by coach
  2550. * @author Carlos Vargas <carlos.vargas@dokeos.com>
  2551. */
  2552. public static function get_email_of_tutor_to_session($session_id, $courseId)
  2553. {
  2554. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2555. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2556. $coachs_emails = array();
  2557. $courseId = intval($courseId);
  2558. $session_id = intval($session_id);
  2559. $sql = "SELECT user_id
  2560. FROM $tbl_session_course_user
  2561. WHERE
  2562. session_id = '$session_id' AND
  2563. c_id = '$courseId' AND
  2564. status = 2
  2565. ";
  2566. $rs = Database::query($sql);
  2567. if (Database::num_rows($rs) > 0) {
  2568. $user_ids = array();
  2569. while ($row = Database::fetch_array($rs)) {
  2570. $user_ids[] = $row['user_id'];
  2571. }
  2572. $sql = "SELECT firstname, lastname, email FROM $tbl_user
  2573. WHERE user_id IN (".implode(",", $user_ids).")";
  2574. $rs_user = Database::query($sql);
  2575. while ($row_emails = Database::fetch_array($rs_user)) {
  2576. $mail_tutor = array(
  2577. 'email' => $row_emails['email'],
  2578. 'complete_name' => api_get_person_name($row_emails['firstname'], $row_emails['lastname'])
  2579. );
  2580. $coachs_emails[] = $mail_tutor;
  2581. }
  2582. }
  2583. return $coachs_emails;
  2584. }
  2585. /**
  2586. * Creates a new extra field for a given course
  2587. * @param string Field's internal variable name
  2588. * @param int Field's type
  2589. * @param string Field's language var name
  2590. * @param string $default
  2591. * @return boolean new extra field id
  2592. */
  2593. public static function create_course_extra_field($variable, $fieldType, $displayText, $default = '')
  2594. {
  2595. $extraField = new ExtraField('course');
  2596. $params = [
  2597. 'variable' => $variable,
  2598. 'field_type' => $fieldType,
  2599. 'display_text' => $displayText,
  2600. 'default_value' => $default
  2601. ];
  2602. return $extraField->save($params);
  2603. }
  2604. /**
  2605. * Updates course attribute. Note that you need to check that your
  2606. * attribute is valid before you use this function
  2607. *
  2608. * @param int $id Course id
  2609. * @param string $name Attribute name
  2610. * @param string $value Attribute value
  2611. *
  2612. * @return Doctrine\DBAL\Driver\Statement|null True if attribute was successfully updated,
  2613. * false if course was not found or attribute name is invalid
  2614. */
  2615. public static function update_attribute($id, $name, $value)
  2616. {
  2617. $id = (int) $id;
  2618. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  2619. $sql = "UPDATE $table SET $name = '".Database::escape_string($value)."'
  2620. WHERE id = '$id'";
  2621. return Database::query($sql);
  2622. }
  2623. /**
  2624. * Update course attributes. Will only update attributes with a non-empty value.
  2625. * Note that you NEED to check that your attributes are valid before using this function
  2626. *
  2627. * @param int Course id
  2628. * @param array Associative array with field names as keys and field values as values
  2629. * @return Doctrine\DBAL\Driver\Statement|null True if update was successful, false otherwise
  2630. */
  2631. public static function update_attributes($id, $attributes)
  2632. {
  2633. $id = (int) $id;
  2634. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  2635. $sql = "UPDATE $table SET ";
  2636. $i = 0;
  2637. foreach ($attributes as $name => $value) {
  2638. if ($value != '') {
  2639. if ($i > 0) {
  2640. $sql .= ", ";
  2641. }
  2642. $sql .= " $name = '".Database::escape_string($value)."'";
  2643. $i++;
  2644. }
  2645. }
  2646. $sql .= " WHERE id = '$id'";
  2647. return Database::query($sql);
  2648. }
  2649. /**
  2650. * Update an extra field value for a given course
  2651. * @param integer Course ID
  2652. * @param string Field variable name
  2653. * @param string Field value
  2654. * @return boolean|null true if field updated, false otherwise
  2655. */
  2656. public static function update_course_extra_field_value($course_code, $variable, $value = '')
  2657. {
  2658. $courseInfo = api_get_course_info($course_code);
  2659. $courseId = $courseInfo['real_id'];
  2660. $extraFieldValues = new ExtraFieldValue('course');
  2661. $params = [
  2662. 'item_id' => $courseId,
  2663. 'variable' => $variable,
  2664. 'value' => $value
  2665. ];
  2666. return $extraFieldValues->save($params);
  2667. }
  2668. /**
  2669. * @param int $session_id
  2670. * @return mixed
  2671. */
  2672. public static function get_session_category_id_by_session_id($session_id)
  2673. {
  2674. if (empty($session_id)) {
  2675. return [];
  2676. }
  2677. $sql = 'SELECT sc.id session_category
  2678. FROM ' . Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY).' sc
  2679. INNER JOIN ' . Database::get_main_table(TABLE_MAIN_SESSION).' s
  2680. ON sc.id = s.session_category_id
  2681. WHERE s.id="' . intval($session_id).'"';
  2682. return Database::result(
  2683. Database::query($sql),
  2684. 0,
  2685. 'session_category'
  2686. );
  2687. }
  2688. /**
  2689. * Gets the value of a course extra field. Returns null if it was not found
  2690. *
  2691. * @param string $variable Name of the extra field
  2692. * @param string $code Course code
  2693. *
  2694. * @return string Value
  2695. */
  2696. public static function get_course_extra_field_value($variable, $code)
  2697. {
  2698. $courseInfo = api_get_course_info($code);
  2699. $courseId = $courseInfo['real_id'];
  2700. $extraFieldValues = new ExtraFieldValue('course');
  2701. $result = $extraFieldValues->get_values_by_handler_and_field_variable($courseId, $variable);
  2702. if (!empty($result['value'])) {
  2703. return $result['value'];
  2704. }
  2705. return null;
  2706. }
  2707. /**
  2708. * Lists details of the course description
  2709. * @param array The course description
  2710. * @param string The encoding
  2711. * @param bool If true is displayed if false is hidden
  2712. * @return string The course description in html
  2713. */
  2714. public static function get_details_course_description_html($descriptions, $charset, $action_show = true)
  2715. {
  2716. $data = null;
  2717. if (isset($descriptions) && count($descriptions) > 0) {
  2718. foreach ($descriptions as $description) {
  2719. $data .= '<div class="sectiontitle">';
  2720. if (api_is_allowed_to_edit() && $action_show) {
  2721. //delete
  2722. $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete&description_id='.$description->id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),
  2723. ENT_QUOTES, $charset)).'\')) return false;">';
  2724. $data .= Display::return_icon('delete.gif', get_lang('Delete'),
  2725. array('style' => 'vertical-align:middle;float:right;'));
  2726. $data .= '</a> ';
  2727. //edit
  2728. $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&description_id='.$description->id.'">';
  2729. $data .= Display::return_icon('edit.png', get_lang('Edit'),
  2730. array('style' => 'vertical-align:middle;float:right; padding-right:4px;'), ICON_SIZE_SMALL);
  2731. $data .= '</a> ';
  2732. }
  2733. $data .= $description->title;
  2734. $data .= '</div>';
  2735. $data .= '<div class="sectioncomment">';
  2736. $data .= $description->content;
  2737. $data .= '</div>';
  2738. }
  2739. } else {
  2740. $data .= '<em>'.get_lang('ThisCourseDescriptionIsEmpty').'</em>';
  2741. }
  2742. return $data;
  2743. }
  2744. /**
  2745. * Returns the details of a course category
  2746. *
  2747. * @param string Category code
  2748. * @return array Course category
  2749. */
  2750. public static function get_course_category($code)
  2751. {
  2752. $table_categories = Database::get_main_table(TABLE_MAIN_CATEGORY);
  2753. $code = Database::escape_string($code);
  2754. $sql = "SELECT * FROM $table_categories WHERE code = '$code'";
  2755. return Database::fetch_array(Database::query($sql));
  2756. }
  2757. /**
  2758. * Returns the details of a course category
  2759. *
  2760. * @param string Category code
  2761. * @return array Course category
  2762. */
  2763. public static function getCategoriesList()
  2764. {
  2765. $table_categories = Database::get_main_table(TABLE_MAIN_CATEGORY);
  2766. $sql = "SELECT * FROM $table_categories";
  2767. $result = Database::query($sql);
  2768. $category = array();
  2769. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2770. $category[$row['code']] = $row['name'];
  2771. }
  2772. return $category;
  2773. }
  2774. /**
  2775. * Subscribes courses to human resource manager (Dashboard feature)
  2776. * @param int $hr_manager_id Human Resource Manager id
  2777. * @param array $courses_list Courses code
  2778. * @return int
  2779. **/
  2780. public static function subscribeCoursesToDrhManager($hr_manager_id, $courses_list)
  2781. {
  2782. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2783. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2784. $hr_manager_id = intval($hr_manager_id);
  2785. $affected_rows = 0;
  2786. //Deleting assigned courses to hrm_id
  2787. if (api_is_multiple_url_enabled()) {
  2788. $sql = "SELECT s.c_id FROM $tbl_course_rel_user s
  2789. INNER JOIN $tbl_course_rel_access_url a
  2790. ON (a.c_id = s.c_id)
  2791. WHERE
  2792. user_id = $hr_manager_id AND
  2793. relation_type=".COURSE_RELATION_TYPE_RRHH." AND
  2794. access_url_id = " . api_get_current_access_url_id()."";
  2795. } else {
  2796. $sql = "SELECT c_id FROM $tbl_course_rel_user
  2797. WHERE user_id = $hr_manager_id AND relation_type=".COURSE_RELATION_TYPE_RRHH." ";
  2798. }
  2799. $result = Database::query($sql);
  2800. if (Database::num_rows($result) > 0) {
  2801. while ($row = Database::fetch_array($result)) {
  2802. $sql = "DELETE FROM $tbl_course_rel_user
  2803. WHERE
  2804. c_id = '{$row['c_id']}' AND
  2805. user_id = $hr_manager_id AND
  2806. relation_type=".COURSE_RELATION_TYPE_RRHH." ";
  2807. Database::query($sql);
  2808. }
  2809. }
  2810. // inserting new courses list
  2811. if (is_array($courses_list)) {
  2812. foreach ($courses_list as $course_code) {
  2813. $courseInfo = api_get_course_info($course_code);
  2814. $courseId = $courseInfo['real_id'];
  2815. $sql = "INSERT IGNORE INTO $tbl_course_rel_user(c_id, user_id, status, relation_type)
  2816. VALUES($courseId, $hr_manager_id, '".DRH."', '".COURSE_RELATION_TYPE_RRHH."')";
  2817. $result = Database::query($sql);
  2818. if (Database::affected_rows($result)) {
  2819. $affected_rows++;
  2820. }
  2821. }
  2822. }
  2823. return $affected_rows;
  2824. }
  2825. /**
  2826. * get courses followed by human resources manager
  2827. * @param int $user_id
  2828. * @param int $status
  2829. * @param int $from
  2830. * @param int $limit
  2831. * @param string $column
  2832. * @param string $direction
  2833. * @param bool $getCount
  2834. *
  2835. * @return array courses
  2836. */
  2837. public static function get_courses_followed_by_drh(
  2838. $user_id,
  2839. $status = DRH,
  2840. $from = null,
  2841. $limit = null,
  2842. $column = null,
  2843. $direction = null,
  2844. $getCount = false
  2845. ) {
  2846. return self::getCoursesFollowedByUser(
  2847. $user_id,
  2848. $status,
  2849. $from,
  2850. $limit,
  2851. $column,
  2852. $direction,
  2853. $getCount
  2854. );
  2855. }
  2856. /**
  2857. * get courses followed by user
  2858. * @param int $user_id
  2859. * @param int $status
  2860. * @param int $from
  2861. * @param int $limit
  2862. * @param string $column
  2863. * @param string $direction
  2864. * @param boolean $getCount
  2865. * @param string $keyword
  2866. * @param int $sessionId
  2867. * @param boolean $showAllAssignedCourses
  2868. * @return array courses
  2869. */
  2870. public static function getCoursesFollowedByUser(
  2871. $user_id,
  2872. $status = null,
  2873. $from = null,
  2874. $limit = null,
  2875. $column = null,
  2876. $direction = null,
  2877. $getCount = false,
  2878. $keyword = null,
  2879. $sessionId = 0,
  2880. $showAllAssignedCourses = false
  2881. ) {
  2882. // Database Table Definitions
  2883. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2884. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2885. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2886. $sessionId = (int) $sessionId;
  2887. $user_id = (int) $user_id;
  2888. $select = "SELECT DISTINCT *, c.id as real_id ";
  2889. if ($getCount) {
  2890. $select = "SELECT COUNT(DISTINCT c.id) as count";
  2891. }
  2892. $whereConditions = '';
  2893. switch ($status) {
  2894. case COURSEMANAGER:
  2895. $whereConditions .= " AND cru.user_id = '$user_id'";
  2896. if (!$showAllAssignedCourses) {
  2897. $whereConditions .= " AND cru.status = ".COURSEMANAGER;
  2898. } else {
  2899. $whereConditions .= " AND relation_type = ".COURSE_RELATION_TYPE_COURSE_MANAGER;
  2900. }
  2901. break;
  2902. case DRH:
  2903. $whereConditions .= " AND
  2904. cru.user_id = '$user_id' AND
  2905. cru.status = ".DRH." AND
  2906. relation_type = '" . COURSE_RELATION_TYPE_RRHH."'
  2907. ";
  2908. break;
  2909. }
  2910. $keywordCondition = null;
  2911. if (!empty($keyword)) {
  2912. $keyword = Database::escape_string($keyword);
  2913. $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
  2914. }
  2915. $orderBy = null;
  2916. $extraInnerJoin = null;
  2917. if (!empty($sessionId)) {
  2918. if ($status == COURSEMANAGER) {
  2919. // Teacher of course or teacher inside session
  2920. $whereConditions = " AND (cru.status = ".COURSEMANAGER." OR srcru.status = 2) ";
  2921. }
  2922. $courseList = SessionManager::get_course_list_by_session_id(
  2923. $sessionId
  2924. );
  2925. if (!empty($courseList)) {
  2926. $courseListToString = implode("','", array_keys($courseList));
  2927. $whereConditions .= " AND c.id IN ('".$courseListToString."')";
  2928. }
  2929. $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2930. $tableSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2931. $orderBy = ' ORDER BY position';
  2932. $extraInnerJoin = " INNER JOIN $tableSessionRelCourse src
  2933. ON (c.id = src.c_id AND src.session_id = $sessionId)
  2934. INNER JOIN $tableSessionRelCourseRelUser srcru
  2935. ON (src.session_id = srcru.session_id AND srcru.c_id = src.c_id)
  2936. ";
  2937. }
  2938. $whereConditions .= $keywordCondition;
  2939. $sql = "$select
  2940. FROM $tbl_course c
  2941. INNER JOIN $tbl_course_rel_user cru
  2942. ON (cru.c_id = c.id)
  2943. INNER JOIN $tbl_course_rel_access_url a
  2944. ON (a.c_id = c.id)
  2945. $extraInnerJoin
  2946. WHERE
  2947. access_url_id = ".api_get_current_access_url_id()."
  2948. $whereConditions
  2949. $orderBy
  2950. ";
  2951. if (isset($from) && isset($limit)) {
  2952. $from = intval($from);
  2953. $limit = intval($limit);
  2954. $sql .= " LIMIT $from, $limit";
  2955. }
  2956. $result = Database::query($sql);
  2957. if ($getCount) {
  2958. $row = Database::fetch_array($result);
  2959. return $row['count'];
  2960. }
  2961. $courses = array();
  2962. if (Database::num_rows($result) > 0) {
  2963. while ($row = Database::fetch_array($result)) {
  2964. $courses[$row['code']] = $row;
  2965. }
  2966. }
  2967. return $courses;
  2968. }
  2969. /**
  2970. * check if a course is special (autoregister)
  2971. * @param int $courseId
  2972. * @return bool
  2973. */
  2974. public static function isSpecialCourse($courseId)
  2975. {
  2976. $extraFieldValue = new ExtraFieldValue('course');
  2977. $result = $extraFieldValue->get_values_by_handler_and_field_variable(
  2978. $courseId,
  2979. 'special_course'
  2980. );
  2981. if (!empty($result)) {
  2982. if ($result['value'] == 1) {
  2983. return true;
  2984. }
  2985. }
  2986. return false;
  2987. }
  2988. /**
  2989. * Update course picture
  2990. * @param array $courseInfo
  2991. * @param string File name
  2992. * @param string The full system name of the image from which course picture will be created.
  2993. * @param string $cropParameters Optional string that contents "x,y,width,height" of a cropped image format
  2994. * @return bool Returns the resulting. In case of internal error or negative validation returns FALSE.
  2995. */
  2996. public static function update_course_picture($courseInfo, $filename, $source_file = null, $cropParameters = null)
  2997. {
  2998. if (empty($courseInfo)) {
  2999. return false;
  3000. }
  3001. // course path
  3002. $store_path = api_get_path(SYS_COURSE_PATH).$courseInfo['path'];
  3003. // image name for courses
  3004. $course_image = $store_path.'/course-pic.png';
  3005. $course_medium_image = $store_path.'/course-pic85x85.png';
  3006. if (file_exists($course_image)) {
  3007. unlink($course_image);
  3008. }
  3009. if (file_exists($course_medium_image)) {
  3010. unlink($course_medium_image);
  3011. }
  3012. //Crop the image to adjust 4:3 ratio
  3013. $image = new Image($source_file);
  3014. $image->crop($cropParameters);
  3015. //Resize the images in two formats
  3016. $medium = new Image($source_file);
  3017. $medium->resize(85);
  3018. $medium->send_image($course_medium_image, -1, 'png');
  3019. $normal = new Image($source_file);
  3020. $normal->resize(400);
  3021. $normal->send_image($course_image, -1, 'png');
  3022. $result = $medium && $normal;
  3023. return $result ? $result : false;
  3024. }
  3025. /**
  3026. * Deletes the course picture
  3027. * @param string $courseCode
  3028. */
  3029. public static function deleteCoursePicture($courseCode)
  3030. {
  3031. $course_info = api_get_course_info($courseCode);
  3032. // course path
  3033. $storePath = api_get_path(SYS_COURSE_PATH).$course_info['path'];
  3034. // image name for courses
  3035. $courseImage = $storePath.'/course-pic.png';
  3036. $courseMediumImage = $storePath.'/course-pic85x85.png';
  3037. $courseSmallImage = $storePath.'/course-pic32.png';
  3038. if (file_exists($courseImage)) {
  3039. unlink($courseImage);
  3040. }
  3041. if (file_exists($courseMediumImage)) {
  3042. unlink($courseMediumImage);
  3043. }
  3044. if (file_exists($courseSmallImage)) {
  3045. unlink($courseSmallImage);
  3046. }
  3047. }
  3048. /**
  3049. * Builds the course block in user_portal.php
  3050. * @todo use Twig
  3051. *
  3052. * @param array $params
  3053. * @return string
  3054. */
  3055. public static function course_item_html_no_icon($params)
  3056. {
  3057. $html = '<div class="course_item">';
  3058. $html .= '<div class="row">';
  3059. $html .= '<div class="col-md-7">';
  3060. $notifications = isset($params['notifications']) ? $params['notifications'] : null;
  3061. $html .= '<h3>'.$params['title'].$notifications.'</h3> ';
  3062. if (isset($params['description'])) {
  3063. $html .= '<p>'.$params['description'].'</p>';
  3064. }
  3065. if (!empty($params['subtitle'])) {
  3066. $html .= '<small>'.$params['subtitle'].'</small>';
  3067. }
  3068. if (!empty($params['teachers'])) {
  3069. $html .= '<h5 class="teacher">'.Display::return_icon('teacher.png', get_lang('Teacher'), array(),
  3070. ICON_SIZE_TINY).$params['teachers'].'</h5>';
  3071. }
  3072. if (!empty($params['coaches'])) {
  3073. $html .= '<h5 class="teacher">'.Display::return_icon('teacher.png', get_lang('Coach'), array(),
  3074. ICON_SIZE_TINY).$params['coaches'].'</h5>';
  3075. }
  3076. $html .= '</div>';
  3077. $params['right_actions'] = isset($params['right_actions']) ? $params['right_actions'] : null;
  3078. $html .= '<div class="pull-right course-box-actions">'.$params['right_actions'].'</div>';
  3079. $html .= '</div>';
  3080. $html .= '</div>';
  3081. return $html;
  3082. }
  3083. /**
  3084. * @param $params
  3085. * @param bool|false $is_sub_content
  3086. * @return string
  3087. */
  3088. public static function session_items_html($params, $is_sub_content = false)
  3089. {
  3090. $html = '';
  3091. $html .= '<div class="row">';
  3092. $html .= '<div class="col-md-2">';
  3093. if (!empty($params['link'])) {
  3094. $html .= '<a class="thumbnail" href="'.$params['link'].'">';
  3095. $html .= $params['icon'];
  3096. $html .= '</a>';
  3097. } else {
  3098. $html .= $params['icon'];
  3099. }
  3100. $html .= '</div>';
  3101. $html .= '<div class="col-md-10">';
  3102. $html .= $params['title'];
  3103. $html .= $params['coaches'];
  3104. $html .= '</div>';
  3105. $html .= '</div>';
  3106. return $html;
  3107. }
  3108. /**
  3109. * Display special courses (and only these) as several HTML divs of class userportal-course-item
  3110. *
  3111. * Special courses are courses that stick on top of the list and are "auto-registerable"
  3112. * in the sense that any user clicking them is registered as a student
  3113. * @param int $user_id User id
  3114. * @param bool $load_dirs Whether to show the document quick-loader or not
  3115. * @return string
  3116. */
  3117. public static function returnSpecialCourses($user_id, $load_dirs = false)
  3118. {
  3119. $user_id = intval($user_id);
  3120. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  3121. $specialCourseList = self::get_special_course_list();
  3122. if (empty($specialCourseList)) {
  3123. return [];
  3124. }
  3125. $sql = "SELECT
  3126. id,
  3127. code,
  3128. subscribe subscr,
  3129. unsubscribe unsubscr
  3130. FROM $table
  3131. WHERE
  3132. id IN ('".implode("','", $specialCourseList)."')
  3133. GROUP BY code";
  3134. $rs_special_course = Database::query($sql);
  3135. $number_of_courses = Database::num_rows($rs_special_course);
  3136. $showCustomIcon = api_get_setting('course_images_in_courses_list');
  3137. $courseList = [];
  3138. if ($number_of_courses > 0) {
  3139. while ($course = Database::fetch_array($rs_special_course)) {
  3140. $course_info = api_get_course_info($course['code']);
  3141. $courseId = $course_info['real_id'];
  3142. if ($course_info['visibility'] == COURSE_VISIBILITY_HIDDEN) {
  3143. continue;
  3144. }
  3145. $params = [];
  3146. //Param (course_code) needed to get the student info in page "My courses"
  3147. $params['course_code'] = $course['code'];
  3148. // Get notifications.
  3149. $course_info['id_session'] = null;
  3150. $courseUserInfo = self::getUserCourseInfo($user_id, $courseId);
  3151. if (empty($courseUserInfo)) {
  3152. $course_info['status'] = STUDENT;
  3153. } else {
  3154. $course_info['status'] = $courseUserInfo['status'];
  3155. }
  3156. $show_notification = !api_get_configuration_value('hide_course_notification')
  3157. ? Display::show_notification($course_info)
  3158. : '';
  3159. $params['edit_actions'] = '';
  3160. $params['document'] = '';
  3161. if (api_is_platform_admin()) {
  3162. $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'];
  3163. if ($load_dirs) {
  3164. $params['document'] = '<a id="document_preview_'.$courseId.'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3165. . Display::returnFontAwesomeIcon('folder-open').'</a>';
  3166. $params['document'] .= Display::div('', ['id' => 'document_result_'.$courseId.'_0', 'class' => 'document_preview_container']);
  3167. }
  3168. } else {
  3169. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED && $load_dirs) {
  3170. $params['document'] = '<a id="document_preview_'.$courseId.'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3171. . Display::returnFontAwesomeIcon('folder-open').'</a>';
  3172. $params['document'] .= Display::div('', ['id' => 'document_result_'.$courseId.'_0', 'class' => 'document_preview_container']);
  3173. }
  3174. }
  3175. $params['visibility'] = $course_info['visibility'];
  3176. $params['status'] = $course_info['status'];
  3177. $params['category'] = $course_info['categoryName'];
  3178. $params['icon'] = Display::return_icon('drawing-pin.png', null, null, ICON_SIZE_LARGE, null);
  3179. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  3180. $params['code_course'] = '('.$course_info['visual_code'].')';
  3181. }
  3182. $params['title'] = $course_info['title'];
  3183. $params['title_cut'] = cut($course_info['title'], 45);
  3184. $params['link'] = $course_info['course_public_url'].'?id_session=0&autoreg=1';
  3185. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  3186. $params['teachers'] = self::getTeachersFromCourse($courseId, true);
  3187. }
  3188. if ($showCustomIcon === 'true') {
  3189. $params['thumbnails'] = $course_info['course_image'];
  3190. $params['image'] = $course_info['course_image_large'];
  3191. }
  3192. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  3193. $params['notifications'] = $show_notification;
  3194. }
  3195. $params['is_special_course'] = true;
  3196. $courseList[] = $params;
  3197. }
  3198. }
  3199. return $courseList;
  3200. }
  3201. /**
  3202. * Display courses (without special courses) as several HTML divs
  3203. * of course categories, as class userportal-catalog-item.
  3204. * @uses displayCoursesInCategory() to display the courses themselves
  3205. * @param int $user_id
  3206. * @param bool $load_dirs Whether to show the document quick-loader or not
  3207. * @param integer $user_id
  3208. * @return string
  3209. */
  3210. public static function returnCourses($user_id, $load_dirs = false)
  3211. {
  3212. $user_id = intval($user_id);
  3213. if (empty($user_id)) {
  3214. $user_id = api_get_user_id();
  3215. }
  3216. // Step 1: We get all the categories of the user
  3217. $table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  3218. $sql = "SELECT id, title FROM $table
  3219. WHERE user_id = '".$user_id."'
  3220. ORDER BY sort ASC";
  3221. $result = Database::query($sql);
  3222. $listItems = [
  3223. 'in_category' => [],
  3224. 'not_category' => []
  3225. ];
  3226. while ($row = Database::fetch_array($result)) {
  3227. // We simply display the title of the category.
  3228. $courseInCategory = self::returnCoursesCategories(
  3229. $row['id'],
  3230. $load_dirs
  3231. );
  3232. $params = [
  3233. 'id_category' => $row ['id'],
  3234. 'title_category' => $row['title'],
  3235. 'courses' => $courseInCategory
  3236. ];
  3237. $listItems['in_category'][] = $params;
  3238. }
  3239. // Step 2: We display the course without a user category.
  3240. $coursesNotCategory = self::returnCoursesCategories(0, $load_dirs);
  3241. if ($coursesNotCategory) {
  3242. $listItems['not_category'] = $coursesNotCategory;
  3243. }
  3244. return $listItems;
  3245. }
  3246. /**
  3247. * Display courses inside a category (without special courses) as HTML dics of
  3248. * class userportal-course-item.
  3249. * @param int $user_category_id User category id
  3250. * @param bool $load_dirs Whether to show the document quick-loader or not
  3251. * @return string
  3252. */
  3253. public static function returnCoursesCategories($user_category_id, $load_dirs = false)
  3254. {
  3255. $user_id = api_get_user_id();
  3256. $user_category_id = (int) $user_category_id;
  3257. // Table definitions
  3258. $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
  3259. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3260. $TABLE_ACCESS_URL_REL_COURSE = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3261. $current_url_id = api_get_current_access_url_id();
  3262. // Get course list auto-register
  3263. $special_course_list = self::get_special_course_list();
  3264. $without_special_courses = '';
  3265. if (!empty($special_course_list)) {
  3266. $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $special_course_list).'")';
  3267. }
  3268. $userCategoryCondition = " (course_rel_user.user_course_cat = $user_category_id) ";
  3269. if (empty($user_category_id)) {
  3270. $userCategoryCondition = ' (course_rel_user.user_course_cat = 0 OR course_rel_user.user_course_cat IS NULL) ';
  3271. }
  3272. $sql = "SELECT DISTINCT
  3273. course.id,
  3274. course_rel_user.status status,
  3275. course.code as course_code
  3276. FROM $TABLECOURS course
  3277. INNER JOIN $TABLECOURSUSER course_rel_user
  3278. ON (course.id = course_rel_user.c_id)
  3279. INNER JOIN $TABLE_ACCESS_URL_REL_COURSE url
  3280. ON (url.c_id = course.id)
  3281. WHERE
  3282. course_rel_user.user_id = '".$user_id."' AND
  3283. $userCategoryCondition
  3284. $without_special_courses ";
  3285. // If multiple URL access mode is enabled, only fetch courses
  3286. // corresponding to the current URL.
  3287. if (api_get_multiple_access_url() && $current_url_id != -1) {
  3288. $sql .= " AND access_url_id='".$current_url_id."'";
  3289. }
  3290. // Use user's classification for courses (if any).
  3291. $sql .= " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  3292. $result = Database::query($sql);
  3293. $courseList = array();
  3294. $showCustomIcon = api_get_setting('course_images_in_courses_list');
  3295. // Browse through all courses.
  3296. $courseAdded = [];
  3297. while ($row = Database::fetch_array($result)) {
  3298. $course_info = api_get_course_info_by_id($row['id']);
  3299. if (isset($course_info['visibility']) &&
  3300. $course_info['visibility'] == COURSE_VISIBILITY_HIDDEN
  3301. ) {
  3302. continue;
  3303. }
  3304. // Skip if already in list
  3305. if (in_array($course_info['real_id'], $courseAdded)) {
  3306. continue;
  3307. }
  3308. $course_info['id_session'] = null;
  3309. $course_info['status'] = $row['status'];
  3310. // For each course, get if there is any notification icon to show
  3311. // (something that would have changed since the user's last visit).
  3312. $showNotification = !api_get_configuration_value('hide_course_notification')
  3313. ? Display::show_notification($course_info)
  3314. : '';
  3315. $iconName = basename($course_info['course_image']);
  3316. $params = array();
  3317. //Param (course_code) needed to get the student process
  3318. $params['course_code'] = $row['course_code'];
  3319. if ($showCustomIcon === 'true' && $iconName != 'course.png') {
  3320. $params['thumbnails'] = $course_info['course_image'];
  3321. $params['image'] = $course_info['course_image_large'];
  3322. }
  3323. $thumbnails = null;
  3324. $image = null;
  3325. if ($showCustomIcon === 'true' && $iconName != 'course.png') {
  3326. $thumbnails = $course_info['course_image'];
  3327. $image = $course_info['course_image_large'];
  3328. } else {
  3329. $image = Display::return_icon('session_default.png', null, null, null, null, true);
  3330. }
  3331. $params['course_id'] = $course_info['real_id'];
  3332. $params['edit_actions'] = '';
  3333. $params['document'] = '';
  3334. if (api_is_platform_admin()) {
  3335. $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course_info['code'];
  3336. if ($load_dirs) {
  3337. $params['document'] = '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3338. . Display::returnFontAwesomeIcon('folder-open').'</a>';
  3339. $params['document'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class' => 'document_preview_container'));
  3340. }
  3341. }
  3342. if ($load_dirs) {
  3343. $params['document'] = '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3344. . Display::returnFontAwesomeIcon('folder-open').'</a>';
  3345. $params['document'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class' => 'document_preview_container'));
  3346. }
  3347. $courseUrl = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  3348. $teachers = [];
  3349. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  3350. $teachers = self::getTeachersFromCourse($course_info['real_id'], true);
  3351. }
  3352. $params['status'] = $row['status'];
  3353. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  3354. $params['code_course'] = '('.$course_info['visual_code'].') ';
  3355. }
  3356. $params['current_user_is_teacher'] = false;
  3357. /** @var array $teacher */
  3358. foreach ($teachers as $teacher) {
  3359. if ($teacher['id'] != $user_id) {
  3360. continue;
  3361. }
  3362. $params['current_user_is_teacher'] = true;
  3363. }
  3364. $params['visibility'] = $course_info['visibility'];
  3365. $params['link'] = $courseUrl;
  3366. $params['thumbnails'] = $thumbnails;
  3367. $params['image'] = $image;
  3368. $params['title'] = $course_info['title'];
  3369. $params['title_cut'] = cut($course_info['title'], 45);
  3370. $params['category'] = $course_info['categoryName'];
  3371. $params['teachers'] = $teachers;
  3372. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  3373. $params['notifications'] = $showNotification;
  3374. }
  3375. $courseAdded[] = $course_info['real_id'];
  3376. $courseList[] = $params;
  3377. }
  3378. return $courseList;
  3379. }
  3380. /**
  3381. * Display courses inside a category (without special courses) as HTML dics of
  3382. * class userportal-course-item.
  3383. * @deprecated use self::returnCoursesCategories(0);
  3384. * @param int User category id
  3385. * @param bool Whether to show the document quick-loader or not
  3386. * @return string
  3387. */
  3388. public static function returnCoursesWithoutCategories($user_category_id, $load_dirs = false)
  3389. {
  3390. $user_id = api_get_user_id();
  3391. // Table definitions
  3392. $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
  3393. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3394. $TABLE_ACCESS_URL_REL_COURSE = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3395. $current_url_id = api_get_current_access_url_id();
  3396. $courseList = [];
  3397. // Get course list auto-register
  3398. $special_course_list = self::get_special_course_list();
  3399. $without_special_courses = '';
  3400. if (!empty($special_course_list)) {
  3401. $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $special_course_list).'")';
  3402. }
  3403. $sql = "SELECT
  3404. course.id,
  3405. course.title,
  3406. course.code,
  3407. course.subscribe subscr,
  3408. course.unsubscribe unsubscr,
  3409. course_rel_user.status status,
  3410. course_rel_user.sort sort,
  3411. course_rel_user.user_course_cat user_course_cat
  3412. FROM $TABLECOURS course
  3413. INNER JOIN $TABLECOURSUSER course_rel_user
  3414. ON (course.id = course_rel_user.c_id)
  3415. INNER JOIN $TABLE_ACCESS_URL_REL_COURSE url
  3416. ON (url.c_id = course.id)
  3417. WHERE
  3418. course_rel_user.user_id = '".$user_id."' AND
  3419. course_rel_user.user_course_cat = '" . $user_category_id."'
  3420. $without_special_courses ";
  3421. // If multiple URL access mode is enabled, only fetch courses
  3422. // corresponding to the current URL.
  3423. if (api_get_multiple_access_url() && $current_url_id != -1) {
  3424. $sql .= " AND url.c_id = course.id AND access_url_id='".$current_url_id."'";
  3425. }
  3426. // Use user's classification for courses (if any).
  3427. $sql .= " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  3428. $result = Database::query($sql);
  3429. $showCustomIcon = api_get_setting('course_images_in_courses_list');
  3430. // Browse through all courses.
  3431. while ($row = Database::fetch_array($result)) {
  3432. $course_info = api_get_course_info($row['code']);
  3433. if (isset($course_info['visibility']) &&
  3434. $course_info['visibility'] == COURSE_VISIBILITY_HIDDEN
  3435. ) {
  3436. continue;
  3437. }
  3438. $course_info['id_session'] = null;
  3439. $course_info['status'] = $row['status'];
  3440. // For each course, get if there is any notification icon to show
  3441. // (something that would have changed since the user's last visit).
  3442. $showNotification = !api_get_configuration_value('hide_course_notification')
  3443. ? Display::show_notification($course_info)
  3444. : '';
  3445. $thumbnails = null;
  3446. $image = null;
  3447. $iconName = basename($course_info['course_image']);
  3448. if ($showCustomIcon === 'true' && $iconName != 'course.png') {
  3449. $thumbnails = $course_info['course_image'];
  3450. $image = $course_info['course_image_large'];
  3451. } else {
  3452. $image = Display::return_icon('session_default.png', null, null, null, null, true);
  3453. }
  3454. $params = array();
  3455. //Param (course_code) needed to get the student process
  3456. $params['course_code'] = $row['code'];
  3457. $params['edit_actions'] = '';
  3458. $params['document'] = '';
  3459. if (api_is_platform_admin()) {
  3460. $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course_info['code'];
  3461. if ($load_dirs) {
  3462. $params['document'] = '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3463. . Display::returnFontAwesomeIcon('folder-open').'</a>';
  3464. $params['document'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class' => 'document_preview_container'));
  3465. }
  3466. }
  3467. if ($load_dirs) {
  3468. $params['document'] = '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'
  3469. . Display::returnFontAwesomeIcon('folder-open').'</a>';
  3470. $params['document'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class' => 'document_preview_container'));
  3471. }
  3472. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  3473. $teachers = [];
  3474. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  3475. $teachers = self::getTeachersFromCourse($course_info['real_id'], false);
  3476. }
  3477. $params['status'] = $row['status'];
  3478. if (api_get_setting('display_coursecode_in_courselist') == 'true') {
  3479. $params['code_course'] = '('.$course_info['visual_code'].') ';
  3480. }
  3481. $params['visibility'] = $course_info['visibility'];
  3482. $params['link'] = $course_title_url;
  3483. $params['thumbnails'] = $thumbnails;
  3484. $params['image'] = $image;
  3485. $params['title'] = $course_info['title'];
  3486. $params['category'] = $course_info['categoryName'];
  3487. $params['teachers'] = $teachers;
  3488. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  3489. $params['notifications'] = $showNotification;
  3490. }
  3491. $courseList[] = $params;
  3492. }
  3493. return $courseList;
  3494. }
  3495. /**
  3496. * Retrieves the user defined course categories
  3497. * @param int $userId
  3498. * @return array
  3499. */
  3500. public static function get_user_course_categories($userId = 0)
  3501. {
  3502. $userId = empty($userId) ? api_get_user_id() : (int) $userId;
  3503. $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  3504. $sql = "SELECT * FROM $table_category
  3505. WHERE user_id = $userId
  3506. ORDER BY sort ASC
  3507. ";
  3508. $result = Database::query($sql);
  3509. $output = array();
  3510. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3511. $output[$row['id']] = $row;
  3512. }
  3513. return $output;
  3514. }
  3515. /**
  3516. * Return an array the user_category id and title for the course $courseId for user $userId
  3517. * @param $userId
  3518. * @param $courseId
  3519. * @return array
  3520. */
  3521. public static function getUserCourseCategoryForCourse($userId, $courseId)
  3522. {
  3523. $tblCourseRelUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3524. $tblUserCategory = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  3525. $courseId = intval($courseId);
  3526. $userId = intval($userId);
  3527. $sql = "SELECT user_course_cat, title
  3528. FROM $tblCourseRelUser cru
  3529. LEFT JOIN $tblUserCategory ucc
  3530. ON cru.user_course_cat = ucc.id
  3531. WHERE
  3532. cru.user_id = $userId AND c_id= $courseId ";
  3533. $res = Database::query($sql);
  3534. $data = array();
  3535. if (Database::num_rows($res) > 0) {
  3536. $data = Database::fetch_assoc($res);
  3537. }
  3538. return $data;
  3539. }
  3540. /**
  3541. * Get the course id based on the original id and field name in the extra fields.
  3542. * Returns 0 if course was not found
  3543. *
  3544. * @param string $value Original course code
  3545. * @param string $variable Original field name
  3546. * @return array
  3547. */
  3548. public static function getCourseInfoFromOriginalId($value, $variable)
  3549. {
  3550. $extraFieldValue = new ExtraFieldValue('course');
  3551. $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  3552. $variable,
  3553. $value
  3554. );
  3555. if (!empty($result)) {
  3556. $courseInfo = api_get_course_info_by_id($result['item_id']);
  3557. return $courseInfo;
  3558. }
  3559. return [];
  3560. }
  3561. /**
  3562. * Display code for one specific course a logged in user is subscribed to.
  3563. * Shows a link to the course, what's new icons...
  3564. *
  3565. * $my_course['d'] - course directory
  3566. * $my_course['i'] - course title
  3567. * $my_course['c'] - visual course code
  3568. * $my_course['k'] - system course code
  3569. *
  3570. * @param array Course details
  3571. * @param integer Session ID
  3572. * @param string CSS class to apply to course entry
  3573. * @param boolean Whether the session is supposedly accessible now
  3574. * (not in the case it has passed and is in invisible/unaccessible mode)
  3575. * @param bool Whether to show the document quick-loader or not
  3576. * @return string The HTML to be printed for the course entry
  3577. *
  3578. * @version 1.0.3
  3579. * @todo refactor into different functions for database calls | logic | display
  3580. * @todo replace single-character $my_course['d'] indices
  3581. * @todo move code for what's new icons to a separate function to clear things up
  3582. * @todo add a parameter user_id so that it is possible to show the
  3583. * courselist of other users (=generalisation).
  3584. * This will prevent having to write a new function for this.
  3585. */
  3586. public static function get_logged_user_course_html(
  3587. $course,
  3588. $session_id = 0,
  3589. $class = 'courses',
  3590. $session_accessible = true,
  3591. $load_dirs = false
  3592. ) {
  3593. $now = date('Y-m-d h:i:s');
  3594. $user_id = api_get_user_id();
  3595. $course_info = api_get_course_info_by_id($course['real_id']);
  3596. $course_visibility = $course_info['visibility'];
  3597. if ($course_visibility == COURSE_VISIBILITY_HIDDEN) {
  3598. return '';
  3599. }
  3600. $userInCourseStatus = self::getUserInCourseStatus(
  3601. $user_id,
  3602. $course_info['real_id']
  3603. );
  3604. $course_info['status'] = empty($session_id) ? $userInCourseStatus : STUDENT;
  3605. $course_info['id_session'] = $session_id;
  3606. $is_coach = api_is_coach($session_id, $course_info['real_id']);
  3607. // Display course entry.
  3608. // Show a hyperlink to the course, unless the course is closed and user is not course admin.
  3609. $session_url = '';
  3610. $params = array();
  3611. $params['icon'] = Display::return_icon(
  3612. 'blackboard_blue.png',
  3613. null,
  3614. array(),
  3615. ICON_SIZE_LARGE,
  3616. null,
  3617. true
  3618. );
  3619. // Display the "what's new" icons
  3620. $notifications = '';
  3621. if (
  3622. ($course_visibility != COURSE_VISIBILITY_CLOSED && $course_visibility != COURSE_VISIBILITY_HIDDEN) ||
  3623. !api_get_configuration_value('hide_course_notification')
  3624. ) {
  3625. $notifications .= Display::show_notification($course_info);
  3626. }
  3627. if ($session_accessible) {
  3628. if ($course_visibility != COURSE_VISIBILITY_CLOSED ||
  3629. $userInCourseStatus == COURSEMANAGER
  3630. ) {
  3631. if (empty($course_info['id_session'])) {
  3632. $course_info['id_session'] = 0;
  3633. }
  3634. $sessionCourseAvailable = false;
  3635. $sessionCourseStatus = api_get_session_visibility($session_id, $course_info['real_id']);
  3636. if (in_array($sessionCourseStatus,
  3637. array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_AVAILABLE))) {
  3638. $sessionCourseAvailable = true;
  3639. }
  3640. if ($userInCourseStatus == COURSEMANAGER || $sessionCourseAvailable) {
  3641. $session_url = $course_info['course_public_url'].'?id_session='.$course_info['id_session'];
  3642. $session_title = '<a href="'.$session_url.'">'.$course_info['name'].'</a>'.$notifications;
  3643. } else {
  3644. $session_title = $course_info['name'];
  3645. }
  3646. } else {
  3647. $session_title =
  3648. $course_info['name'].' '.
  3649. Display::tag('span', get_lang('CourseClosed'), array('class' => 'item_closed'));
  3650. }
  3651. } else {
  3652. $session_title = $course_info['name'];
  3653. }
  3654. $thumbnails = null;
  3655. $image = null;
  3656. $showCustomIcon = api_get_setting('course_images_in_courses_list');
  3657. $iconName = basename($course_info['course_image']);
  3658. if ($showCustomIcon === 'true' && $iconName != 'course.png') {
  3659. $thumbnails = $course_info['course_image'];
  3660. $image = $course_info['course_image_large'];
  3661. } else {
  3662. $image = Display::return_icon('session_default.png', null, null, null, null, true);
  3663. }
  3664. $params['thumbnails'] = $thumbnails;
  3665. $params['image'] = $image;
  3666. $params['link'] = $session_url;
  3667. $params['title'] = $session_title;
  3668. $params['edit_actions'] = '';
  3669. $params['document'] = '';
  3670. $params['category'] = $course_info['categoryName'];
  3671. if ($course_visibility != COURSE_VISIBILITY_CLOSED &&
  3672. $course_visibility != COURSE_VISIBILITY_HIDDEN
  3673. ) {
  3674. if (api_is_platform_admin()) {
  3675. $params['edit_actions'] .= api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course_info['code'];
  3676. if ($load_dirs) {
  3677. $params['document'] .= '<a id="document_preview_'.$course_info['real_id'].'_'.$course_info['id_session'].'" class="document_preview btn btn-default btn-sm" href="javascript:void(0);">'.
  3678. Display::returnFontAwesomeIcon('folder-open').'</a>';
  3679. $params['document'] .= Display::div('', array(
  3680. 'id' => 'document_result_'.$course_info['real_id'].'_'.$course_info['id_session'],
  3681. 'class' => 'document_preview_container'
  3682. ));
  3683. }
  3684. }
  3685. }
  3686. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  3687. $teacher_list = self::getTeachersFromCourse(
  3688. $course_info['real_id'],
  3689. true
  3690. );
  3691. $course_coachs = self::get_coachs_from_course(
  3692. $course_info['id_session'],
  3693. $course_info['real_id']
  3694. );
  3695. $params['teachers'] = $teacher_list;
  3696. if (($course_info['status'] == STUDENT && !empty($course_info['id_session'])) ||
  3697. ($is_coach && $course_info['status'] != COURSEMANAGER)
  3698. ) {
  3699. $params['coaches'] = $course_coachs;
  3700. }
  3701. }
  3702. $special = isset($course['special_course']) ? true : false;
  3703. $params['title'] = $session_title;
  3704. $params['special'] = $special;
  3705. $params['code'] = $course_info['visual_code'];
  3706. $params['extra'] = '';
  3707. $html = $params;
  3708. $session_category_id = null;
  3709. if (1) {
  3710. $session = '';
  3711. $active = false;
  3712. if (!empty($course_info['id_session'])) {
  3713. $session = api_get_session_info($course_info['id_session']);
  3714. $sessionCoachName = '';
  3715. if (!empty($session['id_coach'])) {
  3716. $coachInfo = api_get_user_info($session['id_coach']);
  3717. $sessionCoachName = $coachInfo['complete_name'];
  3718. }
  3719. $session_category_id = self::get_session_category_id_by_session_id($course_info['id_session']);
  3720. if (
  3721. $session['access_start_date'] == '0000-00-00 00:00:00' || empty($session['access_start_date']) ||
  3722. $session['access_start_date'] == '0000-00-00'
  3723. ) {
  3724. $session['dates'] = '';
  3725. if (api_get_setting('show_session_coach') === 'true') {
  3726. $session['coach'] = get_lang('GeneralCoach').': '.$sessionCoachName;
  3727. }
  3728. $active = true;
  3729. } else {
  3730. $session ['dates'] = ' - '.get_lang('From').' '.$session['access_start_date'].' '.get_lang('To').' '.$session['access_end_date'];
  3731. if (api_get_setting('show_session_coach') === 'true') {
  3732. $session['coach'] = get_lang('GeneralCoach').': '.$sessionCoachName;
  3733. }
  3734. $date_start = $session['access_start_date'];
  3735. $date_end = $session['access_end_date'];
  3736. $active = !$date_end ? ($date_start <= $now) : ($date_start <= $now && $date_end >= $now);
  3737. }
  3738. }
  3739. $user_course_category = '';
  3740. if (isset($course_info['user_course_cat'])) {
  3741. $user_course_category = $course_info['user_course_cat'];
  3742. }
  3743. $output = array(
  3744. $user_course_category,
  3745. $html,
  3746. $course_info['id_session'],
  3747. $session,
  3748. 'active' => $active,
  3749. 'session_category_id' => $session_category_id
  3750. );
  3751. if (api_get_setting('allow_skills_tool') === 'true') {
  3752. $entityManager = Database::getManager();
  3753. $objUser = $entityManager->find('ChamiloUserBundle:User', $user_id);
  3754. $objCourse = $entityManager->find('ChamiloCoreBundle:Course', $course['real_id']);
  3755. $objSession = $entityManager->find('ChamiloCoreBundle:Session', $session_id);
  3756. $skill = $entityManager
  3757. ->getRepository('ChamiloCoreBundle:Skill')
  3758. ->getLastByUser($objUser, $objCourse, $objSession);
  3759. $output['skill'] = null;
  3760. if ($skill) {
  3761. $output['skill']['name'] = $skill->getName();
  3762. $output['skill']['icon'] = $skill->getIcon();
  3763. }
  3764. }
  3765. } else {
  3766. $output = array($course_info['user_course_cat'], $html);
  3767. }
  3768. return $output;
  3769. }
  3770. /**
  3771. *
  3772. * @param string source course code
  3773. * @param int source session id
  3774. * @param string destination course code
  3775. * @param int destination session id
  3776. * @param integer $source_session_id
  3777. * @param integer $destination_session_id
  3778. * @return bool
  3779. */
  3780. public static function copy_course(
  3781. $source_course_code,
  3782. $source_session_id,
  3783. $destination_course_code,
  3784. $destination_session_id,
  3785. $params = array()
  3786. ) {
  3787. $course_info = api_get_course_info($source_course_code);
  3788. if (!empty($course_info)) {
  3789. $cb = new CourseBuilder('', $course_info);
  3790. $course = $cb->build($source_session_id, $source_course_code, true);
  3791. $course_restorer = new CourseRestorer($course);
  3792. $course_restorer->skip_content = $params;
  3793. $course_restorer->restore($destination_course_code, $destination_session_id, true, true);
  3794. return true;
  3795. }
  3796. return false;
  3797. }
  3798. /**
  3799. * A simpler version of the copy_course, the function creates an empty course with an autogenerated course code
  3800. *
  3801. * @param string new course title
  3802. * @param string source course code
  3803. * @param int source session id
  3804. * @param int destination session id
  3805. * @param bool new copied tools (Exercises and LPs)will be set to invisible by default?
  3806. * @param string $new_title
  3807. *
  3808. * @return array
  3809. */
  3810. public static function copy_course_simple(
  3811. $new_title,
  3812. $source_course_code,
  3813. $source_session_id = 0,
  3814. $destination_session_id = 0,
  3815. $params = array()
  3816. ) {
  3817. $source_course_info = api_get_course_info($source_course_code);
  3818. if (!empty($source_course_info)) {
  3819. $new_course_code = self::generate_nice_next_course_code($source_course_code);
  3820. if ($new_course_code) {
  3821. $new_course_info = self::create_course($new_title, $new_course_code, false);
  3822. if (!empty($new_course_info['code'])) {
  3823. $result = self::copy_course($source_course_code, $source_session_id, $new_course_info['code'],
  3824. $destination_session_id, $params);
  3825. if ($result) {
  3826. return $new_course_info;
  3827. }
  3828. }
  3829. }
  3830. }
  3831. return false;
  3832. }
  3833. /**
  3834. * Creates a new course code based in a given code
  3835. *
  3836. * @param string wanted code
  3837. * <code> $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3</code>
  3838. * if the course code doest not exist in the DB the same course code will be returned
  3839. * @return string wanted unused code
  3840. */
  3841. public static function generate_nice_next_course_code($wanted_code)
  3842. {
  3843. $course_code_ok = !self::course_code_exists($wanted_code);
  3844. if (!$course_code_ok) {
  3845. $wanted_code = self::generate_course_code($wanted_code);
  3846. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  3847. $wanted_code = Database::escape_string($wanted_code);
  3848. $sql = "SELECT count(id) as count
  3849. FROM $table
  3850. WHERE code LIKE '$wanted_code%'";
  3851. $result = Database::query($sql);
  3852. if (Database::num_rows($result) > 0) {
  3853. $row = Database::fetch_array($result);
  3854. $count = $row['count'] + 1;
  3855. $wanted_code = $wanted_code.'_'.$count;
  3856. $result = api_get_course_info($wanted_code);
  3857. if (empty($result)) {
  3858. return $wanted_code;
  3859. }
  3860. }
  3861. return false;
  3862. }
  3863. return $wanted_code;
  3864. }
  3865. /**
  3866. * Gets the status of the users agreement in a course course-session
  3867. *
  3868. * @param int $user_id
  3869. * @param string $course_code
  3870. * @param int $session_id
  3871. * @return boolean
  3872. */
  3873. public static function is_user_accepted_legal($user_id, $course_code, $session_id = null)
  3874. {
  3875. $user_id = intval($user_id);
  3876. $course_code = Database::escape_string($course_code);
  3877. $session_id = intval($session_id);
  3878. $courseInfo = api_get_course_info($course_code);
  3879. $courseId = $courseInfo['real_id'];
  3880. // Course legal
  3881. $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
  3882. if ($enabled == 'true') {
  3883. require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
  3884. $plugin = CourseLegalPlugin::create();
  3885. return $plugin->isUserAcceptedLegal($user_id, $course_code, $session_id);
  3886. }
  3887. if (empty($session_id)) {
  3888. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3889. $sql = "SELECT legal_agreement FROM $table
  3890. WHERE user_id = $user_id AND c_id = $courseId ";
  3891. $result = Database::query($sql);
  3892. if (Database::num_rows($result) > 0) {
  3893. $result = Database::fetch_array($result);
  3894. if ($result['legal_agreement'] == 1) {
  3895. return true;
  3896. }
  3897. }
  3898. return false;
  3899. } else {
  3900. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3901. $sql = "SELECT legal_agreement FROM $table
  3902. WHERE user_id = $user_id AND c_id = $courseId AND session_id = $session_id";
  3903. $result = Database::query($sql);
  3904. if (Database::num_rows($result) > 0) {
  3905. $result = Database::fetch_array($result);
  3906. if ($result['legal_agreement'] == 1) {
  3907. return true;
  3908. }
  3909. }
  3910. return false;
  3911. }
  3912. }
  3913. /**
  3914. * Saves the user-course legal agreement
  3915. * @param int user id
  3916. * @param string course code
  3917. * @param int session id
  3918. * @return mixed
  3919. */
  3920. public static function save_user_legal($user_id, $course_code, $session_id = null)
  3921. {
  3922. // Course plugin legal
  3923. $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
  3924. if ($enabled == 'true') {
  3925. require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
  3926. $plugin = CourseLegalPlugin::create();
  3927. return $plugin->saveUserLegal($user_id, $course_code, $session_id);
  3928. }
  3929. $user_id = intval($user_id);
  3930. $course_code = Database::escape_string($course_code);
  3931. $session_id = intval($session_id);
  3932. $courseInfo = api_get_course_info($course_code);
  3933. $courseId = $courseInfo['real_id'];
  3934. if (empty($session_id)) {
  3935. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3936. $sql = "UPDATE $table SET legal_agreement = '1'
  3937. WHERE user_id = $user_id AND c_id = $courseId ";
  3938. Database::query($sql);
  3939. } else {
  3940. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3941. $sql = "UPDATE $table SET legal_agreement = '1'
  3942. WHERE user_id = $user_id AND c_id = $courseId AND session_id = $session_id";
  3943. Database::query($sql);
  3944. }
  3945. }
  3946. /**
  3947. * @param int $user_id
  3948. * @param int $course_id
  3949. * @param int $session_id
  3950. * @param int $url_id
  3951. * @return bool
  3952. */
  3953. public static function get_user_course_vote($user_id, $course_id, $session_id = null, $url_id = null)
  3954. {
  3955. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  3956. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3957. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3958. $user_id = intval($user_id);
  3959. if (empty($user_id)) {
  3960. return false;
  3961. }
  3962. $params = array(
  3963. 'user_id' => $user_id,
  3964. 'c_id' => $course_id,
  3965. 'session_id' => $session_id,
  3966. 'url_id' => $url_id
  3967. );
  3968. $result = Database::select(
  3969. 'vote',
  3970. $table_user_course_vote,
  3971. array(
  3972. 'where' => array(
  3973. 'user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params
  3974. )
  3975. ),
  3976. 'first'
  3977. );
  3978. if (!empty($result)) {
  3979. return $result['vote'];
  3980. }
  3981. return false;
  3982. }
  3983. /**
  3984. * @param int $course_id
  3985. * @param int $session_id
  3986. * @param int $url_id
  3987. * @return array
  3988. */
  3989. public static function get_course_ranking($course_id, $session_id = null, $url_id = null)
  3990. {
  3991. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3992. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3993. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3994. $now = api_get_utc_datetime();
  3995. $params = array(
  3996. 'c_id' => $course_id,
  3997. 'session_id' => $session_id,
  3998. 'url_id' => $url_id,
  3999. 'creation_date' => $now,
  4000. );
  4001. $result = Database::select(
  4002. 'c_id, accesses, total_score, users',
  4003. $table_course_ranking,
  4004. array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)),
  4005. 'first'
  4006. );
  4007. $point_average_in_percentage = 0;
  4008. $point_average_in_star = 0;
  4009. $users_who_voted = 0;
  4010. if (!empty($result['users'])) {
  4011. $users_who_voted = $result['users'];
  4012. $point_average_in_percentage = round($result['total_score'] / $result['users'] * 100 / 5, 2);
  4013. $point_average_in_star = round($result['total_score'] / $result['users'], 1);
  4014. }
  4015. $result['user_vote'] = false;
  4016. if (!api_is_anonymous()) {
  4017. $result['user_vote'] = self::get_user_course_vote(api_get_user_id(), $course_id, $session_id, $url_id);
  4018. }
  4019. $result['point_average'] = $point_average_in_percentage;
  4020. $result['point_average_star'] = $point_average_in_star;
  4021. $result['users_who_voted'] = $users_who_voted;
  4022. return $result;
  4023. }
  4024. /**
  4025. *
  4026. * Updates the course ranking
  4027. * @param int course id
  4028. * @param int session id
  4029. * @param id url id
  4030. * @param integer $session_id
  4031. * @return array
  4032. **/
  4033. public static function update_course_ranking(
  4034. $course_id = null,
  4035. $session_id = null,
  4036. $url_id = null,
  4037. $points_to_add = null,
  4038. $add_access = true,
  4039. $add_user = true
  4040. ) {
  4041. // Course catalog stats modifications see #4191
  4042. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  4043. $now = api_get_utc_datetime();
  4044. $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
  4045. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  4046. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  4047. $params = array(
  4048. 'c_id' => $course_id,
  4049. 'session_id' => $session_id,
  4050. 'url_id' => $url_id,
  4051. 'creation_date' => $now,
  4052. 'total_score' => 0,
  4053. 'users' => 0
  4054. );
  4055. $result = Database::select(
  4056. 'id, accesses, total_score, users',
  4057. $table_course_ranking,
  4058. array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)),
  4059. 'first'
  4060. );
  4061. // Problem here every time we load the courses/XXXX/index.php course home page we update the access
  4062. if (empty($result)) {
  4063. if ($add_access) {
  4064. $params['accesses'] = 1;
  4065. }
  4066. //The votes and users are empty
  4067. if (isset($points_to_add) && !empty($points_to_add)) {
  4068. $params['total_score'] = intval($points_to_add);
  4069. }
  4070. if ($add_user) {
  4071. $params['users'] = 1;
  4072. }
  4073. $result = Database::insert($table_course_ranking, $params);
  4074. } else {
  4075. $my_params = array();
  4076. if ($add_access) {
  4077. $my_params['accesses'] = intval($result['accesses']) + 1;
  4078. }
  4079. if (isset($points_to_add) && !empty($points_to_add)) {
  4080. $my_params['total_score'] = $result['total_score'] + $points_to_add;
  4081. }
  4082. if ($add_user) {
  4083. $my_params['users'] = $result['users'] + 1;
  4084. }
  4085. if (!empty($my_params)) {
  4086. $result = Database::update(
  4087. $table_course_ranking,
  4088. $my_params,
  4089. array('c_id = ? AND session_id = ? AND url_id = ?' => $params)
  4090. );
  4091. }
  4092. }
  4093. return $result;
  4094. }
  4095. /**
  4096. * Add user vote to a course
  4097. *
  4098. * @param int user id
  4099. * @param int vote [1..5]
  4100. * @param int course id
  4101. * @param int session id
  4102. * @param int url id (access_url_id)
  4103. * @return false|string 'added', 'updated' or 'nothing'
  4104. */
  4105. public static function add_course_vote($user_id, $vote, $course_id, $session_id = null, $url_id = null)
  4106. {
  4107. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  4108. $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
  4109. if (empty($course_id) || empty($user_id)) {
  4110. return false;
  4111. }
  4112. if (!in_array($vote, array(1, 2, 3, 4, 5))) {
  4113. return false;
  4114. }
  4115. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  4116. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  4117. $vote = intval($vote);
  4118. $params = array(
  4119. 'user_id' => intval($user_id),
  4120. 'c_id' => $course_id,
  4121. 'session_id' => $session_id,
  4122. 'url_id' => $url_id,
  4123. 'vote' => $vote
  4124. );
  4125. $action_done = 'nothing';
  4126. $result = Database::select(
  4127. 'id, vote',
  4128. $table_user_course_vote,
  4129. array('where' => array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params)),
  4130. 'first'
  4131. );
  4132. if (empty($result)) {
  4133. Database::insert($table_user_course_vote, $params);
  4134. $points_to_add = $vote;
  4135. $add_user = true;
  4136. $action_done = 'added';
  4137. } else {
  4138. $my_params = array('vote' => $vote);
  4139. $points_to_add = $vote - $result['vote'];
  4140. $add_user = false;
  4141. Database::update(
  4142. $table_user_course_vote,
  4143. $my_params,
  4144. array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params)
  4145. );
  4146. $action_done = 'updated';
  4147. }
  4148. // Current points
  4149. if (!empty($points_to_add)) {
  4150. self::update_course_ranking(
  4151. $course_id,
  4152. $session_id,
  4153. $url_id,
  4154. $points_to_add,
  4155. false,
  4156. $add_user
  4157. );
  4158. }
  4159. return $action_done;
  4160. }
  4161. /**
  4162. * Remove course ranking + user votes
  4163. *
  4164. * @param int $course_id
  4165. * @param int $session_id
  4166. * @param int $url_id
  4167. *
  4168. */
  4169. public static function remove_course_ranking($course_id, $session_id, $url_id = null)
  4170. {
  4171. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  4172. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  4173. if (!empty($course_id) && isset($session_id)) {
  4174. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  4175. $params = array(
  4176. 'c_id' => $course_id,
  4177. 'session_id' => $session_id,
  4178. 'url_id' => $url_id,
  4179. );
  4180. Database::delete($table_course_ranking, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
  4181. Database::delete($table_user_course_vote, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
  4182. }
  4183. }
  4184. /**
  4185. * Returns an array with the hottest courses
  4186. * @param int $days number of days
  4187. * @param int $limit number of hottest courses
  4188. * @return array
  4189. */
  4190. public static function return_hot_courses($days = 30, $limit = 6)
  4191. {
  4192. if (api_is_invitee()) {
  4193. return array();
  4194. }
  4195. $limit = intval($limit);
  4196. // Getting my courses
  4197. $my_course_list = self::get_courses_list_by_user_id(api_get_user_id());
  4198. $my_course_code_list = array();
  4199. foreach ($my_course_list as $course) {
  4200. $my_course_code_list[$course['real_id']] = $course['real_id'];
  4201. }
  4202. if (api_is_drh()) {
  4203. $courses = self::get_courses_followed_by_drh(api_get_user_id());
  4204. foreach ($courses as $course) {
  4205. $my_course_code_list[$course['real_id']] = $course['real_id'];
  4206. }
  4207. }
  4208. $table_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4209. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4210. $table_course_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4211. //$table_course_access table uses the now() and interval ...
  4212. $now = api_get_utc_datetime(time());
  4213. $sql = "SELECT COUNT(course_access_id) course_count, a.c_id, visibility
  4214. FROM $table_course c
  4215. INNER JOIN $table_course_access a
  4216. ON (c.id = a.c_id)
  4217. INNER JOIN $table_course_url u
  4218. ON u.c_id = c.id
  4219. WHERE
  4220. u.access_url_id = ".api_get_current_access_url_id()." AND
  4221. login_course_date <= '$now' AND
  4222. login_course_date > DATE_SUB('$now', INTERVAL $days DAY) AND
  4223. visibility <> '".COURSE_VISIBILITY_CLOSED."' AND visibility <> '".COURSE_VISIBILITY_HIDDEN."'
  4224. GROUP BY a.c_id
  4225. ORDER BY course_count DESC
  4226. LIMIT $limit
  4227. ";
  4228. $result = Database::query($sql);
  4229. $courses = array();
  4230. if (Database::num_rows($result)) {
  4231. $courses = Database::store_result($result, 'ASSOC');
  4232. $courses = self::process_hot_course_item($courses, $my_course_code_list);
  4233. }
  4234. return $courses;
  4235. }
  4236. /**
  4237. * @param array $courses
  4238. * @param array $my_course_code_list
  4239. * @return mixed
  4240. */
  4241. public static function process_hot_course_item($courses, $my_course_code_list = array())
  4242. {
  4243. $hotCourses = [];
  4244. $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
  4245. $stok = Security::get_existing_token();
  4246. $user_id = api_get_user_id();
  4247. foreach ($courses as $courseId) {
  4248. $course_info = api_get_course_info_by_id($courseId['c_id']);
  4249. $courseCode = $course_info['code'];
  4250. $categoryCode = !empty($course_info['categoryCode']) ? $course_info['categoryCode'] : "";
  4251. $my_course = $course_info;
  4252. $my_course['go_to_course_button'] = '';
  4253. $my_course['register_button'] = '';
  4254. $access_link = self::get_access_link_by_user(
  4255. api_get_user_id(),
  4256. $course_info,
  4257. $my_course_code_list
  4258. );
  4259. $userRegisterdInCourse = self::is_user_subscribed_in_course($user_id, $course_info['code']);
  4260. $userRegisterdInCourseAsTeacher = self::is_course_teacher($user_id, $course_info['code']);
  4261. $userRegisterd = ($userRegisterdInCourse && $userRegisterdInCourseAsTeacher);
  4262. $my_course['is_registerd'] = $userRegisterd;
  4263. $my_course['title_cut'] = cut($course_info['title'], 45);
  4264. // if user registered as student
  4265. /* if ($userRegisterdInCourse) {
  4266. $icon = '<em class="fa fa-graduation-cap"></em>';
  4267. $title = get_lang("AlreadyRegisteredToCourse");
  4268. $my_course['already_register_as'] = Display::tag(
  4269. 'button',
  4270. $icon,
  4271. array(
  4272. 'id' => 'register',
  4273. 'class' => 'btn btn-default btn-sm',
  4274. 'title' => $title,
  4275. 'aria-label' => $title
  4276. )
  4277. );
  4278. } elseif ($userRegisterdInCourseAsTeacher) {
  4279. // if user registered as teacher
  4280. $icon = '<em class="fa fa-suitcase"></em>';
  4281. $title = get_lang("YouAreATeacherOfThisCourse");
  4282. $my_course['already_register_as'] = Display::tag(
  4283. 'button',
  4284. $icon,
  4285. array(
  4286. 'id' => 'register',
  4287. 'class' => 'btn btn-default btn-sm',
  4288. 'title' => $title,
  4289. 'aria-label' => $title
  4290. )
  4291. );
  4292. } */
  4293. //Course visibility
  4294. if ($access_link && in_array('register', $access_link)) {
  4295. $my_course['register_button'] = Display::url(
  4296. get_lang('Subscribe').' '.
  4297. Display::returnFontAwesomeIcon('sign-in'),
  4298. api_get_path(WEB_COURSE_PATH).$course_info['path'].
  4299. '/index.php?action=subscribe&sec_token='.$stok,
  4300. array(
  4301. 'class' => 'btn btn-success btn-sm',
  4302. 'title' => get_lang('Subscribe'),
  4303. 'aria-label' => get_lang('Subscribe')
  4304. )
  4305. );
  4306. }
  4307. if ($access_link && in_array('enter', $access_link) ||
  4308. $course_info['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
  4309. ) {
  4310. $my_course['go_to_course_button'] = Display::url(
  4311. get_lang('GoToCourse').' '.
  4312. Display::returnFontAwesomeIcon('share'),
  4313. api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php',
  4314. array(
  4315. 'class' => 'btn btn-default btn-sm',
  4316. 'title' => get_lang('GoToCourse'),
  4317. 'aria-label' => get_lang('GoToCourse')
  4318. )
  4319. );
  4320. }
  4321. if ($access_link && in_array('unsubscribe', $access_link)) {
  4322. $my_course['unsubscribe_button'] = Display::url(
  4323. get_lang('Unreg').' '.
  4324. Display::returnFontAwesomeIcon('sign-out'),
  4325. api_get_path(WEB_CODE_PATH).'auth/courses.php?action=unsubscribe&unsubscribe='.$courseCode
  4326. . '&sec_token='.$stok.'&category_code='.$categoryCode,
  4327. array(
  4328. 'class' => 'btn btn-danger btn-sm',
  4329. 'title' => get_lang('Unreg'),
  4330. 'aria-label' => get_lang('Unreg')
  4331. )
  4332. );
  4333. }
  4334. // start buycourse validation
  4335. // display the course price and buy button if the buycourses plugin is enabled and this course is configured
  4336. $plugin = BuyCoursesPlugin::create();
  4337. $isThisCourseInSale = $plugin->buyCoursesForGridCatalogValidator(
  4338. $course_info['real_id'],
  4339. BuyCoursesPlugin::PRODUCT_TYPE_COURSE
  4340. );
  4341. if ($isThisCourseInSale) {
  4342. // set the price label
  4343. $my_course['price'] = $isThisCourseInSale['html'];
  4344. // set the Buy button instead register.
  4345. if ($isThisCourseInSale['verificator'] && !empty($my_course['register_button'])) {
  4346. $my_course['register_button'] = $plugin->returnBuyCourseButton($course_info['real_id'], BuyCoursesPlugin::PRODUCT_TYPE_COURSE);
  4347. }
  4348. }
  4349. // end buycourse validation
  4350. //Description
  4351. $my_course['description_button'] = '';
  4352. $my_course['description_button'] = Display::url(
  4353. Display::returnFontAwesomeIcon('info-circle'),
  4354. api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?a=show_course_information&code='.$course_info['code'],
  4355. [
  4356. 'class' => 'btn btn-default btn-sm ajax',
  4357. 'data-title' => get_lang('Description'),
  4358. 'title' => get_lang('Description'),
  4359. 'aria-label' => get_lang('Description')
  4360. ]
  4361. );
  4362. $my_course['teachers'] = self::getTeachersFromCourse($course_info['real_id'], true);
  4363. $point_info = self::get_course_ranking($course_info['real_id'], 0);
  4364. $my_course['rating_html'] = '';
  4365. if (api_get_configuration_value('hide_course_rating') === false) {
  4366. $my_course['rating_html'] = Display::return_rating_system(
  4367. 'star_'.$course_info['real_id'],
  4368. $ajax_url.'&course_id='.$course_info['real_id'],
  4369. $point_info
  4370. );
  4371. }
  4372. $hotCourses[] = $my_course;
  4373. }
  4374. return $hotCourses;
  4375. }
  4376. /**
  4377. * @param int $limit
  4378. * @return array
  4379. */
  4380. public static function return_most_accessed_courses($limit = 5)
  4381. {
  4382. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  4383. $params['url_id'] = api_get_current_access_url_id();
  4384. $result = Database::select(
  4385. 'c_id, accesses, total_score, users',
  4386. $table_course_ranking,
  4387. array('where' => array('url_id = ?' => $params), 'order' => 'accesses DESC', 'limit' => $limit),
  4388. 'all',
  4389. true
  4390. );
  4391. return $result;
  4392. }
  4393. /**
  4394. * Get courses count
  4395. * @param int Access URL ID (optional)
  4396. * @param int $visibility
  4397. * @param integer $access_url_id
  4398. *
  4399. * @return int Number of courses
  4400. */
  4401. public static function count_courses($access_url_id = null, $visibility = null)
  4402. {
  4403. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4404. $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4405. $sql = "SELECT count(c.id) FROM $table_course c";
  4406. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  4407. $sql .= ", $table_course_rel_access_url u
  4408. WHERE c.id = u.c_id AND u.access_url_id = $access_url_id";
  4409. if (!empty($visibility)) {
  4410. $visibility = intval($visibility);
  4411. $sql .= " AND visibility = $visibility ";
  4412. }
  4413. } else {
  4414. if (!empty($visibility)) {
  4415. $visibility = intval($visibility);
  4416. $sql .= " WHERE visibility = $visibility ";
  4417. }
  4418. }
  4419. $res = Database::query($sql);
  4420. $row = Database::fetch_row($res);
  4421. return $row[0];
  4422. }
  4423. /**
  4424. * Get active courses count.
  4425. * Active = all courses except the ones with hidden visibility.
  4426. *
  4427. * @param int $urlId Access URL ID (optional)
  4428. * @return int Number of courses
  4429. */
  4430. public static function countActiveCourses($urlId = null)
  4431. {
  4432. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4433. $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4434. $sql = "SELECT count(id) FROM $table_course c";
  4435. if (!empty($urlId) && $urlId == intval($urlId)) {
  4436. $sql .= ", $table_course_rel_access_url u
  4437. WHERE
  4438. c.id = u.c_id AND
  4439. u.access_url_id = $urlId AND
  4440. visibility <> ".COURSE_VISIBILITY_HIDDEN;
  4441. } else {
  4442. $sql .= " WHERE visibility <> ".COURSE_VISIBILITY_HIDDEN;
  4443. }
  4444. $res = Database::query($sql);
  4445. $row = Database::fetch_row($res);
  4446. return $row[0];
  4447. }
  4448. /**
  4449. * Returns the SQL conditions to filter course only visible by the user in the catalogue
  4450. *
  4451. * @param string $courseTableAlias Alias of the course table
  4452. * @param bool $hideClosed Whether to hide closed and hidden courses
  4453. * @return string SQL conditions
  4454. */
  4455. public static function getCourseVisibilitySQLCondition(
  4456. $courseTableAlias,
  4457. $hideClosed = false
  4458. ) {
  4459. $visibilityCondition = '';
  4460. $hidePrivate = api_get_setting('course_catalog_hide_private');
  4461. if ($hidePrivate === 'true') {
  4462. $visibilityCondition .= ' AND '.$courseTableAlias.'.visibility <> '.COURSE_VISIBILITY_REGISTERED;
  4463. }
  4464. if ($hideClosed) {
  4465. $visibilityCondition .= ' AND '.$courseTableAlias.'.visibility NOT IN ('.COURSE_VISIBILITY_CLOSED.','.COURSE_VISIBILITY_HIDDEN.')';
  4466. }
  4467. // Check if course have users allowed to see it in the catalogue, then show only if current user is allowed to see it
  4468. $currentUserId = api_get_user_id();
  4469. $restrictedCourses = self::getCatalogueCourseList(true);
  4470. $allowedCoursesToCurrentUser = self::getCatalogueCourseList(true, $currentUserId);
  4471. if (!empty($restrictedCourses)) {
  4472. $visibilityCondition .= ' AND ('.$courseTableAlias.'.code NOT IN ("'.implode('","', $restrictedCourses).'")';
  4473. $visibilityCondition .= ' OR '.$courseTableAlias.'.code IN ("'.implode('","', $allowedCoursesToCurrentUser).'"))';
  4474. }
  4475. // Check if course have users denied to see it in the catalogue, then show only if current user is not denied to see it
  4476. $restrictedCourses = self::getCatalogueCourseList(false);
  4477. $notAllowedCoursesToCurrentUser = self::getCatalogueCourseList(false, $currentUserId);
  4478. if (!empty($restrictedCourses)) {
  4479. $visibilityCondition .= ' AND ('.$courseTableAlias.'.code NOT IN ("'.implode('","', $restrictedCourses).'")';
  4480. $visibilityCondition .= ' OR '.$courseTableAlias.'.code NOT IN ("'.implode('","', $notAllowedCoursesToCurrentUser).'"))';
  4481. }
  4482. return $visibilityCondition;
  4483. }
  4484. /**
  4485. * Get available le courses count
  4486. * @param int $accessUrlId (optional)
  4487. * @param integer $accessUrlId
  4488. * @return int Number of courses
  4489. */
  4490. public static function countAvailableCourses($accessUrlId = 1)
  4491. {
  4492. $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  4493. $tableCourseRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4494. $specialCourseList = self::get_special_course_list();
  4495. $withoutSpecialCourses = '';
  4496. if (!empty($specialCourseList)) {
  4497. $withoutSpecialCourses = ' AND c.id NOT IN ("'.implode('","', $specialCourseList).'")';
  4498. }
  4499. $visibilityCondition = self::getCourseVisibilitySQLCondition('c', true);
  4500. $accessUrlId = (int) $accessUrlId;
  4501. if (empty($accessUrlId)) {
  4502. $accessUrlId = 1;
  4503. }
  4504. $sql = "SELECT count(c.id)
  4505. FROM $tableCourse c
  4506. INNER JOIN $tableCourseRelAccessUrl u
  4507. ON (c.id = u.c_id)
  4508. WHERE
  4509. u.access_url_id = $accessUrlId AND
  4510. c.visibility != 0 AND
  4511. c.visibility != 4
  4512. $withoutSpecialCourses
  4513. $visibilityCondition
  4514. ";
  4515. $res = Database::query($sql);
  4516. $row = Database::fetch_row($res);
  4517. return $row[0];
  4518. }
  4519. /**
  4520. * Return a link to go to the course, validating the visibility of the
  4521. * course and the user status
  4522. * @param int User ID
  4523. * @param array Course details array
  4524. * @param array List of courses to which the user is subscribed (if not provided, will be generated)
  4525. * @param integer $uid
  4526. * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
  4527. */
  4528. static function get_access_link_by_user($uid, $course, $user_courses = array())
  4529. {
  4530. if (empty($uid) or empty($course)) {
  4531. return false;
  4532. }
  4533. if (empty($user_courses)) {
  4534. // get the array of courses to which the user is subscribed
  4535. $user_courses = self::get_courses_list_by_user_id($uid);
  4536. foreach ($user_courses as $k => $v) {
  4537. $user_courses[$k] = $v['real_id'];
  4538. }
  4539. }
  4540. if (!isset($course['real_id']) && empty($course['real_id'])) {
  4541. $course = api_get_course_info($course['code']);
  4542. }
  4543. if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
  4544. return array();
  4545. }
  4546. $is_admin = api_is_platform_admin_by_id($uid);
  4547. $options = array();
  4548. // Register button
  4549. if (!api_is_anonymous($uid) &&
  4550. (
  4551. ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD || $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
  4552. //$course['visibility'] == COURSE_VISIBILITY_REGISTERED && $course['subscribe'] == SUBSCRIBE_ALLOWED
  4553. ) &&
  4554. $course['subscribe'] == SUBSCRIBE_ALLOWED &&
  4555. (!in_array($course['real_id'], $user_courses) || empty($user_courses))
  4556. ) {
  4557. $options[] = 'register';
  4558. }
  4559. // Go To Course button (only if admin, if course public or if student already subscribed)
  4560. if ($is_admin ||
  4561. $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
  4562. (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code'])) ||
  4563. (in_array($course['real_id'], $user_courses) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
  4564. ) {
  4565. $options[] = 'enter';
  4566. }
  4567. if ($is_admin ||
  4568. $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
  4569. (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code'])) ||
  4570. (in_array($course['real_id'], $user_courses) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
  4571. ) {
  4572. $options[] = 'enter';
  4573. }
  4574. if ($course['visibility'] != COURSE_VISIBILITY_HIDDEN &&
  4575. empty($course['registration_code']) &&
  4576. $course['unsubscribe'] == UNSUBSCRIBE_ALLOWED &&
  4577. api_user_is_login($uid) &&
  4578. in_array($course['real_id'], $user_courses)
  4579. ) {
  4580. $options[] = 'unsubscribe';
  4581. }
  4582. return $options;
  4583. }
  4584. /**
  4585. * @param array $courseInfo
  4586. * @param array $teachers
  4587. * @param bool $deleteTeachersNotInList
  4588. * @param bool $editTeacherInSessions
  4589. * @param bool $deleteSessionTeacherNotInList
  4590. * @param array $teacherBackup
  4591. * @param Monolog\Logger $logger
  4592. *
  4593. * @return false|null
  4594. */
  4595. public static function updateTeachers(
  4596. $courseInfo,
  4597. $teachers,
  4598. $deleteTeachersNotInList = true,
  4599. $editTeacherInSessions = false,
  4600. $deleteSessionTeacherNotInList = false,
  4601. $teacherBackup = array(),
  4602. $logger = null
  4603. ) {
  4604. if (!is_array($teachers)) {
  4605. $teachers = array($teachers);
  4606. }
  4607. if (empty($courseInfo) || !isset($courseInfo['real_id'])) {
  4608. return false;
  4609. }
  4610. $teachers = array_filter($teachers);
  4611. $courseId = $courseInfo['real_id'];
  4612. $course_code = $courseInfo['code'];
  4613. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4614. $alreadyAddedTeachers = self::get_teacher_list_from_course_code($course_code);
  4615. if ($deleteTeachersNotInList) {
  4616. // Delete only teacher relations that doesn't match the selected teachers
  4617. $cond = null;
  4618. if (count($teachers) > 0) {
  4619. foreach ($teachers as $key) {
  4620. $key = Database::escape_string($key);
  4621. $cond .= " AND user_id <> '".$key."'";
  4622. }
  4623. }
  4624. // Recover user categories
  4625. $sql = 'SELECT * FROM '.$course_user_table.'
  4626. WHERE c_id ="' . $courseId.'" AND status="1" AND relation_type = 0 '.$cond;
  4627. $result = Database::query($sql);
  4628. if (Database::num_rows($result)) {
  4629. $teachersToDelete = Database::store_result($result, 'ASSOC');
  4630. foreach ($teachersToDelete as $data) {
  4631. $userId = $data['user_id'];
  4632. $teacherBackup[$userId][$course_code] = $data;
  4633. }
  4634. }
  4635. $sql = 'DELETE FROM '.$course_user_table.'
  4636. WHERE c_id ="' . $courseId.'" AND status="1" AND relation_type = 0 '.$cond;
  4637. Database::query($sql);
  4638. }
  4639. if (count($teachers) > 0) {
  4640. foreach ($teachers as $userId) {
  4641. $userId = intval($userId);
  4642. // We check if the teacher is already subscribed in this course
  4643. $sql = 'SELECT 1 FROM '.$course_user_table.'
  4644. WHERE user_id = "' . $userId.'" AND c_id = "'.$courseId.'" ';
  4645. $result = Database::query($sql);
  4646. if (Database::num_rows($result)) {
  4647. $sql = 'UPDATE '.$course_user_table.'
  4648. SET status = "1"
  4649. WHERE c_id = "' . $courseId.'" AND user_id = "'.$userId.'" ';
  4650. } else {
  4651. $userCourseCategory = '0';
  4652. if (isset($teacherBackup[$userId]) &&
  4653. isset($teacherBackup[$userId][$course_code])
  4654. ) {
  4655. $courseUserData = $teacherBackup[$userId][$course_code];
  4656. $userCourseCategory = $courseUserData['user_course_cat'];
  4657. if ($logger) {
  4658. $logger->addInfo("Recovering user_course_cat: $userCourseCategory");
  4659. }
  4660. }
  4661. $sql = "INSERT INTO $course_user_table SET
  4662. c_id = $courseId,
  4663. user_id = $userId,
  4664. status = '1',
  4665. is_tutor = '0',
  4666. sort = '0',
  4667. relation_type = '0',
  4668. user_course_cat = '$userCourseCategory'
  4669. ";
  4670. }
  4671. Database::query($sql);
  4672. }
  4673. }
  4674. if ($editTeacherInSessions) {
  4675. $sessions = SessionManager::get_session_by_course($courseId);
  4676. if (!empty($sessions)) {
  4677. if ($logger) {
  4678. $logger->addInfo("Edit teachers in sessions");
  4679. }
  4680. foreach ($sessions as $session) {
  4681. $sessionId = $session['id'];
  4682. // Remove old and add new
  4683. if ($deleteSessionTeacherNotInList) {
  4684. foreach ($teachers as $userId) {
  4685. if ($logger) {
  4686. $logger->addInfo("Set coach #$userId in session #$sessionId of course #$courseId ");
  4687. }
  4688. SessionManager::set_coach_to_course_session(
  4689. $userId,
  4690. $sessionId,
  4691. $courseId
  4692. );
  4693. }
  4694. $teachersToDelete = array();
  4695. if (!empty($alreadyAddedTeachers)) {
  4696. $teachersToDelete = array_diff(array_keys($alreadyAddedTeachers), $teachers);
  4697. }
  4698. if (!empty($teachersToDelete)) {
  4699. foreach ($teachersToDelete as $userId) {
  4700. if ($logger) {
  4701. $logger->addInfo("Delete coach #$userId in session #$sessionId of course #$courseId ");
  4702. }
  4703. SessionManager::set_coach_to_course_session(
  4704. $userId,
  4705. $sessionId,
  4706. $courseId,
  4707. true
  4708. );
  4709. }
  4710. }
  4711. } else {
  4712. // Add new teachers only
  4713. foreach ($teachers as $userId) {
  4714. if ($logger) {
  4715. $logger->addInfo("Add coach #$userId in session #$sessionId of course #$courseId ");
  4716. }
  4717. SessionManager::set_coach_to_course_session(
  4718. $userId,
  4719. $sessionId,
  4720. $courseId
  4721. );
  4722. }
  4723. }
  4724. }
  4725. }
  4726. }
  4727. }
  4728. /**
  4729. * Course available settings variables see c_course_setting table
  4730. * @param AppPlugin $appPlugin
  4731. * @return array
  4732. */
  4733. public static function getCourseSettingVariables(AppPlugin $appPlugin)
  4734. {
  4735. $pluginCourseSettings = $appPlugin->getAllPluginCourseSettings();
  4736. $courseSettings = array(
  4737. // Get allow_learning_path_theme from table
  4738. 'allow_learning_path_theme',
  4739. // Get allow_open_chat_window from table
  4740. 'allow_open_chat_window',
  4741. 'allow_public_certificates',
  4742. // Get allow_user_edit_agenda from table
  4743. 'allow_user_edit_agenda',
  4744. // Get allow_user_edit_announcement from table
  4745. 'allow_user_edit_announcement',
  4746. // Get allow_user_image_forum from table
  4747. 'allow_user_image_forum',
  4748. //Get allow show user list
  4749. 'allow_user_view_user_list',
  4750. // Get course_theme from table
  4751. 'course_theme',
  4752. //Get allow show user list
  4753. 'display_info_advance_inside_homecourse',
  4754. 'documents_default_visibility',
  4755. // Get send_mail_setting (work)from table
  4756. 'email_alert_manager_on_new_doc',
  4757. // Get send_mail_setting (work)from table
  4758. 'email_alert_manager_on_new_quiz',
  4759. // Get send_mail_setting (dropbox) from table
  4760. 'email_alert_on_new_doc_dropbox',
  4761. 'email_alert_students_on_new_homework',
  4762. // Get send_mail_setting (auth)from table
  4763. 'email_alert_to_teacher_on_new_user_in_course',
  4764. 'enable_lp_auto_launch',
  4765. 'pdf_export_watermark_text',
  4766. 'show_system_folders',
  4767. 'exercise_invisible_in_session',
  4768. 'enable_forum_auto_launch',
  4769. 'show_course_in_user_language'
  4770. );
  4771. $allowLPReturnLink = api_get_setting('allow_lp_return_link');
  4772. if ($allowLPReturnLink === 'true') {
  4773. $courseSettings[] = 'lp_return_link';
  4774. }
  4775. if (!empty($pluginCourseSettings)) {
  4776. $courseSettings = array_merge(
  4777. $courseSettings,
  4778. $pluginCourseSettings
  4779. );
  4780. }
  4781. return $courseSettings;
  4782. }
  4783. /**
  4784. * @param AppPlugin $appPlugin
  4785. * @param string $variable
  4786. * @param string|array $value
  4787. * @param int $courseId
  4788. * @return bool
  4789. */
  4790. public static function saveCourseConfigurationSetting(AppPlugin $appPlugin, $variable, $value, $courseId)
  4791. {
  4792. $settingList = self::getCourseSettingVariables($appPlugin);
  4793. if (!in_array($variable, $settingList)) {
  4794. return false;
  4795. }
  4796. $courseSettingTable = Database::get_course_table(TABLE_COURSE_SETTING);
  4797. if (is_array($value)) {
  4798. $value = implode(',', $value);
  4799. }
  4800. if (self::hasCourseSetting($variable, $courseId)) {
  4801. // Update
  4802. Database::update(
  4803. $courseSettingTable,
  4804. array('value' => $value),
  4805. array('variable = ? AND c_id = ?' => array($variable, $courseId))
  4806. );
  4807. } else {
  4808. // Create
  4809. Database::insert(
  4810. $courseSettingTable,
  4811. [
  4812. 'title' => $variable,
  4813. 'value' => $value,
  4814. 'c_id' => $courseId,
  4815. 'variable' => $variable,
  4816. ]
  4817. );
  4818. }
  4819. return true;
  4820. }
  4821. /**
  4822. * Check if course setting exists
  4823. * @param string $variable
  4824. * @param int $courseId
  4825. * @return bool
  4826. */
  4827. public static function hasCourseSetting($variable, $courseId)
  4828. {
  4829. $courseSetting = Database::get_course_table(TABLE_COURSE_SETTING);
  4830. $courseId = intval($courseId);
  4831. $variable = Database::escape_string($variable);
  4832. $sql = "SELECT variable FROM $courseSetting
  4833. WHERE c_id = $courseId AND variable = '$variable'";
  4834. $result = Database::query($sql);
  4835. return Database::num_rows($result) > 0;
  4836. }
  4837. /**
  4838. * Get information from the track_e_course_access table
  4839. * @param int $sessionId
  4840. * @param int $userId
  4841. * @param int $limit
  4842. * @return array
  4843. */
  4844. public static function getCourseAccessPerSessionAndUser($sessionId, $userId, $limit = 0)
  4845. {
  4846. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4847. $sessionId = intval($sessionId);
  4848. $userId = intval($userId);
  4849. $sql = "SELECT * FROM $table
  4850. WHERE session_id = $sessionId AND user_id = $userId";
  4851. if (!empty($limit)) {
  4852. $limit = intval($limit);
  4853. $sql .= " LIMIT $limit";
  4854. }
  4855. $result = Database::query($sql);
  4856. return Database::store_result($result);
  4857. }
  4858. /**
  4859. * Get information from the track_e_course_access table
  4860. * @param int $courseId
  4861. * @param int $sessionId
  4862. * @param string $startDate
  4863. * @param string $endDate
  4864. * @return array
  4865. */
  4866. public static function getCourseAccessPerCourseAndSession(
  4867. $courseId,
  4868. $sessionId,
  4869. $startDate,
  4870. $endDate
  4871. ) {
  4872. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4873. $courseId = intval($courseId);
  4874. $sessionId = intval($sessionId);
  4875. $startDate = Database::escape_string($startDate);
  4876. $endDate = Database::escape_string($endDate);
  4877. $sql = "SELECT * FROM $table
  4878. WHERE
  4879. c_id = $courseId AND
  4880. session_id = $sessionId AND
  4881. login_course_date BETWEEN '$startDate' AND '$endDate'
  4882. ";
  4883. $result = Database::query($sql);
  4884. return Database::store_result($result);
  4885. }
  4886. /**
  4887. * Get login information from the track_e_course_access table, for any
  4888. * course in the given session
  4889. * @param int $sessionId
  4890. * @param int $userId
  4891. * @return array
  4892. */
  4893. public static function getFirstCourseAccessPerSessionAndUser($sessionId, $userId)
  4894. {
  4895. $sessionId = intval($sessionId);
  4896. $userId = intval($userId);
  4897. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4898. $sql = "SELECT * FROM $table
  4899. WHERE session_id = $sessionId AND user_id = $userId
  4900. ORDER BY login_course_date ASC
  4901. LIMIT 1";
  4902. $result = Database::query($sql);
  4903. $courseAccess = array();
  4904. if (Database::num_rows($result)) {
  4905. $courseAccess = Database::fetch_array($result, 'ASSOC');
  4906. }
  4907. return $courseAccess;
  4908. }
  4909. /**
  4910. * @param int $courseId
  4911. * @param int $sessionId
  4912. * @param bool $getAllSessions
  4913. * @return mixed
  4914. */
  4915. public static function getCountForum(
  4916. $courseId,
  4917. $sessionId = 0,
  4918. $getAllSessions = false
  4919. ) {
  4920. $forum = Database::get_course_table(TABLE_FORUM);
  4921. if ($getAllSessions) {
  4922. $sql = "SELECT count(*) as count
  4923. FROM $forum f
  4924. WHERE f.c_id = %s";
  4925. } else {
  4926. $sql = "SELECT count(*) as count
  4927. FROM $forum f
  4928. WHERE f.c_id = %s and f.session_id = %s";
  4929. }
  4930. $sql = sprintf($sql, intval($courseId), intval($sessionId));
  4931. $result = Database::query($sql);
  4932. $row = Database::fetch_array($result);
  4933. return $row['count'];
  4934. }
  4935. /**
  4936. * @param int $userId
  4937. * @param int $courseId
  4938. * @param int $sessionId
  4939. * @return mixed
  4940. */
  4941. public static function getCountPostInForumPerUser(
  4942. $userId,
  4943. $courseId,
  4944. $sessionId = 0
  4945. ) {
  4946. $forum = Database::get_course_table(TABLE_FORUM);
  4947. $forum_post = Database::get_course_table(TABLE_FORUM_POST);
  4948. $sql = "SELECT count(distinct post_id) as count
  4949. FROM $forum_post p
  4950. INNER JOIN $forum f
  4951. ON f.forum_id = p.forum_id AND f.c_id = p.c_id
  4952. WHERE p.poster_id = %s and f.session_id = %s and p.c_id = %s";
  4953. $sql = sprintf(
  4954. $sql,
  4955. intval($userId),
  4956. intval($sessionId),
  4957. intval($courseId)
  4958. );
  4959. $result = Database::query($sql);
  4960. $row = Database::fetch_array($result);
  4961. return $row['count'];
  4962. }
  4963. /**
  4964. * @param int $userId
  4965. * @param int $courseId
  4966. * @param int $sessionId
  4967. * @return mixed
  4968. */
  4969. public static function getCountForumPerUser(
  4970. $userId,
  4971. $courseId,
  4972. $sessionId = 0
  4973. ) {
  4974. $forum = Database::get_course_table(TABLE_FORUM);
  4975. $forum_post = Database::get_course_table(TABLE_FORUM_POST);
  4976. $sql = "SELECT count(distinct f.forum_id) as count
  4977. FROM $forum_post p
  4978. INNER JOIN $forum f
  4979. ON f.forum_id = p.forum_id AND f.c_id = p.c_id
  4980. WHERE p.poster_id = %s and f.session_id = %s and p.c_id = %s";
  4981. $sql = sprintf(
  4982. $sql,
  4983. intval($userId),
  4984. intval($sessionId),
  4985. intval($courseId)
  4986. );
  4987. $result = Database::query($sql);
  4988. $row = Database::fetch_array($result);
  4989. return $row['count'];
  4990. }
  4991. /**
  4992. * Returns the course name from a given code
  4993. * @param string $code
  4994. */
  4995. public static function getCourseNameFromCode($code)
  4996. {
  4997. $tbl_main_categories = Database::get_main_table(TABLE_MAIN_COURSE);
  4998. $sql = 'SELECT title
  4999. FROM ' . $tbl_main_categories.'
  5000. WHERE code = "' . Database::escape_string($code).'"';
  5001. $result = Database::query($sql);
  5002. if ($col = Database::fetch_array($result)) {
  5003. return $col['title'];
  5004. }
  5005. }
  5006. /**
  5007. * Generates a course code from a course title
  5008. * @todo Such a function might be useful in other places too. It might be moved in the CourseManager class.
  5009. * @todo the function might be upgraded for avoiding code duplications (currently, it might suggest a code that is already in use)
  5010. * @param string $title A course title
  5011. * @return string A proposed course code
  5012. * +
  5013. * @assert (null,null) === false
  5014. * @assert ('ABC_DEF', null) === 'ABCDEF'
  5015. * @assert ('ABC09*^[%A', null) === 'ABC09A'
  5016. */
  5017. public static function generate_course_code($title)
  5018. {
  5019. return substr(
  5020. preg_replace('/[^A-Z0-9]/', '', strtoupper(api_replace_dangerous_char($title))),
  5021. 0,
  5022. self::MAX_COURSE_LENGTH_CODE
  5023. );
  5024. }
  5025. /**
  5026. * @param $courseId
  5027. * @return array
  5028. */
  5029. public static function getCourseSettings($courseId)
  5030. {
  5031. $settingTable = Database::get_course_table(TABLE_COURSE_SETTING);
  5032. $courseId = intval($courseId);
  5033. $sql = "SELECT * FROM $settingTable WHERE c_id = $courseId";
  5034. $result = Database::query($sql);
  5035. $settings = array();
  5036. if (Database::num_rows($result)) {
  5037. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5038. $settings[$row['variable']] = $row;
  5039. }
  5040. }
  5041. return $settings;
  5042. }
  5043. /**
  5044. * this function gets all the users of the course,
  5045. * including users from linked courses
  5046. */
  5047. public static function getCourseUsers()
  5048. {
  5049. //this would return only the users from real courses:
  5050. $session_id = api_get_session_id();
  5051. if ($session_id != 0) {
  5052. $user_list = self::get_real_and_linked_user_list(api_get_course_id(), true, $session_id);
  5053. } else {
  5054. $user_list = self::get_real_and_linked_user_list(api_get_course_id(), false, 0);
  5055. }
  5056. return $user_list;
  5057. }
  5058. /**
  5059. * this function gets all the groups of the course,
  5060. * not including linked courses
  5061. */
  5062. public static function getCourseGroups()
  5063. {
  5064. $session_id = api_get_session_id();
  5065. if ($session_id != 0) {
  5066. $new_group_list = self::get_group_list_of_course(api_get_course_id(), $session_id, 1);
  5067. } else {
  5068. $new_group_list = self::get_group_list_of_course(api_get_course_id(), 0, 1);
  5069. }
  5070. return $new_group_list;
  5071. }
  5072. /**
  5073. * @param FormValidator $form
  5074. * @param array $to_already_selected
  5075. *
  5076. * @return HTML_QuickForm_element
  5077. */
  5078. public static function addUserGroupMultiSelect(&$form, $to_already_selected)
  5079. {
  5080. $user_list = self::getCourseUsers();
  5081. $group_list = self::getCourseGroups();
  5082. $array = self::buildSelectOptions($group_list, $user_list, $to_already_selected);
  5083. $result = array();
  5084. foreach ($array as $content) {
  5085. $result[$content['value']] = $content['content'];
  5086. }
  5087. return $form->addElement(
  5088. 'advmultiselect',
  5089. 'users',
  5090. get_lang('Users'),
  5091. $result,
  5092. array('select_all_checkbox' => true)
  5093. );
  5094. }
  5095. /**
  5096. * This function separates the users from the groups
  5097. * users have a value USER:XXX (with XXX the groups id have a value
  5098. * GROUP:YYY (with YYY the group id)
  5099. * @param array $to Array of strings that define the type and id of each destination
  5100. * @return array Array of groups and users (each an array of IDs)
  5101. */
  5102. public static function separateUsersGroups($to)
  5103. {
  5104. $groupList = array();
  5105. $userList = array();
  5106. foreach ($to as $to_item) {
  5107. if (!empty($to_item)) {
  5108. $parts = explode(':', $to_item);
  5109. $type = isset($parts[0]) ? $parts[0] : '';
  5110. $id = isset($parts[1]) ? $parts[1] : '';
  5111. switch ($type) {
  5112. case 'GROUP':
  5113. $groupList[] = intval($id);
  5114. break;
  5115. case 'USER':
  5116. $userList[] = intval($id);
  5117. break;
  5118. }
  5119. }
  5120. }
  5121. $send_to['groups'] = $groupList;
  5122. $send_to['users'] = $userList;
  5123. return $send_to;
  5124. }
  5125. /**
  5126. * Shows the form for sending a message to a specific group or user.
  5127. * @param FormValidator $form
  5128. * @param int $group_id id
  5129. * @param array $to
  5130. */
  5131. public static function addGroupMultiSelect($form, $groupInfo, $to = array())
  5132. {
  5133. $group_users = GroupManager::get_subscribed_users($groupInfo);
  5134. $array = self::buildSelectOptions(null, $group_users, $to);
  5135. $result = array();
  5136. foreach ($array as $content) {
  5137. $result[$content['value']] = $content['content'];
  5138. }
  5139. return $form->addElement('advmultiselect', 'users', get_lang('Users'), $result);
  5140. }
  5141. /**
  5142. * this function shows the form for sending a message to a specific group or user.
  5143. * @param array $group_list
  5144. * @param array $user_list
  5145. * @param array $to_already_selected
  5146. * @return array
  5147. */
  5148. public static function buildSelectOptions(
  5149. $group_list = array(),
  5150. $user_list = array(),
  5151. $to_already_selected = array()
  5152. ) {
  5153. if (empty($to_already_selected)) {
  5154. $to_already_selected = array();
  5155. }
  5156. $result = array();
  5157. // adding the groups to the select form
  5158. if ($group_list) {
  5159. foreach ($group_list as $this_group) {
  5160. if (is_array($to_already_selected)) {
  5161. if (!in_array(
  5162. "GROUP:".$this_group['id'],
  5163. $to_already_selected
  5164. )
  5165. ) { // $to_already_selected is the array containing the groups (and users) that are already selected
  5166. $user_label = ($this_group['userNb'] > 0) ? get_lang('Users') : get_lang('LowerCaseUser');
  5167. $user_disabled = ($this_group['userNb'] > 0) ? "" : "disabled=disabled";
  5168. $result[] = array(
  5169. 'disabled' => $user_disabled,
  5170. 'value' => "GROUP:".$this_group['id'],
  5171. 'content' => "G: ".$this_group['name']." - ".$this_group['userNb']." ".$user_label
  5172. );
  5173. }
  5174. }
  5175. }
  5176. }
  5177. // adding the individual users to the select form
  5178. if ($user_list) {
  5179. foreach ($user_list as $user) {
  5180. if (is_array($to_already_selected)) {
  5181. if (!in_array(
  5182. "USER:".$user['user_id'],
  5183. $to_already_selected
  5184. )
  5185. ) { // $to_already_selected is the array containing the users (and groups) that are already selected
  5186. $result[] = array(
  5187. 'value' => "USER:".$user['user_id'],
  5188. 'content' => api_get_person_name($user['firstname'], $user['lastname'])
  5189. );
  5190. }
  5191. }
  5192. }
  5193. }
  5194. return $result;
  5195. }
  5196. /**
  5197. * @return array a list (array) of all courses.
  5198. */
  5199. public static function get_course_list()
  5200. {
  5201. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  5202. return Database::store_result(Database::query("SELECT *, id as real_id FROM $table"));
  5203. }
  5204. /**
  5205. * Returns course code from a given gradebook category's id
  5206. * @param int Category ID
  5207. * @return string Course code
  5208. */
  5209. public static function get_course_by_category($category_id)
  5210. {
  5211. $category_id = intval($category_id);
  5212. $info = Database::fetch_array(
  5213. Database::query('SELECT course_code FROM '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).'
  5214. WHERE id=' . $category_id), 'ASSOC'
  5215. );
  5216. return $info ? $info['course_code'] : false;
  5217. }
  5218. /**
  5219. * This function gets all the courses that are not in a session
  5220. * @param date Start date
  5221. * @param date End date
  5222. * @param bool $includeClosed Whether to include closed and hidden courses
  5223. * @return array Not-in-session courses
  5224. */
  5225. public static function getCoursesWithoutSession($startDate = null, $endDate = null, $includeClosed = false)
  5226. {
  5227. $dateConditional = ($startDate && $endDate) ?
  5228. " WHERE session_id IN (SELECT id FROM ".Database::get_main_table(TABLE_MAIN_SESSION).
  5229. " WHERE access_start_date = '$startDate' AND access_end_date = '$endDate')" : null;
  5230. $visibility = ($includeClosed ? '' : 'visibility NOT IN (0, 4) AND ');
  5231. $sql = "SELECT id, code, title
  5232. FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  5233. WHERE $visibility code NOT IN (
  5234. SELECT DISTINCT course_code
  5235. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE).$dateConditional."
  5236. )
  5237. ORDER BY id";
  5238. $result = Database::query($sql);
  5239. $courses = array();
  5240. while ($row = Database::fetch_array($result)) {
  5241. $courses[] = $row;
  5242. }
  5243. return $courses;
  5244. }
  5245. /**
  5246. * Get list of courses based on users of a group for a group admin
  5247. * @param int $userId The user id
  5248. * @return array
  5249. */
  5250. public static function getCoursesFollowedByGroupAdmin($userId)
  5251. {
  5252. $coursesList = [];
  5253. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  5254. $courseUserTable = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5255. $userGroup = new UserGroup();
  5256. $userIdList = $userGroup->getGroupUsersByUser($userId);
  5257. if (empty($userIdList)) {
  5258. return [];
  5259. }
  5260. $sql = "SELECT DISTINCT(c.id), c.title
  5261. FROM $courseTable c
  5262. INNER JOIN $courseUserTable cru ON c.id = cru.c_id
  5263. WHERE (
  5264. cru.user_id IN (".implode(', ', $userIdList).")
  5265. AND cru.relation_type = 0
  5266. )";
  5267. if (api_is_multiple_url_enabled()) {
  5268. $courseAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  5269. $accessUrlId = api_get_current_access_url_id();
  5270. if ($accessUrlId != -1) {
  5271. $sql = "SELECT DISTINCT(c.id), c.title
  5272. FROM $courseTable c
  5273. INNER JOIN $courseUserTable cru ON c.id = cru.c_id
  5274. INNER JOIN $courseAccessUrlTable crau ON c.id = crau.c_id
  5275. WHERE crau.access_url_id = $accessUrlId
  5276. AND (
  5277. cru.id_user IN (".implode(', ', $userIdList).") AND
  5278. cru.relation_type = 0
  5279. )";
  5280. }
  5281. }
  5282. $result = Database::query($sql);
  5283. while ($row = Database::fetch_assoc($result)) {
  5284. $coursesList[] = $row;
  5285. }
  5286. return $coursesList;
  5287. }
  5288. /**
  5289. * Direct course link see #5299
  5290. *
  5291. * You can send to your students an URL like this
  5292. * http://chamilodev.beeznest.com/main/auth/inscription.php?c=ABC&e=3
  5293. * Where "c" is the course code and "e" is the exercise Id, after a successful
  5294. * registration the user will be sent to the course or exercise
  5295. *
  5296. */
  5297. public static function redirectToCourse($form_data)
  5298. {
  5299. $course_code_redirect = Session::read('course_redirect');
  5300. $_user = api_get_user_info();
  5301. $user_id = api_get_user_id();
  5302. if (!empty($course_code_redirect)) {
  5303. $course_info = api_get_course_info($course_code_redirect);
  5304. if (!empty($course_info)) {
  5305. if (in_array($course_info['visibility'],
  5306. array(COURSE_VISIBILITY_OPEN_PLATFORM, COURSE_VISIBILITY_OPEN_WORLD))
  5307. ) {
  5308. if (self::is_user_subscribed_in_course($user_id, $course_info['code'])) {
  5309. $form_data['action'] = $course_info['course_public_url'];
  5310. $form_data['message'] = sprintf(get_lang('YouHaveBeenRegisteredToCourseX'), $course_info['title']);
  5311. $form_data['button'] = Display::button(
  5312. 'next',
  5313. get_lang('GoToCourse', null, $_user['language']),
  5314. array('class' => 'btn btn-primary btn-large')
  5315. );
  5316. $exercise_redirect = intval(Session::read('exercise_redirect'));
  5317. // Specify the course id as the current context does not
  5318. // hold a global $_course array
  5319. $objExercise = new Exercise($course_info['real_id']);
  5320. $result = $objExercise->read($exercise_redirect);
  5321. if (!empty($exercise_redirect) && !empty($result)) {
  5322. $form_data['action'] = api_get_path(WEB_CODE_PATH).'exercise/overview.php?exerciseId='.$exercise_redirect.'&cidReq='.$course_info['code'];
  5323. $form_data['message'] .= '<br />'.get_lang('YouCanAccessTheExercise');
  5324. $form_data['button'] = Display::button(
  5325. 'next',
  5326. get_lang('Go', null, $_user['language']),
  5327. array('class' => 'btn btn-primary btn-large')
  5328. );
  5329. }
  5330. if (!empty($form_data['action'])) {
  5331. header('Location: '.$form_data['action']);
  5332. exit;
  5333. }
  5334. }
  5335. }
  5336. }
  5337. }
  5338. return $form_data;
  5339. }
  5340. /**
  5341. * return html code for displaying a course title in the standard view (not the Session view)
  5342. * @param $courseId
  5343. * @param bool $loadDirs
  5344. * @return string
  5345. */
  5346. public static function displayCourseHtml($courseId, $loadDirs = false)
  5347. {
  5348. $params = self::getCourseParamsForDisplay($courseId, $loadDirs);
  5349. $html = self::course_item_html($params, false);
  5350. return $html;
  5351. }
  5352. /**
  5353. * Return tab of params to display a course title in the My Courses tab
  5354. * Check visibility, right, and notification icons, and load_dirs option
  5355. * // get html course params
  5356. * //
  5357. * @param $courseId
  5358. * @param bool $loadDirs
  5359. * @return array with keys ['right_actions'] ['teachers'] ['notifications']
  5360. */
  5361. public static function getCourseParamsForDisplay($courseId, $loadDirs = false)
  5362. {
  5363. $user_id = api_get_user_id();
  5364. // Table definitions
  5365. $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
  5366. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5367. $TABLE_ACCESS_URL_REL_COURSE = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  5368. $current_url_id = api_get_current_access_url_id();
  5369. // Get course list auto-register
  5370. $special_course_list = self::get_special_course_list();
  5371. $without_special_courses = '';
  5372. if (!empty($special_course_list)) {
  5373. $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $special_course_list).'")';
  5374. }
  5375. //AND course_rel_user.relation_type<>".COURSE_RELATION_TYPE_RRHH."
  5376. $sql = "SELECT
  5377. course.id,
  5378. course.title,
  5379. course.code,
  5380. course.subscribe subscr,
  5381. course.unsubscribe unsubscr,
  5382. course_rel_user.status status,
  5383. course_rel_user.sort sort,
  5384. course_rel_user.user_course_cat user_course_cat
  5385. FROM
  5386. $TABLECOURS course
  5387. INNER JOIN $TABLECOURSUSER course_rel_user
  5388. ON (course.id = course_rel_user.c_id)
  5389. INNER JOIN $TABLE_ACCESS_URL_REL_COURSE url
  5390. ON (url.c_id = course.id)
  5391. WHERE
  5392. course.id=".intval($courseId)." AND
  5393. course_rel_user.user_id = ".intval($user_id)."
  5394. $without_special_courses
  5395. ";
  5396. // If multiple URL access mode is enabled, only fetch courses
  5397. // corresponding to the current URL.
  5398. if (api_get_multiple_access_url() && $current_url_id != -1) {
  5399. $sql .= " AND url.c_id = course.id AND access_url_id=".intval($current_url_id);
  5400. }
  5401. // Use user's classification for courses (if any).
  5402. $sql .= " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  5403. $result = Database::query($sql);
  5404. // Browse through all courses. We can only have one course because
  5405. // of the course.id=".intval($courseId) in sql query
  5406. $course = Database::fetch_array($result);
  5407. $course_info = api_get_course_info_by_id($courseId);
  5408. if (empty($course_info)) {
  5409. return '';
  5410. }
  5411. //$course['id_session'] = null;
  5412. $course_info['id_session'] = null;
  5413. $course_info['status'] = $course['status'];
  5414. // For each course, get if there is any notification icon to show
  5415. // (something that would have changed since the user's last visit).
  5416. $show_notification = !api_get_configuration_value('hide_course_notification')
  5417. ? Display::show_notification($course_info)
  5418. : '';
  5419. // New code displaying the user's status in respect to this course.
  5420. $status_icon = Display::return_icon(
  5421. 'blackboard.png',
  5422. $course_info['title'],
  5423. array(),
  5424. ICON_SIZE_LARGE
  5425. );
  5426. $params = array();
  5427. $params['right_actions'] = '';
  5428. if (api_is_platform_admin()) {
  5429. if ($loadDirs) {
  5430. $params['right_actions'] .= '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview" href="javascript:void(0);">'.Display::return_icon('folder.png', get_lang('Documents'), array('align' => 'absmiddle'), ICON_SIZE_SMALL).'</a>';
  5431. $params['right_actions'] .= '<a href="'.api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'].'">'.Display::return_icon('edit.png', get_lang('Edit'), array('align' => 'absmiddle'), ICON_SIZE_SMALL).'</a>';
  5432. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  5433. } else {
  5434. $params['right_actions'] .= '<a class="btn btn-default btn-sm" title="'.get_lang('Edit').'" href="'.api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'].'">'.Display::returnFontAwesomeIcon('pencil').'</a>';
  5435. }
  5436. if ($course_info['status'] == COURSEMANAGER) {
  5437. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  5438. }
  5439. } else {
  5440. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  5441. if ($loadDirs) {
  5442. $params['right_actions'] .= '<a id="document_preview_'.$course_info['real_id'].'_0" class="document_preview" href="javascript:void(0);">'.Display::return_icon('folder.png', get_lang('Documents'), array('align' => 'absmiddle'), ICON_SIZE_SMALL).'</a>';
  5443. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  5444. } else {
  5445. if ($course_info['status'] == COURSEMANAGER) {
  5446. $params['right_actions'] .= '<a class="btn btn-default btn-sm" title="'.get_lang('Edit').'" href="'.api_get_path(WEB_CODE_PATH).'course_info/infocours.php?cidReq='.$course['code'].'">'.Display::returnFontAwesomeIcon('pencil').'</a>';
  5447. }
  5448. }
  5449. }
  5450. }
  5451. $course_title_url = '';
  5452. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  5453. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/?id_session=0';
  5454. $course_title = Display::url($course_info['title'], $course_title_url);
  5455. } else {
  5456. $course_title = $course_info['title'].' '.Display::tag('span', get_lang('CourseClosed'), array('class'=>'item_closed'));
  5457. }
  5458. // Start displaying the course block itself
  5459. if (api_get_setting('display_coursecode_in_courselist') === 'true') {
  5460. $course_title .= ' ('.$course_info['visual_code'].') ';
  5461. }
  5462. $teachers = '';
  5463. if (api_get_setting('display_teacher_in_courselist') === 'true') {
  5464. $teachers = self::get_teacher_list_from_course_code_to_string($course['code'], self::USER_SEPARATOR, true);
  5465. }
  5466. $params['link'] = $course_title_url;
  5467. $params['icon'] = $status_icon;
  5468. $params['title'] = $course_title;
  5469. $params['teachers'] = $teachers;
  5470. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  5471. $params['notifications'] = $show_notification;
  5472. }
  5473. return $params;
  5474. }
  5475. /**
  5476. * Get the course id based on the original id and field name in the extra fields.
  5477. * Returns 0 if course was not found
  5478. *
  5479. * @param string $original_course_id_value Original course id
  5480. * @param string $original_course_id_name Original field name
  5481. * @return int Course id
  5482. */
  5483. public static function get_course_id_from_original_id($original_course_id_value, $original_course_id_name)
  5484. {
  5485. $extraFieldValue = new ExtraFieldValue('course');
  5486. $value = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  5487. $original_course_id_name,
  5488. $original_course_id_value
  5489. );
  5490. if ($value) {
  5491. return $value['item_id'];
  5492. }
  5493. return 0;
  5494. }
  5495. /**
  5496. * Helper function to create a default gradebook (if necessary) upon course creation
  5497. * @param int $modelId The gradebook model ID
  5498. * @param string $courseCode Course code
  5499. * @return void
  5500. */
  5501. public static function createDefaultGradebook($modelId, $courseCode)
  5502. {
  5503. if (api_get_setting('gradebook_enable_grade_model') === 'true') {
  5504. //Create gradebook_category for the new course and add
  5505. // a gradebook model for the course
  5506. if (isset($modelId) &&
  5507. !empty($modelId) &&
  5508. $modelId != '-1'
  5509. ) {
  5510. GradebookUtils::create_default_course_gradebook(
  5511. $courseCode,
  5512. $modelId
  5513. );
  5514. }
  5515. }
  5516. }
  5517. /**
  5518. * Helper function to check if there is a course template and, if so, to
  5519. * copy the template as basis for the new course
  5520. * @param string $courseCode Course code
  5521. * @param int $courseTemplate 0 if no course template is defined
  5522. */
  5523. public static function useTemplateAsBasisIfRequired($courseCode, $courseTemplate)
  5524. {
  5525. $template = api_get_setting('course_creation_use_template');
  5526. $teacherCanSelectCourseTemplate = api_get_setting('teacher_can_select_course_template') === 'true';
  5527. $courseTemplate = isset($courseTemplate) ? intval($courseTemplate) : 0;
  5528. $useTemplate = false;
  5529. if ($teacherCanSelectCourseTemplate && $courseTemplate) {
  5530. $useTemplate = true;
  5531. $originCourse = api_get_course_info_by_id($courseTemplate);
  5532. } elseif (!empty($template)) {
  5533. $useTemplate = true;
  5534. $originCourse = api_get_course_info_by_id($template);
  5535. }
  5536. if ($useTemplate) {
  5537. // Include the necessary libraries to generate a course copy
  5538. // Call the course copy object
  5539. $originCourse['official_code'] = $originCourse['code'];
  5540. $cb = new CourseBuilder(null, $originCourse);
  5541. $course = $cb->build(null, $originCourse['code']);
  5542. $cr = new CourseRestorer($course);
  5543. $cr->set_file_option();
  5544. $cr->restore($courseCode);
  5545. }
  5546. }
  5547. /**
  5548. * Helper method to get the number of users defined with a specific course extra field
  5549. * @param string $name Field title
  5550. * @param string $tableExtraFields The extra fields table name
  5551. * @param string $tableUserFieldValues The user extra field value table name
  5552. * @return int The number of users with this extra field with a specific value
  5553. */
  5554. public static function getCountRegisteredUsersWithCourseExtraField(
  5555. $name,
  5556. $tableExtraFields = '',
  5557. $tableUserFieldValues = ''
  5558. ) {
  5559. if (empty($tableExtraFields)) {
  5560. $tableExtraFields = Database::get_main_table(TABLE_EXTRA_FIELD);
  5561. }
  5562. if (empty($tableUserFieldValues)) {
  5563. $tableUserFieldValues = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5564. }
  5565. $registered_users_with_extra_field = 0;
  5566. if (!empty($name) && $name != '-') {
  5567. $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
  5568. $name = Database::escape_string($name);
  5569. $sql = "SELECT count(v.item_id) as count
  5570. FROM $tableUserFieldValues v
  5571. INNER JOIN $tableExtraFields f
  5572. ON (f.id = v.field_id)
  5573. WHERE value = '$name' AND extra_field_type = $extraFieldType";
  5574. $result_count = Database::query($sql);
  5575. if (Database::num_rows($result_count)) {
  5576. $row_count = Database::fetch_array($result_count);
  5577. $registered_users_with_extra_field = $row_count['count'];
  5578. }
  5579. }
  5580. return $registered_users_with_extra_field;
  5581. }
  5582. /**
  5583. * Check if a specific access-url-related setting is a problem or not
  5584. * @param array $_configuration The $_configuration array
  5585. * @param int $accessUrlId The access URL ID
  5586. * @param string $param
  5587. * @param string $msgLabel
  5588. * @return bool|string
  5589. */
  5590. private static function checkCreateCourseAccessUrlParam($_configuration, $accessUrlId, $param, $msgLabel)
  5591. {
  5592. if (isset($_configuration[$accessUrlId][$param]) && $_configuration[$accessUrlId][$param] > 0) {
  5593. $num = self::count_courses($accessUrlId);
  5594. if ($num >= $_configuration[$accessUrlId][$param]) {
  5595. api_warn_hosting_contact($param);
  5596. Display::addFlash(
  5597. Display::return_message($msgLabel)
  5598. );
  5599. }
  5600. }
  5601. return false;
  5602. }
  5603. /**
  5604. * Fill course with all necessary items
  5605. * @param array $courseInfo Course info array
  5606. * @param array $params Parameters from the course creation form
  5607. * @param int $authorId
  5608. * @return void
  5609. */
  5610. private static function fillCourse($courseInfo, $params, $authorId = 0)
  5611. {
  5612. $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
  5613. AddCourse::prepare_course_repository($courseInfo['directory'], $courseInfo['code']);
  5614. AddCourse::fill_db_course(
  5615. $courseInfo['real_id'],
  5616. $courseInfo['directory'],
  5617. $courseInfo['course_language'],
  5618. $params['exemplary_content'],
  5619. $authorId
  5620. );
  5621. if (isset($params['gradebook_model_id'])) {
  5622. self::createDefaultGradebook($params['gradebook_model_id'], $courseInfo['code']);
  5623. }
  5624. // If parameter defined, copy the contents from a specific
  5625. // template course into this new course
  5626. if (isset($params['course_template'])) {
  5627. self::useTemplateAsBasisIfRequired($courseInfo['id'], $params['course_template']);
  5628. }
  5629. $params['course_code'] = $courseInfo['code'];
  5630. $params['item_id'] = $courseInfo['real_id'];
  5631. $courseFieldValue = new ExtraFieldValue('course');
  5632. $courseFieldValue->saveFieldValues($params);
  5633. }
  5634. /**
  5635. * Get the course categories form a course list
  5636. * @param array $courseList
  5637. * @return array
  5638. */
  5639. public static function getCourseCategoriesFromCourseList(array $courseList)
  5640. {
  5641. $allCategories = array_column($courseList, 'category');
  5642. $categories = array_unique($allCategories);
  5643. sort($categories);
  5644. return $categories;
  5645. }
  5646. /**
  5647. * @return int
  5648. */
  5649. public static function getCountOpenCourses()
  5650. {
  5651. $visibility = [
  5652. COURSE_VISIBILITY_REGISTERED,
  5653. COURSE_VISIBILITY_OPEN_PLATFORM,
  5654. COURSE_VISIBILITY_OPEN_WORLD
  5655. ];
  5656. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  5657. $sql = "SELECT count(id) count
  5658. FROM $table
  5659. WHERE visibility IN (".implode(',', $visibility).")";
  5660. $result = Database::query($sql);
  5661. $row = Database::fetch_array($result);
  5662. return $row['count'];
  5663. }
  5664. /**
  5665. * @return int
  5666. */
  5667. public static function getCountExercisesFromOpenCourse()
  5668. {
  5669. $visibility = [
  5670. COURSE_VISIBILITY_REGISTERED,
  5671. COURSE_VISIBILITY_OPEN_PLATFORM,
  5672. COURSE_VISIBILITY_OPEN_WORLD
  5673. ];
  5674. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  5675. $tableExercise = Database::get_course_table(TABLE_QUIZ_TEST);
  5676. $sql = "SELECT count(e.iid) count
  5677. FROM $table c INNER JOIN $tableExercise e
  5678. ON (c.id = e.c_id)
  5679. WHERE e.active <> -1 AND visibility IN (".implode(',', $visibility).")";
  5680. $result = Database::query($sql);
  5681. $row = Database::fetch_array($result);
  5682. return $row['count'];
  5683. }
  5684. }