course.lib.php 220 KB

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