course.lib.php 248 KB

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