course.lib.php 243 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291
  1. <?php
  2. /* For licensing terms, see /license.txt*/
  3. use Chamilo\CourseBundle\ToolChain;
  4. use Chamilo\CoreBundle\Entity\Course;
  5. use Chamilo\CourseBundle\Entity\CTool;
  6. use Chamilo\CourseBundle\Manager\SettingsManager;
  7. use Chamilo\CoreBundle\Framework\Container;
  8. /**
  9. * Class CourseManager
  10. *
  11. * This is the course library for Chamilo.
  12. *
  13. * All main course functions should be placed here.
  14. *
  15. *
  16. * The implementation changed, initially a course was a real course
  17. * if target_course_code was 0 , this was changed to NULL.
  18. * There are probably some places left with the wrong code.
  19. *
  20. * @package chamilo.library
  21. */
  22. class CourseManager
  23. {
  24. const MAX_COURSE_LENGTH_CODE = 40;
  25. //This constant is used to show separate user names in the course list (userportal), footer, etc
  26. const USER_SEPARATOR = ' |';
  27. public $columns = array();
  28. public static $toolList;
  29. public static $courseSettingsManager;
  30. public static $em;
  31. private static $manager;
  32. /**
  33. * @param ToolChain $toolList
  34. */
  35. public static function setToolList($toolList)
  36. {
  37. self::$toolList = $toolList;
  38. }
  39. /**
  40. * @return ToolChain
  41. */
  42. public static function getToolList()
  43. {
  44. return self::$toolList;
  45. }
  46. /**
  47. * @return SettingsManager
  48. */
  49. public static function getCourseSettingsManager()
  50. {
  51. return self::$courseSettingsManager;
  52. }
  53. /**
  54. * @param SettingsManager $courseSettingsManager
  55. */
  56. public static function setCourseSettingsManager($courseSettingsManager)
  57. {
  58. self::$courseSettingsManager = $courseSettingsManager;
  59. }
  60. /**
  61. * @param \Doctrine\ORM\EntityManager
  62. */
  63. public static function setEntityManager($em)
  64. {
  65. self::$em = $em;
  66. }
  67. /**
  68. * @return \Doctrine\ORM\EntityManager
  69. */
  70. public static function getEntityManager()
  71. {
  72. return self::$em;
  73. }
  74. /**
  75. * @return Chamilo\CoreBundle\Entity\CourseManager
  76. */
  77. public static function setCourseManager($manager)
  78. {
  79. self::$manager = $manager;
  80. }
  81. /**
  82. * @return Chamilo\CoreBundle\Entity\CourseManager
  83. */
  84. public static function getCourseManager()
  85. {
  86. return self::$manager;
  87. }
  88. /**
  89. * Creates a course
  90. * @param array with the columns in the main.course table
  91. * @param mixed false if the course was not created, array with the course info
  92. * @return mixed False on error, or an array with course attributes on success
  93. * @todo remove globals
  94. * @assert () === false
  95. */
  96. public static function create_course($params)
  97. {
  98. global $_configuration;
  99. // Check portal limits
  100. $access_url_id = 1;
  101. if (api_get_multiple_access_url()) {
  102. $access_url_id = api_get_current_access_url_id();
  103. }
  104. if (is_array($_configuration[$access_url_id]) &&
  105. isset($_configuration[$access_url_id]['hosting_limit_courses']) &&
  106. $_configuration[$access_url_id]['hosting_limit_courses'] > 0
  107. ) {
  108. $num = self::count_courses();
  109. if ($num >= $_configuration[$access_url_id]['hosting_limit_courses']) {
  110. return api_set_failure('PortalCoursesLimitReached');
  111. }
  112. }
  113. if (empty($params['title'])) {
  114. return false;
  115. }
  116. if (empty($params['wanted_code'])) {
  117. $params['wanted_code'] = $params['title'];
  118. // Check whether the requested course code has already been occupied.
  119. $params['wanted_code'] = self::generate_course_code(api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE));
  120. }
  121. // Create the course keys
  122. $keys = self::define_course_keys($params['wanted_code']);
  123. $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
  124. if (count($keys)) {
  125. $params['code'] = $keys['currentCourseCode'];
  126. $params['visual_code'] = $keys['currentCourseId'];
  127. $params['directory'] = $keys['currentCourseRepository'];
  128. $course_info = api_get_course_info($params['code']);
  129. if (empty($course_info)) {
  130. $course_id = self::register_course($params);
  131. $course_info = api_get_course_info_by_id($course_id);
  132. if (!empty($course_info)) {
  133. self::prepare_course_repository($course_info['directory'], $course_info['code']);
  134. self::fill_db_course($course_id, $course_info['directory'], $course_info['course_language'], $params['exemplary_content']);
  135. //Create an empty gradebook
  136. if (isset($params['create_gradebook_evaluation']) && $params['create_gradebook_evaluation'] == true) {
  137. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  138. $category_id = create_default_course_gradebook($course_info['code']);
  139. if ($category_id && isset($params['gradebook_params'])) {
  140. $eval = new Evaluation();
  141. $eval->set_name($params['gradebook_params']['name']);
  142. $eval->set_user_id($params['gradebook_params']['user_id']);
  143. $eval->set_course_code($course_info['code']);
  144. $eval->set_category_id($category_id);
  145. $eval->set_weight($params['gradebook_params']['weight']);
  146. $eval->set_max($params['gradebook_params']['max']);
  147. $eval->set_visible(0);
  148. $eval->add();
  149. }
  150. }
  151. if (api_get_setting('gradebook.gradebook_enable_grade_model') == 'true') {
  152. //Create gradebook_category for the new course and add a gradebook model for the course
  153. if (isset($params['gradebook_model_id']) && !empty($params['gradebook_model_id']) && $params['gradebook_model_id'] != '-1') {
  154. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  155. create_default_course_gradebook($course_info['code'], $params['gradebook_model_id']);
  156. }
  157. }
  158. //Saving extra course fields
  159. $field_value = new ExtraFieldValue('course');
  160. $params['course_code'] = $course_info['code'];
  161. $field_value->save_field_values($params);
  162. return $course_info;
  163. }
  164. } else {
  165. //Course already exists
  166. if (isset($params['return_item_if_already_exists']) && $params['return_item_if_already_exists']) {
  167. return $course_info;
  168. }
  169. }
  170. }
  171. return false;
  172. }
  173. /**
  174. * Updates a course with the given array of attributes
  175. * @param array Array of attributes
  176. * @return array Array of course attributes
  177. * @assert () === false
  178. */
  179. public static function update($params)
  180. {
  181. if (!is_array($params) or count($params)<1) {
  182. return false;
  183. }
  184. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  185. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  186. $course_code = $params['code'];
  187. $courseInfo = api_get_course_info($course_code);
  188. $visual_code = $params['visual_code'];
  189. $field_value = new ExtraFieldValue('course');
  190. $params['course_code'] = $course_code;
  191. $field_value->save_field_values($params);
  192. /*$tutor_id = $params['tutor_name'];
  193. $tutor_name=$platform_teachers[$tutor_id];*/
  194. $teachers = $params['group']['course_teachers'];
  195. $title = $params['title'];
  196. $category_code = $params['category_code'];
  197. $department_name = $params['department_name'];
  198. $department_url = $params['department_url'];
  199. $course_language = $params['course_language'];
  200. $course['disk_quota'] = $params['disk_quota']*1024*1024;
  201. $disk_quota = $params['disk_quota'];
  202. $visibility = $params['visibility'];
  203. $subscribe = $params['subscribe'];
  204. $unsubscribe = $params['unsubscribe'];
  205. if (!stristr($department_url, 'http://')) {
  206. $department_url = 'http://'.$department_url;
  207. }
  208. //tutor_name='".Database::escape_string($tutor_name)."',
  209. $sql = "UPDATE $course_table SET
  210. course_language='".Database::escape_string($course_language)."',
  211. title='".Database::escape_string($title)."',
  212. category_code='".Database::escape_string($category_code)."',
  213. visual_code='".Database::escape_string($visual_code)."',
  214. department_name='".Database::escape_string($department_name)."',
  215. department_url='".Database::escape_string($department_url)."',
  216. disk_quota='".Database::escape_string($disk_quota)."',
  217. visibility = '".Database::escape_string($visibility)."',
  218. subscribe = '".Database::escape_string($subscribe)."',
  219. unsubscribe='".Database::escape_string($unsubscribe)."'
  220. WHERE code='".Database::escape_string($course_code)."'";
  221. Database::query($sql);
  222. //Delete only teacher relations that doesn't match the selected teachers
  223. $cond='';
  224. if (count($teachers)>0) {
  225. foreach($teachers as $key) {
  226. $cond.=" AND user_id<>'".$key."'";
  227. }
  228. }
  229. $sql = 'DELETE FROM '.$course_user_table.' WHERE c_id = "'.Database::escape_string($courseInfo['real_id']).'" AND status="1"'.$cond;
  230. Database::query($sql);
  231. if (count($teachers)>0) {
  232. foreach ($teachers as $key) {
  233. //We check if the teacher is already subscribed in this course
  234. $sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND c_id = "'.$courseInfo['real_id'].'" ';
  235. $result = Database::query($sql_select_teacher);
  236. if (Database::num_rows($result) == 1) {
  237. $sql = 'UPDATE '.$course_user_table.' SET status = "1" WHERE c_id = "'.$courseInfo['real_id'].'" AND user_id = "'.$key.'" ';
  238. } else {
  239. $sql = "INSERT INTO ".$course_user_table . " SET
  240. c_id = '".Database::escape_string($courseInfo['real_id']). "',
  241. user_id = '".$key . "',
  242. status = '1',
  243. role = '',
  244. tutor_id = '0',
  245. sort = '0',
  246. user_course_cat = '0'";
  247. }
  248. Database::query($sql);
  249. }
  250. }
  251. //user_id = '".$tutor_id . "',
  252. $sql = "INSERT IGNORE INTO ".$course_user_table . " SET
  253. course_code = '".Database::escape_string($course_code). "',
  254. status = '1',
  255. role = '',
  256. tutor_id='0',
  257. sort='0',
  258. user_course_cat='0'";
  259. Database::query($sql);
  260. $course_info = api_get_course_info($course_code);
  261. return $course_info;
  262. }
  263. /**
  264. * Returns all the information of a given course code from the course table
  265. * @param string $course_code, the course code
  266. * @return an array with all the fields of the course table
  267. * @deprecated use api_get_course_info()
  268. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  269. * @assert (array(1,2,3)) === false
  270. */
  271. public static function get_course_information($course_code)
  272. {
  273. return Database::fetch_array(Database::query(
  274. "SELECT *, id as real_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  275. WHERE code='".Database::escape_string($course_code)."'"),'ASSOC'
  276. );
  277. }
  278. /**
  279. * Returns all the information of a given coursecode from the course
  280. * table by it integer ID
  281. * @param int the course id
  282. * @return an array with all the fields of the course table
  283. * @assert (-1) === false
  284. */
  285. public static function get_course_information_by_id($course_id)
  286. {
  287. return Database::select('*, id as real_id', Database::get_main_table(TABLE_MAIN_COURSE), array('where'=>array('id = ?' =>intval($course_id))),'first');
  288. }
  289. /**
  290. * Returns a list of courses. Should work with quickform syntax
  291. * @param integer Offset (from the 7th = '6'). Optional.
  292. * @param integer Number of results we want. Optional.
  293. * @param string The column we want to order it by. Optional, defaults to first column.
  294. * @param string The direction of the order (ASC or DESC). Optional, defaults to ASC.
  295. * @param string The visibility of the course, or all by default.
  296. * @param string If defined, only return results for which the course *title* begins with this string
  297. * @return mixed Array of courses details, or false on error
  298. * @assert (array(1,2,3)) === false
  299. */
  300. public static function get_courses_list($from = 0, $howmany = 0, $orderby = 1, $orderdirection = 'ASC', $visibility = -1, $startwith = '')
  301. {
  302. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." ";
  303. if (!empty($startwith)) {
  304. $sql .= "WHERE title LIKE '".Database::escape_string($startwith)."%' ";
  305. if ($visibility !== -1 && $visibility == strval(intval($visibility))) {
  306. $sql .= " AND visibility = $visibility ";
  307. }
  308. } else {
  309. $sql .= "WHERE 1 ";
  310. if ($visibility !== -1 && $visibility == strval(intval($visibility))) {
  311. $sql .= " AND visibility = $visibility ";
  312. }
  313. }
  314. if (!empty($orderby)) {
  315. $sql .= " ORDER BY ".Database::escape_string($orderby)." ";
  316. } else {
  317. $sql .= " ORDER BY 1 ";
  318. }
  319. if (!in_array($orderdirection, array('ASC', 'DESC'))) {
  320. $sql .= 'ASC';
  321. } else {
  322. $sql .= Database::escape_string($orderdirection);
  323. }
  324. if (!empty($howmany) && is_int($howmany) and $howmany > 0) {
  325. $sql .= ' LIMIT '.Database::escape_string($howmany);
  326. } else {
  327. $sql .= ' LIMIT 1000000'; //virtually no limit
  328. }
  329. if (!empty($from)) {
  330. $from = intval($from);
  331. $sql .= ' OFFSET '.Database::escape_string($from);
  332. } else {
  333. $sql .= ' OFFSET 0';
  334. }
  335. return Database::store_result(Database::query($sql));
  336. }
  337. /**
  338. * Returns the access settings of the course:
  339. * which visibility;
  340. * wether subscribing is allowed;
  341. * wether unsubscribing is allowed.
  342. *
  343. * @param string $course_code, the course code
  344. * @todo for more consistency: use course_info call from database API
  345. * @return an array with int fields "visibility", "subscribe", "unsubscribe"
  346. * @assert () === false
  347. */
  348. public static function get_access_settings($course_code)
  349. {
  350. return Database::fetch_array(Database::query(
  351. "SELECT visibility, subscribe, unsubscribe from ".Database::get_main_table(TABLE_MAIN_COURSE)."
  352. WHERE code = '".Database::escape_string($course_code)."'")
  353. );
  354. }
  355. /**
  356. * Returns the status of a user in a course, which is COURSEMANAGER
  357. * or STUDENT.
  358. * @param int User ID
  359. * @param string Course code
  360. * @return int the status of the user in that course
  361. * @assert () === false
  362. */
  363. public static function get_user_in_course_status($user_id, $courseId)
  364. {
  365. $result = Database::fetch_array(Database::query(
  366. "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  367. WHERE c_id = '".Database::escape_string($courseId)."' AND user_id = ".Database::escape_string($user_id))
  368. );
  369. return $result['status'];
  370. }
  371. /**
  372. * Gets the ID of a course tutor for a user, given the user and the course
  373. * @param int User ID
  374. * @param string Course code
  375. * @return mixed The tutor ID
  376. * @assert () === false
  377. */
  378. public static function get_tutor_in_course_status($user_id, $courseId)
  379. {
  380. $result = Database::fetch_array(Database::query(
  381. "SELECT tutor_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  382. WHERE c_id = '".Database::escape_string($courseId)."' AND user_id = ".Database::escape_string($user_id))
  383. );
  384. return $result['tutor_id'];
  385. }
  386. /**
  387. * Unsubscribe one or more users from a course
  388. * @param mixed user_id or an array with user ids
  389. * @param int session id
  390. * @param int course id
  391. * @return mixed False on user ID not found, void otherwise
  392. * @assert () === false
  393. */
  394. public static function unsubscribe_user($user_id, $courseId, $session_id = 0)
  395. {
  396. if (!isset($user_id)) {
  397. return false;
  398. }
  399. if (!is_array($user_id)) {
  400. $user_id = array($user_id);
  401. }
  402. if (count($user_id) == 0) {
  403. return false;
  404. }
  405. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  406. if (!empty($session_id)) {
  407. $session_id = intval($session_id);
  408. } else {
  409. $session_id = api_get_session_id();
  410. }
  411. $user_list = array();
  412. //Cleaning the $user_id variable
  413. if (is_array($user_id)) {
  414. $new_user_id_list = array();
  415. foreach ($user_id as $my_user_id) {
  416. $new_user_id_list[]= intval($my_user_id);
  417. }
  418. $new_user_id_list = array_filter($new_user_id_list);
  419. $user_list = $new_user_id_list;
  420. $user_ids = implode(',', $new_user_id_list);
  421. } else {
  422. $user_ids = intval($user_id);
  423. $user_list[] = $user_id;
  424. }
  425. $courseId = intval($courseId);
  426. $courseInfo = api_get_course_info_by_id($courseId);
  427. $courseCode = $courseInfo['code'];
  428. // Unsubscribe user from all groups in the course.
  429. Database::query("DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")");
  430. Database::query("DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")");
  431. // Erase user student publications (works) in the course - by André Boivin
  432. //@todo field student_publication.author should be the user id
  433. $sqlu = "SELECT * FROM $table_user WHERE user_id IN (".$user_ids.")";
  434. $resu = Database::query($sqlu);
  435. $username = Database::fetch_array($resu,'ASSOC');
  436. $userfirstname = $username['firstname'];
  437. $userlastname = $username['lastname'];
  438. $publication_name = $userfirstname.' '.$userlastname ;
  439. $table_course_user_publication = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  440. $sql = "DELETE FROM $table_course_user_publication WHERE c_id = $courseId AND author = '".Database::escape_string($publication_name)."'";
  441. Database::query($sql);
  442. // Unsubscribe user from all blogs in the course.
  443. Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_REL_USER)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")");
  444. Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")");
  445. //Deleting users in forum_notification and mailqueue course tables
  446. $sql_delete_forum_notification = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_NOTIFICATION)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")";
  447. Database::query($sql_delete_forum_notification);
  448. $sql_delete_mail_queue = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_MAIL_QUEUE)." WHERE c_id = $courseId AND user_id IN (".$user_ids.")";
  449. Database::query($sql_delete_mail_queue);
  450. $item_property_lp_subscription = "DELETE FROM ".Database::get_course_table(TABLE_ITEM_PROPERTY)."
  451. WHERE lastedit_type = 'LearnpathSubscription' AND tool = 'learnpath' AND c_id = $courseId AND to_user_id IN (".$user_ids.")";
  452. Database::query($item_property_lp_subscription);
  453. // Unsubscribe user from the course.
  454. if (!empty($session_id)) {
  455. // Delete in table session_rel_course_rel_user
  456. Database::query("DELETE FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  457. WHERE id_session ='".$session_id."' AND c_id = '".$courseId."' AND id_user IN ($user_ids)");
  458. foreach ($user_id as $uid) {
  459. // check if a user is register in the session with other course
  460. $sql = "SELECT id_user FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." WHERE id_session='$session_id' AND id_user='$uid'";
  461. $rs = Database::query($sql);
  462. if (Database::num_rows($rs) == 0) {
  463. // Delete in table session_rel_user
  464. Database::query("DELETE FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  465. WHERE id_session ='".$session_id."' AND id_user='$uid' AND relation_type<>".SESSION_RELATION_TYPE_RRHH."");
  466. }
  467. }
  468. // Update the table session
  469. $row = Database::fetch_array(Database::query("SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  470. WHERE id_session = '".$session_id."' AND relation_type<>".SESSION_RELATION_TYPE_RRHH." "));
  471. $count = $row[0]; // number of users by session
  472. $result = Database::query("UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION)." SET nbr_users = '$count'
  473. WHERE id = '".$session_id."'");
  474. // Update the table session_rel_course
  475. $row = Database::fetch_array(@Database::query("SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  476. WHERE id_session = '$session_id' AND c_id = '$courseId' AND status<>2" ));
  477. $count = $row[0]; // number of users by session and course
  478. $result = @Database::query("UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE)." SET nbr_users = '$count' WHERE id_session = '$session_id' AND c_id = '$courseId' ");
  479. } else {
  480. Database::query("DELETE FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  481. WHERE user_id IN (".$user_ids.") AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND c_id = '".$courseId."'");
  482. // add event to system log
  483. $user_id = api_get_user_id();
  484. Event::addEvent(LOG_UNSUBSCRIBE_USER_FROM_COURSE, LOG_COURSE_CODE, $courseCode, api_get_utc_datetime(), $user_id);
  485. foreach ($user_list as $user_id_to_delete) {
  486. $user_info = api_get_user_info($user_id_to_delete);
  487. Event::addEvent(LOG_UNSUBSCRIBE_USER_FROM_COURSE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id);
  488. }
  489. }
  490. }
  491. /**
  492. * Subscribe a user to a course. No checks are performed here to see if
  493. * course subscription is allowed.
  494. * @param int User ID
  495. * @param string Course code
  496. * @param int Status (STUDENT, COURSEMANAGER, COURSE_ADMIN, NORMAL_COURSE_MEMBER)
  497. * @return bool True on success, false on failure
  498. * @see add_user_to_course
  499. * @assert ('', '') === false
  500. */
  501. public static function subscribe_user($user_id, $course_code, $status = STUDENT, $session_id = 0)
  502. {
  503. if ($user_id != strval(intval($user_id))) {
  504. return false; //detected possible SQL injection
  505. }
  506. $course_code = Database::escape_string($course_code);
  507. $courseInfo = api_get_course_info($course_code);
  508. $courseId = $courseInfo['real_id'];
  509. if (empty($user_id) || empty ($course_code)) {
  510. return false;
  511. }
  512. if (!empty($session_id)) {
  513. $session_id = intval($session_id);
  514. } else {
  515. $session_id = api_get_session_id();
  516. }
  517. $status = ($status == STUDENT || $status == COURSEMANAGER) ? $status : STUDENT;
  518. //$role_id = ($status == COURSEMANAGER) ? COURSE_ADMIN : NORMAL_COURSE_MEMBER;
  519. // A preliminary check whether the user has bben already registered on the platform.
  520. if (Database::num_rows(@Database::query("SELECT status FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  521. WHERE user_id = '$user_id' ")) == 0) {
  522. return false; // The user has not been registered to the platform.
  523. }
  524. // Check whether the user has not been already subscribed to the course.
  525. if (empty($session_id)) {
  526. if (Database::num_rows(@Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  527. WHERE user_id = '$user_id' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND c_id = ".$courseId)) > 0) {
  528. return false; // The user has been already subscribed to the course.
  529. }
  530. }
  531. if (!empty($session_id)) {
  532. // Check whether the user has not already been stored in the session_rel_course_user table
  533. if (Database::num_rows(@Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  534. WHERE c_id = '".$courseId."'
  535. AND id_session ='".$session_id."'
  536. AND id_user = '".$user_id."'")) > 0) {
  537. return false;
  538. }
  539. // check if the user is registered in the session with other course
  540. $sql = "SELECT id_user FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." WHERE id_session='".$session_id."' AND id_user='$user_id'";
  541. $rs = Database::query($sql);
  542. if (Database::num_rows($rs) == 0) {
  543. // Check whether the user has not already been stored in the session_rel_user table
  544. if (Database::num_rows(@Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  545. WHERE id_session ='".$session_id."' AND id_user = '".$user_id."' AND relation_type<>".SESSION_RELATION_TYPE_RRHH." ")) > 0) {
  546. return false;
  547. }
  548. }
  549. // Add him/her in the table session_rel_course_rel_user
  550. @Database::query("INSERT INTO ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  551. SET id_session ='".$session_id."',
  552. c_id = '".$courseId."',
  553. id_user = '".$user_id."'");
  554. // Add him/her in the table session_rel_user
  555. @Database::query("INSERT INTO ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."SET id_session ='".$session_id."', id_user = '".$user_id."'");
  556. // Update the table session
  557. $row = Database::fetch_array(@Database::query("SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_USER)."
  558. WHERE id_session = '".$session_id."' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""));
  559. $count = $row[0]; // number of users by session
  560. $result = @Database::query("UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION)." SET nbr_users = '$count' WHERE id = '".$session_id."'");
  561. // Update the table session_rel_course
  562. $row = Database::fetch_array(@Database::query("SELECT COUNT(*) FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  563. WHERE id_session = '".$session_id."' AND c_id = ".$courseId." AND status <> 2" ));
  564. $count = $row[0]; // number of users by session
  565. $result = @Database::query("UPDATE ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE)." SET nbr_users = '$count'
  566. WHERE id_session = '".$session_id."' AND c_id = '$courseId' ");
  567. } else {
  568. $course_sort = self::userCourseSort($user_id, $courseId);
  569. $result = @Database::query("INSERT INTO ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  570. SET
  571. c_id = ".$courseId.",
  572. user_id = '$user_id',
  573. status = '".$status."',
  574. sort = '". ($course_sort)."'");
  575. // Add event to the system log
  576. Event::addEvent(LOG_SUBSCRIBE_USER_TO_COURSE, LOG_COURSE_CODE, $course_code, api_get_utc_datetime(), api_get_user_id());
  577. $user_info = api_get_user_info($user_id);
  578. Event::addEvent(LOG_SUBSCRIBE_USER_TO_COURSE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), api_get_user_id());
  579. }
  580. return (bool)$result;
  581. }
  582. /**
  583. * Get the course id based on the original id and field name in the extra fields. Returns 0 if course was not found
  584. *
  585. * @param string Original course id
  586. * @param string Original field name
  587. * @return int Course id
  588. * @assert ('', '') === false
  589. */
  590. public static function get_course_code_from_original_id($original_course_id_value, $original_course_id_name) {
  591. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  592. $table_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  593. $sql = "SELECT course_code FROM $table_field cf INNER JOIN $t_cfv cfv ON cfv.field_id=cf.id
  594. WHERE field_variable='$original_course_id_name' AND field_value='$original_course_id_value'";
  595. $res = Database::query($sql);
  596. $row = Database::fetch_object($res);
  597. if ($row) {
  598. return $row->course_code;
  599. } else {
  600. return 0;
  601. }
  602. }
  603. /**
  604. * Gets the course code from the course id. Returns null if course id was not found
  605. *
  606. * @param int Course id
  607. * @return string Course code
  608. * @assert ('') === false
  609. */
  610. public static function get_course_code_from_course_id($id)
  611. {
  612. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  613. $id = intval($id);
  614. $sql = "SELECT code FROM $table WHERE id = '$id' ";
  615. $res = Database::query($sql);
  616. $row = Database::fetch_object($res);
  617. if ($row) {
  618. return $row->code;
  619. } else {
  620. return null;
  621. }
  622. }
  623. /**
  624. * Subscribe a user $user_id to a course $course_code.
  625. * @author Hugues Peeters
  626. * @author Roan Embrechts
  627. *
  628. * @param int $user_id the id of the user
  629. * @param int $courseId the course code
  630. * @param string $status (optional) The user's status in the course
  631. *
  632. * @return boolean true if subscription succeeds, boolean false otherwise.
  633. * @assert ('', '') === false
  634. */
  635. public static function add_user_to_course($user_id, $courseId, $status = STUDENT) {
  636. $debug = false;
  637. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  638. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  639. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  640. $status = ($status == STUDENT || $status == COURSEMANAGER) ? $status : STUDENT;
  641. if (empty($user_id) || empty($courseId) || ($user_id != strval(intval($user_id)))) {
  642. return false;
  643. }
  644. $courseId = Database::escape_string($courseId);
  645. // Check in advance whether the user has already been registered on the platform.
  646. if (Database::num_rows(Database::query("SELECT status FROM ".$user_table." WHERE user_id = '$user_id' ")) == 0) {
  647. if ($debug) error_log('The user has not been registered to the platform');
  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. if (Database::num_rows(Database::query("SELECT * FROM ".$course_user_table." WHERE user_id = '$user_id' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND c_id = '$courseId'")) > 0) {
  652. if ($debug) error_log('The user has been already subscribed to the course');
  653. return false; // The user has been subscribed to the course.
  654. }
  655. // Check in advance whether subscription is allowed or not for this course.
  656. if (Database::num_rows(Database::query("SELECT code, visibility FROM ".$course_table." WHERE id = '$courseId' AND subscribe = '".SUBSCRIBE_NOT_ALLOWED."'")) > 0) {
  657. if ($debug) error_log('Subscription is not allowed for this course');
  658. return false; // Subscription is not allowed for this course.
  659. }
  660. // Ok, subscribe the user.
  661. $max_sort = api_max_sort_value('0', $user_id);
  662. return (bool)Database::query("INSERT INTO ".$course_user_table."
  663. SET c_id = '$courseId',
  664. user_id = '$user_id',
  665. status = '".$status."',
  666. sort = '". ($max_sort + 1)."'");
  667. }
  668. /**
  669. * @return true if there already are one or more courses
  670. * with the same code OR visual_code (visualcode), false otherwise
  671. */
  672. public static function course_code_exists($wanted_course_code) {
  673. $wanted_course_code = Database::escape_string($wanted_course_code);
  674. $result = Database::fetch_array(Database::query("SELECT COUNT(*) as number FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  675. WHERE code = '$wanted_course_code' OR visual_code = '$wanted_course_code'"));
  676. return $result['number'] > 0;
  677. }
  678. /**
  679. * @return an array with the course info of all real courses on the platform
  680. */
  681. public static function get_real_course_list() {
  682. $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE target_course_code IS NULL");
  683. $real_course_list = array();
  684. while ($result = Database::fetch_array($sql_result)) {
  685. $real_course_list[$result['code']] = $result;
  686. }
  687. return $real_course_list;
  688. }
  689. /**
  690. * Get course list as coach
  691. *
  692. * @param int user id
  693. * @return array course list
  694. *
  695. * */
  696. public static function get_course_list_as_coach($user_id, $include_courses_in_sessions = false) {
  697. //1. Getting courses as teacher (No session)
  698. $courses_temp = CourseManager::get_course_list_of_user_as_course_admin($user_id);
  699. $courses_as_admin = array();
  700. if (!empty($courses_temp)) {
  701. foreach($courses_temp as $course_item) {
  702. $courses_as_admin[0][$course_item['real_id']] = $course_item['real_id'];
  703. }
  704. }
  705. //2. Include courses in sessions
  706. if ($include_courses_in_sessions) {
  707. $sessions = SessionManager::get_sessions_coached_by_user($user_id);
  708. if (!empty($sessions)) {
  709. foreach($sessions as $session_item) {
  710. $courses = Tracking :: get_courses_followed_by_coach($user_id, $session_item['id']);
  711. if (is_array($courses)) {
  712. foreach($courses as $course_item) {
  713. $courses_as_admin[$session_item['id']][$course_item] = $course_item;
  714. }
  715. }
  716. }
  717. }
  718. }
  719. return $courses_as_admin;
  720. }
  721. /**
  722. * @param int $user_id
  723. * @param bool $include_sessions
  724. * @return array
  725. */
  726. public static function get_user_list_from_courses_as_coach($user_id, $include_sessions = true)
  727. {
  728. $students_in_courses = array();
  729. $sessions = CourseManager::get_course_list_as_coach($user_id, true);
  730. if (!empty($sessions)) {
  731. foreach($sessions as $session_id => $courses) {
  732. if (!$include_sessions) {
  733. if (!empty($session_id)) {
  734. continue;
  735. }
  736. }
  737. if (empty($session_id)) {
  738. foreach($courses as $course_code) {
  739. $students_in_course = CourseManager::get_user_list_from_course_code($course_code);
  740. foreach($students_in_course as $user_item) {
  741. //Only students
  742. if ($user_item['status_rel'] == STUDENT)
  743. $students_in_courses[$user_item['user_id']] = $user_item['user_id'];
  744. }
  745. }
  746. } else {
  747. $students_in_course = SessionManager::get_users_by_session($session_id, '0');
  748. if (is_array($students_in_course)) {
  749. foreach ($students_in_course as $user_item) {
  750. if ($user_item['moved_to'] == 0) {
  751. $students_in_courses[$user_item['user_id']] = $user_item['user_id'];
  752. }
  753. }
  754. }
  755. }
  756. }
  757. }
  758. $students = Tracking :: get_student_followed_by_coach($user_id);
  759. if (!empty($students_in_courses)) {
  760. if (!empty($students)) {
  761. $students = array_merge($students, $students_in_courses);
  762. } else {
  763. $students = $students_in_courses;
  764. }
  765. }
  766. if (!empty($students)) {
  767. $students = array_unique($students);
  768. }
  769. return $students;
  770. }
  771. /**
  772. * @param int $user_id
  773. * @return an array with the course info of all the courses (real and virtual)
  774. * of which the current user is course admin.
  775. */
  776. public static function get_course_list_of_user_as_course_admin($user_id)
  777. {
  778. if ($user_id != strval(intval($user_id))) {
  779. return array();
  780. }
  781. // Definitions database tables and variables
  782. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  783. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  784. $user_id = intval($user_id);
  785. $data = array();
  786. $sql_nb_cours = "SELECT course_rel_user.c_id,
  787. course.title, course.id,
  788. course.id as real_id
  789. FROM $tbl_course_user as course_rel_user
  790. INNER JOIN $tbl_course as course
  791. ON course.id = course_rel_user.c_id
  792. WHERE course_rel_user.user_id='$user_id' AND course_rel_user.status='1'
  793. ORDER BY course.title";
  794. if (api_get_multiple_access_url()) {
  795. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  796. $access_url_id = api_get_current_access_url_id();
  797. if ($access_url_id != -1) {
  798. $sql_nb_cours = " SELECT course_rel_user.c_id, course.title, course.id, course.id as real_id
  799. FROM $tbl_course_user as course_rel_user
  800. INNER JOIN $tbl_course as course
  801. ON course.id = course_rel_user.c_id
  802. INNER JOIN $tbl_course_rel_access_url course_rel_url
  803. ON (course_rel_url.c_id = course.id)
  804. WHERE access_url_id = $access_url_id AND course_rel_user.user_id='$user_id' AND course_rel_user.status='1'
  805. ORDER BY course.title";
  806. }
  807. }
  808. $result_nb_cours = Database::query($sql_nb_cours);
  809. if (Database::num_rows($result_nb_cours) > 0) {
  810. while ($row = Database::fetch_array($result_nb_cours,'ASSOC')) {
  811. $data[$row['c_id']] = $row;
  812. }
  813. }
  814. return $data;
  815. }
  816. /**
  817. * Check if user is subscribed inside a course
  818. * @param int User id
  819. * @param int course id
  820. * @param bool True for checking inside sessions too, by default is not checked
  821. * @return bool true if the user is registered in the course, false otherwise
  822. */
  823. public static function is_user_subscribed_in_course($user_id, $courseId = null, $in_a_session = false, $session_id = null)
  824. {
  825. $user_id = intval($user_id);
  826. if (empty($session_id)) {
  827. $session_id = api_get_session_id();
  828. } else {
  829. $session_id = intval($session_id);
  830. }
  831. $condition_course_id = null;
  832. if (isset($courseId)) {
  833. $courseId = intval($courseId);
  834. $condition_course_id = ' AND c_id = "'.$courseId.'" ';
  835. }
  836. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  837. WHERE user_id = $user_id AND relation_type<>".COURSE_RELATION_TYPE_RRHH." $condition_course_id ";
  838. $result = Database::fetch_array(Database::query($sql));
  839. if (!empty($result)) {
  840. return true; // The user has been registered in this course.
  841. }
  842. if (!$in_a_session) {
  843. return false; // The user has not been registered in this course.
  844. }
  845. if (Database::num_rows(Database::query('SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
  846. ' WHERE id_user = '.$user_id.' '.$condition_course_id.' ')) > 0) {
  847. return true;
  848. }
  849. if (Database::num_rows(Database::query('SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
  850. ' WHERE id_user = '.$user_id.' AND status=2 '.$condition_course_id.' ')) > 0) {
  851. return true;
  852. }
  853. if (Database::num_rows(Database::query('SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_SESSION).
  854. ' WHERE id='.$session_id.' AND id_coach='.$user_id)) > 0) {
  855. return true;
  856. }
  857. return false;
  858. }
  859. /**
  860. * Is the user a teacher in the given course?
  861. *
  862. * @param int $user_id, the id (int) of the user
  863. * @param int $course_code, the course code
  864. *
  865. * @return true if the user is a teacher in the course, false otherwise
  866. */
  867. public static function is_course_teacher($user_id, $courseId) {
  868. if ($user_id != strval(intval($user_id))) {
  869. return false;
  870. }
  871. $sql_result = Database::query('SELECT status FROM '.Database::get_main_table(TABLE_MAIN_COURSE_USER).
  872. ' WHERE c_id ="'.Database::escape_string($courseId).'" and user_id="'.$user_id.'"');
  873. if (Database::num_rows($sql_result) > 0) {
  874. return Database::result($sql_result, 0, 'status') == 1;
  875. }
  876. return false;
  877. }
  878. /**
  879. * Is the user subscribed in the real course or linked courses?
  880. *
  881. * @param int the id of the user
  882. * @param array info about the course (comes from course table, see database lib)
  883. *
  884. * @return true if the user is registered in the real course or linked courses, false otherwise
  885. */
  886. public static function is_user_subscribed_in_real_or_linked_course ($user_id, $courseId, $session_id = '') {
  887. if ($user_id != strval(intval($user_id))) {
  888. return false;
  889. }
  890. $session_id = intval($session_id);
  891. $courseId = Database::escape_string($courseId);
  892. if ($session_id == '') {
  893. $result = Database::fetch_array(Database::query("SELECT *
  894. FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." course
  895. LEFT JOIN ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." course_user
  896. ON course.id = course_user.c_id
  897. WHERE course_user.user_id = '$user_id' AND
  898. course_user.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
  899. course.id = '$courseId'"));
  900. return !empty($result);
  901. }
  902. // From here we trust session id.
  903. // Is he/she subscribed to the session's course?
  904. // A user?
  905. if (Database::num_rows(Database::query("SELECT id_user
  906. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  907. WHERE id_session='".$session_id."'
  908. AND id_user='$user_id'"))) {
  909. return true;
  910. }
  911. // A course coach?
  912. if (Database::num_rows(Database::query("SELECT id_user
  913. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  914. WHERE id_session='".$session_id."'
  915. AND id_user = '$user_id' AND status = 2
  916. AND c_id ='$courseId'"))) {
  917. return true;
  918. }
  919. // A session coach?
  920. if (Database::num_rows(Database::query("SELECT id_coach
  921. FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." AS session
  922. WHERE session.id='".$session_id."'
  923. AND id_coach='$user_id'"))) {
  924. return true;
  925. }
  926. return false;
  927. }
  928. /**
  929. * Return user info array of all users registered in the specified course
  930. * This only returns the users that are registered in this actual course, not linked courses.
  931. *
  932. * @param string $course_code the code of the course
  933. * @param boolean $with_session determines if the course is used in a session or not
  934. * @param integer $session_id the id of the session
  935. * @param string $limit the LIMIT statement of the sql statement
  936. * @param string $order_by the field to order the users by. Valid values are 'lastname', 'firstname', 'username', 'email', 'official_code' OR a part of a SQL statement that starts with ORDER BY ...
  937. * @param int if using the session_id: 0 or 2 (student, coach), if using session_id = 0 STUDENT or COURSEMANAGER
  938. * @return array
  939. */
  940. public static function get_user_list_from_course_code($course_code = null, $session_id = 0, $limit = null, $order_by = null, $filter_by_status = null, $return_count = null, $add_reports = false, $resumed_report = false, $extra_field = null)
  941. {
  942. // variable initialisation
  943. $session_id = intval($session_id);
  944. $course_code = Database::escape_string($course_code);
  945. $where = array();
  946. // if the $order_by does not contain 'ORDER BY' we have to check if it is a valid field that can be sorted on
  947. if (!strstr($order_by,'ORDER BY')) {
  948. //if (!empty($order_by) AND in_array($order_by, array('lastname', 'firstname', 'username', 'email', 'official_code'))) {
  949. if (!empty($order_by)) {
  950. $order_by = 'ORDER BY '.$order_by;
  951. } else {
  952. $order_by = '';
  953. }
  954. }
  955. $courseInfo = api_get_course_info($course_code);
  956. $courseId = null;
  957. if ($courseInfo) {
  958. $courseId = $courseInfo['real_id'];
  959. }
  960. $filter_by_status_condition = null;
  961. if (!empty($session_id) && !empty($courseId)) {
  962. $sql = 'SELECT DISTINCT user.user_id, session_course_user.status as status_session, user.* ';
  963. $sql .= ' FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
  964. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' as session_course_user
  965. ON user.user_id = session_course_user.id_user
  966. AND session_course_user.c_id="'.$courseId.'"
  967. AND session_course_user.id_session = '.$session_id;
  968. $where[] = ' session_course_user.c_id IS NOT NULL ';
  969. // 2 = coach
  970. // 0 = student
  971. if (isset($filter_by_status)) {
  972. $filter_by_status = intval($filter_by_status);
  973. $filter_by_status_condition = " session_course_user.status = $filter_by_status AND ";
  974. }
  975. } else {
  976. if ($return_count) {
  977. $sql = " SELECT COUNT(*) as count";
  978. if ($resumed_report) {
  979. //$sql = " SELECT count(field_id) ";
  980. }
  981. } else {
  982. if (empty($course_code)) {
  983. $sql = 'SELECT DISTINCT course.title, course.code, course_rel_user.status as status_rel, user.user_id, course_rel_user.role, course_rel_user.tutor_id, user.* ';
  984. } else {
  985. $sql = 'SELECT DISTINCT course_rel_user.status as status_rel, user.user_id, course_rel_user.role, course_rel_user.tutor_id, user.* ';
  986. }
  987. }
  988. $sql .= ' FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
  989. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_COURSE_USER).' as course_rel_user
  990. ON user.user_id = course_rel_user.user_id AND
  991. course_rel_user.relation_type <> '.COURSE_RELATION_TYPE_RRHH;
  992. if (!empty($courseInfo)) {
  993. $sql .= " AND course_rel_user.c_id = ".$courseId;
  994. } else {
  995. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  996. $sql .= " INNER JOIN $course_table course ON course_rel_user.c_id = course.id";
  997. }
  998. $where[] = ' course_rel_user.c_id IS NOT NULL ';
  999. if (isset($filter_by_status) && $filter_by_status != '') {
  1000. $filter_by_status = intval($filter_by_status);
  1001. $filter_by_status_condition = " course_rel_user.status = $filter_by_status AND ";
  1002. }
  1003. }
  1004. $multiple_access_url = api_get_multiple_access_url();
  1005. if ($multiple_access_url) {
  1006. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au ON (au.user_id = user.user_id) ';
  1007. }
  1008. if ($return_count && $resumed_report) {
  1009. $extra_field_info = UserManager::get_extra_field_information_by_name($extra_field);
  1010. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES).' as ufv ON (user.user_id = ufv.user_id AND (field_id = '.$extra_field_info['id'].' OR field_id IS NULL ) )';
  1011. }
  1012. $sql .= ' WHERE '.$filter_by_status_condition.' '.implode(' OR ', $where);
  1013. if ($multiple_access_url) {
  1014. $current_access_url_id = api_get_current_access_url_id();
  1015. $sql .= " AND (access_url_id = $current_access_url_id ) ";
  1016. }
  1017. if ($return_count && $resumed_report) {
  1018. $sql .= ' AND field_id IS NOT NULL GROUP BY field_value ';
  1019. }
  1020. $sql .= ' '.$order_by.' '.$limit;
  1021. $rs = Database::query($sql);
  1022. $users = array();
  1023. if ($add_reports) {
  1024. $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
  1025. }
  1026. $counter = 1;
  1027. $count_rows = Database::num_rows($rs);
  1028. if ($return_count && $resumed_report) {
  1029. return $count_rows;
  1030. }
  1031. $table_user_field_value = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1032. if ($count_rows) {
  1033. while ($user = Database::fetch_array($rs)) {
  1034. $report_info = array();
  1035. if ($return_count) {
  1036. return $user['count'];
  1037. }
  1038. $user_info = $user;
  1039. $user_info['status'] = $user['status'];
  1040. if (isset($user['role'])) {
  1041. $user_info['role'] = $user['role'];
  1042. }
  1043. if (isset($user['tutor_id'])) {
  1044. $user_info['tutor_id'] = $user['tutor_id'];
  1045. }
  1046. if (!empty($session_id)) {
  1047. $user_info['status_session'] = $user['status_session'];
  1048. }
  1049. $user_info['complete_name'] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
  1050. if ($add_reports) {
  1051. $course_code = $user['code'];
  1052. if ($resumed_report) {
  1053. foreach ($extra_fields as $extra) {
  1054. if ($extra['1'] == $extra_field) {
  1055. $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
  1056. break;
  1057. }
  1058. }
  1059. if (empty($user_data[$extra['1']])) {
  1060. $row_key = '-1';
  1061. $name = '-';
  1062. } else {
  1063. $row_key = $user_data[$extra['1']];
  1064. $name = $user_data[$extra['1']];
  1065. }
  1066. $users[$row_key]['extra_'.$extra['1']] = $name;
  1067. $users[$row_key]['training_hours'] += Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, 0);
  1068. $users[$row_key]['count_users'] += $counter;
  1069. $registered_users_with_extra_field = 0;
  1070. if (!empty($name) && $name != '-') {
  1071. $name = Database::escape_string($name);
  1072. $sql = "SELECT count(user_id) as count FROM $table_user_field_value WHERE field_value = '$name'";
  1073. $result_count = Database::query($sql);
  1074. if (Database::num_rows($result_count)) {
  1075. $row_count = Database::fetch_array($result_count);
  1076. $registered_users_with_extra_field = $row_count['count'];
  1077. }
  1078. }
  1079. $users[$row_key]['count_users_registered'] = $registered_users_with_extra_field;
  1080. $users[$row_key]['average_hours_per_user'] = $users[$row_key]['training_hours'] / $users[$row_key]['count_users'];
  1081. $category = Category::load (null, null, $course_code);
  1082. if (!isset($users[$row_key]['count_certificates'])) {
  1083. $users[$row_key]['count_certificates'] = 0;
  1084. }
  1085. if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
  1086. $users[$row_key]['count_certificates']++;
  1087. }
  1088. } else {
  1089. $report_info['course'] = $user['title'];
  1090. $report_info['user'] = api_get_person_name($user['firstname'], $user['lastname']);
  1091. $report_info['time'] = api_time_to_hms(Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, 0));
  1092. $category = Category :: load (null, null, $course_code);
  1093. $report_info['certificate'] = Display::label(get_lang('No'));
  1094. if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) {
  1095. $report_info['certificate'] = Display::label(get_lang('Yes'), 'success');
  1096. }
  1097. //$report_info['score'] = Tracking::get_avg_student_score($user['user_id'], $courseId, array(), 0);
  1098. $progress = intval(Tracking::get_avg_student_progress($user['user_id'], $courseId, array(), 0));
  1099. $report_info['progress_100'] = $progress == 100 ? Display::label(get_lang('Yes'), 'success') : Display::label(get_lang('No'));
  1100. $report_info['progress'] = $progress."%";
  1101. foreach ($extra_fields as $extra) {
  1102. $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']);
  1103. $report_info[$extra['1']] = $user_data[$extra['1']];
  1104. }
  1105. $users[] = $report_info;
  1106. }
  1107. } else {
  1108. $users[$user['user_id']] = $user_info;
  1109. }
  1110. }
  1111. $counter++;
  1112. }
  1113. return $users;
  1114. }
  1115. static function get_count_user_list_from_course_code($resumed_report = false, $extra_field = null) {
  1116. return self::get_user_list_from_course_code(null, 0, null, null, null, true, false, $resumed_report, $extra_field);
  1117. }
  1118. /**
  1119. * Gets subscribed users in a course or in a course/session
  1120. *
  1121. * @param string $course_code
  1122. * @param int $session_id
  1123. * @return int
  1124. */
  1125. public static function get_users_count_in_course($course_code, $session_id = 0) {
  1126. // variable initialisation
  1127. $session_id = intval($session_id);
  1128. $course_code = Database::escape_string($course_code);
  1129. $courseInfo = api_get_course_info($course_code);
  1130. $courseId = $courseInfo['real_id'];
  1131. $sql = 'SELECT DISTINCT count(*) as count FROM '.Database::get_main_table(TABLE_MAIN_USER).' as user ';
  1132. $where = array();
  1133. if (!empty($session_id)) {
  1134. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' as session_course_user
  1135. ON user.user_id = session_course_user.id_user
  1136. AND session_course_user.c_id = "'.$courseId.'"
  1137. AND session_course_user.id_session = '.$session_id.'
  1138. INNER JOIN '.Database::get_main_table(TABLE_MAIN_SESSION_USER).' as su
  1139. ON ( su.id_session = session_course_user.id_session AND
  1140. user.user_id = su.id_user AND
  1141. su.moved_to = 0 AND
  1142. su.moved_status <> '.SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION.'
  1143. )';
  1144. $where[] = ' session_course_user.c_id IS NOT NULL ';
  1145. } else {
  1146. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_COURSE_USER).' as course_rel_user
  1147. ON user.user_id = course_rel_user.user_id AND course_rel_user.relation_type<>'.COURSE_RELATION_TYPE_RRHH.'
  1148. AND course_rel_user.c_id ="'.$courseId.'"';
  1149. $where[] = ' course_rel_user.c_id IS NOT NULL ';
  1150. }
  1151. $multiple_access_url = api_get_multiple_access_url();
  1152. if ($multiple_access_url) {
  1153. $sql .= ' LEFT JOIN '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au ON (au.user_id = user.user_id) ';
  1154. }
  1155. $sql .= ' WHERE '.implode(' OR ', $where);
  1156. if ($multiple_access_url) {
  1157. $current_access_url_id = api_get_current_access_url_id();
  1158. $sql .= " AND (access_url_id = $current_access_url_id ) ";
  1159. }
  1160. $rs = Database::query($sql);
  1161. $count = 0;
  1162. if (Database::num_rows($rs)) {
  1163. $user = Database::fetch_array($rs);
  1164. $count = $user['count'];
  1165. }
  1166. return $count;
  1167. }
  1168. /**
  1169. * Get a list of coaches of a course and a session
  1170. * @param string Course code
  1171. * @param int Session ID
  1172. * @return array List of users
  1173. */
  1174. public static function get_coach_list_from_course_code($courseId, $session_id) {
  1175. if ($session_id != strval(intval($session_id))) {
  1176. return array();
  1177. }
  1178. $courseId = Database::escape_string($courseId);
  1179. $users = array();
  1180. // We get the coach for the given course in a given session.
  1181. $rs = Database::query('SELECT id_user FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
  1182. ' WHERE id_session="'.$session_id.'" AND c_id="'.$courseId.'" AND status = 2');
  1183. while ($user = Database::fetch_array($rs)) {
  1184. $user_info = api_get_user_info($user['id_user']);
  1185. $user_info['status'] = $user['status'];
  1186. $user_info['role'] = $user['role'];
  1187. $user_info['tutor_id'] = $user['tutor_id'];
  1188. $user_info['email'] = $user['email'];
  1189. $users[$user['id_user']] = $user_info;
  1190. }
  1191. // We get the session coach.
  1192. $rs = Database::query('SELECT id_coach FROM '.Database::get_main_table(TABLE_MAIN_SESSION).' WHERE id="'.$session_id.'"');
  1193. $session_id_coach = Database::result($rs, 0, 'id_coach');
  1194. $user_info = api_get_user_info($session_id_coach);
  1195. $user_info['status'] = $user['status'];
  1196. $user_info['role'] = $user['role']; //Role field exists?
  1197. $user_info['tutor_id'] = $user['tutor_id'];
  1198. $user_info['email'] = $user['email'];
  1199. $users[$session_id_coach] = $user_info;
  1200. return $users;
  1201. }
  1202. /**
  1203. * Return user info array of all users registered in the specified real or virtual course
  1204. * This only returns the users that are registered in this actual course, not linked courses.
  1205. *
  1206. * @param string $course_code
  1207. * @param boolean $full list to true if we want sessions students too
  1208. * @return array with user id
  1209. */
  1210. public static function get_student_list_from_course_code($courseId, $with_session = false, $session_id = 0, $group_id = 0) {
  1211. $session_id = intval($session_id);
  1212. $courseId = Database::escape_string($courseId);
  1213. $students = array();
  1214. if ($session_id == 0) {
  1215. if (empty($group_id)) {
  1216. // students directly subscribed to the course
  1217. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  1218. WHERE c_id = ".$courseId." AND status = ".STUDENT;
  1219. $rs = Database::query($sql);
  1220. while ($student = Database::fetch_array($rs)) {
  1221. $students[$student['user_id']] = $student;
  1222. }
  1223. } else {
  1224. $students = GroupManager::get_users($group_id, false, $courseId);
  1225. $students = array_flip($students);
  1226. }
  1227. }
  1228. // students subscribed to the course through a session
  1229. if ($with_session) {
  1230. $sql_query = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
  1231. WHERE c_id = '$courseId' AND status <> 2";
  1232. if ($session_id != 0) {
  1233. $sql_query .= ' AND id_session = '.$session_id;
  1234. }
  1235. $rs = Database::query($sql_query);
  1236. while($student = Database::fetch_array($rs)) {
  1237. $students[$student['id_user']] = $student;
  1238. }
  1239. }
  1240. return $students;
  1241. }
  1242. /**
  1243. * Return user info array of all teacher-users registered in the specified real or virtual course
  1244. * This only returns the users that are registered in this actual course, not linked courses.
  1245. *
  1246. * @param int $courseId
  1247. * @return array with user id
  1248. */
  1249. public static function get_teacher_list_from_course_code($courseId)
  1250. {
  1251. $courseId = Database::escape_string($courseId);
  1252. $teachers = array();
  1253. $sql = "SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.email, u.username, u.status
  1254. FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." cu
  1255. INNER JOIN ".Database::get_main_table(TABLE_MAIN_USER)." u
  1256. ON (cu.user_id = u.user_id)
  1257. WHERE
  1258. cu.c_id = '$courseId' AND
  1259. cu.status = 1 ";
  1260. $rs = Database::query($sql);
  1261. while ($teacher = Database::fetch_array($rs)) {
  1262. $teachers[$teacher['user_id']] = $teacher;
  1263. }
  1264. return $teachers;
  1265. }
  1266. /**
  1267. * @param $courseId
  1268. * @param string $separator
  1269. * @param bool $add_link_to_profile
  1270. * @return string
  1271. */
  1272. public static function get_teacher_list_from_course_code_to_string($courseId, $separator = null, $add_link_to_profile = false)
  1273. {
  1274. $teacher_list = self::get_teacher_list_from_course_code($courseId);
  1275. return self::formatUserListToString($teacher_list, $separator, $add_link_to_profile);
  1276. }
  1277. public static function formatUserListToString($userList, $separator = null, $add_link_to_profile = false)
  1278. {
  1279. if (empty($separator)) {
  1280. $separator = self::USER_SEPARATOR;
  1281. }
  1282. $teacher_string = '';
  1283. $list = array();
  1284. if (!empty($userList)) {
  1285. foreach($userList as $teacher) {
  1286. $teacher_name = api_get_person_name($teacher['firstname'], $teacher['lastname']);
  1287. if ($add_link_to_profile) {
  1288. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&resizable=0&height=300&user_id='.$teacher['user_id'];
  1289. $teacher_name = Display::url($teacher_name, $url, array('class' => 'ajax'));
  1290. }
  1291. $list[]= $teacher_name;
  1292. }
  1293. if (!empty($list)) {
  1294. $teacher_string = ArrayClass::array_to_string($list, $separator);
  1295. }
  1296. }
  1297. return $teacher_string;
  1298. }
  1299. /**
  1300. * This function returns information about coachs from a course in session
  1301. * @param int - optional, session id
  1302. * @param string - optional, course code
  1303. * @return array - array containing user_id, lastname, firstname, username
  1304. *
  1305. */
  1306. public static function get_coachs_from_course($session_id = 0, $courseId = null) {
  1307. if (!empty($session_id)) {
  1308. $session_id = intval($session_id);
  1309. } else {
  1310. $session_id = api_get_session_id();
  1311. }
  1312. if (!empty($courseId)) {
  1313. $courseId = Database::escape_string($courseId);
  1314. } else {
  1315. $courseId = api_get_course_int_id();
  1316. }
  1317. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  1318. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1319. $coaches = array();
  1320. $sql = "SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username
  1321. FROM $tbl_user u, $tbl_session_course_user scu
  1322. WHERE u.user_id = scu.id_user AND scu.id_session = '$session_id' AND scu.c_id = $courseId AND scu.status = 2";
  1323. $rs = Database::query($sql);
  1324. if (Database::num_rows($rs) > 0) {
  1325. while ($row = Database::fetch_array($rs)) {
  1326. $coaches[] = $row;
  1327. }
  1328. return $coaches;
  1329. } else {
  1330. return false;
  1331. }
  1332. }
  1333. public static function get_coachs_from_course_to_string($session_id = 0, $courseId = null, $separator = self::USER_SEPARATOR, $add_link_to_profile = false) {
  1334. $coachs_course = self::get_coachs_from_course($session_id, $courseId);
  1335. $course_coachs = array();
  1336. if (is_array($coachs_course)) {
  1337. foreach ($coachs_course as $coach_course) {
  1338. $coach_name = api_get_person_name($coach_course['firstname'], $coach_course['lastname']);
  1339. if ($add_link_to_profile) {
  1340. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&resizable=0&height=300&user_id='.$coach_course['user_id'];
  1341. $coach_name = Display::url($coach_name, $url, array('class' => 'ajax'));
  1342. }
  1343. $course_coachs[] = $coach_name;
  1344. }
  1345. }
  1346. $coaches_to_string = null;
  1347. if (is_array($course_coachs) && count($course_coachs)> 0 ) {
  1348. $coaches_to_string = ArrayClass::array_to_string($course_coachs, $separator);
  1349. }
  1350. return $coaches_to_string;
  1351. }
  1352. public static function get_coach_list_from_course_code_to_string($courseId, $session_id) {
  1353. $tutor_data = '';
  1354. if ($session_id != 0) {
  1355. $coaches = self::get_email_of_tutor_to_session($session_id, $courseId);
  1356. $coach_list = array();
  1357. foreach ($coaches as $coach) {
  1358. $coach_list[] = $coach['complete_name'];
  1359. }
  1360. if (!empty($coach_list)) {
  1361. $tutor_data = implode(self::USER_SEPARATOR, $coach_list);
  1362. }
  1363. }
  1364. return $tutor_data;
  1365. }
  1366. /**
  1367. * Return user info array of all users registered in the specified course
  1368. * this includes the users of the course itsel and the users of all linked courses.
  1369. *
  1370. * @param array $course_info
  1371. * @return array with user info
  1372. */
  1373. public static function get_real_and_linked_user_list($course_code, $with_sessions = true, $session_id = 0, $order_by = null) {
  1374. $complete_user_list = array();
  1375. //get users from real course
  1376. $user_list = self::get_user_list_from_course_code($course_code, $session_id, null, $order_by);
  1377. foreach ($user_list as $this_user) {
  1378. $complete_user_list[] = $this_user;
  1379. }
  1380. return $complete_user_list;
  1381. }
  1382. /*
  1383. GROUP FUNCTIONS
  1384. */
  1385. /**
  1386. * Get the list of groups from the course
  1387. * @param string Course code
  1388. * @param int Session ID (optional)
  1389. * @param int get empty groups (optional)
  1390. * @return array List of groups info
  1391. */
  1392. public static function get_group_list_of_course($course_code, $session_id = 0, $in_get_empty_group = 0)
  1393. {
  1394. $course_info = api_get_course_info($course_code);
  1395. if (empty($course_info)) {
  1396. return array();
  1397. }
  1398. $course_id = $course_info['real_id'];
  1399. $group_list = array();
  1400. $session_id != 0 ? $session_condition = ' WHERE g.session_id IN(1,'.intval($session_id).')' : $session_condition = ' WHERE g.session_id = 0';
  1401. if ($in_get_empty_group == 0) {
  1402. // get only groups that are not empty
  1403. $sql = "SELECT DISTINCT g.iid as id, g.name
  1404. FROM ".Database::get_course_table(TABLE_GROUP)." AS g
  1405. INNER JOIN ".Database::get_course_table(TABLE_GROUP_USER)." gu
  1406. ON (g.iid = gu.group_id AND g.c_id = $course_id AND gu.c_id = $course_id)
  1407. $session_condition
  1408. ORDER BY g.name";
  1409. } else {
  1410. // get all groups even if they are empty
  1411. $sql = "SELECT g.iid as id, g.name
  1412. FROM ".Database::get_course_table(TABLE_GROUP)." AS g
  1413. $session_condition
  1414. AND c_id = $course_id";
  1415. }
  1416. $result = Database::query($sql);
  1417. while ($group_data = Database::fetch_array($result)) {
  1418. $group_data['userNb'] = GroupManager::number_of_students($group_data['id'], $course_id);
  1419. $group_list[$group_data['id']] = $group_data;
  1420. }
  1421. return $group_list;
  1422. }
  1423. /**
  1424. * Delete a course
  1425. * This function deletes a whole course-area from the platform. When the
  1426. * given course is a virtual course, the database and directory will not be
  1427. * deleted.
  1428. * When the given course is a real course, also all virtual courses refering
  1429. * to the given course will be deleted.
  1430. * Considering the fact that we remove all traces of the course in the main
  1431. * database, it makes sense to remove all tracking as well (if stats databases exist)
  1432. * so that a new course created with this code would not use the remains of an older
  1433. * course.
  1434. *
  1435. * @param string The code of the course to delete
  1436. * course from the groups in the real course if they are not subscribed in
  1437. * that real course.
  1438. */
  1439. public static function delete_course($code)
  1440. {
  1441. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1442. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1443. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1444. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1445. $table_course_rel_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1446. $table_course_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
  1447. $table_course_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1448. $table_course_survey_question_option= Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1449. $table_stats_hotpots = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  1450. $table_stats_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1451. $table_stats_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1452. $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  1453. $table_stats_lastaccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  1454. $table_stats_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1455. $table_stats_online = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
  1456. $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  1457. $table_stats_downloads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  1458. $table_stats_links = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  1459. $table_stats_uploads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
  1460. $courseInfo = api_get_course_info($code);
  1461. if (empty($courseInfo)) {
  1462. return false;
  1463. }
  1464. //self::create_database_dump($courseInfo);
  1465. $code = Database::escape_string($code);
  1466. $courseId = $courseInfo['real_id'];
  1467. $course_tables = self::get_course_tables();
  1468. // Cleaning c_x tables
  1469. if (!empty($courseInfo['id'])) {
  1470. foreach ($course_tables as $table) {
  1471. $table = Database::get_course_table($table);
  1472. $sql = "DELETE FROM $table WHERE c_id = $courseId ";
  1473. Database::query($sql);
  1474. }
  1475. }
  1476. if (!empty($courseInfo['directory'])) {
  1477. $course_dir = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'];
  1478. $archive_dir = api_get_path(SYS_ARCHIVE_PATH).$courseInfo['directory'].'_'.time();
  1479. if (is_dir($course_dir)) {
  1480. rename($course_dir, $archive_dir);
  1481. }
  1482. }
  1483. // Unsubscribe all classes from the course
  1484. /*$sql = "DELETE FROM $table_course_class WHERE course_code='".$code."'";
  1485. Database::query($sql);*/
  1486. // Unsubscribe all users from the course
  1487. $sql = "DELETE FROM $table_course_user WHERE c_id ='".$courseId."'";
  1488. Database::query($sql);
  1489. // Delete the course from the sessions tables
  1490. $sql = "DELETE FROM $table_session_course WHERE c_id='".$courseId."'";
  1491. Database::query($sql);
  1492. $sql = "DELETE FROM $table_session_course_user WHERE c_id='".$courseId."'";
  1493. Database::query($sql);
  1494. // Delete from Course - URL
  1495. $sql = "DELETE FROM $table_course_rel_url WHERE c_id = '".$courseId."'";
  1496. Database::query($sql);
  1497. $sql = 'SELECT survey_id FROM '.$table_course_survey.' WHERE course_code="'.$code.'"';
  1498. $result_surveys = Database::query($sql);
  1499. while($surveys = Database::fetch_array($result_surveys)) {
  1500. $survey_id = $surveys[0];
  1501. $sql = 'DELETE FROM '.$table_course_survey_question.' WHERE survey_id="'.$survey_id.'"';
  1502. Database::query($sql);
  1503. $sql = 'DELETE FROM '.$table_course_survey_question_option.' WHERE survey_id="'.$survey_id.'"';
  1504. Database::query($sql);
  1505. $sql = 'DELETE FROM '.$table_course_survey.' WHERE survey_id="'.$survey_id.'"';
  1506. Database::query($sql);
  1507. }
  1508. // Delete the course from the stats tables
  1509. $sql = "DELETE FROM $table_stats_hotpots WHERE c_id = '".$courseId."'";
  1510. Database::query($sql);
  1511. $sql = "DELETE FROM $table_stats_attempt WHERE c_id = '".$courseId."'";
  1512. Database::query($sql);
  1513. $sql = "DELETE FROM $table_stats_exercises WHERE c_id = '".$courseId."'";
  1514. Database::query($sql);
  1515. $sql = "DELETE FROM $table_stats_access WHERE c_id = '".$courseId."'";
  1516. Database::query($sql);
  1517. $sql = "DELETE FROM $table_stats_lastaccess WHERE c_id = '".$courseId."'";
  1518. Database::query($sql);
  1519. $sql = "DELETE FROM $table_stats_course_access WHERE c_id = '".$courseId."'";
  1520. Database::query($sql);
  1521. $sql = "DELETE FROM $table_stats_online WHERE course = '".$code."'";
  1522. Database::query($sql);
  1523. $sql = "DELETE FROM $table_stats_default WHERE default_cours_code = '".$code."'";
  1524. Database::query($sql);
  1525. $sql = "DELETE FROM $table_stats_downloads WHERE c_id = '".$courseId."'";
  1526. Database::query($sql);
  1527. $sql = "DELETE FROM $table_stats_links WHERE c_id = '".$courseId."'";
  1528. Database::query($sql);
  1529. $sql = "DELETE FROM $table_stats_uploads WHERE upload_cours_id = '".$code."'";
  1530. Database::query($sql);
  1531. if (api_is_multiple_url_enabled()) {
  1532. $url_id = 1;
  1533. if (api_get_current_access_url_id() != -1) {
  1534. $url_id = api_get_current_access_url_id();
  1535. }
  1536. UrlManager::delete_url_rel_course($courseId, $url_id);
  1537. }
  1538. // delete extra course fields
  1539. $t_cf = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  1540. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  1541. $sql = "SELECT distinct field_id FROM $t_cfv WHERE course_code = '$code'";
  1542. $res_field_ids = Database::query($sql);
  1543. $field_ids = array();
  1544. while($row_field_id = Database::fetch_row($res_field_ids)) {
  1545. $field_ids[] = $row_field_id[0];
  1546. }
  1547. // Delete from table_course_field_value from a given course_code
  1548. $sql_course_field_value = "DELETE FROM $t_cfv WHERE course_code = '$code'";
  1549. Database::query($sql_course_field_value);
  1550. $sql = "SELECT distinct field_id FROM $t_cfv";
  1551. $res_field_all_ids = Database::query($sql);
  1552. $field_all_ids = array();
  1553. while($row_field_all_id = Database::fetch_row($res_field_all_ids)){
  1554. $field_all_ids[] = $row_field_all_id[0];
  1555. }
  1556. if (isset($field_ids) && is_array($field_ids) && count($field_ids) > 0) {
  1557. foreach ($field_ids as $field_id) {
  1558. // check if field id is used into table field value
  1559. if (!empty($field_all_ids) && is_array($field_all_ids)) {
  1560. if (in_array($field_id, $field_all_ids)) {
  1561. continue;
  1562. } else {
  1563. $sql_course_field = "DELETE FROM $t_cf WHERE id = '$field_id'";
  1564. Database::query($sql_course_field);
  1565. }
  1566. }
  1567. }
  1568. }
  1569. // Delete the course from the database
  1570. /*$sql = "DELETE FROM $table_course WHERE id = '".$courseId."'";
  1571. Database::query($sql);*/
  1572. $em = self::getEntityManager();
  1573. $course = $em->getRepository('ChamiloCoreBundle:Course')->find($courseId);
  1574. $em->remove($course);
  1575. $em->flush();
  1576. // Add event to system log
  1577. $user_id = api_get_user_id();
  1578. Event::addEvent(LOG_COURSE_DELETE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $code);
  1579. }
  1580. /**
  1581. * Creates a file called mysql_dump.sql in the course folder
  1582. * @param array course info
  1583. * @return
  1584. */
  1585. public static function create_database_dump($courseInfo)
  1586. {
  1587. $sql_dump = null;
  1588. if (empty($courseInfo)) {
  1589. return null;
  1590. }
  1591. $course_tables = self::get_course_tables();
  1592. if (!empty($courseInfo['real_id'])) {
  1593. // Cleaning c_x tables
  1594. foreach ($course_tables as $table) {
  1595. $table = Database::get_course_table($table);
  1596. $sql = "SELECT * FROM $table WHERE c_id = {$courseInfo['real_id']} ";
  1597. $res_table = Database::query($sql);
  1598. while ($row = Database::fetch_array($res_table, 'ASSOC')) {
  1599. $row_to_save = array();
  1600. foreach ($row as $key => $value) {
  1601. $row_to_save[$key] = $key."='".Database::escape_string($row[$key])."'";
  1602. }
  1603. $sql_dump .= "INSERT INTO $table SET ".implode(', ', $row_to_save).';';
  1604. }
  1605. }
  1606. }
  1607. if (is_dir(api_get_path(SYS_COURSE_PATH).$courseInfo['directory'])) {
  1608. $file_name = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/mysql_dump.sql';
  1609. $handle = fopen($file_name, 'a+');
  1610. if ($handle !== false) {
  1611. fwrite($handle, $sql_dump);
  1612. fclose($handle);
  1613. }
  1614. }
  1615. }
  1616. /**
  1617. * Sort courses for a specific user ??
  1618. * @param int User ID
  1619. * @param string Course code
  1620. * @return int Minimum course order
  1621. * @todo Review documentation
  1622. */
  1623. public static function userCourseSort($user_id, $courseId) {
  1624. if ($user_id != strval(intval($user_id))) {
  1625. return false;
  1626. }
  1627. $courseId = Database::escape_string($courseId);
  1628. $TABLECOURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  1629. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1630. $course_title = Database::result(Database::query('SELECT title FROM '.$TABLECOURSE.' WHERE id = "'.$courseId.'"'), 0, 0);
  1631. $sql = 'SELECT course.code as code, course.title as title, cu.sort as sort
  1632. FROM '.$TABLECOURSUSER.' as cu, '.$TABLECOURSE.' as course
  1633. WHERE course.id = cu.c_id AND
  1634. user_id = "'.$user_id.'" AND
  1635. cu.relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND
  1636. user_course_cat = 0
  1637. ORDER BY cu.sort';
  1638. $result = Database::query($sql);
  1639. $course_title_precedent = '';
  1640. $counter = 0;
  1641. $course_found = false;
  1642. $course_sort = 1;
  1643. if (Database::num_rows($result) > 0) {
  1644. while ($courses = Database::fetch_array($result)) {
  1645. if ($course_title_precedent == '') {
  1646. $course_title_precedent = $courses['title'];
  1647. }
  1648. if (api_strcasecmp($course_title_precedent, $course_title) < 0) {
  1649. $course_found = true;
  1650. $course_sort = $courses['sort'];
  1651. if ($counter == 0) {
  1652. $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id = "'.$user_id.'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND user_course_cat="0" AND sort > "'.$course_sort.'"';
  1653. $course_sort++;
  1654. } else {
  1655. $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id = "'.$user_id.'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND user_course_cat="0" AND sort >= "'.$course_sort.'"';
  1656. }
  1657. Database::query($sql);
  1658. break;
  1659. } else {
  1660. $course_title_precedent = $courses['title'];
  1661. }
  1662. $counter++;
  1663. }
  1664. // We must register the course in the beginning of the list
  1665. if (!$course_found) {
  1666. $course_sort = Database::result(Database::query('SELECT min(sort) as min_sort FROM '.$TABLECOURSUSER.' WHERE user_id="'.$user_id.'" AND user_course_cat="0"'), 0, 0);
  1667. Database::query('UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id= "'.$user_id.'" AND user_course_cat="0"');
  1668. }
  1669. }
  1670. return $course_sort;
  1671. }
  1672. /**
  1673. * create recursively all categories as option of the select passed in paramater.
  1674. *
  1675. * @param object $select_element the quickform select where the options will be added
  1676. * @param string $category_selected_code the option value to select by default (used mainly for edition of courses)
  1677. * @param string $parent_code the parent category of the categories added (default=null for root category)
  1678. * @param string $padding the indent param (you shouldn't indicate something here)
  1679. */
  1680. public static function select_and_sort_categories($select_element, $category_selected_code = '', $parent_code = null , $padding = '') {
  1681. $sql = "SELECT code, name, auth_course_child, auth_cat_child
  1682. FROM ".Database::get_main_table(TABLE_MAIN_CATEGORY)."
  1683. WHERE parent_id ".(is_null($parent_code) ? "IS NULL" : "='".Database::escape_string($parent_code)."'")."
  1684. ORDER BY code";
  1685. $res = Database::query($sql);
  1686. while ($cat = Database::fetch_array($res)) {
  1687. $params = $cat['auth_course_child'] == 'TRUE' ? '' : 'disabled';
  1688. $params .= ($cat['code'] == $category_selected_code) ? ' selected' : '';
  1689. $select_element->addOption($padding.'('.$cat['code'].') '.$cat['name'], $cat['code'], $params);
  1690. if ($cat['auth_cat_child']) {
  1691. self::select_and_sort_categories($select_element, $category_selected_code, $cat['code'], $padding.' - ');
  1692. }
  1693. }
  1694. }
  1695. /**
  1696. * check if course exists
  1697. * @param string course_code
  1698. * @param string whether to accept virtual course codes or not
  1699. * @return true if exists, false else
  1700. */
  1701. public static function course_exists($course_code, $accept_virtual = false) {
  1702. if ($accept_virtual === true) {
  1703. $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).'"';
  1704. } else {
  1705. $sql = 'SELECT 1 FROM '.Database::get_main_table(TABLE_MAIN_COURSE).' WHERE code="'.Database::escape_string($course_code).'"';
  1706. }
  1707. return Database::num_rows(Database::query($sql));
  1708. }
  1709. /**
  1710. * Send an email to tutor after the auth-suscription of a student in your course
  1711. * @author Carlos Vargas <carlos.vargas@dokeos.com>, Dokeos Latino
  1712. * @param int $user_id the id of the user
  1713. * @param string $course_code the course code
  1714. * @param string $send_to_tutor_also
  1715. * @return string we return the message that is displayed when the action is succesfull
  1716. */
  1717. public static function email_to_tutor($user_id, $course_code, $send_to_tutor_also = false)
  1718. {
  1719. if ($user_id != strval(intval($user_id))) {
  1720. return false;
  1721. }
  1722. $course_code = Database::escape_string($course_code);
  1723. $student = Database::fetch_array(Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1724. WHERE user_id='".$user_id."'"));
  1725. $courseInfo = api_get_course_info($course_code);
  1726. $name_course = $courseInfo['title'];
  1727. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." WHERE c_id = '".$courseInfo['real_id']."'";
  1728. // TODO: Ivan: This is a mistake, please, have a look at it. Intention here is diffcult to be guessed.
  1729. //if ($send_to_tutor_also = true)
  1730. // Proposed change:
  1731. if ($send_to_tutor_also) {
  1732. //
  1733. $sql .= " AND tutor_id=1";
  1734. } else {
  1735. $sql .= " AND status=1";
  1736. }
  1737. $result = Database::query($sql);
  1738. while ($row = Database::fetch_array($result)) {
  1739. $tutor = Database::fetch_array(Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1740. WHERE user_id='".$row['user_id']."'"));
  1741. $emailto = $tutor['email'];
  1742. $emailsubject = get_lang('NewUserInTheCourse').': '.$name_course;
  1743. $emailbody = get_lang('Dear').': '. api_get_person_name($tutor['firstname'], $tutor['lastname'])."\n";
  1744. $emailbody .= get_lang('MessageNewUserInTheCourse').': '.$name_course."\n";
  1745. $emailbody .= get_lang('UserName').': '.$student['username']."\n";
  1746. if (api_is_western_name_order()) {
  1747. $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
  1748. $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
  1749. } else {
  1750. $emailbody .= get_lang('LastName').': '.$student['lastname']."\n";
  1751. $emailbody .= get_lang('FirstName').': '.$student['firstname']."\n";
  1752. }
  1753. $emailbody .= get_lang('Email').': '.$student['email']."\n\n";
  1754. $recipient_name = api_get_person_name($tutor['firstname'], $tutor['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
  1755. $sender_name = api_get_person_name(api_get_setting('platform.administrator_name'), api_get_setting('platform.administrator_surname'), null, PERSON_NAME_EMAIL_ADDRESS);
  1756. $email_admin = api_get_setting('platform.administrator_email');
  1757. @api_mail($recipient_name, $emailto, $emailsubject, $emailbody, $sender_name,$email_admin);
  1758. }
  1759. }
  1760. /**
  1761. * @return array
  1762. */
  1763. public static function get_special_course_list()
  1764. {
  1765. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  1766. $tbl_course_field = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
  1767. $tbl_course_field_value = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  1768. //we filter the courses from the URL
  1769. $join_access_url = $where_access_url='';
  1770. if (api_get_multiple_access_url()) {
  1771. $access_url_id = api_get_current_access_url_id();
  1772. if ($access_url_id != -1) {
  1773. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1774. $join_access_url= " INNER JOIN $tbl_course course ON (course.code = tcfv.course_code)
  1775. INNER JOIN $tbl_url_course url_rel_course
  1776. ON url_rel_course.c_id = course.id ";
  1777. $where_access_url =" AND access_url_id = $access_url_id ";
  1778. }
  1779. }
  1780. // get course list auto-register
  1781. $sql = "SELECT DISTINCT(tcfv.course_code) FROM $tbl_course_field_value tcfv INNER JOIN $tbl_course_field tcf
  1782. ON tcfv.field_id = tcf.id $join_access_url
  1783. WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 $where_access_url";
  1784. $special_course_result = Database::query($sql);
  1785. $special_course_list = array();
  1786. if (Database::num_rows($special_course_result)>0) {
  1787. $special_course_list = array();
  1788. while ($result_row = Database::fetch_array($special_course_result)) {
  1789. $special_course_list[] = $result_row['course_code'];
  1790. }
  1791. }
  1792. return $special_course_list;
  1793. }
  1794. /**
  1795. * Get list of courses for a given user
  1796. * @param int user ID
  1797. * @param boolean Whether to include courses from session or not
  1798. * @return array List of codes and db names
  1799. * @author isaac flores paz
  1800. */
  1801. public static function get_courses_list_by_user_id($user_id, $include_sessions = false) {
  1802. $user_id = intval($user_id);
  1803. $course_list = array();
  1804. $codes = array();
  1805. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1806. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1807. $tbl_user_course_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  1808. $special_course_list = self::get_special_course_list();
  1809. $with_special_courses = $without_special_courses = '';
  1810. if (!empty($special_course_list)) {
  1811. $sc_string = '"'.implode('","',$special_course_list).'"';
  1812. $with_special_courses = ' course.code IN ('.$sc_string.')';
  1813. $without_special_courses = ' AND course.code NOT IN ('.$sc_string.')';
  1814. }
  1815. if (!empty($with_special_courses)) {
  1816. $sql = "SELECT DISTINCT(course.code), course.id as real_id
  1817. FROM ".$tbl_course_user." course_rel_user
  1818. LEFT JOIN ".$tbl_course." course
  1819. ON course.id = course_rel_user.c_id
  1820. LEFT JOIN ".$tbl_user_course_category." user_course_category
  1821. ON course_rel_user.user_course_cat = user_course_category.id
  1822. WHERE $with_special_courses
  1823. GROUP BY course.code
  1824. ORDER BY user_course_category.sort,course.title,course_rel_user.sort ASC";
  1825. $rs_special_course = Database::query($sql);
  1826. if (Database::num_rows($rs_special_course) > 0) {
  1827. while ($result_row = Database::fetch_array($rs_special_course)) {
  1828. $result_row['special_course'] = 1;
  1829. $course_list[] = $result_row;
  1830. $codes[] = $result_row['real_id'];
  1831. }
  1832. }
  1833. }
  1834. // get course list not auto-register. Use Distinct to avoid multiple
  1835. // entries when a course is assigned to a HRD (DRH) as watcher
  1836. $sql = "SELECT DISTINCT(course.code), course.id as real_id
  1837. FROM $tbl_course course
  1838. INNER JOIN $tbl_course_user cru ON course.id = cru.c_id
  1839. WHERE cru.user_id='$user_id' $without_special_courses";
  1840. $result = Database::query($sql);
  1841. if (Database::num_rows($result)) {
  1842. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1843. $course_list[] = $row;
  1844. $codes[] = $row['real_id'];
  1845. }
  1846. }
  1847. if ($include_sessions === true) {
  1848. $sql = "SELECT DISTINCT(c.code), c.id as real_id
  1849. FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." s, ".Database::get_main_table(TABLE_MAIN_COURSE)." c
  1850. WHERE id_user = $user_id AND s.c_id =c.id";
  1851. $r = Database::query($sql);
  1852. while ($row = Database::fetch_array($r, 'ASSOC')) {
  1853. if (!in_array($row['real_id'], $codes)) {
  1854. $course_list[] = $row;
  1855. }
  1856. }
  1857. }
  1858. return $course_list;
  1859. }
  1860. /**
  1861. * Get course ID from a given course directory name
  1862. * @param string Course directory (without any slash)
  1863. * @return string Course code, or false if not found
  1864. */
  1865. public static function get_course_id_from_path($path) {
  1866. $path = Database::escape_string(str_replace('.', '', str_replace('/', '', $path)));
  1867. $res = Database::query("SELECT code FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  1868. WHERE directory LIKE BINARY '$path'");
  1869. if ($res === false) {
  1870. return false;
  1871. }
  1872. if (Database::num_rows($res) != 1) {
  1873. return false;
  1874. }
  1875. $row = Database::fetch_array($res);
  1876. return $row['code'];
  1877. }
  1878. /**
  1879. * Get course code(s) from visual code
  1880. * @param string Visual code
  1881. * @return array List of codes for the given visual code
  1882. */
  1883. public static function get_courses_info_from_visual_code($code) {
  1884. $result = array();
  1885. $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
  1886. WHERE visual_code = '".Database::escape_string($code)."'");
  1887. while ($virtual_course = Database::fetch_array($sql_result)) {
  1888. $result[] = $virtual_course;
  1889. }
  1890. return $result;
  1891. }
  1892. /**
  1893. * Get coachs' emails by session
  1894. * @param int session id
  1895. * @param int course id
  1896. * @return array array(email => name_tutor) by coach
  1897. * @author Carlos Vargas <carlos.vargas@dokeos.com>
  1898. */
  1899. public static function get_email_of_tutor_to_session($session_id, $courseId) {
  1900. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1901. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1902. $coachs_emails = array();
  1903. $courseId = Database::escape_string($courseId);
  1904. $session_id = intval($session_id);
  1905. $sql = "SELECT id_user FROM $tbl_session_course_user WHERE id_session='$session_id' AND c_id ='$courseId' AND status =2";
  1906. $rs = Database::query($sql);
  1907. if (Database::num_rows($rs) > 0) {
  1908. $user_ids = array();
  1909. while ($row = Database::fetch_array($rs)) {
  1910. $user_ids[] = $row['id_user'];
  1911. }
  1912. $sql = "SELECT firstname, lastname, email FROM $tbl_user WHERE user_id IN (".implode(",",$user_ids).")";
  1913. $rs_user = Database::query($sql);
  1914. while ($row_emails = Database::fetch_array($rs_user)) {
  1915. $mail_tutor = array('email' => $row_emails['email'], 'complete_name' => api_get_person_name($row_emails['firstname'], $row_emails['lastname']));
  1916. $coachs_emails[] = $mail_tutor;
  1917. }
  1918. }
  1919. return $coachs_emails;
  1920. }
  1921. /**
  1922. * Creates a new extra field for a given course
  1923. * @param string Field's internal variable name
  1924. * @param int Field's type
  1925. * @param string Field's language var name
  1926. * @return int new extra field id
  1927. */
  1928. public static function create_course_extra_field($fieldvarname, $fieldtype, $fieldtitle) {
  1929. // database table definition
  1930. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  1931. $t_cf = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  1932. $fieldvarname = Database::escape_string($fieldvarname);
  1933. $fieldtitle = Database::escape_string($fieldtitle);
  1934. $fieldtype = (int)$fieldtype;
  1935. $time = time();
  1936. $sql_field = "SELECT id FROM $t_cf WHERE field_variable = '$fieldvarname'";
  1937. $res_field = Database::query($sql_field);
  1938. $r_field = Database::fetch_row($res_field);
  1939. if (Database::num_rows($res_field) > 0) {
  1940. return $r_field[0];
  1941. }
  1942. // save new fieldlabel into course_field table
  1943. $sql = "SELECT MAX(field_order) FROM $t_cf";
  1944. $res = Database::query($sql);
  1945. $order = 0;
  1946. if (Database::num_rows($res) > 0) {
  1947. $row = Database::fetch_row($res);
  1948. $order = $row[0] + 1;
  1949. }
  1950. $sql = "INSERT INTO $t_cf
  1951. SET field_type = '$fieldtype',
  1952. field_variable = '$fieldvarname',
  1953. field_display_text = '$fieldtitle',
  1954. field_order = '$order',
  1955. tms = FROM_UNIXTIME($time)";
  1956. Database::query($sql);
  1957. return Database::insert_id();
  1958. }
  1959. /**
  1960. * Updates course attribute. Note that you need to check that your attribute is valid before you use this function
  1961. *
  1962. * @param int Course id
  1963. * @param string Attribute name
  1964. * @param string Attribute value
  1965. * @return bool True if attribute was successfully updated, false if course was not found or attribute name is invalid
  1966. */
  1967. public static function update_attribute($id, $name, $value) {
  1968. $id = (int)$id;
  1969. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  1970. $sql = "UPDATE $table SET $name = '".Database::escape_string($value)."' WHERE id = '$id';";
  1971. return Database::query($sql);
  1972. }
  1973. /**
  1974. * Update course attributes. Will only update attributes with a non-empty value. Note that you NEED to check that your attributes are valid before using this function
  1975. *
  1976. * @param int Course id
  1977. * @param array Associative array with field names as keys and field values as values
  1978. * @return bool True if update was successful, false otherwise
  1979. */
  1980. public static function update_attributes($id, $attributes) {
  1981. $id = (int)$id;
  1982. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  1983. $sql = "UPDATE $table SET ";
  1984. $i = 0;
  1985. foreach($attributes as $name => $value) {
  1986. if($value != '') {
  1987. if($i > 0) {
  1988. $sql .= ", ";
  1989. }
  1990. $sql .= " $name = '".Database::escape_string($value)."'";
  1991. $i++;
  1992. }
  1993. }
  1994. $sql .= " WHERE id = '$id';";
  1995. return Database::query($sql);
  1996. }
  1997. /**
  1998. * Update an extra field value for a given course
  1999. * @param integer Course ID
  2000. * @param string Field variable name
  2001. * @param string Field value
  2002. * @return boolean true if field updated, false otherwise
  2003. */
  2004. public static function update_course_extra_field_value($course_code, $fname, $fvalue = '') {
  2005. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2006. $t_cf = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  2007. $fname = Database::escape_string($fname);
  2008. $course_code = Database::escape_string($course_code);
  2009. $fvalues = '';
  2010. if (is_array($fvalue)) {
  2011. foreach ($fvalue as $val) {
  2012. $fvalues .= Database::escape_string($val).';';
  2013. }
  2014. if (!empty($fvalues)) {
  2015. $fvalues = substr($fvalues, 0, -1);
  2016. }
  2017. } else {
  2018. $fvalues = Database::escape_string($fvalue);
  2019. }
  2020. $sqlcf = "SELECT * FROM $t_cf WHERE field_variable='$fname'";
  2021. $rescf = Database::query($sqlcf);
  2022. if (Database::num_rows($rescf) == 1) {
  2023. // Ok, the field exists
  2024. // Check if enumerated field, if the option is available
  2025. $rowcf = Database::fetch_array($rescf);
  2026. $tms = time();
  2027. $sqlcfv = "SELECT * FROM $t_cfv WHERE course_code = '$course_code' AND field_id = '".$rowcf['id']."' ORDER BY id";
  2028. $rescfv = Database::query($sqlcfv);
  2029. $n = Database::num_rows($rescfv);
  2030. if ($n > 1) {
  2031. //problem, we already have to values for this field and user combination - keep last one
  2032. while ($rowcfv = Database::fetch_array($rescfv)) { // See the TODO note below.
  2033. if ($n > 1) {
  2034. $sqld = "DELETE FROM $t_cfv WHERE id = ".$rowcfv['id'];
  2035. $resd = Database::query($sqld);
  2036. $n--;
  2037. }
  2038. $rowcfv = Database::fetch_array($rescfv);
  2039. if ($rowcfv['field_value'] != $fvalues) {
  2040. $sqlu = "UPDATE $t_cfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowcfv['id'];
  2041. $resu = Database::query($sqlu);
  2042. return ($resu ? true : false);
  2043. }
  2044. return true; // TODO: Sure exit from the function occures in this "while" cycle. Logic should checked. Maybe "if" instead of "while"? It is not clear...
  2045. }
  2046. } elseif ($n == 1) {
  2047. //we need to update the current record
  2048. $rowcfv = Database::fetch_array($rescfv);
  2049. if ($rowcfv['field_value'] != $fvalues) {
  2050. $sqlu = "UPDATE $t_cfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowcfv['id'];
  2051. $resu = Database::query($sqlu);
  2052. return ($resu ? true : false);
  2053. }
  2054. return true;
  2055. } else {
  2056. $sqli = "INSERT INTO $t_cfv (course_code,field_id,field_value,tms) " .
  2057. "VALUES ('$course_code',".$rowcf['id'].",'$fvalues',FROM_UNIXTIME($tms))";
  2058. $resi = Database::query($sqli);
  2059. return ($resi ? true : false);
  2060. }
  2061. } else {
  2062. return false; //field not found
  2063. }
  2064. }
  2065. /**
  2066. * Get the course id of an course by the database name
  2067. * @param string The database name
  2068. * @return string The course id
  2069. */
  2070. public static function get_course_id_by_database_name($db_name) {
  2071. return Database::result(Database::query('SELECT code FROM '.Database::get_main_table(TABLE_MAIN_COURSE).
  2072. ' WHERE db_name="'.Database::escape_string($db_name).'"'), 0, 'code');
  2073. }
  2074. public static function get_session_category_id_by_session_id($session_id) {
  2075. return Database::result(Database::query('SELECT sc.id session_category
  2076. FROM '.Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY).' sc
  2077. INNER JOIN '.Database::get_main_table(TABLE_MAIN_SESSION).' s
  2078. ON sc.id=s.session_category_id WHERE s.id="'.Database::escape_string($session_id).'"'),
  2079. 0, 'session_category');
  2080. }
  2081. /**
  2082. * Get the course id of an course by the database name
  2083. * @param string The database name
  2084. * @return string The course id
  2085. */
  2086. public static function get_course_extra_field_list($code) {
  2087. $tbl_course_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  2088. $tbl_course_field_value = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2089. $sql_field = "SELECT id, field_type, field_variable, field_display_text, field_default_value
  2090. FROM $tbl_course_field WHERE field_visible = '1' ";
  2091. $res_field = Database::query($sql_field);
  2092. $extra_fields = array();
  2093. while($rowcf = Database::fetch_array($res_field)) {
  2094. $extra_field_id = $rowcf['id'];
  2095. $sql_field_value = "SELECT field_value FROM $tbl_course_field_value WHERE course_code = '$code' AND field_id = '$extra_field_id' ";
  2096. $res_field_value = Database::query($sql_field_value);
  2097. if(Database::num_rows($res_field_value) > 0 ) {
  2098. $r_field_value = Database::fetch_row($res_field_value);
  2099. $rowcf['extra_field_value'] = $r_field_value[0];
  2100. }
  2101. $extra_fields[] = $rowcf;
  2102. }
  2103. return $extra_fields;
  2104. }
  2105. /**
  2106. * Gets the value of a course extra field. Returns null if it was not found
  2107. *
  2108. * @param string Name of the extra field
  2109. * @param string Course code
  2110. * @return string Value
  2111. */
  2112. public static function get_course_extra_field_value($field_name, $code) {
  2113. $tbl_course_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  2114. $tbl_course_field_value = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2115. $sql = "SELECT id FROM $tbl_course_field WHERE field_visible = '1' AND field_variable = '$field_name';";
  2116. $res = Database::query($sql);
  2117. $row = Database::fetch_object($res);
  2118. if(!$row) {
  2119. return null;
  2120. } else {
  2121. $sql_field_value = "SELECT field_value FROM $tbl_course_field_value WHERE course_code = '$code' AND field_id = '{$row->id}';";
  2122. $res_field_value = Database::query($sql_field_value);
  2123. $row_field_value = Database::fetch_object($res_field_value);
  2124. if(!$row_field_value) {
  2125. return null;
  2126. } else {
  2127. return $row_field_value['field_value'];
  2128. }
  2129. }
  2130. }
  2131. /**
  2132. * Get the database name of a course by the code
  2133. * @param string The course code
  2134. * @return string The database name
  2135. */
  2136. public static function get_name_database_course($course_code) {
  2137. return Database::result(Database::query('SELECT db_name FROM '.Database::get_main_table(TABLE_MAIN_COURSE).
  2138. ' WHERE code="'.Database::escape_string($course_code).'"'), 0, 'db_name');
  2139. }
  2140. /**
  2141. * Lists details of the course description
  2142. * @param array The course description
  2143. * @param string The encoding
  2144. * @param bool If true is displayed if false is hidden
  2145. * @return string The course description in html
  2146. */
  2147. public static function get_details_course_description_html($descriptions, $charset, $action_show = true) {
  2148. if (isset($descriptions) && count($descriptions) > 0) {
  2149. $data = '';
  2150. foreach ($descriptions as $id => $description) {
  2151. $data .= '<div class="sectiontitle">';
  2152. if (api_is_allowed_to_edit() && $action_show) {
  2153. //delete
  2154. $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=delete&amp;description_id='.$description->id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)).'\')) return false;">';
  2155. $data .= Display::return_icon('delete.gif', get_lang('Delete'), array('style' => 'vertical-align:middle;float:right;'));
  2156. $data .= '</a> ';
  2157. //edit
  2158. $data .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;description_id='.$description->id.'">';
  2159. $data .= Display::return_icon('edit.png', get_lang('Edit'), array('style' => 'vertical-align:middle;float:right; padding-right:4px;'), ICON_SIZE_SMALL);
  2160. $data .= '</a> ';
  2161. }
  2162. $data .= $description->title;
  2163. $data .= '</div>';
  2164. $data .= '<div class="sectioncomment">';
  2165. $data .= $description->content;
  2166. $data .= '</div>';
  2167. }
  2168. } else {
  2169. $data .= '<em>'.get_lang('ThisCourseDescriptionIsEmpty').'</em>';
  2170. }
  2171. return $data;
  2172. }
  2173. /**
  2174. * Returns the details of a course category
  2175. *
  2176. * @param string Category code
  2177. * @return array Course category
  2178. */
  2179. public static function get_course_category($code) {
  2180. $table_categories = Database::get_main_table(TABLE_MAIN_CATEGORY);
  2181. $sql = "SELECT * FROM $table_categories WHERE code = '$code';";
  2182. return Database::fetch_array(Database::query($sql));
  2183. }
  2184. /**
  2185. * Get count rows of a table inside a course database
  2186. * @param string The table of which the rows should be counted
  2187. * @param int optionally count rows by session id
  2188. * @return int The number of rows in the given table.
  2189. */
  2190. public static function count_rows_course_table($table, $session_id = '', $course_id = null) {
  2191. $condition_session = '';
  2192. if ($session_id !== '') {
  2193. $session_id = intval($session_id);
  2194. $condition_session = " AND session_id = '$session_id' ";
  2195. }
  2196. if (!empty($course_id)) {
  2197. $course_id = intval($course_id);
  2198. } else {
  2199. $course_id = api_get_course_int_id();
  2200. }
  2201. $condition_session .= " AND c_id = '$course_id' ";
  2202. $sql = "SELECT COUNT(*) AS n FROM $table WHERE 1=1 $condition_session ";
  2203. $rs = Database::query($sql);
  2204. $row = Database::fetch_row($rs);
  2205. return $row[0];
  2206. }
  2207. /**
  2208. * Subscribes courses to human resource manager (Dashboard feature)
  2209. * @param int Human Resource Manager id
  2210. * @param array Courses code
  2211. * @param int Relation type
  2212. **/
  2213. public static function suscribe_courses_to_hr_manager($hr_manager_id, $courses_list) {
  2214. // Database Table Definitions
  2215. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2216. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2217. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2218. $hr_manager_id = intval($hr_manager_id);
  2219. $affected_rows = 0;
  2220. //Deleting assigned courses to hrm_id
  2221. if (api_is_multiple_url_enabled()) {
  2222. $sql = "SELECT s.c_id FROM $tbl_course_rel_user s INNER JOIN $tbl_course_rel_access_url a ON (a.c_id = s.c_id)
  2223. WHERE user_id = $hr_manager_id AND relation_type=".COURSE_RELATION_TYPE_RRHH." AND access_url_id = ".api_get_current_access_url_id()."";
  2224. } else {
  2225. $sql = "SELECT c_id FROM $tbl_course_rel_user
  2226. WHERE user_id = $hr_manager_id AND relation_type=".COURSE_RELATION_TYPE_RRHH." ";
  2227. }
  2228. $result = Database::query($sql);
  2229. if (Database::num_rows($result) > 0) {
  2230. while ($row = Database::fetch_array($result)) {
  2231. $sql = "DELETE FROM $tbl_course_rel_user WHERE c_id = '{$row['c_id']}' AND user_id = $hr_manager_id AND relation_type=".COURSE_RELATION_TYPE_RRHH." ";
  2232. Database::query($sql);
  2233. }
  2234. }
  2235. // inserting new courses list
  2236. if (is_array($courses_list)) {
  2237. foreach ($courses_list as $courseId) {
  2238. $courseId = Database::escape_string($courseId);
  2239. $insert_sql = "INSERT IGNORE INTO $tbl_course_rel_user(c_id, user_id, status, relation_type) VALUES('$courseId', $hr_manager_id, '".DRH."', '".COURSE_RELATION_TYPE_RRHH."')";
  2240. $result = Database::query($insert_sql);
  2241. if (Database::affected_rows($result)) {
  2242. $affected_rows++;
  2243. }
  2244. }
  2245. }
  2246. return $affected_rows;
  2247. }
  2248. /**
  2249. * get courses followed by human resources manager
  2250. * @param int human resources manager id
  2251. * @return array courses
  2252. */
  2253. public static function get_courses_followed_by_drh($user_id)
  2254. {
  2255. // Database Table Definitions
  2256. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2257. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2258. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2259. $user_id = intval($user_id);
  2260. $assigned_courses_to_hrm = array();
  2261. if (api_get_multiple_access_url()) {
  2262. $sql = "SELECT *, c.id as real_id FROM $tbl_course c
  2263. INNER JOIN $tbl_course_rel_user cru ON (cru.c_id = c.id)
  2264. LEFT JOIN $tbl_course_rel_access_url a ON (a.c_id = c.id)
  2265. WHERE
  2266. cru.user_id = '$user_id' AND
  2267. status = ".DRH." AND
  2268. relation_type = '".COURSE_RELATION_TYPE_RRHH."' AND
  2269. access_url_id = ".api_get_current_access_url_id()."";
  2270. } else {
  2271. $sql = "SELECT *, c.id as real_id FROM $tbl_course c
  2272. INNER JOIN $tbl_course_rel_user cru
  2273. ON
  2274. cru.c_id = c.id AND cru.user_id = '$user_id' AND
  2275. status = ".DRH." AND
  2276. relation_type = '".COURSE_RELATION_TYPE_RRHH."' ";
  2277. }
  2278. $rs_assigned_courses = Database::query($sql);
  2279. if (Database::num_rows($rs_assigned_courses) > 0) {
  2280. while ($row_assigned_courses = Database::fetch_array($rs_assigned_courses)) {
  2281. $assigned_courses_to_hrm[$row_assigned_courses['code']] = $row_assigned_courses;
  2282. }
  2283. }
  2284. return $assigned_courses_to_hrm;
  2285. }
  2286. /**
  2287. * check if a course is special (autoregister)
  2288. * @param string course code
  2289. */
  2290. public static function is_special_course($course_code){
  2291. $tbl_course_field_value = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2292. $tbl_course_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  2293. $is_special = false;
  2294. $sql = "SELECT course_code FROM $tbl_course_field_value tcfv INNER JOIN $tbl_course_field tcf ON " .
  2295. " tcfv.field_id = tcf.id WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 AND course_code='$course_code'";
  2296. $result = Database::query($sql);
  2297. $num_rows = Database::num_rows($result);
  2298. if ($num_rows > 0){
  2299. $is_special = true;
  2300. }
  2301. return $is_special;
  2302. }
  2303. /**
  2304. * Update course picture
  2305. * @param string Course code
  2306. * @param string File name
  2307. * @param string The full system name of the image from which course picture will be created.
  2308. * @return bool Returns the resulting. In case of internal error or negative validation returns FALSE.
  2309. */
  2310. public static function update_course_picture($course_code, $filename, $source_file = null) {
  2311. $course_info = api_get_course_info($course_code);
  2312. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path']; // course path
  2313. $course_image = $store_path.'/course-pic.png'; // image name for courses
  2314. $course_medium_image = $store_path.'/course-pic85x85.png';
  2315. //$extension = strtolower(substr(strrchr($filename, '.'), 1));
  2316. if (file_exists($course_image)) {
  2317. @unlink($course_image);
  2318. }
  2319. if (file_exists($course_medium_image)) {
  2320. @unlink($course_medium_image);
  2321. }
  2322. $my_course_image = new Image($source_file);
  2323. $result = $my_course_image->send_image($course_image, -1, 'png');
  2324. //Redimension image to 100x85
  2325. if ($result) {
  2326. $medium = new Image($course_image);
  2327. //$picture_infos = $medium->get_image_size();
  2328. $medium->resize(100, 85, 0, false);
  2329. $medium->send_image($store_path.'/course-pic85x85.png', -1, 'png');
  2330. }
  2331. return $result;
  2332. }
  2333. /**
  2334. * Builds the course block in user_portal.php
  2335. * @todo use Twig
  2336. */
  2337. public static function course_item_html($params, $is_sub_content = false)
  2338. {
  2339. $rowDiv = '<div class="row">';
  2340. $html = '';
  2341. $class = "well course-box";
  2342. if ($is_sub_content) {
  2343. $class = "course_item";
  2344. }
  2345. if (!empty($params['is_session'])) {
  2346. $class .= " session-item";
  2347. }
  2348. $html .= '<div class="'.$class.'">';
  2349. $html .= $rowDiv;
  2350. $html .= '<div class="col-md-11">';
  2351. $html .= $rowDiv;
  2352. $html .= '<div class="col-md-2 course-box-thumbnail-box">';
  2353. if (!empty($params['link'])) {
  2354. $html .= '<a class="thumbnail" href="'.$params['link'].'">';
  2355. $html .= $params['icon'];
  2356. $html .= '</a>';
  2357. } else {
  2358. $html .= '<div class="thumbnail">';
  2359. $html .= $params['icon'];
  2360. $html .= '</div>';
  2361. }
  2362. $html .= '</div>';
  2363. $notifications = isset($params['notifications']) ? $params['notifications'] : null;
  2364. $param_class = isset($params['class']) ? $params['class'] : '';
  2365. if (!empty($params['is_session'])) {
  2366. $param_class .= ' session-box-text';
  2367. } else {
  2368. $param_class .= ' course-box-text';
  2369. }
  2370. $html .= '<div class="col-md-10 '.$param_class.'">';
  2371. $html .='<h3>'.$params['title'].$notifications.'</h3> ';
  2372. if (!empty($params['subtitle'])) {
  2373. $html .= '<small>'.$params['subtitle'].'</small>';
  2374. }
  2375. if (!empty($params['teachers'])) {
  2376. $html .= '<h5>'.Display::return_icon('teacher.png', get_lang('Teacher'), array(), ICON_SIZE_TINY).$params['teachers'].'</h5>';
  2377. }
  2378. if (!empty($params['coaches'])) {
  2379. $html .= '<h5>'.Display::return_icon('teacher.png', get_lang('Coach'), array(), ICON_SIZE_TINY).$params['coaches'].'</h5>';
  2380. }
  2381. $html .= '</div>';
  2382. $html .= '</div>';
  2383. $html .= '</div>';
  2384. $params['right_actions'] = isset($params['right_actions']) ? $params['right_actions'] : null;
  2385. $html .= '<div class="col-md-1 pull-right course-box-actions">'.$params['right_actions'].'</div>';
  2386. $html .= '</div>';
  2387. $html .= '</div>';
  2388. return $html;
  2389. }
  2390. public static function course_item_parent($main_content, $sub_content, $sub_sub_content = null)
  2391. {
  2392. return '<div class="well">'.$main_content.$sub_content.$sub_sub_content.'</div>';
  2393. }
  2394. /**
  2395. * Display special courses (and only these) as several HTML divs of class userportal-course-item
  2396. *
  2397. * Special courses are courses that stick on top of the list and are "auto-registerable"
  2398. * in the sense that any user clicking them is registered as a student
  2399. * @param int User id
  2400. * @param bool Whether to show the document quick-loader or not
  2401. * @return void
  2402. */
  2403. public static function displaySpecialCourses($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null)
  2404. {
  2405. $user_id = intval($user_id);
  2406. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2407. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2408. $special_course_list = self::get_special_course_list();
  2409. $html = null;
  2410. if (!empty($special_course_list)) {
  2411. $with_special_courses = ' course.code IN ("'.implode('","',$special_course_list).'")';
  2412. } else {
  2413. return null;
  2414. }
  2415. $select = " course.id,
  2416. course.code,
  2417. course.subscribe subscr,
  2418. course.unsubscribe unsubscr,
  2419. course_rel_user.status status,
  2420. course_rel_user.sort sort,
  2421. course_rel_user.user_course_cat user_course_cat,
  2422. course_rel_user.user_id";
  2423. if ($getCount) {
  2424. $select = "COUNT(course.id) as total";
  2425. }
  2426. $sql = "SELECT $select
  2427. FROM $tbl_course course
  2428. LEFT JOIN $tbl_course_user course_rel_user
  2429. ON course.id = course_rel_user.c_id AND course_rel_user.user_id = '$user_id'
  2430. WHERE $with_special_courses ";
  2431. if ($getCount) {
  2432. $result = Database::query($sql);
  2433. $row = Database::fetch_array($result);
  2434. return $row['total'];
  2435. }
  2436. $group = " GROUP BY course.code ";
  2437. $sql .= $group;
  2438. $rs_special_course = Database::query($sql);
  2439. $number_of_courses = Database::num_rows($rs_special_course);
  2440. $key = 0;
  2441. if ($number_of_courses > 0) {
  2442. while ($course = Database::fetch_array($rs_special_course)) {
  2443. $course_info = api_get_course_info($course['code']);
  2444. $params = array();
  2445. $course_info['id_session'] = null;
  2446. $course_info['status'] = $course['status'];
  2447. $show_notification = Display::show_notification($course_info);
  2448. if (empty($course['user_id'])) {
  2449. $course['status'] = STUDENT;
  2450. }
  2451. $params['icon'] = Display::return_icon('blackboard.png', $course_info['title'], array(), ICON_SIZE_LARGE);
  2452. $params['right_actions'] = '';
  2453. if (api_is_platform_admin()) {
  2454. if ($load_dirs) {
  2455. $params['right_actions'] .= '<a id="document_preview_'.$course['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>';
  2456. $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>';
  2457. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course['real_id'].'_0', 'class'=>'document_preview_container'));
  2458. } else {
  2459. $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>';
  2460. }
  2461. if ($course['status'] == COURSEMANAGER) {
  2462. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  2463. }
  2464. } else {
  2465. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2466. if ($load_dirs) {
  2467. $params['right_actions'] .= '<a id="document_preview_'.$course['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>';
  2468. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course['real_id'].'_0', 'class'=>'document_preview_container'));
  2469. }
  2470. }
  2471. }
  2472. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  2473. $course_title = '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0&amp;autoreg=1">'.$course_info['title'].'</a>';
  2474. } else {
  2475. $course_title = $course_info['title']." ".Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2476. }
  2477. if (api_get_setting('course.display_coursecode_in_courselist')
  2478. == 'true') {
  2479. $course_title .= ' ('.$course_info['visual_code'].') ';
  2480. }
  2481. if (api_get_setting('course.display_teacher_in_courselist') == 'true') {
  2482. $params['teachers'] = CourseManager::get_teacher_list_from_course_code_to_string($course['real_id'], self::USER_SEPARATOR, true);
  2483. }
  2484. $course_title .= '&nbsp;';
  2485. $course_title .= Display::return_icon('klipper.png', get_lang('CourseAutoRegister'));
  2486. $params['title'] = $course_title;
  2487. $params['link'] = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0&amp;autoreg=1';
  2488. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2489. $params['notifications'] = $show_notification;
  2490. }
  2491. $html .= self::course_item_html($params, false);
  2492. $key++;
  2493. }
  2494. }
  2495. return $html;
  2496. }
  2497. public static function displayPersonalCourseCategories($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null) {
  2498. $tableUserCourseCategory = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2499. // Table definitions
  2500. $TABLECOURS = Database :: get_main_table(TABLE_MAIN_COURSE);
  2501. $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2502. $TABLE_ACCESS_URL_REL_COURSE = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2503. $current_url_id = api_get_current_access_url_id();
  2504. $sql = "SELECT * FROM $tableUserCourseCategory
  2505. WHERE user_id = $user_id";
  2506. if ($getCount) {
  2507. $sql = "SELECT COUNT(id) as total FROM $tableUserCourseCategory WHERE user_id = $user_id";
  2508. $result = Database::query($sql);
  2509. $row = Database::fetch_array($result);
  2510. return $row['total'];
  2511. }
  2512. $order = " ORDER BY sort";
  2513. $sql .= $order;
  2514. if (isset($start) && isset($maxPerPage)) {
  2515. $start = intval($start);
  2516. $maxPerPage = intval($maxPerPage);
  2517. $limitCondition = " LIMIT $start, $maxPerPage";
  2518. $sql .= $limitCondition;
  2519. }
  2520. $result = Database::query($sql);
  2521. $html = null;
  2522. if (Database::num_rows($result)) {
  2523. while ($category = Database::fetch_array($result)) {
  2524. $categoryId = $category['id'];
  2525. $select = " SELECT DISTINCT
  2526. course.id,
  2527. course.title,
  2528. course.code,
  2529. course.subscribe subscr,
  2530. course.unsubscribe unsubscr,
  2531. course_rel_user.status status,
  2532. course_rel_user.sort sort,
  2533. course_rel_user.user_course_cat user_course_cat";
  2534. $from = "$TABLECOURS course, $TABLECOURSUSER course_rel_user, $TABLE_ACCESS_URL_REL_COURSE url, $tableUserCourseCategory user_cat";
  2535. $where = " course.id = course_rel_user.c_id AND
  2536. url.c_id = course.id AND
  2537. user_cat.user_id = $user_id AND
  2538. course_rel_user.user_id = $user_id AND
  2539. course_rel_user.user_course_cat = $categoryId ";
  2540. // Use user's classification for courses (if any).
  2541. $order = " ORDER BY user_cat.sort ASC";
  2542. $sql = "$select FROM $from WHERE $where ";
  2543. // corresponding to the current URL.
  2544. if (api_get_multiple_access_url() && $current_url_id != -1) {
  2545. $sql .= " AND url.course_code=course.code AND access_url_id='".$current_url_id."'";
  2546. }
  2547. $sql .= $order;
  2548. $resultCourse = Database::query($sql);
  2549. $course_list = array();
  2550. $courseHTML = null;
  2551. // Browse through all courses.
  2552. while ($course = Database::fetch_array($resultCourse)) {
  2553. $course_info = api_get_course_info($course['code']);
  2554. //$course['id_session'] = null;
  2555. $course_info['id_session'] = null;
  2556. $course_info['status'] = $course['status'];
  2557. //In order to avoid doubles
  2558. if (in_array($course_info['real_id'], $course_list)) {
  2559. continue;
  2560. } else {
  2561. $course_list[] = $course_info['real_id'];
  2562. }
  2563. // For each course, get if there is any notification icon to show
  2564. // (something that would have changed since the user's last visit).
  2565. $show_notification = Display :: show_notification($course_info);
  2566. // New code displaying the user's status in respect to this course.
  2567. $status_icon = Display::return_icon('blackboard.png', $course_info['title'], array(), ICON_SIZE_LARGE);
  2568. $params = array();
  2569. $params['right_actions'] = '';
  2570. if (api_is_platform_admin()) {
  2571. if ($load_dirs) {
  2572. $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>';
  2573. $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>';
  2574. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2575. } else {
  2576. $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>';
  2577. }
  2578. if ($course_info['status'] == COURSEMANAGER) {
  2579. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  2580. }
  2581. } else {
  2582. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2583. if ($load_dirs) {
  2584. $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>';
  2585. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2586. } else {
  2587. if ($course_info['status'] == COURSEMANAGER) {
  2588. $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>';
  2589. }
  2590. }
  2591. }
  2592. }
  2593. $course_title_url = '';
  2594. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  2595. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  2596. $course_title = Display::url($course_info['title'], $course_title_url);
  2597. } else {
  2598. $course_title = $course_info['title']." ".Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2599. }
  2600. // Start displaying the course block itself
  2601. if (api_get_setting('course.display_coursecode_in_courselist') == 'true') {
  2602. $course_title .= ' ('.$course_info['visual_code'].') ';
  2603. }
  2604. if (api_get_setting('course.display_teacher_in_courselist') == 'true') {
  2605. $teachers = CourseManager::get_teacher_list_from_course_code_to_string($course['real_id'], self::USER_SEPARATOR, true);
  2606. }
  2607. $params['link'] = $course_title_url;
  2608. $params['icon'] = $status_icon;
  2609. $params['title'] = $course_title;
  2610. $params['teachers'] = $teachers;
  2611. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2612. $params['notifications'] = $show_notification;
  2613. }
  2614. $courseHTML .= self::course_item_html($params, true);
  2615. }
  2616. $params = array();
  2617. $params['icon'] = Display::return_icon('folder_yellow.png', $category['title'], array(), ICON_SIZE_LARGE);
  2618. $params['title'] = $category['title'];
  2619. $params['class'] = 'table_user_course_category';
  2620. $html .= self::course_item_parent(self::course_item_html($params, true), $courseHTML);
  2621. }
  2622. }
  2623. return $html;
  2624. }
  2625. /**
  2626. * @param int $user_id
  2627. * @param $filter
  2628. * @param bool $load_dirs
  2629. * @param int $getCount
  2630. * @param int $start
  2631. * @param null $maxPerPage
  2632. * @return null|string
  2633. */
  2634. public static function displayCourses($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null)
  2635. {
  2636. // Table definitions
  2637. $TABLECOURS = Database :: get_main_table(TABLE_MAIN_COURSE);
  2638. $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2639. $TABLE_ACCESS_URL_REL_COURSE = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2640. $current_url_id = api_get_current_access_url_id();
  2641. // Get course list auto-register
  2642. $special_course_list = self::get_special_course_list();
  2643. $without_special_courses = '';
  2644. if (!empty($special_course_list)) {
  2645. //$without_special_courses = ' AND course.code NOT IN ("'.implode('","',$special_course_list).'")';
  2646. }
  2647. $select = " SELECT DISTINCT
  2648. course.id,
  2649. course.title,
  2650. course.code,
  2651. course.subscribe subscr,
  2652. course.unsubscribe unsubscr,
  2653. course_rel_user.status status,
  2654. course_rel_user.sort sort,
  2655. course_rel_user.user_course_cat user_course_cat,
  2656. course.id as real_id
  2657. ";
  2658. $from = "$TABLECOURS course, $TABLECOURSUSER course_rel_user, $TABLE_ACCESS_URL_REL_COURSE url ";
  2659. $where = " course.id = course_rel_user.c_id AND
  2660. url.c_id = course.id AND
  2661. course_rel_user.user_id = '".$user_id."' AND
  2662. course_rel_user.user_course_cat = 0
  2663. ";
  2664. $order = " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  2665. if ($getCount) {
  2666. $select = "SELECT count(course.id) as total";
  2667. }
  2668. $sql = "$select FROM $from WHERE $where $without_special_courses ";
  2669. // corresponding to the current URL.
  2670. if (api_get_multiple_access_url() && $current_url_id != -1) {
  2671. $sql .= " AND url.c_id = course.id AND access_url_id='".$current_url_id."'";
  2672. }
  2673. $sql .= $order;
  2674. if (isset($start) && isset($maxPerPage)) {
  2675. $start = intval($start);
  2676. $maxPerPage = intval($maxPerPage);
  2677. $limitCondition = " LIMIT $start, $maxPerPage";
  2678. $sql .= $limitCondition;
  2679. }
  2680. if ($getCount) {
  2681. $result = Database::query($sql);
  2682. $row = Database::fetch_array($result);
  2683. return $row['total'];
  2684. }
  2685. $result = Database::query($sql);
  2686. $html = null;
  2687. $course_list = array();
  2688. // Browse through all courses.
  2689. while ($course = Database::fetch_array($result)) {
  2690. $course_info = api_get_course_info($course['code']);
  2691. $course_info['id_session'] = null;
  2692. $course_info['status'] = $course['status'];
  2693. //In order to avoid doubles
  2694. if (in_array($course_info['real_id'], $course_list)) {
  2695. continue;
  2696. } else {
  2697. $course_list[] = $course_info['real_id'];
  2698. }
  2699. // For each course, get if there is any notification icon to show
  2700. // (something that would have changed since the user's last visit).
  2701. $show_notification = Display :: show_notification($course_info);
  2702. // New code displaying the user's status in respect to this course.
  2703. $status_icon = Display::return_icon('blackboard.png', $course_info['title'], array(), ICON_SIZE_LARGE);
  2704. $params = array();
  2705. $params['right_actions'] = '';
  2706. if (api_is_platform_admin()) {
  2707. if ($load_dirs) {
  2708. $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>';
  2709. $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>';
  2710. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2711. } else {
  2712. $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>';
  2713. }
  2714. if ($course_info['status'] == COURSEMANAGER) {
  2715. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  2716. }
  2717. } else {
  2718. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2719. if ($load_dirs) {
  2720. $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>';
  2721. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2722. } else {
  2723. if ($course_info['status'] == COURSEMANAGER) {
  2724. $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>';
  2725. }
  2726. }
  2727. }
  2728. }
  2729. //$course_title = $course_info['title'];
  2730. $course_title_url = '';
  2731. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  2732. //$course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  2733. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['code'].'/index.php?id_session=0';
  2734. $course_title = Display::url($course_info['title'], $course_title_url);
  2735. } else {
  2736. $course_title = $course_info['title']." ".Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2737. }
  2738. // Start displaying the course block itself
  2739. if (api_get_setting('course.display_coursecode_in_courselist') == 'true') {
  2740. $course_title .= ' ('.$course_info['visual_code'].') ';
  2741. }
  2742. $teachers = null;
  2743. if (api_get_setting('course.display_teacher_in_courselist') == 'true') {
  2744. $teachers = $course_info['teacher_list_formatted'];
  2745. }
  2746. $params['link'] = $course_title_url;
  2747. $params['icon'] = $status_icon;
  2748. $params['title'] = $course_title;
  2749. $params['teachers'] = $teachers;
  2750. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2751. $params['notifications'] = $show_notification;
  2752. }
  2753. $is_subcontent = true;
  2754. if (empty($user_category_id)) {
  2755. $is_subcontent = false;
  2756. }
  2757. $html .= self::course_item_html($params, $is_subcontent);
  2758. }
  2759. return $html;
  2760. }
  2761. /**
  2762. * Display courses (without special courses) as several HTML divs
  2763. * of course categories, as class userportal-catalog-item.
  2764. * @uses display_courses_in_category() to display the courses themselves
  2765. * @param int user id
  2766. * @param bool Whether to show the document quick-loader or not
  2767. * @return void
  2768. */
  2769. public static function display_courses($user_id, $load_dirs = false) {
  2770. $user_id = intval($user_id);
  2771. if (empty($user_id)) {
  2772. $user_id = api_get_user_id();
  2773. }
  2774. $html = null;
  2775. // Step 1: We get all the categories of the user
  2776. $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2777. $sql = "SELECT id, title FROM $tucc WHERE user_id='".$user_id."' ORDER BY sort ASC";
  2778. $result = Database::query($sql);
  2779. while ($row = Database::fetch_array($result)) {
  2780. $params = array();
  2781. // We simply display the title of the category.
  2782. $params['icon'] = Display::return_icon('folder_yellow.png', $row['title'], array(), ICON_SIZE_LARGE);
  2783. $params['title'] = $row['title'];
  2784. $params['class'] = 'table_user_course_category';
  2785. $html .= self::course_item_parent(self::course_item_html($params, true), self :: display_courses_in_category($row['id'], $load_dirs));
  2786. }
  2787. // Step 2: We display the course without a user category.
  2788. $html .= self :: display_courses_in_category(0, $load_dirs);
  2789. return $html;
  2790. }
  2791. /**
  2792. * Display courses inside a category (without special courses) as HTML dics of
  2793. * class userportal-course-item.
  2794. * @param int User category id
  2795. * @param bool Whether to show the document quick-loader or not
  2796. * @return void
  2797. */
  2798. public static function display_courses_in_category($user_category_id, $load_dirs = false)
  2799. {
  2800. $user_id = api_get_user_id();
  2801. // Table definitions
  2802. $TABLECOURS = Database :: get_main_table(TABLE_MAIN_COURSE);
  2803. $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2804. $TABLE_ACCESS_URL_REL_COURSE = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2805. $current_url_id = api_get_current_access_url_id();
  2806. // Get course list auto-register
  2807. $special_course_list = self::get_special_course_list();
  2808. $without_special_courses = '';
  2809. if (!empty($special_course_list)) {
  2810. $without_special_courses = ' AND course.code NOT IN ("'.implode('","',$special_course_list).'")';
  2811. }
  2812. //AND course_rel_user.relation_type<>".COURSE_RELATION_TYPE_RRHH."
  2813. $sql = "SELECT course.id,
  2814. course.title,
  2815. course.code,
  2816. course.subscribe subscr,
  2817. course.unsubscribe unsubscr,
  2818. course_rel_user.status status,
  2819. course_rel_user.sort sort,
  2820. course_rel_user.user_course_cat user_course_cat
  2821. FROM $TABLECOURS course,
  2822. $TABLECOURSUSER course_rel_user, ".$TABLE_ACCESS_URL_REL_COURSE." url
  2823. WHERE course.code = course_rel_user.course_code AND
  2824. url.c_id = course.id AND
  2825. course_rel_user.user_id = '".$user_id."' AND
  2826. course_rel_user.user_course_cat='".$user_category_id."' $without_special_courses ";
  2827. // If multiple URL access mode is enabled, only fetch courses
  2828. // corresponding to the current URL.
  2829. if (api_get_multiple_access_url() && $current_url_id != -1) {
  2830. $sql .= " AND url.course_code=course.code AND access_url_id='".$current_url_id."'";
  2831. }
  2832. // Use user's classification for courses (if any).
  2833. $sql .= " ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  2834. $result = Database::query($sql);
  2835. $status_icon = '';
  2836. $html = '';
  2837. $course_list = array();
  2838. // Browse through all courses.
  2839. while ($course = Database::fetch_array($result)) {
  2840. $course_info = api_get_course_info($course['code']);
  2841. //$course['id_session'] = null;
  2842. $course_info['id_session'] = null;
  2843. $course_info['status'] = $course['status'];
  2844. //In order to avoid doubles
  2845. if (in_array($course_info['real_id'], $course_list)) {
  2846. continue;
  2847. } else {
  2848. $course_list[] = $course_info['real_id'];
  2849. }
  2850. // For each course, get if there is any notification icon to show
  2851. // (something that would have changed since the user's last visit).
  2852. $show_notification = Display :: show_notification($course_info);
  2853. // New code displaying the user's status in respect to this course.
  2854. $status_icon = Display::return_icon('blackboard.png', $course_info['title'], array(), ICON_SIZE_LARGE);
  2855. $params = array();
  2856. $params['right_actions'] = '';
  2857. if (api_is_platform_admin()) {
  2858. if ($load_dirs) {
  2859. $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>';
  2860. $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>';
  2861. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2862. } else {
  2863. $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>';
  2864. }
  2865. if ($course_info['status'] == COURSEMANAGER) {
  2866. //echo Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style'=>'width: 11px; height: 11px;'));
  2867. }
  2868. } else {
  2869. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2870. if ($load_dirs) {
  2871. $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>';
  2872. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_0', 'class'=>'document_preview_container'));
  2873. } else {
  2874. if ($course_info['status'] == COURSEMANAGER) {
  2875. $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>';
  2876. }
  2877. }
  2878. }
  2879. }
  2880. $course_title = $course_info['title'];
  2881. $course_title_url = '';
  2882. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
  2883. $course_title_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session=0';
  2884. $course_title = Display::url($course_info['title'], $course_title_url);
  2885. } else {
  2886. $course_title = $course_info['title']." ".Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2887. }
  2888. // Start displaying the course block itself
  2889. if (api_get_setting('course.display_coursecode_in_courselist') == 'true') {
  2890. $course_title .= ' ('.$course_info['visual_code'].') ';
  2891. }
  2892. if (api_get_setting('course.display_teacher_in_courselist') == 'true') {
  2893. $teachers = CourseManager::get_teacher_list_from_course_code_to_string($course['real_id'], self::USER_SEPARATOR, true);
  2894. }
  2895. $params['link'] = $course_title_url;
  2896. $params['icon'] = $status_icon;
  2897. $params['title'] = $course_title;
  2898. $params['teachers'] = $teachers;
  2899. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2900. $params['notifications'] = $show_notification;
  2901. }
  2902. $is_subcontent = true;
  2903. if (empty($user_category_id)) {
  2904. $is_subcontent = false;
  2905. }
  2906. $html .= self::course_item_html($params, $is_subcontent);
  2907. }
  2908. return $html;
  2909. }
  2910. /**
  2911. * Retrieves the user defined course categories
  2912. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2913. * @return array containing all the titles of the user defined courses with the id as key of the array
  2914. */
  2915. function get_user_course_categories()
  2916. {
  2917. $output = array();
  2918. $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  2919. $sql = "SELECT * FROM ".$table_category." WHERE user_id='".Database::escape_string(api_get_user_id())."'";
  2920. $result = Database::query($sql);
  2921. while ($row = Database::fetch_array($result)) {
  2922. $output[$row['id']] = $row['title'];
  2923. }
  2924. return $output;
  2925. }
  2926. /**
  2927. * Get the course id based on the original id and field name in the extra fields. Returns 0 if course was not found
  2928. *
  2929. * @param string Original course id
  2930. * @param string Original field name
  2931. * @return int Course id
  2932. */
  2933. public static function get_course_id_from_original_id($original_course_id_value, $original_course_id_name)
  2934. {
  2935. $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2936. $table_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
  2937. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2938. $sql_course = "SELECT c.id FROM $table_field cf INNER JOIN $t_cfv cfv ON cfv.field_id = cf.id
  2939. INNER JOIN $courseTable as c on c.code = cfv.course_code
  2940. WHERE field_variable='$original_course_id_name' AND field_value='$original_course_id_value'";
  2941. $res = Database::query($sql_course);
  2942. $row = Database::fetch_object($res);
  2943. if ($row != false) {
  2944. return $row->id;
  2945. } else {
  2946. return 0;
  2947. }
  2948. }
  2949. /**
  2950. * Display code for one specific course a logged in user is subscribed to.
  2951. * Shows a link to the course, what's new icons...
  2952. *
  2953. * $my_course['d'] - course directory
  2954. * $my_course['i'] - course title
  2955. * $my_course['c'] - visual course code
  2956. * $my_course['k'] - system course code
  2957. *
  2958. * @param array Course details
  2959. * @param integer Session ID
  2960. * @param string CSS class to apply to course entry
  2961. * @param boolean Whether the session is supposedly accessible now (not in the case it has passed and is in invisible/unaccessible mode)
  2962. * @param bool Whether to show the document quick-loader or not
  2963. * @return string The HTML to be printed for the course entry
  2964. *
  2965. * @version 1.0.3
  2966. * @todo refactor into different functions for database calls | logic | display
  2967. * @todo replace single-character $my_course['d'] indices
  2968. * @todo move code for what's new icons to a separate function to clear things up
  2969. * @todo add a parameter user_id so that it is possible to show the courselist of other users (=generalisation). This will prevent having to write a new function for this.
  2970. */
  2971. public static function get_logged_user_course_html($course, $session_id = 0, $load_dirs = false)
  2972. {
  2973. $course_info = api_get_course_info_by_id($course['id']);
  2974. $course_info['id_session'] = $session_id;
  2975. // Display course entry.
  2976. // Show a link to the course, unless the course is closed and user is not course admin.
  2977. $session_url = '';
  2978. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED || $course_info['user_status_in_course'] == COURSEMANAGER) {
  2979. $session_url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session='.$course_info['id_session'];
  2980. $session_title = '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?id_session='.$course_info['id_session'].'">'.$course_info['name'].'</a>';
  2981. } else {
  2982. $session_title = $course_info['name'].' '.Display::tag('span',get_lang('CourseClosed'), array('class'=>'item_closed'));
  2983. }
  2984. $params = array();
  2985. $params['icon'] = Display::return_icon('blackboard_blue.png', $course_info['name'], array(), ICON_SIZE_LARGE);
  2986. $params['link'] = $session_url;
  2987. $params['title'] = $session_title;
  2988. $params['right_actions'] = '';
  2989. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  2990. if ($load_dirs) {
  2991. $params['right_actions'] .= '<a id="document_preview_'.$course_info['real_id'].'_'.$course_info['id_session'].'" class="document_preview" href="javascript:void(0);">'.
  2992. Display::return_icon('folder.png', get_lang('Documents'), array('align' => 'absmiddle'),ICON_SIZE_SMALL).'</a>';
  2993. $params['right_actions'] .= Display::div('', array('id' => 'document_result_'.$course_info['real_id'].'_'.$course_info['id_session'], 'class'=>'document_preview_container'));
  2994. }
  2995. }
  2996. if (api_get_setting('course.display_coursecode_in_courselist') == 'true') {
  2997. $session_title .= ' ('.$course_info['visual_code'].') ';
  2998. }
  2999. if (api_get_setting('course.display_teacher_in_courselist') == 'true') {
  3000. $teacher_list = CourseManager::get_teacher_list_from_course_code_to_string($course_info['real_id'], self::USER_SEPARATOR, true);
  3001. $course_coachs = CourseManager::get_coachs_from_course_to_string($course_info['id_session'], $course_info['real_id'], self::USER_SEPARATOR, true);
  3002. $params['teachers'] = $teacher_list;
  3003. $params['coaches'] = $course_coachs;
  3004. }
  3005. $session_title .= isset($course['special_course']) ? ' '.Display::return_icon('klipper.png', get_lang('CourseAutoRegister')) : '';
  3006. // Display the "what's new" icons
  3007. if ($course_info['visibility'] != COURSE_VISIBILITY_CLOSED) {
  3008. $session_title .= Display :: show_notification($course_info);
  3009. }
  3010. $params['title'] = $session_title;
  3011. $params['extra'] = '';
  3012. $html = self::course_item_html($params, true);
  3013. return $html;
  3014. }
  3015. /**
  3016. *
  3017. * @param string source course code
  3018. * @param int source session id
  3019. * @param string destination course code
  3020. * @param int destination session id
  3021. * @return bool
  3022. */
  3023. public static function copy_course($source_course_code, $source_session_id, $destination_course_code, $destination_session_id, $params = array()) {
  3024. require_once api_get_path(SYS_CODE_PATH).'coursecopy/classes/CourseBuilder.class.php';
  3025. require_once api_get_path(SYS_CODE_PATH).'coursecopy/classes/CourseRestorer.class.php';
  3026. require_once api_get_path(SYS_CODE_PATH).'coursecopy/classes/CourseSelectForm.class.php';
  3027. $course_info = api_get_course_info($source_course_code);
  3028. if (!empty($course_info)) {
  3029. $cb = new CourseBuilder('', $course_info);
  3030. $course = $cb->build($source_session_id, $source_course_code, true);
  3031. $course_restorer = new CourseRestorer($course);
  3032. $course_restorer->skip_content = $params;
  3033. $course_restorer->restore($destination_course_code, $destination_session_id, true, true);
  3034. return true;
  3035. }
  3036. return false;
  3037. }
  3038. /**
  3039. * A simpler version of the copy_course, the function creates an empty course with an autogenerated course code
  3040. *
  3041. * @param string new course title
  3042. * @param string source course code
  3043. * @param int source session id
  3044. * @param int destination session id
  3045. * @param bool new copied tools (Exercises and LPs)will be set to invisible by default?
  3046. *
  3047. * @return array
  3048. */
  3049. public static function copy_course_simple($new_title, $source_course_code, $source_session_id = 0, $destination_session_id = 0, $params = array())
  3050. {
  3051. $source_course_info = api_get_course_info($source_course_code);
  3052. if (!empty($source_course_info)) {
  3053. $new_course_code = self::generate_nice_next_course_code($source_course_code);
  3054. if ($new_course_code) {
  3055. $new_course_info = self::create_course($new_title, $new_course_code, false);
  3056. if (!empty($new_course_info['code'])) {
  3057. $result = self::copy_course($source_course_code, $source_session_id, $new_course_info['code'], $destination_session_id, $params);
  3058. if ($result) {
  3059. return $new_course_info;
  3060. }
  3061. }
  3062. }
  3063. }
  3064. return false;
  3065. }
  3066. /**
  3067. * Creates a new course code based in a given code
  3068. *
  3069. * @param string wanted code
  3070. * <code> $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3</code>
  3071. * if the course code doest not exist in the DB the same course code will be returned
  3072. * @return string wanted unused code
  3073. */
  3074. public static function generate_nice_next_course_code($wanted_code)
  3075. {
  3076. $course_code_ok = !self::course_code_exists($wanted_code);
  3077. if (!$course_code_ok) {
  3078. $wanted_code = self::generate_course_code($wanted_code);
  3079. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  3080. $wanted_code = Database::escape_string($wanted_code);
  3081. $sql = "SELECT count(*) as count FROM $table WHERE code LIKE '$wanted_code%'";
  3082. $result = Database::query($sql);
  3083. if (Database::num_rows($result) > 0 ) {
  3084. $row = Database::fetch_array($result);
  3085. $count = $row['count'] + 1;
  3086. $wanted_code = $wanted_code.'_'.$count;
  3087. $result = api_get_course_info($wanted_code);
  3088. if (empty($result)) {
  3089. return $wanted_code;
  3090. }
  3091. }
  3092. return false;
  3093. }
  3094. return $wanted_code;
  3095. }
  3096. /**
  3097. * Gets the status of the users agreement in a course course-session
  3098. *
  3099. * @param int user id
  3100. * @param string course code
  3101. * @param int session id
  3102. * @return boolean
  3103. */
  3104. public static function is_user_accepted_legal($user_id, $courseInfo, $session_id = null)
  3105. {
  3106. $user_id = intval($user_id);
  3107. $course_code = $courseInfo['code'];
  3108. $course_id = $courseInfo['real_id'];
  3109. $course_code = Database::escape_string($course_code);
  3110. $session_id = intval($session_id);
  3111. if (empty($session_id)) {
  3112. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3113. $sql = "SELECT legal_agreement FROM $table
  3114. WHERE user_id = $user_id AND c_id = '$course_id' ";
  3115. $result = Database::query($sql);
  3116. if (Database::num_rows($result) > 0 ) {
  3117. $result = Database::fetch_array($result);
  3118. if ($result['legal_agreement'] == 1 ) {
  3119. return true;
  3120. }
  3121. }
  3122. return false;
  3123. } else {
  3124. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3125. $sql = "SELECT legal_agreement FROM $table
  3126. WHERE id_user = $user_id AND c_id ='$course_id' AND id_session = $session_id";
  3127. $result = Database::query($sql);
  3128. if (Database::num_rows($result) > 0 ) {
  3129. $result = Database::fetch_array($result);
  3130. if ($result['legal_agreement'] == 1 ) {
  3131. return true;
  3132. }
  3133. }
  3134. return false;
  3135. }
  3136. return false;
  3137. }
  3138. /**
  3139. * Saves the user-course legal agreement
  3140. * @param int user id
  3141. * @param string course code
  3142. * @param int session id
  3143. */
  3144. function save_user_legal($user_id, $courseInfo, $session_id = null)
  3145. {
  3146. $user_id = intval($user_id);
  3147. $course_code = $courseInfo['code'];
  3148. $course_id = $courseInfo['real_id'];
  3149. $course_code = Database::escape_string($course_code);
  3150. $session_id = intval($session_id);
  3151. if (empty($session_id)) {
  3152. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3153. $sql = "UPDATE $table SET legal_agreement = '1'
  3154. WHERE user_id = $user_id AND c_id ='$course_id' ";
  3155. $result = Database::query($sql);
  3156. } else {
  3157. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3158. $sql = "UPDATE $table SET legal_agreement = '1'
  3159. WHERE id_user = $user_id AND c_id = '$course_id' AND id_session = $session_id";
  3160. $result = Database::query($sql);
  3161. }
  3162. }
  3163. public static function get_user_course_vote($user_id, $course_id, $session_id = null, $url_id = null) {
  3164. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  3165. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3166. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3167. $user_id = intval($user_id);
  3168. if (empty($user_id)) {
  3169. return false;
  3170. }
  3171. $params = array(
  3172. 'user_id' => $user_id,
  3173. 'c_id' => $course_id,
  3174. 'session_id' => $session_id,
  3175. 'url_id' => $url_id
  3176. );
  3177. $result = Database::select('vote', $table_user_course_vote, array('where' => array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
  3178. if (!empty($result)) {
  3179. return $result['vote'];
  3180. }
  3181. return false;
  3182. }
  3183. public static function get_course_ranking($course_id, $session_id = null, $url_id = null) {
  3184. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3185. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3186. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3187. $params = array(
  3188. 'c_id' => $course_id,
  3189. 'session_id' => $session_id,
  3190. 'url_id' => $url_id
  3191. );
  3192. $result = Database::select('c_id, accesses, total_score, users', $table_course_ranking, array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
  3193. $point_average_in_percentage = 0;
  3194. $point_average_in_star = 0;
  3195. $users_who_voted = 0;
  3196. if (!empty($result['users'])) {
  3197. $users_who_voted = $result['users'];
  3198. $point_average_in_percentage = round($result['total_score']/$result['users'] * 100 / 5, 2);
  3199. $point_average_in_star = round($result['total_score']/$result['users'], 1);
  3200. }
  3201. $result['user_vote'] = false;
  3202. if (!api_is_anonymous()) {
  3203. $result['user_vote'] = self::get_user_course_vote(api_get_user_id(), $course_id, $session_id,$url_id);
  3204. }
  3205. $result['point_average'] = $point_average_in_percentage;
  3206. $result['point_average_star'] = $point_average_in_star;
  3207. $result['users_who_voted'] = $users_who_voted;
  3208. return $result;
  3209. }
  3210. /**
  3211. *
  3212. * Updates the course ranking
  3213. * @param int course id
  3214. * @param int session id
  3215. * @param id url id
  3216. *
  3217. **/
  3218. public static function update_course_ranking($course_id = null, $session_id = null, $url_id = null, $points_to_add = null, $add_access = true, $add_user = true)
  3219. {
  3220. //Course catalog stats modifications see #4191
  3221. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3222. $now = api_get_utc_datetime();
  3223. $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
  3224. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3225. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3226. $params = array(
  3227. 'c_id' => $course_id,
  3228. 'session_id' => $session_id,
  3229. 'url_id' => $url_id,
  3230. 'creation_date' => $now,
  3231. );
  3232. $result = Database::select('id, accesses, total_score, users', $table_course_ranking, array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
  3233. // Problem here every thime we load the courses/XXXX/index.php course home page we update the access
  3234. if (empty($result)) {
  3235. if ($add_access) {
  3236. $params['accesses'] = 1;
  3237. }
  3238. //The votes and users are empty
  3239. if (isset($points_to_add) && !empty($points_to_add)) {
  3240. $params['total_score'] = intval($points_to_add);
  3241. }
  3242. if ($add_user) {
  3243. $params['users'] = 1;
  3244. }
  3245. $result = Database::insert($table_course_ranking, $params);
  3246. } else {
  3247. $my_params = array();
  3248. if ($add_access) {
  3249. $my_params['accesses'] = intval($result['accesses']) + 1;
  3250. }
  3251. if (isset($points_to_add) && !empty($points_to_add)) {
  3252. $my_params['total_score'] = $result['total_score'] + $points_to_add;
  3253. }
  3254. if ($add_user) {
  3255. $my_params['users'] = $result['users'] + 1;
  3256. }
  3257. if (!empty($my_params)) {
  3258. $result = Database::update($table_course_ranking, $my_params, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
  3259. }
  3260. }
  3261. return $result;
  3262. }
  3263. /**
  3264. * Add user vote to a course
  3265. *
  3266. * @param int user id
  3267. * @param int vote [1..5]
  3268. * @param int course id
  3269. * @param int session id
  3270. * @param int url id (access_url_id)
  3271. * @return mixed 'added', 'updated' or 'nothing'
  3272. *
  3273. */
  3274. public static function add_course_vote($user_id, $vote, $course_id, $session_id = null, $url_id = null)
  3275. {
  3276. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  3277. $course_id = empty($course_id) ? api_get_course_int_id() : intval($course_id);
  3278. if (empty($course_id) || empty($user_id)) {
  3279. return false;
  3280. }
  3281. if (!in_array($vote, array(1,2,3,4,5))) {
  3282. return false;
  3283. }
  3284. $session_id = !isset($session_id) ? api_get_session_id() : intval($session_id);
  3285. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3286. $vote = intval($vote);
  3287. $params = array(
  3288. 'user_id' => intval($user_id),
  3289. 'c_id' => $course_id,
  3290. 'session_id' => $session_id,
  3291. 'url_id' => $url_id,
  3292. 'vote' => $vote
  3293. );
  3294. $action_done = 'nothing';
  3295. $result = Database::select('id, vote', $table_user_course_vote, array('where' => array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
  3296. if (empty($result)) {
  3297. $result = Database::insert($table_user_course_vote, $params);
  3298. $points_to_add = $vote;
  3299. $add_user = true;
  3300. $action_done = 'added';
  3301. } else {
  3302. $my_params = array('vote' => $vote);
  3303. $points_to_add = $vote - $result['vote'];
  3304. $add_user = false;
  3305. $result = Database::update($table_user_course_vote, $my_params, array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params));
  3306. $action_done = 'updated';
  3307. }
  3308. //Current points
  3309. if (!empty($points_to_add)) {
  3310. self::update_course_ranking($course_id, $session_id, $url_id, $points_to_add, false, $add_user);
  3311. }
  3312. return $action_done;
  3313. }
  3314. /**
  3315. * Remove course ranking + user votes
  3316. *
  3317. * @param int course id
  3318. * @param int session id
  3319. * @param int url id
  3320. *
  3321. */
  3322. public function remove_course_ranking($course_id, $session_id, $url_id = null) {
  3323. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3324. $table_user_course_vote = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
  3325. if (!empty($course_id) && isset($session_id)) {
  3326. $url_id = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
  3327. $params = array(
  3328. 'c_id' => $course_id,
  3329. 'session_id' => $session_id,
  3330. 'url_id' => $url_id,
  3331. );
  3332. Database::delete($table_course_ranking, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
  3333. Database::delete($table_user_course_vote, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
  3334. }
  3335. }
  3336. /**
  3337. * Returns an array with the hottest courses
  3338. * @param int number of days
  3339. * @param int number of hottest courses
  3340. */
  3341. public static function returnHotCourses($days = 30, $limit = 5)
  3342. {
  3343. $urlId = api_get_current_access_url_id();
  3344. $limit = intval($limit);
  3345. // Getting my courses
  3346. $my_course_list = CourseManager::get_courses_list_by_user_id(api_get_user_id());
  3347. $my_course_code_list = array();
  3348. foreach ($my_course_list as $course) {
  3349. $my_course_code_list[$course['real_id']] = $course['real_id'];
  3350. }
  3351. if (api_is_drh()) {
  3352. $courses = CourseManager::get_courses_followed_by_drh(api_get_user_id());
  3353. foreach ($courses as $course) {
  3354. $my_course_code_list[$course['real_id']] = $course['real_id'];
  3355. }
  3356. }
  3357. $table_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  3358. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3359. $table_course_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3360. //@todo all dates in the tracking_course_access, last_access are in the DB time (NOW) not UTC
  3361. /*
  3362. $today = api_get_utc_datetime();
  3363. $today_diff = time() -intval($days)*24*60*60;
  3364. $today_diff = api_get_utc_datetime($today_diff);
  3365. * */
  3366. $sql = "SELECT COUNT(course_access_id) course_count, a.c_id, visibility ".
  3367. "FROM $table_course c INNER JOIN $table_course_access a ".
  3368. " ON (c.id = a.c_id) INNER JOIN $table_course_url u ON u.c_id = c.id ".
  3369. " WHERE u.access_url_id = ".$urlId." AND".
  3370. " login_course_date <= now() AND ".
  3371. " login_course_date > DATE_SUB(now(), INTERVAL $days DAY) AND".
  3372. " visibility <> '".COURSE_VISIBILITY_CLOSED."'".
  3373. " GROUP BY a.c_id".
  3374. " ORDER BY course_count DESC".
  3375. " LIMIT $limit";
  3376. $result = Database::query($sql);
  3377. $courses = array();
  3378. if (Database::num_rows($result)) {
  3379. $courses = Database::store_result($result, 'ASSOC');
  3380. $courses = self::process_hot_course_item($courses, $my_course_code_list);
  3381. }
  3382. return $courses;
  3383. }
  3384. public static function process_hot_course_item($courses, $my_course_code_list = array()) {
  3385. $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
  3386. foreach ($courses as &$my_course) {
  3387. $course_info = api_get_course_info_by_id($my_course['c_id']);
  3388. $my_course['extra_info'] = $course_info;
  3389. $my_course['extra_info']['go_to_course_button'] = '';
  3390. $my_course['extra_info']['register_button'] = '';
  3391. $access_link = self::get_access_link_by_user(api_get_user_id(), $course_info, $my_course_code_list);
  3392. //Course visibility
  3393. if ($access_link && in_array('register', $access_link)) {
  3394. $stok = Security::get_token();
  3395. $my_course['extra_info']['register_button'] = Display::url(get_lang('Subscribe'), api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php?action=subscribe&amp;sec_token='.$stok, array('class' => 'btn btn-primary'));
  3396. }
  3397. if ($access_link && in_array('enter', $access_link)) {
  3398. $my_course['extra_info']['go_to_course_button'] = Display::url(get_lang('GoToCourse'), api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php', array('class' => 'btn btn-primary'));
  3399. }
  3400. // Description
  3401. $my_course['extra_info']['description_button'] = '';
  3402. if ($course_info['visibility'] == COURSE_VISIBILITY_OPEN_WORLD || in_array($course_info['real_id'], $my_course_code_list) ) {
  3403. $my_course['extra_info']['description_button'] = Display::url(get_lang('Description'), api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?a=show_course_information&amp;code='.$course_info['code'], array('class' => 'ajax btn btn-default'));
  3404. }
  3405. $my_course['extra_info']['teachers'] = CourseManager::get_teacher_list_from_course_code_to_string($course_info['real_id']);
  3406. $point_info = self::get_course_ranking($course_info['real_id'], 0);
  3407. $my_course['extra_info']['rating_html'] = Display::return_rating_system('star_'.$course_info['real_id'], $ajax_url.'&amp;course_id='.$course_info['real_id'], $point_info);
  3408. }
  3409. return $courses;
  3410. }
  3411. public static function return_most_accessed_courses($limit = 5) {
  3412. $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
  3413. $params['url_id'] = api_get_current_access_url_id();
  3414. $result = Database::select('c_id, accesses, total_score, users', $table_course_ranking, array('where' => array('url_id = ?' => $params), 'order' => 'accesses DESC', 'limit' => $limit), 'all', true);
  3415. return $result;
  3416. }
  3417. /**
  3418. *
  3419. * @return ResultSet
  3420. */
  3421. static function list_inactive_courses($ceiling, $visibility_level = COURSE_VISIBILITY_REGISTERED) {
  3422. $ceiling = is_numeric($ceiling) ? (int) $ceiling : strtotime($ceiling);
  3423. $ceiling = date('Y-m-d H:i:s', $ceiling);
  3424. $visibility_level = $visibility_level ? $visibility_level : '0';
  3425. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3426. $table_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  3427. $sql = "SELECT
  3428. c.*,
  3429. cat.name AS category
  3430. FROM
  3431. $table_course AS c
  3432. LEFT JOIN
  3433. $table_category AS cat
  3434. ON
  3435. c.category_code = cat.code
  3436. WHERE
  3437. c.visibility >= $visibility_level AND
  3438. c.last_visit<='$ceiling'
  3439. ";
  3440. return ResultSet::create($sql);
  3441. }
  3442. /**
  3443. * Get courses count
  3444. * @param int Access URL ID (optional)
  3445. * @return int Number of courses
  3446. */
  3447. public static function count_courses($access_url_id = null)
  3448. {
  3449. $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3450. $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3451. $sql = "SELECT count(id) FROM $table_course c";
  3452. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  3453. $sql .= ", $table_course_rel_access_url u WHERE c.id = u.c_id AND u.access_url_id = $access_url_id";
  3454. }
  3455. $res = Database::query($sql);
  3456. $row = Database::fetch_row($res);
  3457. return $row[0];
  3458. }
  3459. /**
  3460. * Return a link to go to the course, validating the visibility of the
  3461. * course and the user status
  3462. * @param int User ID
  3463. * @param array Course details array
  3464. * @param array List of courses to which the user is subscribed (if not provided, will be generated)
  3465. * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
  3466. */
  3467. static function get_access_link_by_user($uid, $course, $user_courses = array())
  3468. {
  3469. if (empty($uid) or empty($course)) { return false; }
  3470. if (empty($user_courses)) {
  3471. // get the array of courses to which the user is subscribed
  3472. $user_courses = CourseManager::get_courses_list_by_user_id($uid);
  3473. foreach ($user_courses as $k => $v) {
  3474. $user_courses[$k] = $v['real_id'];
  3475. }
  3476. }
  3477. if (!isset($course['real_id']) && empty($course['real_id'])) {
  3478. $course = api_get_course_info($course['code']);
  3479. }
  3480. $is_admin = api_is_platform_admin_by_id($uid);
  3481. $options = array();
  3482. // Register button
  3483. if (!api_is_anonymous($uid) &&
  3484. !$is_admin &&
  3485. (
  3486. ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD || $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) ||
  3487. $course['visibility'] == COURSE_VISIBILITY_REGISTERED && $course['subscribe'] == SUBSCRIBE_ALLOWED
  3488. ) &&
  3489. $course['subscribe'] == SUBSCRIBE_ALLOWED &&
  3490. (!in_array($course['real_id'], $user_courses) || empty($user_courses))
  3491. ) {
  3492. $options[]= 'register';
  3493. }
  3494. // Go To Course button (only if admin, if course public or if student already subscribed)
  3495. if ($is_admin ||
  3496. $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
  3497. (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code']) ) ||
  3498. (in_array($course['real_id'], $user_courses) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
  3499. ) {
  3500. $options[]= 'enter';
  3501. }
  3502. return $options;
  3503. }
  3504. // TODO: Such a function might be useful in other places too. It might be moved in the CourseManager class.
  3505. // Also, the function might be upgraded for avoiding code duplications.
  3506. static function generate_course_code($course_title, $encoding = null) {
  3507. if (empty($encoding)) {
  3508. $encoding = api_get_system_encoding();
  3509. }
  3510. return substr(preg_replace('/[^A-Z0-9]/', '', strtoupper(api_transliterate($course_title, 'X', $encoding))), 0, CourseManager::MAX_COURSE_LENGTH_CODE);
  3511. }
  3512. /**
  3513. * Defines the four needed keys to create a course based on several parameters.
  3514. * @param string The code you want for this course
  3515. * @param string Prefix added for ALL keys
  3516. * @param string Prefix added for databases only
  3517. * @param string Prefix added for paths only
  3518. * @param bool Add unique prefix
  3519. * @param bool Use code-independent keys
  3520. * @return array An array with the needed keys ['currentCourseCode'], ['currentCourseId'], ['currentCourseDbName'], ['currentCourseRepository']
  3521. * @todo Eliminate the global variables.
  3522. */
  3523. static function define_course_keys($wanted_code, $prefix_for_all = '', $prefix_for_base_name = '', $prefix_for_path = '', $add_unique_prefix = false, $use_code_indepedent_keys = true)
  3524. {
  3525. global $prefixAntiNumber, $_configuration;
  3526. $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  3527. $wanted_code = self::generate_course_code($wanted_code);
  3528. $keys_course_code = $wanted_code;
  3529. if (!$use_code_indepedent_keys) {
  3530. $wanted_code = '';
  3531. }
  3532. if ($add_unique_prefix) {
  3533. $unique_prefix = substr(md5(uniqid(rand())), 0, 10);
  3534. } else {
  3535. $unique_prefix = '';
  3536. }
  3537. $keys = array();
  3538. $final_suffix = array('CourseId' => '', 'CourseDb' => '', 'CourseDir' => '');
  3539. $limit_numb_try = 100;
  3540. $keys_are_unique = false;
  3541. $try_new_fsc_id = $try_new_fsc_db = $try_new_fsc_dir = 0;
  3542. while (!$keys_are_unique) {
  3543. $keys_course_id = $prefix_for_all . $unique_prefix . $wanted_code . $final_suffix['CourseId'];
  3544. //$keys_course_db_name = $prefix_for_base_name . $unique_prefix . strtoupper($keys_course_id) . $final_suffix['CourseDb'];
  3545. $keys_course_repository = $prefix_for_path . $unique_prefix . $wanted_code . $final_suffix['CourseDir'];
  3546. $keys_are_unique = true;
  3547. // Check whether they are unique.
  3548. $query = "SELECT 1 FROM ".$course_table." WHERE code='".$keys_course_id."' LIMIT 0,1";
  3549. $result = Database::query($query);
  3550. //if ($keys_course_id == DEFAULT_COURSE || Database::num_rows($result)) {
  3551. if (Database::num_rows($result)) {
  3552. $keys_are_unique = false;
  3553. $try_new_fsc_id ++;
  3554. $final_suffix['CourseId'] = substr(md5(uniqid(rand())), 0, 4);
  3555. }
  3556. if (file_exists(api_get_path(SYS_COURSE_PATH).$keys_course_repository)) {
  3557. $keys_are_unique = false;
  3558. $try_new_fsc_dir ++;
  3559. $final_suffix['CourseDir'] = substr(md5(uniqid(rand())), 0, 4);
  3560. }
  3561. if (($try_new_fsc_id + $try_new_fsc_db + $try_new_fsc_dir) > $limit_numb_try) {
  3562. return $keys;
  3563. }
  3564. }
  3565. $keys['currentCourseCode'] = $keys_course_code;
  3566. $keys['currentCourseId'] = $keys_course_id;
  3567. $keys['currentCourseRepository'] = $keys_course_repository;
  3568. return $keys;
  3569. }
  3570. /**
  3571. * Initializes a file repository for a newly created course.
  3572. */
  3573. static function prepare_course_repository($course_repository, $course_code)
  3574. {
  3575. $perm = api_get_permissions_for_new_directories();
  3576. $perm_file = api_get_permissions_for_new_files();
  3577. $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n </head>\n <body>\n </body>\n</html>";
  3578. $cp = api_get_path(SYS_COURSE_PATH).$course_repository;
  3579. //Creating document folder
  3580. mkdir($cp, $perm);
  3581. mkdir($cp . '/document', $perm);
  3582. $cpt = $cp.'/document/index.html';
  3583. $fd = fopen($cpt, 'w');
  3584. fwrite($fd, $htmlpage);
  3585. fclose($fd);
  3586. /*
  3587. @chmod($cpt, $perm_file);
  3588. @copy($cpt, $cp . '/document/index.html');
  3589. mkdir($cp . '/document/images', $perm);
  3590. @copy($cpt, $cp . '/document/images/index.html');
  3591. mkdir($cp . '/document/images/gallery/', $perm);
  3592. @copy($cpt, $cp . '/document/images/gallery/index.html');
  3593. mkdir($cp . '/document/shared_folder/', $perm);
  3594. @copy($cpt, $cp . '/document/shared_folder/index.html');
  3595. mkdir($cp . '/document/audio', $perm);
  3596. @copy($cpt, $cp . '/document/audio/index.html');
  3597. mkdir($cp . '/document/flash', $perm);
  3598. @copy($cpt, $cp . '/document/flash/index.html');
  3599. mkdir($cp . '/document/video', $perm);
  3600. @copy($cpt, $cp . '/document/video/index.html'); */
  3601. // Creating dropbox folder
  3602. mkdir($cp . '/dropbox', $perm);
  3603. $cpt = $cp.'/dropbox/index.html';
  3604. $fd = fopen($cpt, 'w');
  3605. fwrite($fd, $htmlpage);
  3606. fclose($fd);
  3607. @chmod($cpt, $perm_file);
  3608. mkdir($cp . '/group', $perm);
  3609. @copy($cpt, $cp . '/group/index.html');
  3610. mkdir($cp . '/page', $perm);
  3611. @copy($cpt, $cp . '/page/index.html');
  3612. mkdir($cp . '/scorm', $perm);
  3613. @copy($cpt, $cp . '/scorm/index.html');
  3614. mkdir($cp . '/upload', $perm);
  3615. @copy($cpt, $cp . '/upload/index.html');
  3616. mkdir($cp . '/upload/forum', $perm);
  3617. @copy($cpt, $cp . '/upload/forum/index.html');
  3618. mkdir($cp . '/upload/forum/images', $perm);
  3619. @copy($cpt, $cp . '/upload/forum/images/index.html');
  3620. mkdir($cp . '/upload/test', $perm);
  3621. @copy($cpt, $cp . '/upload/test/index.html');
  3622. mkdir($cp . '/upload/blog', $perm);
  3623. @copy($cpt, $cp . '/upload/blog/index.html');
  3624. mkdir($cp . '/upload/learning_path', $perm);
  3625. @copy($cpt, $cp . '/upload/learning_path/index.html');
  3626. mkdir($cp . '/upload/learning_path/images', $perm);
  3627. @copy($cpt, $cp . '/upload/learning_path/images/index.html');
  3628. mkdir($cp . '/upload/calendar', $perm);
  3629. @copy($cpt, $cp . '/upload/calendar/index.html');
  3630. mkdir($cp . '/upload/calendar/images', $perm);
  3631. @copy($cpt, $cp . '/upload/calendar/images/index.html');
  3632. mkdir($cp . '/work', $perm);
  3633. @copy($cpt, $cp . '/work/index.html');
  3634. mkdir($cp . '/upload/announcements', $perm);
  3635. @copy($cpt, $cp . '/upload/announcements/index.html');
  3636. mkdir($cp . '/upload/announcements/images', $perm);
  3637. @copy($cpt, $cp . '/upload/announcements/images/index.html');
  3638. //Oral expression question type
  3639. mkdir($cp . '/exercises', $perm);
  3640. @copy($cpt, $cp . '/exercises/index.html');
  3641. // Create .htaccess in the dropbox directory.
  3642. $fp = fopen($cp . '/dropbox/.htaccess', 'w');
  3643. fwrite($fp, "AuthName AllowLocalAccess
  3644. AuthType Basic
  3645. order deny,allow
  3646. deny from all
  3647. php_flag zlib.output_compression off");
  3648. fclose($fp);
  3649. return 0;
  3650. }
  3651. /**
  3652. * Get current courses
  3653. * */
  3654. static function get_course_tables()
  3655. {
  3656. $tables = array();
  3657. $tables[]= 'tool';
  3658. $tables[]= 'tool_intro';
  3659. $tables[]= 'group_info';
  3660. $tables[]= 'group_category';
  3661. $tables[]= 'group_rel_user';
  3662. $tables[]= 'group_rel_tutor';
  3663. $tables[]= 'item_property';
  3664. $tables[]= 'course_description';
  3665. $tables[]= 'calendar_event';
  3666. $tables[]= 'calendar_event_repeat';
  3667. $tables[]= 'calendar_event_repeat_not';
  3668. $tables[]= 'calendar_event_attachment';
  3669. $tables[]= 'announcement';
  3670. $tables[]= 'announcement_attachment';
  3671. $tables[]= 'student_publication';
  3672. $tables[]= 'student_publication_assignment';
  3673. $tables[]= 'document';
  3674. $tables[]= 'forum_category';
  3675. $tables[]= 'forum_forum';
  3676. $tables[]= 'forum_thread';
  3677. $tables[]= 'forum_post';
  3678. $tables[]= 'forum_mailcue';
  3679. $tables[]= 'forum_attachment';
  3680. $tables[]= 'forum_notification';
  3681. $tables[]= 'forum_thread_qualify';
  3682. $tables[]= 'forum_thread_qualify_log';
  3683. $tables[]= 'link';
  3684. $tables[]= 'link_category';
  3685. $tables[]= 'online_connected';
  3686. $tables[]= 'online_link';
  3687. $tables[]= 'chat_connected';
  3688. $tables[]= 'quiz';
  3689. $tables[]= 'quiz_rel_question';
  3690. $tables[]= 'quiz_question';
  3691. $tables[]= 'quiz_answer';
  3692. $tables[]= 'quiz_question_option';
  3693. $tables[]= 'quiz_category';
  3694. $tables[]= 'quiz_question_rel_category';
  3695. $tables[]= 'dropbox_post';
  3696. $tables[]= 'dropbox_file';
  3697. $tables[]= 'dropbox_person';
  3698. $tables[]= 'dropbox_category';
  3699. $tables[]= 'dropbox_feedback';
  3700. $tables[]= 'lp';
  3701. $tables[]= 'lp_item';
  3702. $tables[]= 'lp_view';
  3703. $tables[]= 'lp_item_view';
  3704. $tables[]= 'lp_iv_interaction';
  3705. $tables[]= 'lp_iv_objective';
  3706. $tables[]= 'blog';
  3707. $tables[]= 'blog_comment';
  3708. $tables[]= 'blog_post';
  3709. $tables[]= 'blog_rating';
  3710. $tables[]= 'blog_rel_user';
  3711. $tables[]= 'blog_task';
  3712. $tables[]= 'blog_task_rel_user';
  3713. $tables[]= 'blog_attachment';
  3714. $tables[]= 'permission_group';
  3715. $tables[]= 'permission_user';
  3716. $tables[]= 'permission_task';
  3717. $tables[]= 'survey';
  3718. $tables[]= 'survey_question';
  3719. $tables[]= 'survey_question_option';
  3720. $tables[]= 'survey_invitation';
  3721. $tables[]= 'survey_answer';
  3722. $tables[]= 'survey_group';
  3723. $tables[]= 'wiki';
  3724. $tables[]= 'wiki_conf';
  3725. $tables[]= 'wiki_discuss';
  3726. $tables[]= 'wiki_mailcue';
  3727. $tables[]= 'course_setting';
  3728. $tables[]= 'glossary';
  3729. //$tables[]= 'notebook';
  3730. $tables[]= 'attendance';
  3731. $tables[]= 'attendance_sheet';
  3732. $tables[]= 'attendance_calendar';
  3733. $tables[]= 'attendance_result';
  3734. $tables[]= 'attendance_sheet_log';
  3735. $tables[]= 'thematic';
  3736. $tables[]= 'thematic_plan';
  3737. $tables[]= 'thematic_advance';
  3738. return $tables;
  3739. }
  3740. static function browse_folders($path, $files, $media)
  3741. {
  3742. $defaultCourseDocumentPath = api_get_path(SYS_DEFAULT_COURSE_DOCUMENT_PATH);
  3743. if ($media == 'images') {
  3744. $code_path = $defaultCourseDocumentPath.'images/';
  3745. }
  3746. if ($media == 'audio') {
  3747. $code_path = $defaultCourseDocumentPath.'audio/';
  3748. }
  3749. if ($media == 'flash') {
  3750. $code_path = $defaultCourseDocumentPath.'flash/';
  3751. }
  3752. if ($media == 'video') {
  3753. $code_path = $defaultCourseDocumentPath.'video/';
  3754. }
  3755. if ($media == 'certificates') {
  3756. $code_path = $defaultCourseDocumentPath.'certificates/';
  3757. }
  3758. if (is_dir($path)) {
  3759. $handle = opendir($path);
  3760. while (false !== ($file = readdir($handle))) {
  3761. if (is_dir($path.$file) && strpos($file, '.') !== 0) {
  3762. $files[]['dir'] = str_replace($code_path, '', $path.$file.'/');
  3763. $files = self::browse_folders($path.$file.'/', $files, $media);
  3764. } elseif (is_file($path.$file) && strpos($file, '.') !== 0) {
  3765. $files[]['file'] = str_replace($code_path, '', $path.$file);
  3766. }
  3767. }
  3768. }
  3769. return $files;
  3770. }
  3771. /**
  3772. * @param $files
  3773. * @param $type
  3774. * @return array
  3775. */
  3776. static function sort_pictures($files, $type)
  3777. {
  3778. $pictures = array();
  3779. foreach ($files as $key => $value){
  3780. if (isset($value[$type]) && !empty($value[$type])) {
  3781. $pictures[][$type] = $value[$type];
  3782. }
  3783. }
  3784. return $pictures;
  3785. }
  3786. /**
  3787. * Fills the course database with some required content and example content.
  3788. */
  3789. public static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
  3790. {
  3791. if (is_null($fill_with_exemplary_content)) {
  3792. $fill_with_exemplary_content = api_get_setting('example_material_course_creation') != 'false';
  3793. }
  3794. $course_id = intval($course_id);
  3795. if (empty($course_id)) {
  3796. return false;
  3797. }
  3798. $now = api_get_utc_datetime(time());
  3799. $toolTable = Database::get_course_table(TABLE_TOOL_LIST);
  3800. $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
  3801. $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
  3802. $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3803. $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
  3804. $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
  3805. $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  3806. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  3807. $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
  3808. $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  3809. $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION);
  3810. $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
  3811. $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
  3812. $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
  3813. $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
  3814. $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
  3815. $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
  3816. $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  3817. $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
  3818. $visible_for_all = 1;
  3819. $visible_for_course_admin = 0;
  3820. $visible_for_platform_admin = 2;
  3821. // Move this in a doctrine listener
  3822. $toolList = self::getToolList();
  3823. $toolList = $toolList->getTools();
  3824. /** @var Course $course */
  3825. $entityManager = Database::getManager();
  3826. $course = $entityManager->getRepository('ChamiloCoreBundle:Course')->find($course_id);
  3827. // @todo move in a manager.
  3828. /** @var Chamilo\CourseBundle\Tool\BaseTool $tool */
  3829. $tools = array();
  3830. $settingsManager = self::getCourseSettingsManager();
  3831. $settingsManager->setCourse($course);
  3832. foreach ($toolList as $tool) {
  3833. $visibility = Text::string2binary(api_get_setting
  3834. ('course.course_create_active_tools', $tool->getName()));
  3835. $toolObject = new CTool();
  3836. $toolObject->setName($tool->getName())
  3837. ->setCategory($tool->getCategory())
  3838. ->setLink($tool->getLink())
  3839. ->setImage($tool->getImage())
  3840. ->setVisibility($visibility)
  3841. ->setAdmin(0)
  3842. ->setTarget($tool->getTarget())
  3843. ;
  3844. $tools[] = $toolObject;
  3845. $settings = $settingsManager->loadSettings($tool->getName());
  3846. $settingsManager->saveSettings($tool->getName(), $settings);
  3847. }
  3848. $course->setTools($tools);
  3849. $entityManager->persist($course);
  3850. $entityManager->flush($course);
  3851. /* Course tools */
  3852. /*if (api_get_setting('service_visio', 'active') == 'true') {
  3853. $mycheck = api_get_setting('service_visio', 'visio_host');
  3854. if (!empty($mycheck)) {
  3855. //Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '" . TOOL_VISIO_CONFERENCE . "','conference/index.php?type=conference','visio_meeting.gif','1','0','squaregrey.gif','NO','_self','interaction','0', '', '')");
  3856. //Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '" . TOOL_VISIO_CLASSROOM . "','conference/index.php?type=classroom','visio.gif','1','0','squaregrey.gif','NO','_self','authoring','0', '', '')");
  3857. }
  3858. }*/
  3859. /*if (api_get_setting('search_enabled') == 'true') {
  3860. //Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '" . TOOL_SEARCH. "','search/','info.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'enable_search')) . "','0','search.gif','NO','_self','authoring','0', '', '')");
  3861. }*/
  3862. // Blogs (Kevin Van Den Haute :: kevin@develop-it.be)
  3863. /*$sql = "INSERT INTO $toolTable VALUES ($course_id, NULL,'" . TOOL_BLOGS . "','blog/blog_admin.php','blog_admin.gif','" . Text::string2binary(api_get_setting('course_create_active_tools', 'blogs')) . "','1','squaregrey.gif','NO','_self','admin','0', '', '')";
  3864. Database::query($sql);*/
  3865. /* Course homepage tools for course admin only */
  3866. /* Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '".TOOL_TRACKING . "','tracking/courseLog.php','statistics.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0', '', '')");
  3867. Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '".TOOL_COURSE_SETTING . "','course_info/infocours.php','reference.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0', '', '')");
  3868. Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '".TOOL_COURSE_MAINTENANCE."','course_info/maintenance.php','backup.gif','$visible_for_course_admin','1','','NO','_self', 'admin','0', '', '')");*/
  3869. /* Course_setting table (courseinfo tool) */
  3870. /*Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_doc',0,'work')");
  3871. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_on_new_doc_dropbox',0,'dropbox')");
  3872. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_agenda',0,'agenda')");
  3873. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_announcement',0,'announcement')");
  3874. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_quiz',1,'quiz')");
  3875. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_image_forum',1,'forum')");
  3876. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'course_theme','','theme')");
  3877. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_learning_path_theme','1','theme')");
  3878. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_open_chat_window',1,'chat')");
  3879. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_to_teacher_on_new_user_in_course',0,'registration')");
  3880. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_view_user_list',1,'user')");
  3881. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'display_info_advance_inside_homecourse',1,'thematic_advance')");
  3882. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_students_on_new_homework',0,'work')");
  3883. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'enable_lp_auto_launch',0,'learning_path')");
  3884. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'pdf_export_watermark_text','','learning_path')");
  3885. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_public_certificates','','certificates')");
  3886. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_fast_exercise_edition', 0 ,'exercise')");
  3887. Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'enable_exercise_auto_launch', 0 ,'exercise')");*/
  3888. /* Course homepage tools for platform admin only */
  3889. /* Group tool */
  3890. Database::query("INSERT INTO $TABLEGROUPCATEGORIES (c_id, id , title , description , max_student , self_reg_allowed , self_unreg_allowed , groups_per_user , display_order )
  3891. VALUES ($course_id, '2', '".Database::escape_string(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
  3892. /* Example Material */
  3893. $language_interface = Container::getTranslator()->getLocale();
  3894. // Example material should be in the same language as the course is.
  3895. $language_interface_original = $language_interface;
  3896. $language_interface = $language;
  3897. //Share folder
  3898. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/shared_folder','".get_lang('UserFolders')."','folder','0')");
  3899. $example_doc_id = Database :: insert_id();
  3900. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  3901. VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3902. //Chat folder
  3903. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/chat_files','".get_lang('ChatFiles')."','folder','0')");
  3904. $example_doc_id = Database :: insert_id();
  3905. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3906. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  3907. $perm = api_get_permissions_for_new_directories();
  3908. $perm_file = api_get_permissions_for_new_files();
  3909. $chat_path = $sys_course_path.$course_repository.'/document/chat_files';
  3910. if (!is_dir($chat_path)) {
  3911. @mkdir($chat_path, api_get_permissions_for_new_directories());
  3912. }
  3913. /* Documents */
  3914. if ($fill_with_exemplary_content) {
  3915. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id,path,title,filetype,size) VALUES ($course_id,'/images','".get_lang('Images')."','folder','0')");
  3916. $example_doc_id = Database :: insert_id();
  3917. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3918. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/images/gallery','".get_lang('DefaultCourseImages')."','folder','0')");
  3919. $example_doc_id = Database :: insert_id();
  3920. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3921. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/audio','".get_lang('Audio')."','folder','0')");
  3922. $example_doc_id = Database :: insert_id();
  3923. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3924. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/flash','".get_lang('Flash')."','folder','0')");
  3925. $example_doc_id = Database :: insert_id();
  3926. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3927. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/video','".get_lang('Video')."','folder','0')");
  3928. $example_doc_id = Database :: insert_id();
  3929. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3930. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/certificates','".get_lang('Certificates')."','folder','0')");
  3931. $example_doc_id = Database :: insert_id();
  3932. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)");
  3933. // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
  3934. $folders_to_copy_from_default_course = array(
  3935. 'images',
  3936. 'audio',
  3937. 'flash',
  3938. 'video',
  3939. 'certificates',
  3940. );
  3941. $default_course_path = api_get_path(SYS_DEFAULT_COURSE_DOCUMENT_PATH);
  3942. $default_document_array = array();
  3943. foreach ($folders_to_copy_from_default_course as $folder) {
  3944. $default_course_folder_path = $default_course_path.$folder.'/';
  3945. $files = self::browse_folders($default_course_folder_path, array(), $folder);
  3946. $sorted_array = self::sort_pictures($files, 'dir');
  3947. $sorted_array = array_merge($sorted_array, self::sort_pictures($files, 'file'));
  3948. $default_document_array[$folder] = $sorted_array;
  3949. }
  3950. //Light protection (adding index.html in every document folder)
  3951. $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n </head>\n <body>\n </body>\n</html>";
  3952. $example_cert_id = 0;
  3953. if (is_array($default_document_array) && count($default_document_array) > 0) {
  3954. foreach ($default_document_array as $media_type => $array_media) {
  3955. $path_documents = "/$media_type/";
  3956. //hack until feature #5242 is implemented
  3957. if ($media_type == 'images') {
  3958. $media_type = 'images/gallery';
  3959. $images_folder = $sys_course_path.$course_repository."/document/images/";
  3960. if (!is_dir($images_folder)) {
  3961. //Creating index.html
  3962. mkdir($images_folder, $perm);
  3963. $fd = fopen($images_folder.'index.html', 'w');
  3964. fwrite($fd, $htmlpage);
  3965. @chmod($images_folder.'index.html', $perm_file);
  3966. }
  3967. }
  3968. $course_documents_folder = $sys_course_path.$course_repository."/document/$media_type/";
  3969. $default_course_path = api_get_path(SYS_DEFAULT_COURSE_DOCUMENT_PATH).$path_documents;
  3970. //echo 'try '.$course_documents_folder; echo '<br />';
  3971. if (!is_dir($course_documents_folder)) {
  3972. //Creating index.html
  3973. mkdir($course_documents_folder, $perm);
  3974. $fd = fopen($course_documents_folder.'index.html', 'w');
  3975. fwrite($fd, $htmlpage);
  3976. @chmod($course_documents_folder.'index.html', $perm_file);
  3977. }
  3978. if (is_array($array_media) && count($array_media)>0) {
  3979. foreach ($array_media as $key => $value) {
  3980. if (isset($value['dir']) && !empty($value['dir'])) {
  3981. if (!is_dir($course_documents_folder.$value['dir'])) {
  3982. //Creating folder
  3983. mkdir($course_documents_folder.$value['dir'], $perm);
  3984. //Creating index.html (for light protection)
  3985. $index_html = $course_documents_folder.$value['dir'].'/index.html';
  3986. $fd = fopen($index_html, 'w');
  3987. fwrite($fd, $htmlpage);
  3988. @chmod($index_html, $perm_file);
  3989. //Inserting folder in the DB
  3990. $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1);
  3991. $temp = explode('/', $folder_path);
  3992. $title = $temp[count($temp)-1];
  3993. //hack until feature #5242 is implemented
  3994. if ($title == 'gallery') {
  3995. $title = get_lang('DefaultCourseImages');
  3996. }
  3997. if ($media_type == 'images/gallery') {
  3998. $folder_path = 'gallery/'.$folder_path;
  3999. }
  4000. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'$path_documents".$folder_path."','".$title."','folder','0')");
  4001. $image_id = Database :: insert_id();
  4002. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$image_id,'DocumentAdded',1,0,NULL,0)");
  4003. }
  4004. }
  4005. if (isset($value['file']) && !empty($value['file'])) {
  4006. if (!file_exists($course_documents_folder.$value['file'])) {
  4007. //Copying file
  4008. copy($default_course_path.$value['file'], $course_documents_folder.$value['file']);
  4009. chmod($course_documents_folder.$value['file'], $perm_file);
  4010. //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
  4011. $temp = explode('/', $value['file']);
  4012. $file_size = filesize($course_documents_folder.$value['file']);
  4013. //hack until feature #5242 is implemented
  4014. if ($media_type == 'images/gallery') {
  4015. $value["file"] = 'gallery/'.$value["file"];
  4016. }
  4017. //Inserting file in the DB
  4018. Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'$path_documents".$value["file"]."','".$temp[count($temp)-1]."','file','$file_size')");
  4019. $image_id = Database :: insert_id();
  4020. if ($path_documents.$value['file'] == '/certificates/default.html') {
  4021. $example_cert_id = $image_id;
  4022. }
  4023. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$image_id,'DocumentAdded',1,0,NULL,1)");
  4024. }
  4025. }
  4026. }
  4027. }
  4028. }
  4029. }
  4030. /* Agenda tool */
  4031. Database::query("INSERT INTO $TABLETOOLAGENDA VALUES ($course_id, NULL, '".Database::escape_string(get_lang('AgendaCreationTitle')) . "', '".Database::escape_string(get_lang('AgendaCreationContenu')) . "', now(), now(), NULL, 0, 0)");
  4032. // We need to add the item properties too!
  4033. $insert_id = Database :: insert_id();
  4034. $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id, '" . TOOL_CALENDAR_EVENT . "',1,NOW(),NOW(),$insert_id,'AgendaAdded',1,0,NULL,1)";
  4035. Database::query($sql);
  4036. /* Links tool */
  4037. $add_google_link_sql = "INSERT INTO $TABLETOOLLINK (c_id, url, title, description, category_id, display_order, on_homepage, target)
  4038. VALUES ($course_id, 'http://www.google.com','Google','".Database::escape_string(get_lang('Google')) . "','0','0','0','_self')";
  4039. Database::query($add_google_link_sql);
  4040. // We need to add the item properties too!
  4041. $insert_id = Database :: insert_id();
  4042. $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  4043. VALUES ($course_id, '" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)";
  4044. Database::query($sql);
  4045. $add_wikipedia_link_sql = "INSERT INTO $TABLETOOLLINK (c_id, url, title, description, category_id, display_order, on_homepage, target)
  4046. VALUES ($course_id, 'http://www.wikipedia.org','Wikipedia','".Database::escape_string(get_lang('Wikipedia')) . "','0','1','0','_self')";
  4047. Database::query($add_wikipedia_link_sql);
  4048. // We need to add the item properties too!
  4049. $insert_id = Database :: insert_id();
  4050. $sql = "INSERT INTO $TABLEITEMPROPERTY (tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)";
  4051. Database::query($sql);
  4052. /* Announcement tool */
  4053. $sql = "INSERT INTO $TABLETOOLANNOUNCEMENTS (c_id, title,content,end_date,display_order,email_sent)
  4054. VALUES ($course_id, '".Database::escape_string(get_lang('AnnouncementExampleTitle')) . "', '".Database::escape_string(get_lang('AnnouncementEx')) . "', NOW(), '1','0')";
  4055. Database::query($sql);
  4056. // We need to add the item properties too!
  4057. $insert_id = Database :: insert_id();
  4058. $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  4059. VALUES ($course_id, '" . TOOL_ANNOUNCEMENT . "',1,NOW(),NOW(),$insert_id,'AnnouncementAdded',1,0,NULL,1)";
  4060. Database::query($sql);
  4061. /* Introduction text */
  4062. $intro_text = '<p style="text-align: center;">
  4063. <img src="'.api_get_path(REL_CODE_PATH).'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
  4064. <h2>'.Database::escape_string(get_lang('IntroductionText')).'</h2>
  4065. </p>';
  4066. Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_COURSE_HOMEPAGE . "','".$intro_text."', 0)");
  4067. Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_STUDENTPUBLICATION . "','".Database::escape_string(get_lang('IntroductionTwo')) . "', 0)");
  4068. // Wiki intro
  4069. $intro_wiki='<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="110" valign="top" align="left"></td><td valign="top" align="left">'.Database::escape_string(get_lang('IntroductionWiki')).'</td></tr></table>';
  4070. Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_WIKI . "','".$intro_wiki. "', 0)");
  4071. /* Exercise tool */
  4072. $html = Database::escape_string('<table width="100%" border="0" cellpadding="0" cellspacing="0">
  4073. <tr><td width="110" valign="top" align="left">
  4074. <img src="'.api_get_path(WEB_DEFAULT_COURSE_DOCUMENT_PATH).'images/mr_dokeos/thinking.jpg"></td><td valign="top" align="left">'.get_lang('Antique').'
  4075. </td></tr></table>');
  4076. // Insert exercise
  4077. Database::query('INSERT INTO '.$TABLEQUIZ .' (c_id, title, description, type, random, random_answers, active, results_disabled ) ' .
  4078. ' VALUES ('.$course_id.', "'.Database::escape_string(get_lang('ExerciceEx')) . '", "'.$html.'", "1", "0", "0", "1", "0")');
  4079. $exercise_id = Database :: insert_id();
  4080. // Insert question
  4081. Database::query("INSERT INTO $TABLEQUIZQUESTIONLIST (c_id, question, description, ponderation, position, type, picture, level)
  4082. VALUES ( '.$course_id.', '".Database::escape_string(get_lang('SocraticIrony')) . "', '".Database::escape_string(get_lang('ManyAnswers')) . "', '10', '1', '2','',1)");
  4083. $questionId = Database :: insert_id();
  4084. Database::query("INSERT INTO $TABLEQUIZQUESTION (c_id, question_id, exercice_id, question_order) VALUES ($course_id,$questionId , $exercise_id, 1)");
  4085. // Insert answers
  4086. Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '$questionId', '".Database::escape_string(get_lang('Ridiculise')) . "', '0', '".Database::escape_string(get_lang('NoPsychology')) . "', '-5', '1')");
  4087. Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '$questionId', '".Database::escape_string(get_lang('AdmitError')) . "', '0', '".Database::escape_string(get_lang('NoSeduction')) . "', '-5', '2')");
  4088. Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '$questionId', '".Database::escape_string(get_lang('Force')) . "', '1', '".Database::escape_string(get_lang('Indeed')) . "', '5', '3')");
  4089. Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '$questionId', '".Database::escape_string(get_lang('Contradiction')) . "', '1', '".Database::escape_string(get_lang('NotFalse')) . "', '5', '4')");
  4090. /* Forum tool */
  4091. Database::query("INSERT INTO $TABLEFORUMCATEGORIES VALUES ($course_id, 1,'".Database::escape_string(get_lang('ExampleForumCategory'))."', '', 1, 0, 0)");
  4092. $insert_id = Database :: insert_id();
  4093. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  4094. VALUES ($course_id, 'forum_category',1,NOW(),NOW(),$insert_id,'ForumCategoryAdded',1,0,NULL,1)");
  4095. Database::query("INSERT INTO $TABLEFORUMS (c_id, forum_title, forum_comment, forum_threads,forum_posts,forum_last_post,forum_category, allow_anonymous, allow_edit,allow_attachments, allow_new_threads,default_view,forum_of_group,forum_group_public_private, forum_order,locked,session_id )
  4096. VALUES ($course_id, '".Database::escape_string(get_lang('ExampleForum'))."', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)");
  4097. $insert_id = Database :: insert_id();
  4098. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  4099. VALUES ($course_id, '".TOOL_FORUM."', 1,NOW(),NOW(),$insert_id,'ForumAdded',1,0,NULL,1)");
  4100. Database::query("INSERT INTO $TABLEFORUMTHREADS (c_id, thread_id, thread_title, forum_id, thread_replies, thread_poster_id, thread_poster_name, thread_views, thread_last_post, thread_date, locked, thread_qualify_max, session_id)
  4101. VALUES ($course_id, 1, '".Database::escape_string(get_lang('ExampleThread'))."', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)");
  4102. $insert_id = Database :: insert_id();
  4103. Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
  4104. VALUES ($course_id, 'forum_thread',1,NOW(),NOW(),$insert_id,'ForumThreadAdded',1,0,NULL,1)");
  4105. Database::query("INSERT INTO $TABLEFORUMPOSTS VALUES ($course_id, 1, '".Database::escape_string(get_lang('ExampleThread'))."', '".Database::escape_string(get_lang('ExampleThreadContent'))."', 1, 1, 1, '', NOW(), 0, 0, 1)");
  4106. /* Gradebook tool */
  4107. $course = api_get_course_info_by_id($course_id);
  4108. $course_code = $course['code'];
  4109. // father gradebook
  4110. Database::query("INSERT INTO $TABLEGRADEBOOK (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('$course_code','',1,'$course_code',0,100,0,NULL,NULL,$example_cert_id)");
  4111. $gbid = Database :: insert_id();
  4112. Database::query("INSERT INTO $TABLEGRADEBOOK (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('$course_code','',1,'$course_code',$gbid,100,1,75,NULL,$example_cert_id)");
  4113. $gbid = Database :: insert_id();
  4114. Database::query("INSERT INTO $TABLEGRADEBOOKLINK (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked) VALUES (1,$exercise_id,1,'$course_code',$gbid,'$now',100,1,0)");
  4115. }
  4116. //Installing plugins in course
  4117. $app_plugin = new AppPlugin();
  4118. $app_plugin->install_course_plugins($course_id);
  4119. $language_interface = $language_interface_original;
  4120. return true;
  4121. }
  4122. /**
  4123. * function register_course to create a record in the course table of the main database
  4124. * @param string $course_sys_code
  4125. * @param string $course_screen_code
  4126. * @param string $course_repository
  4127. * @param string $course_db_name
  4128. * @param string $tutor_name
  4129. * @param string $category
  4130. * @param string $title complete name of course
  4131. * @param string $course_language lang for this course
  4132. * @param string $uid uid of owner
  4133. * @param integer Expiration date in unix time representation
  4134. * @param array Optional array of teachers' user ID
  4135. * @return int 0
  4136. * @todo use an array called $params instead of lots of params
  4137. */
  4138. static function register_course($params)
  4139. {
  4140. global $error_msg, $firstExpirationDelay;
  4141. $title = $params['title'];
  4142. $code = $params['code'];
  4143. $visual_code = $params['visual_code'];
  4144. $directory = isset($params['directory']) ? $params['directory'] : null;
  4145. $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null;
  4146. $category_code = isset($params['category_code']) ? $params['category_code'] : null;
  4147. $defaultLanguage = Container::getTranslator()->getLocale();
  4148. $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : $defaultLanguage;
  4149. $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']);
  4150. $department_name = isset($params['department_name']) ? $params['department_name'] : null;
  4151. $department_url = isset($params['department_url']) ? $params['department_url'] : null;
  4152. $disk_quota = isset($params['disk_quota']) ? $params['disk_quota'] : null;
  4153. if (!isset($params['visibility'])) {
  4154. $default_course_visibility = api_get_setting('course.courses_default_creation_visibility');
  4155. if (isset($default_course_visibility)) {
  4156. $visibility = $default_course_visibility;
  4157. } else {
  4158. $visibility = COURSE_VISIBILITY_OPEN_PLATFORM;
  4159. }
  4160. } else {
  4161. $visibility = $params['visibility'];
  4162. }
  4163. $subscribe = isset($params['subscribe']) ? intval($params['subscribe']) : ($visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0);
  4164. $unsubscribe = isset($params['unsubscribe']) ? intval($params['unsubscribe']) : 0;
  4165. $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null;
  4166. $teachers = isset($params['teachers']) ? $params['teachers'] : null;
  4167. $status = isset($params['status']) ? $params['status'] : null;
  4168. $TABLECOURSE = Database :: get_main_table(TABLE_MAIN_COURSE);
  4169. $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  4170. $ok_to_register_course = true;
  4171. // Check whether all the needed parameters are present.
  4172. if (empty($code)) {
  4173. $error_msg[] = 'courseSysCode is missing';
  4174. $ok_to_register_course = false;
  4175. }
  4176. if (empty($visual_code)) {
  4177. $error_msg[] = 'courseScreenCode is missing';
  4178. $ok_to_register_course = false;
  4179. }
  4180. if (empty($directory)) {
  4181. $error_msg[] = 'courseRepository is missing';
  4182. $ok_to_register_course = false;
  4183. }
  4184. if (empty($title)) {
  4185. $error_msg[] = 'title is missing';
  4186. $ok_to_register_course = false;
  4187. }
  4188. if (empty($expiration_date)) {
  4189. $expiration_date = api_get_utc_datetime(time() + $firstExpirationDelay);
  4190. } else {
  4191. $expiration_date = api_get_utc_datetime($expiration_date);
  4192. }
  4193. if ($visibility < 0 || $visibility > 3) {
  4194. $error_msg[] = 'visibility is invalid';
  4195. $ok_to_register_course = false;
  4196. }
  4197. if (empty($disk_quota)) {
  4198. $disk_quota = api_get_setting('document.default_document_quotum');
  4199. }
  4200. $time = api_get_utc_datetime();
  4201. if (stripos($department_url, 'http://') === false && stripos($department_url, 'https://') === false) {
  4202. $department_url = 'http://'.$department_url;
  4203. }
  4204. //just in case
  4205. if ($department_url == 'http://') {
  4206. $department_url = '';
  4207. }
  4208. $course_id = 0;
  4209. if ($ok_to_register_course) {
  4210. /** @var Course $course */
  4211. $course = self::getCourseManager()->create();
  4212. $course->setCode($code)
  4213. ->setDirectory($directory)
  4214. ->setCourseLanguage($course_language)
  4215. ->setTitle($title)
  4216. ->setDescription(get_lang('CourseDescription'))
  4217. ->setCategoryCode($category_code)
  4218. ->setVisibility($visibility)
  4219. ->setShowScore(1)
  4220. ->setDiskQuota($disk_quota)
  4221. ->setCreationDate(new \DateTime())
  4222. ->setExpirationDate(new \DateTime($expiration_date))
  4223. //->setLastEdit()
  4224. ->setDepartmentName($department_name)
  4225. ->setDepartmentUrl($department_url)
  4226. ->setSubscribe($subscribe)
  4227. ->setUnsubscribe($unsubscribe)
  4228. ->setVisualCode($visual_code)
  4229. ;
  4230. self::getCourseManager()->save($course, true);
  4231. $course_id = $course->getId();
  4232. /*// Here we must add 2 fields.
  4233. $sql = "INSERT INTO ".$TABLECOURSE . " SET
  4234. code = '".Database :: escape_string($code) . "',
  4235. directory = '".Database :: escape_string($directory) . "',
  4236. course_language = '".Database :: escape_string($course_language) . "',
  4237. title = '".Database :: escape_string($title) . "',
  4238. description = '".Database::escape_string(get_lang('CourseDescription')) . "',
  4239. category_code = '".Database :: escape_string($category_code) . "',
  4240. visibility = '".$visibility . "',
  4241. show_score = '1',
  4242. disk_quota = '".intval($disk_quota) . "',
  4243. creation_date = '$time',
  4244. expiration_date = '".$expiration_date . "',
  4245. last_edit = '$time',
  4246. last_visit = NULL,
  4247. tutor_name = '".Database :: escape_string($tutor_name) . "',
  4248. department_name = '".Database :: escape_string($department_name) . "',
  4249. department_url = '".Database :: escape_string($department_url) . "',
  4250. subscribe = '".intval($subscribe) . "',
  4251. unsubscribe = '".intval($unsubscribe) . "',
  4252. visual_code = '".Database :: escape_string($visual_code) . "'";
  4253. Database::query($sql);
  4254. $course_id = Database::insert_id();*/
  4255. //$course->addUsers()
  4256. if ($course_id) {
  4257. $settingsManager = Container::getCourseSettingsManager();
  4258. $schemas = $settingsManager->getSchemas();
  4259. $schemas = array_keys($schemas);
  4260. /**
  4261. * @var string $key
  4262. * @var \Sylius\Bundle\SettingsBundle\Schema\SchemaInterface $schema
  4263. */
  4264. foreach ($schemas as $schema) {
  4265. $settings = $settingsManager->loadSettings($schema);
  4266. $settingsManager->setCourse($course);
  4267. $settingsManager->saveSettings($schema, $settings);
  4268. }
  4269. $sort = api_max_sort_value('0', api_get_user_id());
  4270. $i_course_sort = CourseManager :: userCourseSort($user_id, $code);
  4271. if (!empty($user_id)) {
  4272. $sql = "INSERT INTO ".$TABLECOURSUSER . " SET
  4273. c_id = '".Database :: escape_string($course_id). "',
  4274. user_id = '".intval($user_id) . "',
  4275. status = '1',
  4276. tutor_id = '0',
  4277. sort = '". ($i_course_sort) . "',
  4278. user_course_cat = '0'";
  4279. Database::query($sql);
  4280. }
  4281. if (!empty($teachers)) {
  4282. if (!is_array($teachers)) {
  4283. $teachers = array($teachers);
  4284. }
  4285. foreach ($teachers as $key) {
  4286. //just in case
  4287. if ($key == $user_id) {
  4288. continue;
  4289. }
  4290. if (empty($key)) {
  4291. continue;
  4292. }
  4293. $sql = "INSERT INTO ".$TABLECOURSUSER . " SET
  4294. c_id = '".Database::escape_string($course_id) . "',
  4295. user_id = '".Database::escape_string($key) . "',
  4296. status = '1',
  4297. role = '',
  4298. tutor_id = '0',
  4299. sort = '". ($sort +1) . "',
  4300. user_course_cat = '0'";
  4301. Database::query($sql);
  4302. }
  4303. }
  4304. // Adding the course to an URL
  4305. if (api_is_multiple_url_enabled()) {
  4306. $url_id = 1;
  4307. if (api_get_current_access_url_id() != -1) {
  4308. $url_id = api_get_current_access_url_id();
  4309. }
  4310. UrlManager::add_course_to_url($course_id, $url_id);
  4311. } else {
  4312. UrlManager::add_course_to_url($course_id, 1);
  4313. }
  4314. // Add event to the system log.
  4315. $user_id = api_get_user_id();
  4316. Event::addEvent(LOG_COURSE_CREATE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $code);
  4317. $send_mail_to_admin = api_get_setting('course.send_email_to_admin_when_create_course');
  4318. // @todo Improve code to send to all current portal administrators.
  4319. if ($send_mail_to_admin == 'true') {
  4320. $siteName = api_get_setting('platform.site_name');
  4321. $recipient_email = api_get_setting('platform.administrator_email');
  4322. $recipient_name = api_get_person_name(api_get_setting('platform.administrator_name'), api_get_setting('platform.administrator_surname'));
  4323. $iname = api_get_setting('platform.institution');
  4324. $subject = get_lang('NewCourseCreatedIn').' '.$siteName.' - '.$iname;
  4325. $body = get_lang('Dear').' '.$recipient_name.",\n\n".get_lang('MessageOfNewCourseToAdmin').' '.$siteName.' - '.$iname."\n";
  4326. $body .= get_lang('CourseName').' '.$title."\n";
  4327. $body .= get_lang('Category').' '.$category_code."\n";
  4328. $body .= get_lang('Tutor').' '.$tutor_name."\n";
  4329. $body .= get_lang('Language').' '.$course_language;
  4330. //api_mail_html($recipient_name, $recipient_email, $subject, $message, $siteName, $recipient_email);
  4331. $message = \Swift_Message::newInstance()
  4332. ->setSubject($subject)
  4333. ->setFrom($recipient_email)
  4334. ->setTo($recipient_email)
  4335. ->setBody(
  4336. Container::getTemplate()->render(
  4337. 'ChamiloCoreBundle:Mailer:Course/new_course.html.twig',
  4338. array(
  4339. 'recipient_name' => $recipient_name,
  4340. 'sitename' => $siteName,
  4341. 'institution' => $iname,
  4342. 'course_name' => $title,
  4343. 'category' => $category_code,
  4344. 'tutor' => $tutor_name,
  4345. 'language' => $course_language
  4346. )
  4347. )
  4348. )
  4349. ;
  4350. Container::getMailer()->send($message);
  4351. }
  4352. }
  4353. }
  4354. return $course_id;
  4355. }
  4356. /**
  4357. * This function returns information about coachs from a course in session
  4358. * @param int - optional, session id
  4359. * @param string - optional, course code
  4360. * @return array - array containing user_id, lastname, firstname, username
  4361. */
  4362. public static function get_coaches_from_course($session_id=0, $courseId = null) {
  4363. if (!empty($session_id)) {
  4364. $session_id = intval($session_id);
  4365. } else {
  4366. $session_id = api_get_session_id();
  4367. }
  4368. if (!empty($courseId)) {
  4369. $courseId = Database::escape_string($courseId);
  4370. } else {
  4371. $courseId = api_get_course_int_id();
  4372. }
  4373. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  4374. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4375. $coaches = array();
  4376. $sql = "SELECT u.user_id,u.lastname,u.firstname,u.username
  4377. FROM $tbl_user u,$tbl_session_course_user scu
  4378. WHERE u.user_id = scu.id_user AND scu.id_session = '$session_id' AND scu.c_id = '$courseId' AND scu.status = 2";
  4379. $rs = Database::query($sql);
  4380. if (Database::num_rows($rs) > 0) {
  4381. while ($row = Database::fetch_array($rs)) {
  4382. $coaches[] = $row;
  4383. }
  4384. return $coaches;
  4385. } else {
  4386. return false;
  4387. }
  4388. }
  4389. /**
  4390. * @return a list (array) of all courses.
  4391. * This function was originally in the Database class
  4392. */
  4393. public static function get_course_list()
  4394. {
  4395. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  4396. return Database::store_result(Database::query("SELECT *, id as real_id FROM $table"));
  4397. }
  4398. /**
  4399. * Returns course code from a given gradebook category's id
  4400. * @param int Category ID
  4401. * @return string Course code
  4402. */
  4403. public static function get_course_by_category($category_id)
  4404. {
  4405. $category_id = intval($category_id);
  4406. $info = Database::fetch_array(
  4407. Database::query(
  4408. 'SELECT course_code FROM '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id
  4409. ),
  4410. 'ASSOC'
  4411. );
  4412. return $info ? $info['course_code'] : false;
  4413. }
  4414. /**
  4415. * @param $courseId
  4416. * @return array
  4417. */
  4418. public static function getCourseSettings($courseId)
  4419. {
  4420. $settingTable = Database::get_course_table(TABLE_COURSE_SETTING);
  4421. $courseId = intval($courseId);
  4422. $sql = "SELECT * FROM $settingTable WHERE c_id = $courseId";
  4423. $result = Database::query($sql);
  4424. $settings = array();
  4425. if (Database::num_rows($result)) {
  4426. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4427. $settings[$row['variable']] = $row;
  4428. }
  4429. }
  4430. return $settings;
  4431. }
  4432. function updateTeachers($course_code, $teachers)
  4433. {
  4434. if (empty($teachers)) {
  4435. return false;
  4436. }
  4437. if (!is_array($teachers)) {
  4438. $teachers = array($teachers);
  4439. }
  4440. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4441. // Delete only teacher relations that doesn't match the selected teachers
  4442. $cond = null;
  4443. if (count($teachers)>0) {
  4444. foreach($teachers as $key) {
  4445. $cond.= " AND user_id <> '".$key."'";
  4446. }
  4447. }
  4448. $sql = 'DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
  4449. Database::query($sql);
  4450. if (count($teachers) > 0) {
  4451. foreach ($teachers as $key) {
  4452. //We check if the teacher is already subscribed in this course
  4453. $sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'" ';
  4454. $result = Database::query($sql_select_teacher);
  4455. if (Database::num_rows($result) == 1) {
  4456. $sql = 'UPDATE '.$course_user_table.' SET status = "1" WHERE course_code = "'.$course_code.'" AND user_id = "'.$key.'" ';
  4457. } else {
  4458. $sql = "INSERT INTO ".$course_user_table . " SET
  4459. course_code = '".Database::escape_string($course_code). "',
  4460. user_id = '".$key . "',
  4461. status = '1',
  4462. role = '',
  4463. tutor_id='0',
  4464. sort='0',
  4465. user_course_cat='0'";
  4466. }
  4467. Database::query($sql);
  4468. }
  4469. }
  4470. }
  4471. /**
  4472. * this function gets all the users of the course,
  4473. * including users from linked courses
  4474. */
  4475. public static function getCourseUsers()
  4476. {
  4477. //this would return only the users from real courses:
  4478. $session_id = api_get_session_id();
  4479. if ($session_id != 0) {
  4480. $user_list = self::get_real_and_linked_user_list(api_get_course_id(), true, $session_id);
  4481. } else {
  4482. $user_list = self::get_real_and_linked_user_list(api_get_course_id(), false, 0);
  4483. }
  4484. return $user_list;
  4485. }
  4486. /**
  4487. * this function gets all the groups of the course,
  4488. * not including linked courses
  4489. */
  4490. public static function getCourseGroups()
  4491. {
  4492. $session_id = api_get_session_id();
  4493. if ($session_id != 0) {
  4494. $new_group_list = self::get_group_list_of_course(api_get_course_id(), $session_id, 1);
  4495. } else {
  4496. $new_group_list = self::get_group_list_of_course(api_get_course_id(), 0, 1);
  4497. }
  4498. return $new_group_list;
  4499. }
  4500. /**
  4501. * this function shows the form for sending a message to a specific group or user.
  4502. */
  4503. /**
  4504. * @param FormValidator $form
  4505. * @param $to_already_selected
  4506. */
  4507. public static function addUserGroupMultiSelect(&$form, $to_already_selected)
  4508. {
  4509. $user_list = self::getCourseUsers();
  4510. $group_list = self::getCourseGroups();
  4511. $array = self::buildSelectOptions($group_list, $user_list, $to_already_selected);
  4512. $result = array();
  4513. foreach ($array as $content) {
  4514. $result[$content['value']] = $content['content'];
  4515. }
  4516. $group = $form->addElement('advmultiselect', 'users', get_lang('Users'), $result);
  4517. $group->setButtonAttributes('add');
  4518. $group->setButtonAttributes('remove');
  4519. }
  4520. /**
  4521. * this function shows the form for sending a message to a specific group or user.
  4522. */
  4523. /**
  4524. * @param FormValidator $form
  4525. * @param int $group_id
  4526. * @param array $to
  4527. */
  4528. public static function addGroupMultiSelect($form, $group_id, $to = array())
  4529. {
  4530. $group_users = GroupManager::get_subscribed_users($group_id);
  4531. $array = self::buildSelectOptions(null, $group_users, $to);
  4532. $result = array();
  4533. foreach ($array as $content) {
  4534. $result[$content['value']] = $content['content'];
  4535. }
  4536. $group = $form->addElement('advmultiselect', 'users', get_lang('Users'), $result);
  4537. $group->setButtonAttributes('add');
  4538. $group->setButtonAttributes('remove');
  4539. }
  4540. /**
  4541. * this function shows the form for sending a message to a specific group or user.
  4542. */
  4543. public static function buildSelectOptions(
  4544. $group_list = null,
  4545. $user_list = null,
  4546. $to_already_selected = array()
  4547. ) {
  4548. if (empty($to_already_selected)) {
  4549. $to_already_selected = array();
  4550. }
  4551. $result = array();
  4552. // adding the groups to the select form
  4553. if ($group_list) {
  4554. foreach ($group_list as $this_group) {
  4555. if (is_array($to_already_selected)) {
  4556. if (!in_array(
  4557. "GROUP:".$this_group['id'],
  4558. $to_already_selected
  4559. )
  4560. ) { // $to_already_selected is the array containing the groups (and users) that are already selected
  4561. $user_label = ($this_group['userNb'] > 0) ? get_lang('Users') : get_lang('LowerCaseUser');
  4562. $user_disabled = ($this_group['userNb'] > 0) ? "" : "disabled=disabled";
  4563. $result []= array(
  4564. 'disabled' => $user_disabled,
  4565. 'value' => "GROUP:".$this_group['id'],
  4566. 'content' => "G: ".$this_group['name']." - ".$this_group['userNb']." ".$user_label
  4567. );
  4568. }
  4569. }
  4570. }
  4571. }
  4572. // adding the individual users to the select form
  4573. if ($user_list) {
  4574. foreach ($user_list as $user) {
  4575. if (is_array($to_already_selected)) {
  4576. if (!in_array(
  4577. "USER:".$user['user_id'],
  4578. $to_already_selected
  4579. )
  4580. ) { // $to_already_selected is the array containing the users (and groups) that are already selected
  4581. $result[]= array(
  4582. 'value' => "USER:".$user['user_id'],
  4583. 'content' => api_get_person_name($user['firstname'], $user['lastname'])
  4584. );
  4585. }
  4586. }
  4587. }
  4588. }
  4589. return $result;
  4590. }
  4591. }