course.lib.php 233 KB

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