work.lib.php 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * @package chamilo.work
  6. * @author Thomas, Hugues, Christophe - original version
  7. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University -
  8. * ability for course admins to specify wether uploaded documents are visible or invisible by default.
  9. * @author Roan Embrechts, code refactoring and virtual course support
  10. * @author Frederic Vauthier, directories management
  11. * @author Julio Montoya <gugli100@gmail.com> BeezNest 2011 LOTS of bug fixes
  12. * @todo this lib should be convert in a static class and moved to main/inc/lib
  13. */
  14. /**
  15. * Displays action links (for admins, authorized groups members and authorized students)
  16. * @param string Current dir
  17. * @param integer Whether to show tool options
  18. * @param integer Whether to show upload form option
  19. * @return void
  20. */
  21. function display_action_links($id, $cur_dir_path, $action)
  22. {
  23. global $gradebook;
  24. $id = $my_back_id = intval($id);
  25. if ($action == 'list') {
  26. $my_back_id = 0;
  27. }
  28. $display_output = '';
  29. $origin = isset($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : '';
  30. if (!empty($id)) {
  31. $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'&id='.$my_back_id.'">'.
  32. Display::return_icon('back.png', get_lang('BackToWorksList'),'',ICON_SIZE_MEDIUM).'</a>';
  33. }
  34. if (api_is_allowed_to_edit(null, true) && $origin != 'learnpath') {
  35. // Create dir
  36. if (empty($id)) {
  37. $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=create_dir&origin='.$origin.'&gradebook='.$gradebook.'">';
  38. $display_output .= Display::return_icon('new_work.png', get_lang('CreateAssignment'),'',ICON_SIZE_MEDIUM).'</a>';
  39. }
  40. if (empty($id)) {
  41. // Options
  42. $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=settings&origin='.$origin.'&gradebook='.$gradebook.'">';
  43. $display_output .= Display::return_icon('settings.png', get_lang('EditToolOptions'),'',ICON_SIZE_MEDIUM).'</a>';
  44. }
  45. }
  46. if (api_is_allowed_to_edit(null, true) && $origin != 'learnpath' && api_is_allowed_to_session_edit(false, true)) {
  47. // Delete all files
  48. if (api_get_setting('permanently_remove_deleted_files') == 'true'){
  49. $message = get_lang('ConfirmYourChoiceDeleteAllfiles');
  50. } else {
  51. $message = get_lang('ConfirmYourChoice');
  52. }
  53. }
  54. if ($display_output != '') {
  55. echo '<div class="actions">';
  56. echo $display_output;
  57. echo '</div>';
  58. }
  59. }
  60. /**
  61. * Displays all options for this tool.
  62. * These are
  63. * - make all files visible / invisible
  64. * - set the default visibility of uploaded files
  65. * @param $defaults
  66. */
  67. function settingsForm($defaults)
  68. {
  69. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  70. if (!$is_allowed_to_edit) {
  71. return;
  72. }
  73. $url = api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq().'&action=settings';
  74. $form = new FormValidator('edit_settings', 'post', $url);
  75. $form->addElement('hidden', 'changeProperties', 1);
  76. $form->addElement('header', get_lang('EditToolOptions'));
  77. $group = array(
  78. $form->createElement('radio', 'show_score', null, get_lang('NewVisible'), 0),
  79. $form->createElement('radio', 'show_score', null, get_lang('NewUnvisible'), 1)
  80. );
  81. $form->addGroup($group, '', get_lang('DefaultUpload'));
  82. $group = array(
  83. $form->createElement('radio', 'student_delete_own_publication', null, get_lang('Yes'), 1),
  84. $form->createElement('radio', 'student_delete_own_publication', null, get_lang('No'), 0)
  85. );
  86. $form->addGroup($group, '', get_lang('StudentAllowedToDeleteOwnPublication'));
  87. $form->addElement('button', 'submit', get_lang('Save'));
  88. $form->setDefaults($defaults);
  89. return $form->return_form();
  90. }
  91. /**
  92. * converts 1-9 to 01-09
  93. */
  94. function two_digits($number)
  95. {
  96. $number = (int)$number;
  97. return ($number < 10) ? '0'.$number : $number;
  98. }
  99. /**
  100. * Converts 2008-10-06 12:45:00 to -> array('prefix' => array(year'=>2008, 'month'=>10, etc...)
  101. * @param string
  102. * @param string
  103. * @param array
  104. */
  105. function convert_date_to_array($date, $group)
  106. {
  107. $parts = explode(' ', $date);
  108. $date_parts = explode('-', $parts[0]);
  109. $date_parts_tmp = array();
  110. foreach ($date_parts as $item) {
  111. $date_parts_tmp[] = intval($item);
  112. }
  113. $time_parts = explode(':', $parts[1]);
  114. $time_parts_tmp = array();
  115. foreach ($time_parts as $item) {
  116. $time_parts_tmp[] = intval($item);
  117. }
  118. list($data[$group]['year'], $data[$group]['month'], $data[$group]['day']) = $date_parts_tmp;
  119. list($data[$group]['hour'], $data[$group]['minute']) = $time_parts_tmp;
  120. return $data;
  121. }
  122. /**
  123. * get date from a group of date
  124. */
  125. function get_date_from_group($group)
  126. {
  127. return
  128. $_POST[$group]['year'].'-'.
  129. two_digits($_POST[$group]['month']).'-'.
  130. two_digits($_POST[$group]['day']).' '.
  131. two_digits($_POST[$group]['hour']).':'.
  132. two_digits($_POST[$group]['minute']).':00';
  133. }
  134. /**
  135. * Create a group of select from a date
  136. * @param FormValidator $form
  137. * @param string $prefix
  138. * @return array
  139. */
  140. function create_group_date_select($form, $prefix = '')
  141. {
  142. $minute = range(10, 59);
  143. $d_year = date('Y');
  144. array_unshift($minute, '00', '01', '02', '03', '04', '05', '06', '07', '08', '09');
  145. $group_name = array(
  146. $form->createElement('select', $prefix.'day', '', array_combine(range(1, 31), range(1, 31))),
  147. $form->createElement('select', $prefix.'month', '', array_combine(range(1, 12), api_get_months_long())),
  148. $form->createElement('select', $prefix.'year', '', array($d_year => $d_year, $d_year + 1 => $d_year + 1)),
  149. $form->createElement('select', $prefix.'hour', '', array_combine(range(0, 23), range(0, 23))),
  150. $form->createElement('select', $prefix.'minute', '', $minute)
  151. );
  152. return $group_name;
  153. }
  154. /**
  155. * @param string $path
  156. * @param int $courseId
  157. *
  158. * @return array
  159. */
  160. function get_work_data_by_path($path, $courseId = null)
  161. {
  162. $path = Database::escape_string($path);
  163. if (empty($courseId)) {
  164. $courseId = api_get_course_int_id();
  165. } else {
  166. $courseId = intval($courseId);
  167. }
  168. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  169. $sql = "SELECT * FROM ".$work_table."
  170. WHERE url = '$path' AND c_id = $courseId ";
  171. $result = Database::query($sql);
  172. $return = array();
  173. if (Database::num_rows($result)) {
  174. $return = Database::fetch_array($result, 'ASSOC');
  175. }
  176. return $return;
  177. }
  178. /**
  179. * @param int $id
  180. * @param int $courseId
  181. * @param int $sessionId
  182. * @return array
  183. */
  184. function get_work_data_by_id($id, $courseId = null, $sessionId = null)
  185. {
  186. $id = intval($id);
  187. if (!empty($courseId)) {
  188. $courseId = intval($courseId);
  189. } else {
  190. $courseId = api_get_course_int_id();
  191. }
  192. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  193. $sessionCondition = null;
  194. if (!empty($sessionId)) {
  195. $sessionCondition = api_get_session_condition($sessionId, true);
  196. }
  197. $sql = "SELECT * FROM $table
  198. WHERE
  199. id = $id AND c_id = $courseId
  200. $sessionCondition";
  201. $result = Database::query($sql);
  202. $work = array();
  203. if (Database::num_rows($result)) {
  204. $work = Database::fetch_array($result, 'ASSOC');
  205. if (empty($work['title'])) {
  206. $work['title'] = basename($work['url']);
  207. }
  208. $work['download_url'] = api_get_path(WEB_CODE_PATH).'work/download.php?id='.$work['id'].'&'.api_get_cidreq();
  209. $work['view_url'] = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$work['id'].'&'.api_get_cidreq();
  210. $work['show_url'] = api_get_path(WEB_CODE_PATH).'work/show_file.php?id='.$work['id'].'&'.api_get_cidreq();
  211. if ($work['contains_file']) {
  212. $fileInfo = pathinfo($work['title']);
  213. if (is_array($fileInfo) &&
  214. !empty($fileInfo['extension']) &&
  215. in_array($fileInfo['extension'], array('jpg', 'png', 'gif'))
  216. ) {
  217. $work['show_content'] = '<img src="'.$work['show_url'].'"/>';
  218. }
  219. }
  220. }
  221. return $work;
  222. }
  223. /**
  224. * @param int $user_id
  225. * @param int $work_id
  226. *
  227. * @return int
  228. */
  229. function get_work_count_by_student($user_id, $work_id)
  230. {
  231. $user_id = intval($user_id);
  232. $work_id = intval($work_id);
  233. $course_id = api_get_course_int_id();
  234. $session_id = api_get_session_id();
  235. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  236. $sql = "SELECT COUNT(*) as count
  237. FROM $table
  238. WHERE
  239. c_id = $course_id AND
  240. parent_id = $work_id AND
  241. user_id = $user_id AND
  242. active IN (0, 1) AND
  243. session_id = $session_id ";
  244. $result = Database::query($sql);
  245. $return = 0;
  246. if (Database::num_rows($result)) {
  247. $return = Database::fetch_row($result,'ASSOC');
  248. $return = intval($return[0]);
  249. }
  250. return $return;
  251. }
  252. /**
  253. * @param int $id
  254. * @param int $courseId
  255. *
  256. * @return array
  257. */
  258. function get_work_assignment_by_id($id, $courseId = null)
  259. {
  260. if (empty($courseId)) {
  261. $courseId = api_get_course_int_id();
  262. } else {
  263. $courseId = intval($courseId);
  264. }
  265. $id = intval($id);
  266. $table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  267. $sql = "SELECT * FROM $table
  268. WHERE c_id = $courseId AND publication_id = $id";
  269. $result = Database::query($sql);
  270. $return = array();
  271. if (Database::num_rows($result)) {
  272. $return = Database::fetch_array($result, 'ASSOC');
  273. }
  274. return $return;
  275. }
  276. /**
  277. * @param int $id
  278. * @param array $my_folder_data
  279. * @param string $add_in_where_query
  280. *
  281. * @return array
  282. */
  283. function getWorkList($id, $my_folder_data, $add_in_where_query = null)
  284. {
  285. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  286. $course_id = api_get_course_int_id();
  287. $session_id = api_get_session_id();
  288. $condition_session = api_get_session_condition($session_id);
  289. $group_id = api_get_group_id();
  290. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  291. $linkInfo = GradebookUtils::is_resource_in_course_gradebook(
  292. api_get_course_id(),
  293. 3,
  294. $id,
  295. api_get_session_id()
  296. );
  297. if ($linkInfo) {
  298. $workInGradeBookLinkId = $linkInfo['id'];
  299. if ($workInGradeBookLinkId) {
  300. if ($is_allowed_to_edit) {
  301. if (intval($my_folder_data['qualification']) == 0) {
  302. Display::display_warning_message(
  303. get_lang('MaxWeightNeedToBeProvided')
  304. );
  305. }
  306. }
  307. }
  308. }
  309. $contains_file_query = '';
  310. // Get list from database
  311. if ($is_allowed_to_edit) {
  312. $active_condition = ' active IN (0, 1)';
  313. $sql = "SELECT * FROM $work_table
  314. WHERE
  315. c_id = $course_id
  316. $add_in_where_query
  317. $condition_session AND
  318. $active_condition AND
  319. (parent_id = 0)
  320. $contains_file_query AND
  321. post_group_id = '".$group_id."'
  322. ORDER BY sent_date DESC";
  323. } else {
  324. if (!empty($group_id)) {
  325. // set to select only messages posted by the user's group
  326. $group_query = " WHERE c_id = $course_id AND post_group_id = '".$group_id."' ";
  327. $subdirs_query = "AND parent_id = 0";
  328. } else {
  329. $group_query = " WHERE c_id = $course_id AND post_group_id = '0' ";
  330. $subdirs_query = "AND parent_id = 0";
  331. }
  332. //@todo how we can active or not an assignment?
  333. $active_condition = ' AND active IN (1, 0)';
  334. $sql = "SELECT * FROM $work_table
  335. $group_query
  336. $subdirs_query
  337. $add_in_where_query
  338. $active_condition
  339. $condition_session
  340. ORDER BY title";
  341. }
  342. $work_parents = array();
  343. $sql_result = Database::query($sql);
  344. if (Database::num_rows($sql_result)) {
  345. while ($work = Database::fetch_object($sql_result)) {
  346. if ($work->parent_id == 0) {
  347. $work_parents[] = $work;
  348. }
  349. }
  350. }
  351. return $work_parents;
  352. }
  353. /**
  354. * @param int $userId
  355. * @return array
  356. */
  357. function getWorkPerUser($userId)
  358. {
  359. $works = getWorkList(null, null, null);
  360. $result = array();
  361. if (!empty($works)) {
  362. foreach ($works as $workData) {
  363. $workId = $workData->id;
  364. $result[$workId]['work'] = $workData;
  365. $result[$workId]['work']->user_results = get_work_user_list(
  366. 0,
  367. 100,
  368. null,
  369. null,
  370. $workId,
  371. null,
  372. $userId
  373. );
  374. }
  375. }
  376. return $result;
  377. }
  378. /**
  379. * @param int $workId
  380. * @param int $groupId
  381. * @param int $course_id
  382. * @param int $sessionId
  383. * @return mixed
  384. */
  385. function getUniqueStudentAttemptsTotal($workId, $groupId, $course_id, $sessionId)
  386. {
  387. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  388. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  389. $course_id = intval($course_id);
  390. $workId = intval($workId);
  391. $sessionId = intval($sessionId);
  392. $groupId = intval($groupId);
  393. $sql = "SELECT count(DISTINCT u.user_id)
  394. FROM $work_table w
  395. INNER JOIN $user_table u
  396. ON w.user_id = u.user_id
  397. WHERE
  398. w.c_id = $course_id AND
  399. w.session_id = $sessionId AND
  400. w.parent_id = ".$workId." AND
  401. w.post_group_id = ".$groupId." AND
  402. w.active IN (0, 1)
  403. ";
  404. $res_document = Database::query($sql);
  405. $rowCount = Database::fetch_row($res_document);
  406. return $rowCount[0];
  407. }
  408. /**
  409. * @param mixed $workId
  410. * @param int $groupId
  411. * @param int $course_id
  412. * @param int $sessionId
  413. * @param int $userId user id to filter
  414. * @param array $onlyUserList only parse this user list
  415. * @return mixed
  416. */
  417. function getUniqueStudentAttempts(
  418. $workId,
  419. $groupId,
  420. $course_id,
  421. $sessionId,
  422. $userId = null,
  423. $onlyUserList = array()
  424. ) {
  425. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  426. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  427. $course_id = intval($course_id);
  428. $workCondition = null;
  429. if (is_array($workId)) {
  430. $workId = array_map('intval', $workId);
  431. $workId = implode("','", $workId);
  432. $workCondition = " w.parent_id IN ('".$workId."') AND";
  433. } else {
  434. $workId = intval($workId);
  435. $workCondition = " w.parent_id = ".$workId." AND";
  436. }
  437. $sessionId = intval($sessionId);
  438. $groupId = intval($groupId);
  439. $studentCondition = null;
  440. if (!empty($onlyUserList)) {
  441. $onlyUserList = array_map('intval', $onlyUserList);
  442. $studentCondition = "AND u.user_id IN ('".implode("', '", $onlyUserList)."') ";
  443. } else {
  444. if (empty($userId)) {
  445. return 0;
  446. }
  447. }
  448. $sql = "SELECT count(*) FROM (
  449. SELECT count(*), w.parent_id
  450. FROM $work_table w
  451. INNER JOIN $user_table u
  452. ON w.user_id = u.user_id
  453. WHERE
  454. w.filetype = 'file' AND
  455. w.c_id = $course_id AND
  456. w.session_id = $sessionId AND
  457. $workCondition
  458. w.post_group_id = ".$groupId." AND
  459. w.active IN (0, 1) $studentCondition
  460. ";
  461. if (!empty($userId)) {
  462. $userId = intval($userId);
  463. $sql .= " AND u.user_id = ".$userId;
  464. }
  465. $sql .= " GROUP BY u.user_id, w.parent_id) as t";
  466. $result = Database::query($sql);
  467. $row = Database::fetch_row($result);
  468. return $row[0];
  469. }
  470. /**
  471. * Shows the work list (student view)
  472. * @return string
  473. */
  474. function showStudentWorkGrid()
  475. {
  476. $courseInfo = api_get_course_info();
  477. $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student&'.api_get_cidreq();
  478. $columns = array(
  479. get_lang('Type'),
  480. get_lang('Title'),
  481. get_lang('HandOutDateLimit'),
  482. get_lang('Feedback'),
  483. get_lang('LastUpload')
  484. );
  485. $columnModel = array(
  486. array('name'=>'type', 'index'=>'type', 'width'=>'30', 'align'=>'left', 'sortable' => 'false'),
  487. array('name'=>'title', 'index'=>'title', 'width'=>'250', 'align'=>'left'),
  488. array('name'=>'expires_on', 'index'=>'expires_on', 'width'=>'80', 'align'=>'left', 'sortable'=>'false'),
  489. array('name'=>'feedback', 'index'=>'feedback', 'width'=>'80', 'align'=>'left'),
  490. array('name'=>'last_upload', 'index'=>'feedback', 'width'=>'125', 'align'=>'left'),
  491. );
  492. if ($courseInfo['show_score'] == 0) {
  493. $columnModel[] = array(
  494. 'name' => 'others',
  495. 'index' => 'others',
  496. 'width' => '80',
  497. 'align' => 'left',
  498. 'sortable' => 'false'
  499. );
  500. $columns[] = get_lang('Others');
  501. }
  502. $params = array(
  503. 'autowidth' => 'true',
  504. 'height' => 'auto'
  505. );
  506. $html = '<script>
  507. $(function() {
  508. '.Display::grid_js('workList', $url, $columns, $columnModel, $params, array(), null, true).'
  509. });
  510. </script>';
  511. $html .= Display::grid_html('workList');
  512. return $html;
  513. }
  514. /**
  515. * Shows the work list (teacher view)
  516. * @return string
  517. */
  518. function showTeacherWorkGrid()
  519. {
  520. $columnModel = array(
  521. array('name'=>'type', 'index'=>'type', 'width'=>'35', 'align'=>'left', 'sortable' => 'false'),
  522. array('name'=>'title', 'index'=>'title', 'width'=>'300', 'align'=>'left', 'wrap_cell' => "true"),
  523. array('name'=>'sent_date', 'index'=>'sent_date', 'width'=>'125', 'align'=>'left'),
  524. array('name'=>'expires_on', 'index'=>'expires_on', 'width'=>'125', 'align'=>'left'),
  525. array('name'=>'amount', 'index'=>'end_on', 'width'=>'110', 'align'=>'left'),
  526. array('name'=>'actions', 'index'=>'actions', 'width'=>'110', 'align'=>'left', 'sortable'=>'false')
  527. );
  528. $token = null;
  529. $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_teacher&'.api_get_cidreq();
  530. $deleteUrl = api_get_path(WEB_AJAX_PATH).'work.ajax.php?a=delete_work&'.api_get_cidreq();
  531. $columns = array(
  532. get_lang('Type'),
  533. get_lang('Title'),
  534. get_lang('SentDate'),
  535. get_lang('HandOutDateLimit'),
  536. get_lang('AmountSubmitted'),
  537. get_lang('Actions')
  538. );
  539. $params = array(
  540. 'multiselect' => true,
  541. 'autowidth' => 'true',
  542. 'height' => 'auto'
  543. );
  544. $html = '<script>
  545. $(function() {
  546. '.Display::grid_js('workList', $url, $columns, $columnModel, $params, array(), null, true).'
  547. $("#workList").jqGrid(
  548. "navGrid",
  549. "#workList_pager",
  550. { edit: false, add: false, del: true },
  551. { height:280, reloadAfterSubmit:false }, // edit options
  552. { height:280, reloadAfterSubmit:false }, // add options
  553. { reloadAfterSubmit:false, url: "'.$deleteUrl.'" }, // del options
  554. { width:500 } // search options
  555. );
  556. });
  557. </script>';
  558. $html .= Display::grid_html('workList');
  559. return $html;
  560. }
  561. /**
  562. * Builds the form thats enables the user to
  563. * select a directory to browse/upload in
  564. * This function has been copied from the document/document.inc.php library
  565. *
  566. * @param array $folders
  567. * @param string $curdirpath
  568. * @param string $group_dir
  569. * @return string html form
  570. */
  571. // TODO: This function is a candidate for removal, it is not used anywhere.
  572. function build_work_directory_selector($folders, $curdirpath, $group_dir = '')
  573. {
  574. $form = '<form name="selector" action="'.api_get_self().'?'.api_get_cidreq().'" method="POST">';
  575. $form .= get_lang('CurrentDirectory').' <select name="curdirpath" onchange="javascript: document.selector.submit();">';
  576. //group documents cannot be uploaded in the root
  577. if ($group_dir == '') {
  578. $form .= '<option value="/">/ ('.get_lang('Root').')</option>';
  579. if (is_array($folders)) {
  580. foreach ($folders as $folder) {
  581. $selected = ($curdirpath == $folder) ? ' selected="selected"' : '';
  582. $form .= '<option'.$selected.' value="'.$folder.'">'.$folder.'</option>'."\n";
  583. }
  584. }
  585. } else {
  586. foreach ($folders as $folder) {
  587. $selected = ($curdirpath == $folder) ? ' selected="selected"' : '';
  588. $display_folder = substr($folder, strlen($group_dir));
  589. $display_folder = ($display_folder == '') ? '/ ('.get_lang('Root').')' : $display_folder;
  590. $form .= '<option'.$selected.' value="'.$folder.'">'.$display_folder.'</option>'."\n";
  591. }
  592. }
  593. $form .= '</select>';
  594. $form .= '<noscript><input type="submit" name="change_path" value="'.get_lang('Ok').'" /></noscript>';
  595. $form .= '</form>';
  596. return $form;
  597. }
  598. /**
  599. * Builds the form thats enables the user to
  600. * move a document from one directory to another
  601. * This function has been copied from the document/document.inc.php library
  602. *
  603. * @param array $folders
  604. * @param string $curdirpath
  605. * @param string $move_file
  606. * @param string $group_dir
  607. * @return string html form
  608. */
  609. function build_work_move_to_selector($folders, $curdirpath, $move_file, $group_dir = '')
  610. {
  611. $course_id = api_get_course_int_id();
  612. $move_file = intval($move_file);
  613. $tbl_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  614. $sql = "SELECT title, url FROM $tbl_work WHERE c_id = $course_id AND id ='".$move_file."'";
  615. $result = Database::query($sql);
  616. $row = Database::fetch_array($result, 'ASSOC');
  617. $title = empty($row['title']) ? basename($row['url']) : $row['title'];
  618. global $gradebook;
  619. //@todo use formvalidator please!
  620. $form = '<form class="form-horizontal" name="move_to_form" action="'.api_get_self().'?'.api_get_cidreq().'&gradebook='.$gradebook.'&curdirpath='.Security::remove_XSS($curdirpath).'" method="POST">';
  621. $form .= '<legend>'.get_lang('MoveFile').' - '.Security::remove_XSS($title).'</legend>';
  622. $form .= '<input type="hidden" name="item_id" value="'.$move_file.'" />';
  623. $form .= '<input type="hidden" name="action" value="move_to" />';
  624. $form .= '<div class="control-group">
  625. <label>
  626. <span class="form_required">*</span>'.get_lang('Select').'
  627. </label>
  628. <div class="controls">';
  629. $form .= ' <select name="move_to_id">';
  630. //group documents cannot be uploaded in the root
  631. if ($group_dir == '') {
  632. if ($curdirpath != '/') {
  633. //$form .= '<option value="0">/ ('.get_lang('Root').')</option>';
  634. }
  635. if (is_array($folders)) {
  636. foreach ($folders as $fid => $folder) {
  637. //you cannot move a file to:
  638. //1. current directory
  639. //2. inside the folder you want to move
  640. //3. inside a subfolder of the folder you want to move
  641. if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')) {
  642. $form .= '<option value="'.$fid.'">'.$folder.'</option>';
  643. }
  644. }
  645. }
  646. } else {
  647. if ($curdirpath != '/') {
  648. $form .= '<option value="0">/ ('.get_lang('Root').')</option>';
  649. }
  650. foreach ($folders as $fid => $folder) {
  651. if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')) {
  652. //cannot copy dir into his own subdir
  653. $display_folder = substr($folder, strlen($group_dir));
  654. $display_folder = ($display_folder == '') ? '/ ('.get_lang('Root').')' : $display_folder;
  655. $form .= '<option value="'.$fid.'">'.$display_folder.'</option>'."\n";
  656. }
  657. }
  658. }
  659. $form .= '</select>';
  660. $form .= ' </div>
  661. </div>';
  662. $form .= '<div class="control-group">
  663. <div class="controls">
  664. <button type="submit" class="save" name="move_file_submit">'.get_lang('MoveFile').'</button>
  665. </div>
  666. </div>';
  667. $form .= '</form>';
  668. $form .= '<div style="clear: both; margin-bottom: 10px;"></div>';
  669. return $form;
  670. }
  671. /**
  672. * creates a new directory trying to find a directory name
  673. * that doesn't already exist
  674. * (we could use unique_name() here...)
  675. *
  676. * @author Hugues Peeters <hugues.peeters@claroline.net>
  677. * @author Bert Vanderkimpen
  678. * @author Yannick Warnier <ywarnier@beeznest.org> Adaptation for work tool
  679. * @param string $base_work_dir Base work dir (.../work)
  680. * @param string $desiredDirName complete path of the desired name
  681. *
  682. * @return string actual directory name if it succeeds, boolean false otherwise
  683. */
  684. function create_unexisting_work_directory($base_work_dir, $desired_dir_name)
  685. {
  686. $nb = '';
  687. $base_work_dir = (substr($base_work_dir, -1, 1) == '/' ? $base_work_dir : $base_work_dir.'/');
  688. while (file_exists($base_work_dir.$desired_dir_name.$nb)) {
  689. $nb += 1;
  690. }
  691. if (@mkdir($base_work_dir.$desired_dir_name.$nb, api_get_permissions_for_new_directories())) {
  692. return $desired_dir_name.$nb;
  693. } else {
  694. return false;
  695. }
  696. }
  697. /**
  698. * Delete a work-tool directory
  699. * @param int $id work id to delete
  700. * @return integer -1 on error
  701. */
  702. function deleteDirWork($id)
  703. {
  704. $locked = api_resource_is_locked_by_gradebook($id, LINK_STUDENTPUBLICATION);
  705. if ($locked == true) {
  706. Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
  707. return false;
  708. }
  709. $_course = api_get_course_info();
  710. $id = intval($id);
  711. $work_data = get_work_data_by_id($id);
  712. if (empty($work_data)) {
  713. return false;
  714. }
  715. $base_work_dir = api_get_path(SYS_COURSE_PATH) .$_course['path'].'/work';
  716. $work_data_url = $base_work_dir.$work_data['url'];
  717. $check = Security::check_abs_path($work_data_url.'/', $base_work_dir.'/');
  718. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  719. $TSTDPUBASG = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  720. $t_agenda = Database::get_course_table(TABLE_AGENDA);
  721. $course_id = api_get_course_int_id();
  722. if (!empty($work_data['url'])) {
  723. if ($check) {
  724. // Deleting all contents inside the folder
  725. $sql = "UPDATE $table SET active = 2
  726. WHERE c_id = $course_id AND filetype = 'folder' AND id = $id";
  727. Database::query($sql);
  728. $sql = "UPDATE $table SET active = 2
  729. WHERE c_id = $course_id AND parent_id = $id";
  730. Database::query($sql);
  731. $new_dir = $work_data_url.'_DELETED_'.$id;
  732. if (api_get_setting('permanently_remove_deleted_files') == 'true') {
  733. my_delete($work_data_url);
  734. } else {
  735. if (file_exists($work_data_url)) {
  736. rename($work_data_url, $new_dir);
  737. }
  738. }
  739. // Gets calendar_id from student_publication_assigment
  740. $sql = "SELECT add_to_calendar FROM $TSTDPUBASG
  741. WHERE c_id = $course_id AND publication_id = $id";
  742. $res = Database::query($sql);
  743. $calendar_id = Database::fetch_row($res);
  744. // delete from agenda if it exists
  745. if (!empty($calendar_id[0])) {
  746. $sql = "DELETE FROM $t_agenda
  747. WHERE c_id = $course_id AND id = '".$calendar_id[0]."'";
  748. Database::query($sql);
  749. }
  750. $sql = "DELETE FROM $TSTDPUBASG
  751. WHERE c_id = $course_id AND publication_id = $id";
  752. Database::query($sql);
  753. $link_info = GradebookUtils::is_resource_in_course_gradebook(
  754. api_get_course_id(),
  755. 3,
  756. $id,
  757. api_get_session_id()
  758. );
  759. $link_id = $link_info['id'];
  760. if ($link_info !== false) {
  761. GradebookUtils::remove_resource_from_course_gradebook($link_id);
  762. }
  763. return true;
  764. }
  765. }
  766. }
  767. /**
  768. * Get the path of a document in the student_publication table (path relative to the course directory)
  769. * @param integer $id
  770. * @return string Path (or -1 on error)
  771. */
  772. function get_work_path($id)
  773. {
  774. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  775. $course_id = api_get_course_int_id();
  776. $sql = 'SELECT url FROM '.$table.'
  777. WHERE c_id = '.$course_id.' AND id='.intval($id);
  778. $res = Database::query($sql);
  779. if (Database::num_rows($res)) {
  780. $row = Database::fetch_array($res);
  781. return $row['url'];
  782. }
  783. return -1;
  784. }
  785. /**
  786. * Update the url of a work in the student_publication table
  787. * @param integer $id of the work to update
  788. * @param string $new_path Destination directory where the work has been moved (must end with a '/')
  789. * @param int $parent_id
  790. * @return -1 on error, sql query result on success
  791. */
  792. function updateWorkUrl($id, $new_path, $parent_id)
  793. {
  794. if (empty($id)) return -1;
  795. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  796. $course_id = api_get_course_int_id();
  797. $id = intval($id);
  798. $parent_id = intval($parent_id);
  799. $sql = "SELECT * FROM $table WHERE c_id = $course_id AND id = $id";
  800. $res = Database::query($sql);
  801. if (Database::num_rows($res) != 1) {
  802. return -1;
  803. } else {
  804. $row = Database::fetch_array($res);
  805. $filename = basename($row['url']);
  806. $new_url = $new_path.$filename;
  807. $new_url = Database::escape_string($new_url);
  808. $sql2 = "UPDATE $table SET
  809. url = '$new_url',
  810. parent_id = '$parent_id'
  811. WHERE c_id = $course_id AND id = $id";
  812. $res2 = Database::query($sql2);
  813. return $res2;
  814. }
  815. }
  816. /**
  817. * Update the url of a dir in the student_publication table
  818. * @param array $work_data work original data
  819. * @param string $newPath Example: "folder1"
  820. * @return bool
  821. */
  822. function updateDirName($work_data, $newPath)
  823. {
  824. $course_id = $work_data['c_id'];
  825. $sessionId = intval($work_data['session_id']);
  826. $work_id = intval($work_data['id']);
  827. $oldPath = $work_data['url'];
  828. $originalNewPath = Database::escape_string($newPath);
  829. $newPath = Database::escape_string($newPath);
  830. $newPath = api_replace_dangerous_char($newPath);
  831. $newPath = disable_dangerous_file($newPath);
  832. if ($oldPath == '/'.$newPath) {
  833. return true;
  834. }
  835. if (!empty($newPath)) {
  836. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  837. $sql = "UPDATE $table SET
  838. title = '".$originalNewPath."'
  839. WHERE
  840. c_id = $course_id AND
  841. id = $work_id AND
  842. session_id = $sessionId
  843. ";
  844. Database::query($sql);
  845. }
  846. }
  847. /**
  848. * Return an array with all the folder's ids that are in the given path
  849. * @param string Path of the directory
  850. * @return array The list of ids of all the directories in the path
  851. * @author Julio Montoya Dokeos
  852. * @version April 2008
  853. */
  854. function get_parent_directories($id)
  855. {
  856. $course_id = api_get_course_int_id();
  857. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  858. $id = intval($id);
  859. $sql = "SELECT id FROM $work_table WHERE c_id = $course_id AND parent_id = $id";
  860. $result = Database::query($sql);
  861. $list_id = array();
  862. if (Database::num_rows($result)) {
  863. while ($row = Database::fetch_array($result)) {
  864. $list_id[] = $row['id'];
  865. }
  866. }
  867. return $list_id;
  868. }
  869. /**
  870. * Transform an all directory structure (only directories) in an array
  871. * @param string path of the directory
  872. * @return array the directory structure into an array
  873. * @author Julio Montoya Dokeos
  874. * @version April 2008
  875. */
  876. function directory_to_array($directory)
  877. {
  878. $array_items = array();
  879. if ($handle = @opendir($directory)) {
  880. while (false !== ($file = readdir($handle))) {
  881. if ($file != '.' && $file != '..') {
  882. if (is_dir($directory. '/' . $file)) {
  883. $array_items = array_merge($array_items, directory_to_array($directory. '/' . $file));
  884. $file = $directory . '/' . $file;
  885. $array_items[] = preg_replace("/\/\//si", '/', $file);
  886. }
  887. }
  888. }
  889. closedir($handle);
  890. }
  891. return $array_items;
  892. }
  893. /**
  894. * Insert into the DB of the course all the directories
  895. * @param string path of the /work directory of the course
  896. * @return -1 on error, sql query result on success
  897. * @author Julio Montoya
  898. * @version April 2008
  899. * @param string $base_work_dir
  900. */
  901. function insert_all_directory_in_course_table($base_work_dir)
  902. {
  903. $dir_to_array = directory_to_array($base_work_dir, true);
  904. $only_dir = array();
  905. for ($i = 0; $i < count($dir_to_array); $i++) {
  906. $only_dir[] = substr($dir_to_array[$i], strlen($base_work_dir), strlen($dir_to_array[$i]));
  907. }
  908. $course_id = api_get_course_int_id();
  909. $group_id = api_get_group_id();
  910. $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  911. for($i = 0; $i < count($only_dir); $i++) {
  912. $url = Database::escape_string($only_dir[$i]);
  913. $sql = "INSERT INTO " . $work_table . " SET
  914. c_id = '$course_id',
  915. url = '".$url."',
  916. title = '',
  917. description = '',
  918. author = '',
  919. active = '1',
  920. accepted = '1',
  921. filetype = 'folder',
  922. post_group_id = '".$group_id."'";
  923. Database::query($sql);
  924. }
  925. }
  926. /**
  927. * This function displays the number of files contained in a directory
  928. *
  929. * @param string the path of the directory
  930. * @param boolean true if we want the total quantity of files
  931. * include in others child directories, false only files in the directory
  932. * @return array the first element is an integer with the number of files
  933. * in the folder, the second element is the number of directories
  934. * @author Julio Montoya
  935. * @version April 2008
  936. */
  937. function count_dir($path_dir, $recurse)
  938. {
  939. $count = 0;
  940. $count_dir = 0;
  941. $d = dir($path_dir);
  942. while ($entry = $d->Read()) {
  943. if (!(($entry == '..') || ($entry == '.'))) {
  944. if (is_dir($path_dir.'/'.$entry)) {
  945. $count_dir++;
  946. if ($recurse) {
  947. $count += count_dir($path_dir . '/' . $entry, $recurse);
  948. }
  949. } else {
  950. $count++;
  951. }
  952. }
  953. }
  954. $return_array = array();
  955. $return_array[] = $count;
  956. $return_array[] = $count_dir;
  957. return $return_array;
  958. }
  959. /**
  960. * returns all the javascript that is required for easily
  961. * validation when you create a work
  962. * this goes into the $htmlHeadXtra[] array
  963. */
  964. function to_javascript_work()
  965. {
  966. $origin = isset($_REQUEST['origin']) && !empty($_REQUEST['origin']) ? api_get_tools_lists($_REQUEST['origin']) : '';
  967. $js = '<script>
  968. function updateDocumentTitle(value) {
  969. var temp = value.indexOf("/");
  970. //linux path
  971. if(temp!=-1){
  972. var temp=value.split("/");
  973. } else {
  974. var temp=value.split("\\\");
  975. }
  976. document.getElementById("file_upload").value=temp[temp.length-1];
  977. $("#contains_file_id").attr("value", 1);
  978. }
  979. function checkDate(month, day, year) {
  980. var monthLength =
  981. new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  982. if (!day || !month || !year)
  983. return false;
  984. // check for bisestile year
  985. if (year/4 == parseInt(year/4))
  986. monthLength[1] = 29;
  987. if (month < 1 || month > 12)
  988. return false;
  989. if (day > monthLength[month-1])
  990. return false;
  991. return true;
  992. }
  993. function mktime() {
  994. var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
  995. d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
  996. var dateManip = {
  997. 0: function(tt){ return d.setHours(tt); },
  998. 1: function(tt){ return d.setMinutes(tt); },
  999. 2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
  1000. 3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
  1001. 4: function(tt){ return d.setDate(tt+mb); },
  1002. 5: function(tt){ return d.setYear(tt+ma); }
  1003. };
  1004. for( i = 0; i < argc; i++ ){
  1005. no = parseInt(argv[i]*1);
  1006. if (isNaN(no)) {
  1007. return false;
  1008. } else {
  1009. // arg is number, lets manipulate date object
  1010. if(!dateManip[i](no)){
  1011. // failed
  1012. return false;
  1013. }
  1014. }
  1015. }
  1016. return Math.floor(d.getTime()/1000);
  1017. }
  1018. function setFocus() {
  1019. $("#work_title").focus();
  1020. }
  1021. $(document).ready(function() {
  1022. setFocus();
  1023. var checked = $("#expiry_date").attr("checked");
  1024. if (checked) {
  1025. $("#option2").show();
  1026. $("#option3").show();
  1027. $("#end_date").attr("checked", true);
  1028. } else {
  1029. $("#option2").hide();
  1030. $("#option3").hide();
  1031. $("#end_date").attr("checked", false);
  1032. }
  1033. $("#expiry_date").click(function() {
  1034. $("#option2").toggle();
  1035. });
  1036. $("#end_date").click(function() {
  1037. $("#option3").toggle();
  1038. });
  1039. });
  1040. </script>';
  1041. return $js;
  1042. }
  1043. /**
  1044. * Gets the id of a student publication with a given path
  1045. * @param string $path
  1046. * @return true if is found / false if not found
  1047. */
  1048. // TODO: The name of this function does not fit with the kind of information it returns. Maybe check_work_id() or is_work_id()?
  1049. function get_work_id($path)
  1050. {
  1051. $TBL_STUDENT_PUBLICATION = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1052. $TBL_PROP_TABLE = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1053. $course_id = api_get_course_int_id();
  1054. $path = Database::escape_string($path);
  1055. if (api_is_allowed_to_edit()) {
  1056. $sql = "SELECT work.id
  1057. FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
  1058. WHERE
  1059. props.c_id = $course_id AND
  1060. work.c_id = $course_id AND
  1061. props.tool='work' AND
  1062. work.id=props.ref AND
  1063. work.url LIKE 'work/".$path."%' AND
  1064. work.filetype='file' AND
  1065. props.visibility<>'2'";
  1066. } else {
  1067. $sql = "SELECT work.id
  1068. FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
  1069. WHERE
  1070. props.c_id = $course_id AND
  1071. work.c_id = $course_id AND
  1072. props.tool='work' AND
  1073. work.id=props.ref AND
  1074. work.url LIKE 'work/".$path."%' AND
  1075. work.filetype='file' AND
  1076. props.visibility<>'2' AND
  1077. props.lastedit_user_id = '".api_get_user_id()."'";
  1078. }
  1079. $result = Database::query($sql);
  1080. $num_rows = Database::num_rows($result);
  1081. if ($result && $num_rows > 0) {
  1082. return true;
  1083. } else {
  1084. return false;
  1085. }
  1086. }
  1087. /**
  1088. * @param int $work_id
  1089. * @param int $onlyMeUserId show only my works
  1090. * @param int $notMeUserId show works from everyone except me
  1091. * @return int
  1092. */
  1093. function get_count_work($work_id, $onlyMeUserId = null, $notMeUserId = null)
  1094. {
  1095. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1096. $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1097. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1098. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  1099. $session_id = api_get_session_id();
  1100. $condition_session = api_get_session_condition($session_id, true, false, 'work.session_id');
  1101. $group_id = api_get_group_id();
  1102. $course_info = api_get_course_info();
  1103. $course_id = $course_info['real_id'];
  1104. $work_id = intval($work_id);
  1105. if (!empty($group_id)) {
  1106. // set to select only messages posted by the user's group
  1107. $extra_conditions = " work.post_group_id = '".intval($group_id)."' ";
  1108. } else {
  1109. $extra_conditions = " work.post_group_id = '0' ";
  1110. }
  1111. if ($is_allowed_to_edit) {
  1112. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1113. } else {
  1114. $extra_conditions .= ' AND work.active IN (0, 1) AND accepted = 1';
  1115. if (isset($course_info['show_score']) && $course_info['show_score'] == 1) {
  1116. $extra_conditions .= " AND work.user_id = ".api_get_user_id()." ";
  1117. } else {
  1118. $extra_conditions .= '';
  1119. }
  1120. }
  1121. $extra_conditions .= " AND parent_id = ".$work_id." ";
  1122. $where_condition = null;
  1123. if (!empty($notMeUserId)) {
  1124. $where_condition .= " AND u.user_id <> ".intval($notMeUserId);
  1125. }
  1126. if (!empty($onlyMeUserId)) {
  1127. $where_condition .= " AND u.user_id = ".intval($onlyMeUserId);
  1128. }
  1129. $sql = "SELECT count(*) as count
  1130. FROM $iprop_table prop
  1131. INNER JOIN $work_table work
  1132. ON (
  1133. prop.ref = work.id AND
  1134. prop.c_id = $course_id AND
  1135. prop.tool='work' AND
  1136. prop.visibility <> 2 AND
  1137. work.c_id = $course_id
  1138. )
  1139. INNER JOIN $user_table u ON (work.user_id = u.user_id)
  1140. WHERE $extra_conditions $where_condition $condition_session";
  1141. $result = Database::query($sql);
  1142. $users_with_work = 0;
  1143. if (Database::num_rows($result)) {
  1144. $result = Database::fetch_array($result);
  1145. $users_with_work = $result['count'];
  1146. }
  1147. return $users_with_work;
  1148. }
  1149. /**
  1150. * @param int $start
  1151. * @param int $limit
  1152. * @param string $column
  1153. * @param string $direction
  1154. * @param string $where_condition
  1155. * @param bool $getCount
  1156. * @return array
  1157. */
  1158. function getWorkListStudent(
  1159. $start,
  1160. $limit,
  1161. $column,
  1162. $direction,
  1163. $where_condition,
  1164. $getCount = false
  1165. ) {
  1166. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1167. $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  1168. $courseInfo = api_get_course_info();
  1169. $course_id = $courseInfo['real_id'];
  1170. $session_id = api_get_session_id();
  1171. $condition_session = api_get_session_condition($session_id);
  1172. $group_id = api_get_group_id();
  1173. $userId = api_get_user_id();
  1174. $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
  1175. api_get_user_id(),
  1176. $courseInfo
  1177. );
  1178. if (!in_array($direction, array('asc','desc'))) {
  1179. $direction = 'desc';
  1180. }
  1181. if (!empty($where_condition)) {
  1182. $where_condition = ' AND ' . $where_condition;
  1183. }
  1184. $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
  1185. $start = intval($start);
  1186. $limit = intval($limit);
  1187. // Get list from database
  1188. if (!empty($group_id)) {
  1189. $group_query = " WHERE w.c_id = $course_id AND post_group_id = '".$group_id."' ";
  1190. $subdirs_query = "AND parent_id = 0";
  1191. } else {
  1192. $group_query = " WHERE w.c_id = $course_id AND post_group_id = '0' ";
  1193. $subdirs_query = "AND parent_id = 0";
  1194. }
  1195. $active_condition = ' AND active IN (1, 0)';
  1196. if ($getCount) {
  1197. $select = "SELECT count(w.id) as count ";
  1198. } else {
  1199. $select = "SELECT w.*, a.expires_on, expires_on, ends_on, enable_qualification ";
  1200. }
  1201. $sql = "$select
  1202. FROM $workTable w
  1203. LEFT JOIN $workTableAssignment a
  1204. ON (a.publication_id = w.id AND a.c_id = w.c_id)
  1205. $group_query
  1206. $subdirs_query
  1207. $active_condition
  1208. $condition_session
  1209. $where_condition
  1210. ";
  1211. $sql .= " ORDER BY $column $direction ";
  1212. if (!empty($start) && !empty($limit)) {
  1213. $sql .= " LIMIT $start, $limit";
  1214. }
  1215. $result = Database::query($sql);
  1216. if ($getCount) {
  1217. $row = Database::fetch_array($result);
  1218. return $row['count'];
  1219. }
  1220. $works = array();
  1221. $url = api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq();
  1222. if ($isDrhOfCourse) {
  1223. $url = api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq();
  1224. }
  1225. $urlOthers = api_get_path(WEB_CODE_PATH).'work/work_list_others.php?'.api_get_cidreq().'&id=';
  1226. while ($work = Database::fetch_array($result, 'ASSOC')) {
  1227. $isSubscribed = userIsSubscribedToWork($userId, $work['id'], $course_id);
  1228. if ($isSubscribed == false) {
  1229. continue;
  1230. }
  1231. $visibility = api_get_item_visibility($courseInfo, 'work', $work['id'], $session_id);
  1232. if ($visibility != 1) {
  1233. continue;
  1234. }
  1235. $work['type'] = Display::return_icon('work.png');
  1236. $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
  1237. if (empty($work['title'])) {
  1238. $work['title'] = basename($work['url']);
  1239. }
  1240. $whereCondition = " AND u.user_id = ".intval($userId);
  1241. $workList = get_work_user_list(
  1242. 0,
  1243. 1000,
  1244. null,
  1245. null,
  1246. $work['id'],
  1247. $whereCondition
  1248. );
  1249. $count = getTotalWorkComment($workList, $courseInfo);
  1250. if (!is_null($count) && !empty($count)) {
  1251. $work['feedback'] = ' '.Display::label($count.' '.get_lang('Feedback'), 'info');
  1252. }
  1253. $lastWork = getLastWorkStudentFromParentByUser($userId, $work['id'], $courseInfo);
  1254. if (!empty($lastWork)) {
  1255. $work['last_upload'] = Display::label($lastWork['qualification'], 'warning').' - ';
  1256. $work['last_upload'] .= api_get_local_time($lastWork['sent_date']);
  1257. }
  1258. $work['title'] = Display::url($work['title'], $url.'&id='.$work['id']);
  1259. $work['others'] = Display::url(
  1260. Display::return_icon('group.png', get_lang('Others')),
  1261. $urlOthers.$work['id']
  1262. );
  1263. $works[] = $work;
  1264. }
  1265. return $works;
  1266. }
  1267. /**
  1268. * @param int $start
  1269. * @param int $limit
  1270. * @param string $column
  1271. * @param string $direction
  1272. * @param string $where_condition
  1273. * @param bool $getCount
  1274. * @return array
  1275. */
  1276. function getWorkListTeacher(
  1277. $start,
  1278. $limit,
  1279. $column,
  1280. $direction,
  1281. $where_condition,
  1282. $getCount = false
  1283. ) {
  1284. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1285. $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  1286. $courseInfo = api_get_course_info();
  1287. $course_id = api_get_course_int_id();
  1288. $session_id = api_get_session_id();
  1289. $condition_session = api_get_session_condition($session_id);
  1290. $group_id = api_get_group_id();
  1291. $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
  1292. if (!in_array($direction, array('asc', 'desc'))) {
  1293. $direction = 'desc';
  1294. }
  1295. if (!empty($where_condition)) {
  1296. $where_condition = ' AND ' . $where_condition;
  1297. }
  1298. $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
  1299. $start = intval($start);
  1300. $limit = intval($limit);
  1301. $works = array();
  1302. // Get list from database
  1303. if ($is_allowed_to_edit) {
  1304. $active_condition = ' active IN (0, 1)';
  1305. if ($getCount) {
  1306. $select = " SELECT count(w.id) as count";
  1307. } else {
  1308. $select = " SELECT w.*, a.expires_on, expires_on, ends_on, enable_qualification ";
  1309. }
  1310. $sql = " $select
  1311. FROM $workTable w
  1312. LEFT JOIN $workTableAssignment a
  1313. ON (a.publication_id = w.id AND a.c_id = w.c_id)
  1314. WHERE
  1315. w.c_id = $course_id
  1316. $condition_session AND
  1317. $active_condition AND
  1318. (parent_id = 0) AND
  1319. post_group_id = '".$group_id."'
  1320. $where_condition
  1321. ORDER BY $column $direction
  1322. LIMIT $start, $limit";
  1323. $result = Database::query($sql);
  1324. if ($getCount) {
  1325. $row = Database::fetch_array($result);
  1326. return $row['count'];
  1327. }
  1328. $url = api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq();
  1329. while ($work = Database::fetch_array($result, 'ASSOC')) {
  1330. $workId = $work['id'];
  1331. $work['type'] = Display::return_icon('work.png');
  1332. $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
  1333. $totalUsers = getStudentSubscribedToWork(
  1334. $workId,
  1335. $course_id,
  1336. $group_id,
  1337. $session_id,
  1338. true
  1339. );
  1340. $countUniqueAttempts = getUniqueStudentAttemptsTotal(
  1341. $workId,
  1342. $group_id,
  1343. $course_id,
  1344. $session_id
  1345. );
  1346. $work['amount'] = Display::label(
  1347. $countUniqueAttempts . '/' .
  1348. $totalUsers,
  1349. 'success'
  1350. );
  1351. $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $session_id);
  1352. if ($visibility == 1) {
  1353. $icon = 'visible.png';
  1354. $text = get_lang('Visible');
  1355. $action = 'invisible';
  1356. $class = '';
  1357. } else {
  1358. $icon = 'invisible.png';
  1359. $text = get_lang('invisible');
  1360. $action = 'visible';
  1361. $class = 'muted';
  1362. }
  1363. $visibilityLink = Display::url(
  1364. Display::return_icon($icon, $text, array(), ICON_SIZE_SMALL),
  1365. api_get_path(WEB_CODE_PATH).'work/work.php?id='.$workId.'&action='.$action.'&'.api_get_cidreq()
  1366. );
  1367. if (empty($work['title'])) {
  1368. $work['title'] = basename($work['url']);
  1369. }
  1370. $work['title'] = Display::url($work['title'], $url.'&id='.$workId, ['class' => $class]);
  1371. $work['title'] .= ' '.Display::label(get_count_work($work['id']), 'success');
  1372. $work['sent_date'] = api_get_local_time($work['sent_date']);
  1373. $editLink = Display::url(
  1374. Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL),
  1375. api_get_path(WEB_CODE_PATH).'work/edit_work.php?id='.$workId.'&'.api_get_cidreq()
  1376. );
  1377. if ($countUniqueAttempts > 0) {
  1378. $downloadLink = Display::url(
  1379. Display::return_icon(
  1380. 'save_pack.png',
  1381. get_lang('Save'),
  1382. array(),
  1383. ICON_SIZE_SMALL
  1384. ),
  1385. api_get_path(WEB_CODE_PATH) . 'work/downloadfolder.inc.php?id=' . $workId . '&' . api_get_cidreq()
  1386. );
  1387. } else {
  1388. $downloadLink = Display::url(
  1389. Display::return_icon(
  1390. 'save_pack_na.png',
  1391. get_lang('Save'),
  1392. array(),
  1393. ICON_SIZE_SMALL
  1394. ),
  1395. '#'
  1396. );
  1397. }
  1398. $deleteUrl = api_get_path(WEB_CODE_PATH).'work/work.php?id='.$workId.'&action=delete_dir&'.api_get_cidreq();
  1399. $deleteLink = '<a href="#" onclick="showConfirmationPopup(this, \'' . $deleteUrl . '\' ) " >' .
  1400. Display::return_icon(
  1401. 'delete.png',
  1402. get_lang('Delete'),
  1403. array(),
  1404. ICON_SIZE_SMALL
  1405. ) . '</a>';
  1406. if (!api_is_allowed_to_edit()) {
  1407. $deleteLink = null;
  1408. $editLink = null;
  1409. }
  1410. $work['actions'] = $visibilityLink.$downloadLink.$editLink.$deleteLink;
  1411. $works[] = $work;
  1412. }
  1413. }
  1414. return $works;
  1415. }
  1416. /**
  1417. * @param int $start
  1418. * @param int $limit
  1419. * @param string $column
  1420. * @param string $direction
  1421. * @param int $workId
  1422. * @param int $studentId
  1423. * @param string $whereCondition
  1424. * @param bool $getCount
  1425. * @return array
  1426. */
  1427. function get_work_user_list_from_documents(
  1428. $start,
  1429. $limit,
  1430. $column,
  1431. $direction,
  1432. $workId,
  1433. $studentId = null,
  1434. $whereCondition,
  1435. $getCount = false
  1436. ) {
  1437. if ($getCount) {
  1438. $select1 = " SELECT count(u.user_id) as count ";
  1439. $select2 = " SELECT count(u.user_id) as count ";
  1440. } else {
  1441. $select1 = " SELECT DISTINCT u.firstname, u.lastname, u.user_id, w.title, w.parent_id, w.document_id document_id, w.id, qualification, qualificator_id";
  1442. $select2 = " SELECT DISTINCT u.firstname, u.lastname, u.user_id, d.title, w.parent_id, d.id document_id, 0, 0, 0";
  1443. }
  1444. $documentTable = Database::get_course_table(TABLE_DOCUMENT);
  1445. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1446. $workRelDocument = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  1447. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  1448. $courseId = api_get_course_int_id();
  1449. $sessionId = api_get_session_id();
  1450. if (empty($studentId)) {
  1451. $studentId = api_get_user_id();
  1452. }
  1453. $studentId = intval($studentId);
  1454. $workId = intval($workId);
  1455. $userCondition = " AND u.user_id = $studentId ";
  1456. $sessionCondition = " AND w.session_id = $sessionId ";
  1457. $workCondition = " AND w_rel.work_id = $workId";
  1458. $workParentCondition = " AND w.parent_id = $workId";
  1459. $sql = "(
  1460. $select1 FROM $userTable u
  1461. INNER JOIN $workTable w ON (u.user_id = w.user_id AND w.active IN (0, 1) AND w.filetype = 'file')
  1462. WHERE
  1463. w.c_id = $courseId
  1464. $userCondition
  1465. $sessionCondition
  1466. $whereCondition
  1467. $workParentCondition
  1468. ) UNION (
  1469. $select2 FROM $workTable w
  1470. INNER JOIN $workRelDocument w_rel ON (w_rel.work_id = w.id AND w.active IN (0, 1) AND w_rel.c_id = w.c_id)
  1471. INNER JOIN $documentTable d ON (w_rel.document_id = d.id AND d.c_id = w.c_id)
  1472. INNER JOIN $userTable u ON (u.user_id = $studentId)
  1473. WHERE
  1474. w.c_id = $courseId
  1475. $workCondition
  1476. $sessionCondition AND
  1477. d.id NOT IN (
  1478. SELECT w.document_id id
  1479. FROM $workTable w
  1480. WHERE
  1481. user_id = $studentId AND
  1482. c_id = $courseId AND
  1483. filetype = 'file' AND
  1484. active IN (0, 1)
  1485. $sessionCondition
  1486. $workParentCondition
  1487. )
  1488. )";
  1489. $start = intval($start);
  1490. $limit = intval($limit);
  1491. $direction = in_array(strtolower($direction), array('desc', 'asc')) ? $direction : 'desc';
  1492. $column = Database::escape_string($column);
  1493. if ($getCount) {
  1494. $result = Database::query($sql);
  1495. $result = Database::fetch_array($result);
  1496. return $result['count'];
  1497. }
  1498. $sql .= " ORDER BY $column $direction";
  1499. $sql .= " LIMIT $start, $limit";
  1500. $result = Database::query($sql);
  1501. $currentUserId = api_get_user_id();
  1502. $work_data = get_work_data_by_id($workId);
  1503. $qualificationExists = false;
  1504. if (!empty($work_data['qualification']) && intval($work_data['qualification']) > 0) {
  1505. $qualificationExists = true;
  1506. }
  1507. $urlAdd = api_get_path(WEB_CODE_PATH).'work/upload_from_template.php?'.api_get_cidreq();
  1508. $urlEdit = api_get_path(WEB_CODE_PATH).'work/edit.php?'.api_get_cidreq();
  1509. $urlDelete = api_get_path(WEB_CODE_PATH).'work/work_list.php?action=delete&'.api_get_cidreq();
  1510. $urlView = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq();
  1511. $editIcon = Display::return_icon('edit.png', get_lang('Edit'));
  1512. $addIcon = Display::return_icon('add.png', get_lang('Add'));
  1513. $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'));
  1514. $viewIcon = Display::return_icon('default.png', get_lang('View'));
  1515. $allowEdition = api_get_course_setting('student_delete_own_publication');
  1516. $workList = array();
  1517. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1518. $userId = $row['user_id'];
  1519. $documentId = $row['document_id'];
  1520. $itemId = $row['id'];
  1521. $addLinkShowed = false;
  1522. if (empty($documentId)) {
  1523. $url = $urlEdit.'&item_id='.$row['id'].'&id='.$workId;
  1524. $editLink = Display::url($editIcon, $url);
  1525. if ($allowEdition == false) {
  1526. $editLink = null;
  1527. }
  1528. } else {
  1529. $documentToWork = getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId);
  1530. if (empty($documentToWork)) {
  1531. $url = $urlAdd.'&document_id='.$documentId.'&id='.$workId;
  1532. $editLink = Display::url($addIcon, $url);
  1533. $addLinkShowed = true;
  1534. } else {
  1535. $row['title'] = $documentToWork['title'];
  1536. $row['sent_date'] = $documentToWork['sent_date'];
  1537. $newWorkId = $documentToWork['id'];
  1538. $url = $urlEdit.'&item_id='.$newWorkId.'&id='.$workId;
  1539. $editLink = Display::url($editIcon, $url);
  1540. if ($allowEdition == false) {
  1541. $editLink = null;
  1542. }
  1543. }
  1544. }
  1545. if ($allowEdition && !empty($itemId)) {
  1546. $deleteLink = Display::url($deleteIcon, $urlDelete.'&item_id='.$itemId.'&id='.$workId);
  1547. } else {
  1548. $deleteLink = null;
  1549. }
  1550. $viewLink = null;
  1551. if (!empty($itemId)) {
  1552. $viewLink = Display::url($viewIcon, $urlView.'&id='.$itemId);
  1553. }
  1554. //$row['type'] = build_document_icon_tag('file', $row['url']);
  1555. $row['type'] = null;
  1556. if ($qualificationExists) {
  1557. if (empty($row['qualificator_id'])) {
  1558. $status = Display::label(get_lang('NotRevised'), 'warning');
  1559. } else {
  1560. $status = Display::label(get_lang('Revised'), 'success');
  1561. }
  1562. $row['qualificator_id'] = $status;
  1563. }
  1564. if (!empty($row['qualification'])) {
  1565. $row['qualification'] = Display::label($row['qualification'], 'info');
  1566. }
  1567. if (!empty($row['sent_date'])) {
  1568. $row['sent_date'] = api_get_local_time($row['sent_date']);
  1569. }
  1570. if ($userId == $currentUserId) {
  1571. $row['actions'] = $viewLink.$editLink.$deleteLink;
  1572. }
  1573. if ($addLinkShowed) {
  1574. $row['qualification'] = '';
  1575. $row['qualificator_id'] = '';
  1576. }
  1577. $workList[] = $row;
  1578. }
  1579. return $workList;
  1580. }
  1581. /**
  1582. * @param int $start
  1583. * @param int $limit
  1584. * @param int $column
  1585. * @param string $direction
  1586. * @param int $work_id
  1587. * @param array $where_condition
  1588. * @param int $studentId
  1589. * @param bool $getCount
  1590. * @return array
  1591. */
  1592. function get_work_user_list(
  1593. $start,
  1594. $limit,
  1595. $column,
  1596. $direction,
  1597. $work_id,
  1598. $where_condition = null,
  1599. $studentId = null,
  1600. $getCount = false
  1601. ) {
  1602. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1603. $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1604. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1605. $session_id = api_get_session_id();
  1606. $group_id = api_get_group_id();
  1607. $course_info = api_get_course_info();
  1608. $course_id = $course_info['real_id'];
  1609. $work_id = intval($work_id);
  1610. $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
  1611. $start = intval($start);
  1612. $limit = intval($limit);
  1613. if (!in_array($direction, array('asc','desc'))) {
  1614. $direction = 'desc';
  1615. }
  1616. $work_data = get_work_data_by_id($work_id);
  1617. $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
  1618. $condition_session = api_get_session_condition($session_id, true, false, 'work.session_id');
  1619. $locked = api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION);
  1620. $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
  1621. api_get_user_id(),
  1622. $course_info
  1623. );
  1624. if (!empty($work_data)) {
  1625. if (!empty($group_id)) {
  1626. $extra_conditions = " work.post_group_id = '".intval($group_id)."' ";
  1627. // set to select only messages posted by the user's group
  1628. } else {
  1629. $extra_conditions = " work.post_group_id = '0' ";
  1630. }
  1631. if ($is_allowed_to_edit || $isDrhOfCourse) {
  1632. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1633. } else {
  1634. if (isset($course_info['show_score']) &&
  1635. $course_info['show_score'] == 1
  1636. ) {
  1637. $extra_conditions .= " AND (u.user_id = ".api_get_user_id()." AND work.active IN (0, 1)) ";
  1638. } else {
  1639. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1640. }
  1641. }
  1642. $extra_conditions .= " AND parent_id = ".$work_id." ";
  1643. $select = 'SELECT DISTINCT
  1644. u.user_id,
  1645. work.id as id,
  1646. title as title,
  1647. description,
  1648. url,
  1649. sent_date,
  1650. contains_file,
  1651. has_properties,
  1652. view_properties,
  1653. qualification,
  1654. weight,
  1655. allow_text_assignment,
  1656. u.firstname,
  1657. u.lastname,
  1658. u.username,
  1659. parent_id,
  1660. accepted,
  1661. qualificator_id';
  1662. if ($getCount) {
  1663. $select = "SELECT DISTINCT count(u.user_id) as count ";
  1664. }
  1665. $user_condition = "INNER JOIN $user_table u ON (work.user_id = u.user_id) ";
  1666. $work_condition = "$iprop_table prop INNER JOIN $work_table work
  1667. ON (prop.ref = work.id AND prop.c_id = $course_id AND work.c_id = $course_id ) ";
  1668. $work_assignment = get_work_assignment_by_id($work_id);
  1669. if (!empty($studentId)) {
  1670. $where_condition.= " AND u.user_id = ".intval($studentId);
  1671. }
  1672. $sql = " $select
  1673. FROM $work_condition $user_condition
  1674. WHERE $extra_conditions $where_condition $condition_session
  1675. AND u.status != " . INVITEE . "
  1676. ORDER BY $column $direction";
  1677. if (!empty($start) && !empty($limit)) {
  1678. $sql .= " LIMIT $start, $limit";
  1679. }
  1680. $result = Database::query($sql);
  1681. $works = array();
  1682. if ($getCount) {
  1683. $work = Database::fetch_array($result, 'ASSOC');
  1684. return $work['count'];
  1685. }
  1686. $url = api_get_path(WEB_CODE_PATH).'work/';
  1687. $unoconv = api_get_configuration_value('unoconv.binaries');
  1688. while ($work = Database::fetch_array($result, 'ASSOC')) {
  1689. $item_id = $work['id'];
  1690. // Get the author ID for that document from the item_property table
  1691. $is_author = false;
  1692. $can_read = false;
  1693. $owner_id = $work['user_id'];
  1694. /* Because a bug found when saving items using the api_item_property_update()
  1695. the field $item_property_data['insert_user_id'] is not reliable. */
  1696. if (!$is_allowed_to_edit && $owner_id == api_get_user_id()) {
  1697. $is_author = true;
  1698. }
  1699. if ($course_info['show_score'] == 0) {
  1700. $can_read = true;
  1701. }
  1702. if ($work['accepted'] == '0') {
  1703. $class = 'invisible';
  1704. } else {
  1705. $class = '';
  1706. }
  1707. $qualification_exists = false;
  1708. if (!empty($work_data['qualification']) &&
  1709. intval($work_data['qualification']) > 0
  1710. ) {
  1711. $qualification_exists = true;
  1712. }
  1713. $qualification_string = '';
  1714. if ($qualification_exists) {
  1715. if ($work['qualification'] == '') {
  1716. $qualification_string = Display::label('-');
  1717. } else {
  1718. $label = 'info';
  1719. $relativeScore = $work['qualification']/$work_data['qualification'];
  1720. if ($relativeScore < 0.5) {
  1721. $label = 'important';
  1722. } elseif ($relativeScore < 0.75) {
  1723. $label = 'warning';
  1724. }
  1725. $qualification_string = Display::label(
  1726. $work['qualification'].' / '.$work_data['qualification'],
  1727. $label
  1728. );
  1729. }
  1730. }
  1731. $work['qualification_score'] = $work['qualification'];
  1732. $add_string = '';
  1733. $time_expires = '';
  1734. if (!empty($work_assignment['expires_on'])) {
  1735. $time_expires = api_strtotime(
  1736. $work_assignment['expires_on'],
  1737. 'UTC'
  1738. );
  1739. }
  1740. if (!empty($work_assignment['expires_on']) &&
  1741. !empty($time_expires) && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) {
  1742. $add_string = Display::label(get_lang('Expired'), 'important');
  1743. }
  1744. if (($can_read && $work['accepted'] == '1') ||
  1745. ($is_author && in_array($work['accepted'], array('1', '0'))) ||
  1746. ($is_allowed_to_edit || api_is_drh())
  1747. ) {
  1748. // Firstname, lastname, username
  1749. $work['firstname'] = Display::div($work['firstname'], array('class' => $class));
  1750. $work['lastname'] = Display::div($work['lastname'], array('class' => $class));
  1751. $work['title_clean'] = $work['title'];
  1752. if (strlen($work['title']) > 30) {
  1753. $short_title = substr($work['title'], 0, 27).'...';
  1754. $work['title'] = Display::span($short_title, array('class' => $class, 'title' => $work['title']));
  1755. } else {
  1756. $work['title'] = Display::div($work['title'], array('class' => $class));
  1757. }
  1758. // Type.
  1759. $work['type'] = DocumentManager::build_document_icon_tag('file', $work['url']);
  1760. // File name.
  1761. $link_to_download = null;
  1762. // If URL is present then there's a file to download keep BC.
  1763. if ($work['contains_file'] || !empty($work['url'])) {
  1764. $link_to_download = '<a href="'.$url.'download.php?id='.$item_id.'&'.api_get_cidreq().'">'.
  1765. Display::return_icon('save.png', get_lang('Save'),array(), ICON_SIZE_SMALL).'</a> ';
  1766. }
  1767. $send_to = Portfolio::share('work', $work['id'], array('style' => 'white-space:nowrap;'));
  1768. $feedback = null;
  1769. $count = getWorkCommentCount($item_id, $course_info);
  1770. if (!is_null($count) && !empty($count)) {
  1771. if ($qualification_exists) {
  1772. $feedback .= "<br />";
  1773. }
  1774. $feedback .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1775. Display::label($count.' '.get_lang('Feedback'), 'info').'</a> ';
  1776. }
  1777. $work['qualification'] = $qualification_string.$feedback;
  1778. $work['qualification_only'] = $qualification_string;
  1779. // Date.
  1780. $work_date = api_convert_and_format_date($work['sent_date']);
  1781. $work['sent_date_from_db'] = $work['sent_date'];
  1782. $work['sent_date'] = date_to_str_ago(api_get_local_time($work['sent_date'])) . ' ' . $add_string . '<br />' . $work_date;
  1783. // Actions.
  1784. $action = '';
  1785. if (api_is_allowed_to_edit()) {
  1786. $action .= $item_id.'<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1787. Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a> ';
  1788. if ($unoconv && empty($work['contains_file'])) {
  1789. $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=export_to_doc&item_id='.$item_id.'" title="'.get_lang('ExportToDoc').'" >'.
  1790. Display::return_icon('export_doc.png', get_lang('ExportToDoc'),array(), ICON_SIZE_SMALL).'</a> ';
  1791. }
  1792. $action .= '
  1793. <form
  1794. id="file_upload_'.$item_id.'"
  1795. class="work_correction_upload file_upload file_upload_small"
  1796. action="'.api_get_path(WEB_AJAX_PATH).'work.ajax.php?'.api_get_cidreq().'&a=upload_correction_file&item_id='.$item_id.'" method="POST" enctype="multipart/form-data">
  1797. <input type="file" name="file" multiple>
  1798. <button type="submit">Upload</button>
  1799. </form>
  1800. ';
  1801. $action .= "
  1802. <script>
  1803. $(document).ready(function() {
  1804. $('#file_upload_".$item_id."').fileUploadUI({
  1805. uploadTable: $('.files'),
  1806. downloadTable: $('.files'),
  1807. buildUploadRow: function (files, index) {
  1808. $('.files').show();
  1809. return $('<tr><td>' + files[index].name + '<\/td>' +
  1810. '<td class=\"file_upload_progress\"><div><\/div><\/td>' +
  1811. '<td class=\"file_upload_cancel\">' +
  1812. '<button class=\"ui-state-default ui-corner-all\" title=\"".get_lang('Cancel')."\">' +
  1813. '<span class=\"ui-icon ui-icon-cancel\">".get_lang('Cancel')."<\/span>' +'<\/button>'+
  1814. '<\/td><\/tr>');
  1815. },
  1816. buildDownloadRow: function (file) {
  1817. return $('<tr><td>' + file.name + '<\/td> <td> ' + file.size + ' <\/td> <td>&nbsp;' + file.result + ' <\/td> <\/tr>');
  1818. }
  1819. });
  1820. });
  1821. </script>
  1822. ";
  1823. if ($locked) {
  1824. if ($qualification_exists) {
  1825. $action .= Display::return_icon('rate_work_na.png', get_lang('CorrectAndRate'),array(), ICON_SIZE_SMALL);
  1826. } else {
  1827. $action .= Display::return_icon('edit_na.png', get_lang('Comment'),array(), ICON_SIZE_SMALL);
  1828. }
  1829. } else {
  1830. if ($qualification_exists) {
  1831. $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Edit').'" >'.
  1832. Display::return_icon('rate_work.png', get_lang('CorrectAndRate'), array(), ICON_SIZE_SMALL).'</a>';
  1833. } else {
  1834. $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'.
  1835. Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>';
  1836. }
  1837. }
  1838. if ($work['contains_file']) {
  1839. if ($locked) {
  1840. $action .= Display::return_icon('move_na.png', get_lang('Move'),array(), ICON_SIZE_SMALL);
  1841. } else {
  1842. $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=move&item_id='.$item_id.'" title="'.get_lang('Move').'">'.
  1843. Display::return_icon('move.png', get_lang('Move'),array(), ICON_SIZE_SMALL).'</a>';
  1844. }
  1845. }
  1846. if ($work['accepted'] == '1') {
  1847. $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=make_invisible&item_id='.$item_id.'" title="'.get_lang('Invisible').'" >'.
  1848. Display::return_icon('visible.png', get_lang('Invisible'),array(), ICON_SIZE_SMALL).'</a>';
  1849. } else {
  1850. $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=make_visible&item_id='.$item_id.'" title="'.get_lang('Visible').'" >'.
  1851. Display::return_icon('invisible.png', get_lang('Visible'),array(), ICON_SIZE_SMALL).'</a> ';
  1852. }
  1853. if ($locked) {
  1854. $action .= Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
  1855. } else {
  1856. $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=delete&item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'.
  1857. Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
  1858. }
  1859. } elseif ($is_author && (empty($work['qualificator_id']) || $work['qualificator_id'] == 0)) {
  1860. $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1861. Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>';
  1862. if (api_get_course_setting('student_delete_own_publication') == 1) {
  1863. if (api_is_allowed_to_session_edit(false, true)) {
  1864. $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'.
  1865. Display::return_icon('edit.png', get_lang('Comment'),array(), ICON_SIZE_SMALL).'</a>';
  1866. }
  1867. $action .= ' <a href="'.$url.'work_list.php?'.api_get_cidreq().'&action=delete&item_id='.$item_id.'&id='.$work['parent_id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'.
  1868. Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
  1869. } else {
  1870. $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
  1871. }
  1872. } else {
  1873. $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1874. Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>';
  1875. $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
  1876. }
  1877. // Status.
  1878. if (empty($work['qualificator_id'])) {
  1879. $qualificator_id = Display::label(get_lang('NotRevised'), 'warning');
  1880. } else {
  1881. $qualificator_id = Display::label(get_lang('Revised'), 'success');
  1882. }
  1883. $work['qualificator_id'] = $qualificator_id;
  1884. $work['actions'] = $send_to.$link_to_download.$action;
  1885. $works[] = $work;
  1886. }
  1887. }
  1888. return $works;
  1889. }
  1890. }
  1891. /**
  1892. * Send reminder to users who have not given the task
  1893. *
  1894. * @param int
  1895. * @return array
  1896. * @author cvargas carlos.vargas@beeznest.com cfasanando, christian.fasanado@beeznest.com
  1897. */
  1898. function send_reminder_users_without_publication($task_data)
  1899. {
  1900. $_course = api_get_course_info();
  1901. $task_id = $task_data['id'];
  1902. $task_title = !empty($task_data['title']) ? $task_data['title'] : basename($task_data['url']);
  1903. $subject = '[' . api_get_setting('siteName') . '] ';
  1904. // The body can be as long as you wish, and any combination of text and variables
  1905. $content = get_lang('ReminderToSubmitPendingTask')."\n".get_lang('CourseName').' : '.$_course['name']."\n";
  1906. $content .= get_lang('WorkName').' : '.$task_title."\n";
  1907. $list_users = get_list_users_without_publication($task_id);
  1908. $mails_sent_to = array();
  1909. foreach ($list_users as $user) {
  1910. $name_user = api_get_person_name($user[1], $user[0], null, PERSON_NAME_EMAIL_ADDRESS);
  1911. $dear_line = get_lang('Dear')." ".api_get_person_name($user[1], $user[0]) .", \n\n";
  1912. $body = $dear_line.$content;
  1913. MessageManager::send_message($user[3], $subject, $body);
  1914. $mails_sent_to[] = $name_user;
  1915. }
  1916. return $mails_sent_to;
  1917. }
  1918. /**
  1919. * Sends an email to the students of a course when a homework is created
  1920. *
  1921. * @param string course_id
  1922. *
  1923. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  1924. * @author Julio Montoya <gugli100@gmail.com> Adding session support - 2011
  1925. */
  1926. function send_email_on_homework_creation($course_id)
  1927. {
  1928. // Get the students of the course
  1929. $session_id = api_get_session_id();
  1930. if (empty($session_id)) {
  1931. $students = CourseManager::get_student_list_from_course_code($course_id);
  1932. } else {
  1933. $students = CourseManager::get_student_list_from_course_code($course_id, true, $session_id);
  1934. }
  1935. $emailsubject = '[' . api_get_setting('siteName') . '] '.get_lang('HomeworkCreated');
  1936. $currentUser = api_get_user_info(api_get_user_id());
  1937. if (!empty($students)) {
  1938. foreach($students as $student) {
  1939. $user_info = api_get_user_info($student["user_id"]);
  1940. if(!empty($user_info["mail"])) {
  1941. $name_user = api_get_person_name(
  1942. $user_info["firstname"],
  1943. $user_info["lastname"],
  1944. null,
  1945. PERSON_NAME_EMAIL_ADDRESS
  1946. );
  1947. $emailbody = get_lang('Dear')." ".$name_user.",\n\n";
  1948. $emailbody .= get_lang('HomeworkHasBeenCreatedForTheCourse')." ".$course_id.". "."\n\n".get_lang('PleaseCheckHomeworkPage');
  1949. $emailbody .= "\n\n".api_get_person_name($currentUser["firstname"], $currentUser["lastname"]);
  1950. $additionalParameters = array(
  1951. 'smsType' => SmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE,
  1952. 'userId' => $student["user_id"],
  1953. 'courseTitle' => $course_id
  1954. );
  1955. api_mail_html(
  1956. $name_user,
  1957. $user_info["mail"],
  1958. $emailsubject,
  1959. $emailbody,
  1960. api_get_person_name(
  1961. $currentUser["firstname"],
  1962. $currentUser["lastname"],
  1963. null,
  1964. PERSON_NAME_EMAIL_ADDRESS
  1965. ),
  1966. $currentUser["mail"],
  1967. null,
  1968. null,
  1969. null,
  1970. $additionalParameters
  1971. );
  1972. }
  1973. }
  1974. }
  1975. }
  1976. /**
  1977. * @param string $url
  1978. * @return bool
  1979. */
  1980. function is_work_exist_by_url($url)
  1981. {
  1982. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1983. $url = Database::escape_string($url);
  1984. $sql = "SELECT id FROM $work_table WHERE url='$url'";
  1985. $result = Database::query($sql);
  1986. if (Database::num_rows($result)> 0) {
  1987. $row = Database::fetch_row($result);
  1988. if (empty($row)) {
  1989. return false;
  1990. } else {
  1991. return true;
  1992. }
  1993. } else {
  1994. return false;
  1995. }
  1996. }
  1997. /**
  1998. * @param $name
  1999. * @param $values
  2000. * @param string $checked
  2001. * @return string
  2002. */
  2003. function make_select($name, $values, $checked = '')
  2004. {
  2005. $output = '<select name="'.$name.'" id="'.$name.'">';
  2006. foreach ($values as $key => $value) {
  2007. $output .= '<option value="'.$key.'" '.(($checked==$key) ? 'selected="selected"' : '').'>'.$value.'</option>';
  2008. }
  2009. $output .= '</select>';
  2010. return $output;
  2011. }
  2012. /**
  2013. * @param $name
  2014. * @param string $checked
  2015. * @param null $label
  2016. * @return string
  2017. */
  2018. function make_checkbox($name, $checked = '', $label = null)
  2019. {
  2020. $check = '<input id ="'.$name.'" type="checkbox" value="1" name="'.$name.'" '.((!empty($checked))?'checked="checked"':'').'/>';
  2021. if (!empty($label)) {
  2022. $check .="<label for ='$name'>$label</label>";
  2023. }
  2024. return $check;
  2025. }
  2026. /**
  2027. * @param $prefix
  2028. * @param string $default
  2029. * @return string
  2030. */
  2031. function draw_date_picker($prefix, $default = '')
  2032. {
  2033. if (empty($default)) {
  2034. $default = api_get_local_time();
  2035. }
  2036. $parts = explode(' ', $default);
  2037. list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
  2038. list($d_hour, $d_minute) = explode(':', $parts[1]);
  2039. $minute = range(10, 59);
  2040. array_unshift($minute, '00', '01', '02', '03', '04', '05', '06', '07', '08', '09');
  2041. $date_form = make_select($prefix.'_day', array_combine(range(1, 31), range(1, 31)), $d_day);
  2042. $date_form .= make_select($prefix.'_month', array_combine(range(1, 12), api_get_months_long()), $d_month);
  2043. $date_form .= make_select($prefix.'_year', array($d_year => $d_year, $d_year + 1 => $d_year + 1), $d_year).'&nbsp;&nbsp;&nbsp;&nbsp;';
  2044. $date_form .= make_select($prefix.'_hour', array_combine(range(0, 23), range(0, 23)), $d_hour).' : ';
  2045. $date_form .= make_select($prefix.'_minute', $minute, $d_minute);
  2046. return $date_form;
  2047. }
  2048. /**
  2049. * @param string $prefix
  2050. * @param array of values
  2051. * @return string
  2052. *
  2053. */
  2054. function get_date_from_select($prefix, $array = array())
  2055. {
  2056. return
  2057. $array[$prefix]['year'].'-'.
  2058. two_digits($array[$prefix]['month']).'-'.
  2059. two_digits($array[$prefix]['day']).' '.
  2060. two_digits($array[$prefix]['hour']).':'.
  2061. two_digits($array[$prefix]['minute']).':00';
  2062. }
  2063. /**
  2064. * Check if a user is the author of a work document.
  2065. * @param int $itemId
  2066. * @param int $userId
  2067. * @param int $courseId
  2068. * @param int $sessionId
  2069. * @return bool
  2070. */
  2071. function user_is_author($itemId, $userId = null, $courseId = null, $sessionId = null)
  2072. {
  2073. if (empty($itemId)) {
  2074. return false;
  2075. }
  2076. if (empty($userId)) {
  2077. $userId = api_get_user_id();
  2078. }
  2079. $isAuthor = false;
  2080. $is_allowed_to_edit = api_is_allowed_to_edit();
  2081. if ($is_allowed_to_edit) {
  2082. $isAuthor = true;
  2083. } else {
  2084. if (empty($courseId)) {
  2085. $courseId = api_get_course_int_id();
  2086. }
  2087. if (empty($sessionId)) {
  2088. $sessionId = api_get_session_id();
  2089. }
  2090. $data = api_get_item_property_info($courseId, 'work', $itemId, $sessionId);
  2091. if ($data['insert_user_id'] == $userId) {
  2092. $isAuthor = true;
  2093. }
  2094. $workData = get_work_data_by_id($itemId);
  2095. if ($workData['user_id'] == $userId) {
  2096. $isAuthor = true;
  2097. }
  2098. }
  2099. if (!$isAuthor) {
  2100. return false;
  2101. }
  2102. return $isAuthor;
  2103. }
  2104. /**
  2105. * Get list of users who have not given the task
  2106. * @param int
  2107. * @param int
  2108. * @return array
  2109. * @author cvargas
  2110. * @author Julio Montoya <gugli100@gmail.com> Fixing query
  2111. */
  2112. function get_list_users_without_publication($task_id, $studentId = null)
  2113. {
  2114. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2115. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2116. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2117. $session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2118. //condition for the session
  2119. $session_id = api_get_session_id();
  2120. $course_id = api_get_course_int_id();
  2121. $task_id = intval($task_id);
  2122. if ($session_id == 0) {
  2123. $sql = "SELECT user_id as id FROM $work_table
  2124. WHERE
  2125. c_id = $course_id AND
  2126. parent_id='$task_id' AND
  2127. active IN (0, 1)";
  2128. } else {
  2129. $sql = "SELECT user_id as id FROM $work_table
  2130. WHERE
  2131. c_id = $course_id AND
  2132. parent_id='$task_id' AND
  2133. session_id='".$session_id."' AND
  2134. active IN (0, 1)";
  2135. }
  2136. $result = Database::query($sql);
  2137. $users_with_tasks = array();
  2138. while($row = Database::fetch_array($result)) {
  2139. $users_with_tasks[] = $row['id'];
  2140. }
  2141. if ($session_id == 0) {
  2142. $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
  2143. FROM $table_course_user AS cu, $table_user AS u
  2144. WHERE u.status != 1 and cu.c_id='".api_get_course_int_id()."' AND u.user_id = cu.user_id";
  2145. } else {
  2146. $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
  2147. FROM $session_course_rel_user AS cu, $table_user AS u
  2148. WHERE
  2149. u.status != 1 AND
  2150. cu.c_id='".api_get_course_int_id()."' AND
  2151. u.user_id = cu.user_id AND
  2152. cu.session_id = '".$session_id."'";
  2153. }
  2154. if (!empty($studentId)) {
  2155. $sql_users.= " AND u.user_id = ".intval($studentId);
  2156. }
  2157. $group_id = api_get_group_id();
  2158. $new_group_user_list = array();
  2159. if ($group_id) {
  2160. $group_user_list = GroupManager::get_subscribed_users($group_id);
  2161. if (!empty($group_user_list)) {
  2162. foreach($group_user_list as $group_user) {
  2163. $new_group_user_list[] = $group_user['user_id'];
  2164. }
  2165. }
  2166. }
  2167. $result_users = Database::query($sql_users);
  2168. $users_without_tasks = array();
  2169. while ($row_users = Database::fetch_row($result_users)) {
  2170. if (in_array($row_users[0], $users_with_tasks)) {
  2171. continue;
  2172. }
  2173. if ($group_id && !in_array($row_users[0], $new_group_user_list)) {
  2174. continue;
  2175. }
  2176. $userId = $row_users[0];
  2177. $row_users[0] = $row_users[1];
  2178. $row_users[1] = $row_users[2];
  2179. $row_users[2] = Display::encrypted_mailto_link($row_users[3]);
  2180. $row_users[3] = $userId;
  2181. $users_without_tasks[] = $row_users;
  2182. }
  2183. return $users_without_tasks;
  2184. }
  2185. /**
  2186. * Display list of users who have not given the task
  2187. *
  2188. * @param int task id
  2189. * @param int $studentId
  2190. * @return array
  2191. * @author cvargas carlos.vargas@beeznest.com cfasanando, christian.fasanado@beeznest.com
  2192. * @author Julio Montoya <gugli100@gmail.com> Fixes
  2193. */
  2194. function display_list_users_without_publication($task_id, $studentId = null)
  2195. {
  2196. global $origin;
  2197. $table_header[] = array(get_lang('LastName'), true);
  2198. $table_header[] = array(get_lang('FirstName'), true);
  2199. $table_header[] = array(get_lang('Email'), true);
  2200. $data = get_list_users_without_publication($task_id);
  2201. $sorting_options = array();
  2202. $sorting_options['column'] = 1;
  2203. $paging_options = array();
  2204. $my_params = array();
  2205. if (isset($_GET['curdirpath'])) {
  2206. $my_params['curdirpath'] = Security::remove_XSS($_GET['curdirpath']);
  2207. }
  2208. if (isset($_GET['edit_dir'])) {
  2209. $my_params['edit_dir'] = Security::remove_XSS($_GET['edit_dir']);
  2210. }
  2211. if (isset($_GET['list'])) {
  2212. $my_params['list'] = Security::remove_XSS($_GET['list']);
  2213. }
  2214. $my_params['origin'] = $origin;
  2215. $my_params['id'] = intval($_GET['id']);
  2216. //$column_show
  2217. $column_show[] = 1;
  2218. $column_show[] = 1;
  2219. $column_show[] = 1;
  2220. Display::display_sortable_config_table(
  2221. 'work',
  2222. $table_header,
  2223. $data,
  2224. $sorting_options,
  2225. $paging_options,
  2226. $my_params,
  2227. $column_show
  2228. );
  2229. }
  2230. /**
  2231. * @param int $documentId
  2232. * @param int $workId
  2233. * @param int $courseId
  2234. */
  2235. function addDocumentToWork($documentId, $workId, $courseId)
  2236. {
  2237. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2238. $params = array(
  2239. 'document_id' => $documentId,
  2240. 'work_id' => $workId,
  2241. 'c_id' => $courseId
  2242. );
  2243. Database::insert($table, $params);
  2244. }
  2245. /**
  2246. * @param int $documentId
  2247. * @param int $workId
  2248. * @param int $courseId
  2249. * @return array
  2250. */
  2251. function getDocumentToWork($documentId, $workId, $courseId)
  2252. {
  2253. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2254. $params = array(
  2255. 'document_id = ? and work_id = ? and c_id = ?' => array($documentId, $workId, $courseId)
  2256. );
  2257. return Database::select('*', $table, array('where' => $params));
  2258. }
  2259. /**
  2260. * @param int $documentId
  2261. * @param int $workId
  2262. * @param int $courseId
  2263. * @param int $sessionId
  2264. * @param int $userId
  2265. * @param int $active
  2266. * @return array
  2267. */
  2268. function getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId, $active = 1)
  2269. {
  2270. $workRel = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2271. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2272. $documentId = intval($documentId);
  2273. $workId = intval($workId);
  2274. $courseId = intval($courseId);
  2275. $userId = intval($userId);
  2276. $sessionId = intval($sessionId);
  2277. $active = intval($active);
  2278. $sql = "SELECT w.* FROM $work w INNER JOIN $workRel rel ON (w.parent_id = rel.work_id)
  2279. WHERE
  2280. w.document_id = $documentId AND
  2281. w.parent_id = $workId AND
  2282. w.c_id = $courseId AND
  2283. w.session_id = $sessionId AND
  2284. user_id = $userId AND
  2285. active = $active
  2286. ";
  2287. $result = Database::query($sql);
  2288. $workInfo = array();
  2289. if (Database::num_rows($result)) {
  2290. $workInfo = Database::fetch_array($result, 'ASSOC');
  2291. }
  2292. return $workInfo;
  2293. }
  2294. /**
  2295. *
  2296. * @param int $workId
  2297. * @param int $courseId
  2298. * @return array
  2299. */
  2300. function getAllDocumentToWork($workId, $courseId)
  2301. {
  2302. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2303. $params = array(
  2304. 'work_id = ? and c_id = ?' => array($workId, $courseId)
  2305. );
  2306. return Database::select('*', $table, array('where' => $params));
  2307. }
  2308. /**
  2309. * @param int $documentId
  2310. * @param int $workId
  2311. * @param int $courseId
  2312. */
  2313. function deleteDocumentToWork($documentId, $workId, $courseId)
  2314. {
  2315. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2316. $params = array(
  2317. 'document_id = ? and work_id = ? and c_id = ?' => array($documentId, $workId, $courseId)
  2318. );
  2319. Database::delete($table, $params);
  2320. }
  2321. /**
  2322. * @param int $userId
  2323. * @param int $workId
  2324. * @param int $courseId
  2325. */
  2326. function addUserToWork($userId, $workId, $courseId)
  2327. {
  2328. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2329. $params = array(
  2330. 'user_id' => $userId,
  2331. 'work_id' => $workId,
  2332. 'c_id' => $courseId
  2333. );
  2334. Database::insert($table, $params);
  2335. }
  2336. /**
  2337. * @param int $userId
  2338. * @param int $workId
  2339. * @param int $courseId
  2340. * @return array
  2341. */
  2342. function getUserToWork($userId, $workId, $courseId)
  2343. {
  2344. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2345. $params = array(
  2346. 'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
  2347. );
  2348. return Database::select('*', $table, array('where' => $params));
  2349. }
  2350. /**
  2351. * @param int $workId
  2352. * @param int $courseId
  2353. * @param bool $getCount
  2354. * @return array
  2355. */
  2356. function getAllUserToWork($workId, $courseId, $getCount = false)
  2357. {
  2358. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2359. $params = array(
  2360. 'work_id = ? and c_id = ?' => array($workId, $courseId)
  2361. );
  2362. if ($getCount) {
  2363. $count = 0;
  2364. $result = Database::select(
  2365. 'count(user_id) as count',
  2366. $table,
  2367. array('where' => $params),
  2368. 'simple'
  2369. );
  2370. if (!empty($result)) {
  2371. $count = intval($result['count']);
  2372. }
  2373. return $count;
  2374. } else {
  2375. return Database::select('*', $table, array('where' => $params));
  2376. }
  2377. }
  2378. /**
  2379. * @param int $userId
  2380. * @param int $workId
  2381. * @param int $courseId
  2382. */
  2383. function deleteUserToWork($userId, $workId, $courseId)
  2384. {
  2385. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2386. $params = array(
  2387. 'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
  2388. );
  2389. Database::delete($table, $params);
  2390. }
  2391. /**
  2392. * @param int $userId
  2393. * @param int $workId
  2394. * @param int $courseId
  2395. * @return bool
  2396. */
  2397. function userIsSubscribedToWork($userId, $workId, $courseId)
  2398. {
  2399. $subscribedUsers = getAllUserToWork($workId, $courseId);
  2400. if (empty($subscribedUsers)) {
  2401. return true;
  2402. } else {
  2403. $subscribedUsersList = array();
  2404. foreach ($subscribedUsers as $item) {
  2405. $subscribedUsersList[] = $item['user_id'];
  2406. }
  2407. if (in_array($userId, $subscribedUsersList)) {
  2408. return true;
  2409. }
  2410. }
  2411. return false;
  2412. }
  2413. /**
  2414. * Get the list of students that have to submit their work
  2415. * @param integer $workId The internal ID of the assignment
  2416. * @param integer $courseId The course ID
  2417. * @param integer $groupId The group ID, if any
  2418. * @param integer $sessionId The session ID, if any
  2419. * @param bool $getCount Whether we want just the amount or the full result
  2420. * @return array|int An integer (if we just asked for the count) or an array of users
  2421. */
  2422. function getStudentSubscribedToWork(
  2423. $workId,
  2424. $courseId,
  2425. $groupId = null,
  2426. $sessionId = null,
  2427. $getCount = false
  2428. ) {
  2429. $usersInWork = null;
  2430. $usersInCourse = null;
  2431. if (empty($groupId)) {
  2432. $courseInfo = api_get_course_info_by_id($courseId);
  2433. $status = STUDENT;
  2434. if (!empty($sessionId)) {
  2435. $status = 0;
  2436. }
  2437. $usersInCourse = CourseManager::get_user_list_from_course_code(
  2438. $courseInfo['code'],
  2439. $sessionId,
  2440. null,
  2441. null,
  2442. $status,
  2443. $getCount
  2444. );
  2445. } else {
  2446. $usersInCourse = GroupManager::get_users(
  2447. $groupId,
  2448. false,
  2449. null,
  2450. null,
  2451. $getCount,
  2452. $courseId
  2453. );
  2454. }
  2455. $usersInWork = getAllUserToWork($workId, $courseId, $getCount);
  2456. if (empty($usersInWork)) {
  2457. return $usersInCourse;
  2458. } else {
  2459. return $usersInWork;
  2460. }
  2461. }
  2462. /**
  2463. * @param int $userId
  2464. * @param int $workId
  2465. * @param int $courseId
  2466. * @return bool
  2467. */
  2468. function allowOnlySubscribedUser($userId, $workId, $courseId)
  2469. {
  2470. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  2471. return true;
  2472. }
  2473. if (userIsSubscribedToWork($userId, $workId, $courseId) == false) {
  2474. api_not_allowed(true);
  2475. }
  2476. }
  2477. /**
  2478. * @param int $workId
  2479. * @param array $courseInfo
  2480. * @param int $documentId
  2481. * @return array
  2482. */
  2483. function getDocumentTemplateFromWork($workId, $courseInfo, $documentId)
  2484. {
  2485. $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
  2486. if (!empty($documents)) {
  2487. foreach ($documents as $doc) {
  2488. if ($documentId != $doc['document_id']) {
  2489. continue;
  2490. }
  2491. $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
  2492. $fileInfo = pathinfo($docData['path']);
  2493. if ($fileInfo['extension'] == 'html') {
  2494. if (file_exists($docData['absolute_path']) && is_file($docData['absolute_path'])) {
  2495. $docData['file_content'] = file_get_contents($docData['absolute_path']);
  2496. return $docData;
  2497. }
  2498. }
  2499. }
  2500. }
  2501. return array();
  2502. }
  2503. /**
  2504. * @param int $workId
  2505. * @param array $courseInfo
  2506. * @return string
  2507. */
  2508. function getAllDocumentsFromWorkToString($workId, $courseInfo)
  2509. {
  2510. $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
  2511. $content = null;
  2512. if (!empty($documents)) {
  2513. $content .= '<ul class="nav nav-list well">';
  2514. $content .= '<li class="nav-header">'.get_lang('Documents').'</li>';
  2515. foreach ($documents as $doc) {
  2516. $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
  2517. if ($docData) {
  2518. $content .= '<li><a target="_blank" href="'.$docData['url'].'">'.$docData['title'].'</a></li>';
  2519. }
  2520. }
  2521. $content .= '</ul><br />';
  2522. }
  2523. return $content;
  2524. }
  2525. /**
  2526. * Returns fck editor toolbar
  2527. * @return array
  2528. */
  2529. function getWorkDescriptionToolbar()
  2530. {
  2531. return array(
  2532. 'ToolbarStartExpanded' => 'true',
  2533. 'ToolbarSet' => 'Work',
  2534. 'Width' => '100%',
  2535. 'Height' => '400'
  2536. );
  2537. }
  2538. /**
  2539. * @param array $work
  2540. * @return array
  2541. */
  2542. function getWorkComments($work)
  2543. {
  2544. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2545. $userTable= Database::get_main_table(TABLE_MAIN_USER);
  2546. $courseId = intval($work['c_id']);
  2547. $workId = intval($work['id']);
  2548. if (empty($courseId) || empty($workId)) {
  2549. return array();
  2550. }
  2551. $sql = "SELECT
  2552. c.id, c.user_id, u.firstname, u.lastname, u.username, u.picture_uri
  2553. FROM $commentTable c
  2554. INNER JOIN $userTable u ON (u.user_id = c.user_id)
  2555. WHERE c_id = $courseId AND work_id = $workId
  2556. ORDER BY sent_at
  2557. ";
  2558. $result = Database::query($sql);
  2559. $comments = Database::store_result($result, 'ASSOC');
  2560. if (!empty($comments)) {
  2561. foreach ($comments as &$comment) {
  2562. $comment['picture'] = UserManager::getUserPicture($comment['user_id']);
  2563. $commentInfo = getWorkComment($comment['id']);
  2564. if (!empty($commentInfo)) {
  2565. $comment = array_merge($comment, $commentInfo);
  2566. }
  2567. }
  2568. }
  2569. return $comments;
  2570. }
  2571. /**
  2572. * Get total score from a work list
  2573. * @param $workList
  2574. * @return int|null
  2575. */
  2576. function getTotalWorkScore($workList)
  2577. {
  2578. $count = 0;
  2579. foreach ($workList as $data) {
  2580. $count += $data['qualification_score'];
  2581. }
  2582. return $count;
  2583. }
  2584. /**
  2585. * Get comment count from a work list (docs sent by students)
  2586. * @param array $workList
  2587. * @param array $courseInfo
  2588. * @return int|null
  2589. */
  2590. function getTotalWorkComment($workList, $courseInfo = array())
  2591. {
  2592. if (empty($courseInfo)) {
  2593. $courseInfo = api_get_course_info();
  2594. }
  2595. $count = 0;
  2596. foreach ($workList as $data) {
  2597. $count += getWorkCommentCount($data['id'], $courseInfo);
  2598. }
  2599. return $count;
  2600. }
  2601. /**
  2602. * Get comment count for a specific work sent by a student.
  2603. * @param int $id
  2604. * @param array $courseInfo
  2605. * @return int
  2606. */
  2607. function getWorkCommentCount($id, $courseInfo = array())
  2608. {
  2609. if (empty($courseInfo)) {
  2610. $courseInfo = api_get_course_info();
  2611. }
  2612. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2613. $id = intval($id);
  2614. $sql = "SELECT count(*) as count
  2615. FROM $commentTable
  2616. WHERE work_id = $id AND c_id = ".$courseInfo['real_id'];
  2617. $result = Database::query($sql);
  2618. if (Database::num_rows($result)) {
  2619. $comment = Database::fetch_array($result);
  2620. return $comment['count'];
  2621. }
  2622. return 0;
  2623. }
  2624. /**
  2625. * Get comment count for a specific parent
  2626. * @param int $parentId
  2627. * @param array $courseInfo
  2628. * @param int $sessionId
  2629. * @return int
  2630. */
  2631. function getWorkCommentCountFromParent(
  2632. $parentId,
  2633. $courseInfo = array(),
  2634. $sessionId = 0
  2635. ) {
  2636. if (empty($courseInfo)) {
  2637. $courseInfo = api_get_course_info();
  2638. }
  2639. if (empty($sessionId)) {
  2640. $sessionId = api_get_session_id();
  2641. } else {
  2642. $sessionId = intval($sessionId);
  2643. }
  2644. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2645. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2646. $parentId = intval($parentId);
  2647. $sql = "SELECT count(*) as count
  2648. FROM $commentTable c INNER JOIN $work w
  2649. ON c.c_id = w.c_id AND w.id = c.work_id
  2650. WHERE
  2651. session_id = $sessionId AND
  2652. parent_id = $parentId AND
  2653. w.c_id = ".$courseInfo['real_id'];
  2654. $result = Database::query($sql);
  2655. if (Database::num_rows($result)) {
  2656. $comment = Database::fetch_array($result);
  2657. return $comment['count'];
  2658. }
  2659. return 0;
  2660. }
  2661. /**
  2662. * Get last work information from parent
  2663. * @param int $parentId
  2664. * @param array $courseInfo
  2665. * @param int $sessionId
  2666. * @return int
  2667. */
  2668. function getLastWorkStudentFromParent(
  2669. $parentId,
  2670. $courseInfo = array(),
  2671. $sessionId = 0
  2672. ) {
  2673. if (empty($courseInfo)) {
  2674. $courseInfo = api_get_course_info();
  2675. }
  2676. if (empty($sessionId)) {
  2677. $sessionId = api_get_session_id();
  2678. } else {
  2679. $sessionId = intval($sessionId);
  2680. }
  2681. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2682. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2683. $parentId = intval($parentId);
  2684. $sql = "SELECT w.*
  2685. FROM $commentTable c INNER JOIN $work w
  2686. ON c.c_id = w.c_id AND w.id = c.work_id
  2687. WHERE
  2688. session_id = $sessionId AND
  2689. parent_id = $parentId AND
  2690. w.c_id = ".$courseInfo['real_id']."
  2691. ORDER BY w.sent_date
  2692. LIMIT 1
  2693. ";
  2694. $result = Database::query($sql);
  2695. if (Database::num_rows($result)) {
  2696. $comment = Database::fetch_array($result, 'ASSOC');
  2697. /*if (!empty($comment)) {
  2698. $comment['assignment'] = get_work_assignment_by_id(
  2699. $comment['id'],
  2700. $courseInfo['real_id']
  2701. );
  2702. }*/
  2703. return $comment;
  2704. }
  2705. return array();
  2706. }
  2707. /**
  2708. * Get last work information from parent
  2709. * @param int $parentId
  2710. * @param array $courseInfo
  2711. * @param int $sessionId
  2712. * @return int
  2713. */
  2714. function getLastWorkStudentFromParentByUser(
  2715. $userId,
  2716. $parentId,
  2717. $courseInfo = array(),
  2718. $sessionId = 0
  2719. ) {
  2720. if (empty($courseInfo)) {
  2721. $courseInfo = api_get_course_info();
  2722. }
  2723. if (empty($sessionId)) {
  2724. $sessionId = api_get_session_id();
  2725. } else {
  2726. $sessionId = intval($sessionId);
  2727. }
  2728. $userId = intval($userId);
  2729. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2730. $parentId = intval($parentId);
  2731. $sql = "SELECT *
  2732. FROM $work
  2733. WHERE
  2734. user_id = $userId AND
  2735. session_id = $sessionId AND
  2736. parent_id = $parentId AND
  2737. c_id = ".$courseInfo['real_id']."
  2738. ORDER BY sent_date DESC
  2739. LIMIT 1
  2740. ";
  2741. $result = Database::query($sql);
  2742. if (Database::num_rows($result)) {
  2743. $work = Database::fetch_array($result, 'ASSOC');
  2744. /*if (!empty($comment)) {
  2745. $comment['assignment'] = get_work_assignment_by_id(
  2746. $comment['id'],
  2747. $courseInfo['real_id']
  2748. );
  2749. }*/
  2750. return $work;
  2751. }
  2752. return array();
  2753. }
  2754. /**
  2755. * @param int $id comment id
  2756. * @param array $courseInfo
  2757. * @return string
  2758. */
  2759. function getWorkComment($id, $courseInfo = array())
  2760. {
  2761. if (empty($courseInfo)) {
  2762. $courseInfo = api_get_course_info();
  2763. }
  2764. if (empty($courseInfo['real_id'])) {
  2765. return array();
  2766. }
  2767. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2768. $id = intval($id);
  2769. $sql = "SELECT * FROM $commentTable
  2770. WHERE id = $id AND c_id = ".$courseInfo['real_id'];
  2771. $result = Database::query($sql);
  2772. $comment = array();
  2773. if (Database::num_rows($result)) {
  2774. $comment = Database::fetch_array($result, 'ASSOC');
  2775. $filePath = null;
  2776. $fileUrl = null;
  2777. $deleteUrl = null;
  2778. $fileName = null;
  2779. if (!empty($comment['file'])) {
  2780. $work = get_work_data_by_id($comment['work_id']);
  2781. $workParent = get_work_data_by_id($work['parent_id']);
  2782. $filePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/'.$workParent['url'].'/'.$comment['file'];
  2783. $fileUrl = api_get_path(WEB_CODE_PATH).'work/download_comment_file.php?comment_id='.$id.'&'.api_get_cidreq();
  2784. $deleteUrl = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$comment['work_id'].'&action=delete_attachment&comment_id='.$id;
  2785. $fileParts = explode('_', $comment['file']);
  2786. $fileName = str_replace($fileParts[0].'_'.$fileParts[1].'_', '', $comment['file']);
  2787. }
  2788. $comment['delete_file_url'] = $deleteUrl;
  2789. $comment['file_path'] = $filePath;
  2790. $comment['file_url'] = $fileUrl;
  2791. $comment['file_name_to_show'] = $fileName;
  2792. }
  2793. return $comment;
  2794. }
  2795. /**
  2796. * @param int $id
  2797. * @param array $courseInfo
  2798. */
  2799. function deleteCommentFile($id, $courseInfo = array())
  2800. {
  2801. $workComment = getWorkComment($id, $courseInfo);
  2802. if (isset($workComment['file']) && !empty($workComment['file'])) {
  2803. if (file_exists($workComment['file_path'])) {
  2804. $result = my_delete($workComment['file_path']);
  2805. if ($result) {
  2806. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2807. $params = array('file' => '');
  2808. Database::update(
  2809. $commentTable,
  2810. $params,
  2811. array('id = ? AND c_id = ? ' => array($workComment['id'], $workComment['c_id']))
  2812. );
  2813. }
  2814. }
  2815. }
  2816. }
  2817. /**
  2818. * Adds a comments to the work document
  2819. * @param array $courseInfo
  2820. * @param int $userId
  2821. * @param array $work
  2822. * @param array $data
  2823. * @return int
  2824. */
  2825. function addWorkComment($courseInfo, $userId, $parentWork, $work, $data)
  2826. {
  2827. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2828. $params = array(
  2829. 'work_id' => $work['id'],
  2830. 'c_id' => $work['c_id'],
  2831. 'user_id' => $userId,
  2832. 'comment' => $data['comment'],
  2833. 'sent_at' => api_get_utc_datetime()
  2834. );
  2835. $commentId = Database::insert($commentTable, $params);
  2836. if ($commentId) {
  2837. $sql = "UPDATE $commentTable SET id = iid WHERE iid = $commentId";
  2838. Database::query($sql);
  2839. }
  2840. $userIdListToSend = array();
  2841. if (api_is_allowed_to_edit()) {
  2842. if (isset($data['send_mail']) && $data['send_mail']) {
  2843. // Teacher sends a feedback
  2844. $userIdListToSend = array($work['user_id']);
  2845. }
  2846. } else {
  2847. $sessionId = api_get_session_id();
  2848. if (empty($sessionId)) {
  2849. $teachers = CourseManager::get_teacher_list_from_course_code(
  2850. $courseInfo['code']
  2851. );
  2852. if (!empty($teachers)) {
  2853. $userIdListToSend = array_keys($teachers);
  2854. }
  2855. } else {
  2856. $teachers = SessionManager::getCoachesByCourseSession(
  2857. $sessionId,
  2858. $courseInfo['code']
  2859. );
  2860. if (!empty($teachers)) {
  2861. $userIdListToSend = array_values($teachers);
  2862. }
  2863. }
  2864. }
  2865. $url = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$work['id'];
  2866. $subject = sprintf(get_lang('ThereIsANewWorkFeedback'), $parentWork['title']);
  2867. $content = sprintf(get_lang('ThereIsANewWorkFeedbackInWorkXHere'), $work['title'], $url);
  2868. if (!empty($userIdListToSend)) {
  2869. foreach ($userIdListToSend as $userId) {
  2870. MessageManager::send_message_simple(
  2871. $userId,
  2872. $subject,
  2873. $content
  2874. );
  2875. }
  2876. }
  2877. $fileData = isset($data['file']) ? $data['file'] : null;
  2878. if (!empty($commentId) && !empty($fileData)) {
  2879. $workParent = get_work_data_by_id($work['parent_id']);
  2880. if (!empty($workParent)) {
  2881. $uploadDir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work'.$workParent['url'];
  2882. $newFileName = 'comment_'.$commentId.'_'.php2phps(
  2883. api_replace_dangerous_char($fileData['name'])
  2884. );
  2885. $newFilePath = $uploadDir.'/'.$newFileName;
  2886. $result = move_uploaded_file($fileData['tmp_name'], $newFilePath);
  2887. if ($result) {
  2888. $params = array('file' => $newFileName);
  2889. Database::update(
  2890. $commentTable,
  2891. $params,
  2892. array('id = ? AND c_id = ? ' => array($commentId, $work['c_id']))
  2893. );
  2894. }
  2895. }
  2896. }
  2897. }
  2898. /**
  2899. * @param array $work
  2900. * @param string $page
  2901. * @return string
  2902. */
  2903. function getWorkCommentForm($work, $page = 'view')
  2904. {
  2905. $url = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$work['id'].'&action=send_comment&'.api_get_cidreq().'&page='.$page;
  2906. $form = new FormValidator(
  2907. 'work_comment',
  2908. 'post',
  2909. $url
  2910. );
  2911. $form->addElement('file', 'file', get_lang('Attachment'));
  2912. $form->addElement('textarea', 'comment', get_lang('Comment'), array('rows' => '8'));
  2913. $form->addElement('hidden', 'id', $work['id']);
  2914. $form->addElement('hidden', 'page', $page);
  2915. if (api_is_allowed_to_edit()) {
  2916. $form->addElement('checkbox', 'send_mail', null, get_lang('SendMail'));
  2917. }
  2918. $form->addButtonSend(get_lang('Send'), 'button');
  2919. return $form->returnForm();
  2920. }
  2921. /**
  2922. * @param array $homework result of get_work_assignment_by_id()
  2923. * @return string
  2924. */
  2925. function getWorkDateValidationStatus($homework)
  2926. {
  2927. $message = null;
  2928. $has_expired = false;
  2929. $has_ended = false;
  2930. if (!empty($homework)) {
  2931. if (!empty($homework['expires_on']) || !empty($homework['ends_on'])) {
  2932. $time_now = time();
  2933. if (!empty($homework['expires_on'])) {
  2934. $time_expires = api_strtotime($homework['expires_on'], 'UTC');
  2935. $difference = $time_expires - $time_now;
  2936. if ($difference < 0) {
  2937. $has_expired = true;
  2938. }
  2939. }
  2940. if (empty($homework['expires_on'])) {
  2941. $has_expired = false;
  2942. }
  2943. if (!empty($homework['ends_on'])) {
  2944. $time_ends = api_strtotime($homework['ends_on'], 'UTC');
  2945. $difference2 = $time_ends - $time_now;
  2946. if ($difference2 < 0) {
  2947. $has_ended = true;
  2948. }
  2949. }
  2950. $ends_on = api_convert_and_format_date($homework['ends_on']);
  2951. $expires_on = api_convert_and_format_date($homework['expires_on']);
  2952. }
  2953. if ($has_ended) {
  2954. $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
  2955. } elseif ($has_expired) {
  2956. $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
  2957. } else {
  2958. if ($has_expired) {
  2959. $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
  2960. }
  2961. }
  2962. }
  2963. return array(
  2964. 'message' => $message,
  2965. 'has_ended' => $has_ended,
  2966. 'has_expired' => $has_expired
  2967. );
  2968. }
  2969. /**
  2970. * @param FormValidator $form
  2971. * @param int $uploadFormType
  2972. */
  2973. function setWorkUploadForm($form, $uploadFormType = 0)
  2974. {
  2975. $form->addElement('header', get_lang('UploadADocument'));
  2976. $form->addElement('hidden', 'contains_file', 0, array('id'=>'contains_file_id'));
  2977. $form->addElement('hidden', 'active', 1);
  2978. $form->addElement('hidden', 'accepted', 1);
  2979. $form->addElement('text', 'title', get_lang('Title'), array('id' => 'file_upload', 'class' => 'span4'));
  2980. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  2981. switch ($uploadFormType) {
  2982. case 0:
  2983. // File and text.
  2984. $form->addElement('file', 'file', get_lang('UploadADocument'), 'size="40" onchange="updateDocumentTitle(this.value)"');
  2985. $form->add_real_progress_bar('uploadWork', 'file');
  2986. $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
  2987. break;
  2988. case 1:
  2989. // Only text.
  2990. $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
  2991. $form->addRule('description', get_lang('ThisFieldIsRequired'), 'required');
  2992. break;
  2993. case 2:
  2994. // Only file.
  2995. $form->addElement('file', 'file', get_lang('UploadADocument'), 'size="40" onchange="updateDocumentTitle(this.value)"');
  2996. $form->add_real_progress_bar('uploadWork', 'file');
  2997. $form->addRule('file', get_lang('ThisFieldIsRequired'), 'required');
  2998. break;
  2999. }
  3000. $form->addButtonUpload(get_lang('Upload'), 'submitWork');
  3001. }
  3002. /**
  3003. * @param array $my_folder_data
  3004. * @param array $_course
  3005. * @param bool $isCorrection
  3006. * @param array $workInfo
  3007. *
  3008. * @return array
  3009. */
  3010. function uploadWork($my_folder_data, $_course, $isCorrection = false, $workInfo = [])
  3011. {
  3012. if (empty($_FILES['file']['size'])) {
  3013. return array('error' => Display :: return_message(get_lang('UplUploadFailedSizeIsZero'), 'error'));
  3014. }
  3015. $updir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work/'; //directory path to upload
  3016. // Try to add an extension to the file if it has'nt one
  3017. $filename = add_ext_on_mime(stripslashes($_FILES['file']['name']), $_FILES['file']['type']);
  3018. // Replace dangerous characters
  3019. $filename = api_replace_dangerous_char($filename);
  3020. // Transform any .php file in .phps fo security
  3021. $filename = php2phps($filename);
  3022. $filesize = filesize($_FILES['file']['tmp_name']);
  3023. if (empty($filesize)) {
  3024. return array(
  3025. 'error' => Display:: return_message(
  3026. get_lang('UplUploadFailedSizeIsZero'),
  3027. 'error'
  3028. ),
  3029. );
  3030. } elseif (!filter_extension($new_file_name)) {
  3031. return array(
  3032. 'error' => Display:: return_message(
  3033. get_lang('UplUnableToSaveFileFilteredExtension'),
  3034. 'error'
  3035. ),
  3036. );
  3037. }
  3038. $totalSpace = DocumentManager::documents_total_space($_course['real_id']);
  3039. $course_max_space = DocumentManager::get_course_quota($_course['code']);
  3040. $total_size = $filesize + $totalSpace;
  3041. if ($total_size > $course_max_space) {
  3042. return array(
  3043. 'error' => Display :: return_message(get_lang('NoSpace'), 'error')
  3044. );
  3045. }
  3046. // Compose a unique file name to avoid any conflict
  3047. $new_file_name = api_get_unique_id();
  3048. if ($isCorrection) {
  3049. if (!empty($workInfo['url'])) {
  3050. $new_file_name = basename($workInfo['url']).'_correction';
  3051. } else {
  3052. $new_file_name = $new_file_name.'_correction';
  3053. }
  3054. }
  3055. $curdirpath = basename($my_folder_data['url']);
  3056. // If we come from the group tools the groupid will be saved in $work_table
  3057. if (is_dir($updir.$curdirpath) || empty($curdirpath)) {
  3058. $result = move_uploaded_file(
  3059. $_FILES['file']['tmp_name'],
  3060. $updir.$curdirpath.'/'.$new_file_name
  3061. );
  3062. } else {
  3063. return array(
  3064. 'error' => Display :: return_message(
  3065. get_lang('FolderDoesntExistsInFileSystem'),
  3066. 'error'
  3067. )
  3068. );
  3069. }
  3070. $url = null;
  3071. if ($result) {
  3072. $url = 'work/'.$curdirpath.'/'.$new_file_name;
  3073. }
  3074. return array(
  3075. 'url' => $url,
  3076. 'filename' => $filename,
  3077. 'error' => null
  3078. );
  3079. }
  3080. /**
  3081. * @param int $workId
  3082. * @param array $courseInfo
  3083. * @param int $session_id
  3084. */
  3085. function sendAlertToUsers($workId, $courseInfo, $session_id)
  3086. {
  3087. $user_list = array();
  3088. $workData = get_work_assignment_by_id($workId, $courseInfo['real_id']);
  3089. //last value is to check this is not "just" an edit
  3090. //YW Tis part serve to send a e-mail to the tutors when a new file is sent
  3091. $send = api_get_course_setting('email_alert_manager_on_new_doc');
  3092. if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_TEACHERS) {
  3093. // Lets predefine some variables. Be sure to change the from address!
  3094. if (empty($session_id)) {
  3095. //Teachers
  3096. $user_list = CourseManager::get_user_list_from_course_code(
  3097. api_get_course_id(),
  3098. null,
  3099. null,
  3100. null,
  3101. COURSEMANAGER
  3102. );
  3103. } else {
  3104. // Coaches
  3105. $user_list = CourseManager::get_user_list_from_course_code(
  3106. api_get_course_id(),
  3107. $session_id,
  3108. null,
  3109. null,
  3110. 2
  3111. );
  3112. }
  3113. }
  3114. if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_STUDENTS) {
  3115. if (!$session_id) {
  3116. $session_id = null;
  3117. }
  3118. $student = CourseManager::get_user_list_from_course_code(
  3119. api_get_course_id(),
  3120. $session_id,
  3121. null,
  3122. null,
  3123. STUDENT,
  3124. null,
  3125. null,
  3126. null,
  3127. null,
  3128. null,
  3129. array(api_get_user_id())
  3130. );
  3131. $user_list = array_merge($user_list, $student);
  3132. }
  3133. if ($send) {
  3134. $senderEmail = api_get_setting('emailAdministrator');
  3135. $senderName = api_get_person_name(
  3136. api_get_setting('administratorName'),
  3137. api_get_setting('administratorSurname'),
  3138. null,
  3139. PERSON_NAME_EMAIL_ADDRESS
  3140. );
  3141. $subject = "[" . api_get_setting('siteName') . "] ".get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$courseInfo['name']." ";
  3142. foreach ($user_list as $user_data) {
  3143. $to_user_id = $user_data['user_id'];
  3144. $user_info = api_get_user_info($to_user_id);
  3145. $message = get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$courseInfo['name']."\n";
  3146. $message .= get_lang('UserName')." : ".api_get_person_name($user_info['firstname'], $user_info['lastname'])."\n";
  3147. $message .= get_lang('DateSent')." : ".api_format_date(api_get_local_time())."\n";
  3148. $message .= get_lang('WorkName')." : ".$workData['title']."\n\n".get_lang('DownloadLink')."\n";
  3149. $url = api_get_path(WEB_CODE_PATH)."work/work.php?cidReq=".$courseInfo['code']."&id_session=".$session_id."&id=".$workData['id'];
  3150. $message .= $url;
  3151. MessageManager::send_message_simple($to_user_id, $subject, $message);
  3152. api_mail_html(
  3153. api_get_person_name(
  3154. $user_info['firstname'].' '.$user_info['lastname'],
  3155. null,
  3156. PERSON_NAME_EMAIL_ADDRESS
  3157. ),
  3158. $user_info['email'],
  3159. $subject,
  3160. $message,
  3161. $senderName,
  3162. $senderEmail
  3163. );
  3164. }
  3165. }
  3166. }
  3167. /**
  3168. * @param array $workInfo
  3169. * @param array $values
  3170. * @param array $courseInfo
  3171. * @param int $sessionId
  3172. * @param int $groupId
  3173. * @param int $userId
  3174. * @return null|string
  3175. */
  3176. function processWorkForm($workInfo, $values, $courseInfo, $sessionId, $groupId, $userId)
  3177. {
  3178. $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  3179. $courseId = $courseInfo['real_id'];
  3180. $groupId = intval($groupId);
  3181. $sessionId = intval($sessionId);
  3182. $userId = intval($userId);
  3183. $title = $values['title'];
  3184. $description = $values['description'];
  3185. $contains_file = isset($values['contains_file']) && !empty($values['contains_file']) ? intval($values['contains_file']): 0;
  3186. $saveWork = true;
  3187. $message = null;
  3188. $filename = null;
  3189. $url = null;
  3190. if ($values['contains_file']) {
  3191. $result = uploadWork($workInfo, $courseInfo);
  3192. if (isset($result['error'])) {
  3193. $message = $result['error'];
  3194. $saveWork = false;
  3195. }
  3196. $filename = isset($result['filename']) ? $result['filename'] : null;
  3197. if (empty($title)) {
  3198. $title = isset($result['title']) && !empty($result['title']) ? $result['title'] : get_lang('Untitled');
  3199. }
  3200. $url = $result['url'];
  3201. }
  3202. if (empty($title)) {
  3203. $title = get_lang('Untitled');
  3204. }
  3205. if ($saveWork) {
  3206. $active = '1';
  3207. $sql = "INSERT INTO ".$work_table." SET
  3208. c_id = $courseId ,
  3209. url = '".$url . "',
  3210. filetype = 'file',
  3211. title = '".Database::escape_string($title)."',
  3212. description = '".Database::escape_string($description)."',
  3213. contains_file = '".$contains_file."',
  3214. active = '".$active."',
  3215. accepted = '1',
  3216. post_group_id = '".$groupId."',
  3217. sent_date = '".api_get_utc_datetime()."',
  3218. parent_id = '".$workInfo['id']."' ,
  3219. session_id = '".$sessionId."',
  3220. user_id = '".$userId."'";
  3221. Database::query($sql);
  3222. $workId = Database::insert_id();
  3223. $sql = "UPDATE $work_table SET id = iid WHERE iid = $workId ";
  3224. Database::query($sql);
  3225. if ($workId) {
  3226. if (array_key_exists('filename', $workInfo) && !empty($filename)) {
  3227. $filename = Database::escape_string($filename);
  3228. $sql = "UPDATE $work_table SET
  3229. filename = '$filename'
  3230. WHERE iid = $workId";
  3231. Database::query($sql);
  3232. }
  3233. if (array_key_exists('document_id', $workInfo)) {
  3234. $documentId = isset($values['document_id']) ? intval($values['document_id']) : 0;
  3235. $sql = "UPDATE $work_table SET
  3236. document_id = '$documentId'
  3237. WHERE iid = $workId";
  3238. Database::query($sql);
  3239. }
  3240. api_item_property_update(
  3241. $courseInfo,
  3242. 'work',
  3243. $workId,
  3244. 'DocumentAdded',
  3245. $userId,
  3246. $groupId
  3247. );
  3248. sendAlertToUsers($workId, $courseInfo, $sessionId);
  3249. Event::event_upload($workId);
  3250. $message = Display::return_message(get_lang('DocAdd'));
  3251. }
  3252. } else {
  3253. if (empty($message)) {
  3254. $message = Display::return_message(get_lang('IsNotPosibleSaveTheDocument'), 'error');
  3255. }
  3256. }
  3257. return $message;
  3258. }
  3259. /**
  3260. * Creates a new task (directory) in the assignment tool
  3261. * @param array $params
  3262. * @param int $user_id
  3263. * @param array $courseInfo
  3264. * @param int $group_id
  3265. * @param int $session_id
  3266. * @return bool|int
  3267. * @note $params can have the following elements, but should at least have the 2 first ones: (
  3268. * 'new_dir' => 'some-name',
  3269. * 'description' => 'some-desc',
  3270. * 'qualification' => 20 (e.g. 20),
  3271. * 'weight' => 50 (percentage) to add to gradebook (e.g. 50),
  3272. * 'allow_text_assignment' => 0/1/2,
  3273. * @todo Rename createAssignment or createWork, or something like that
  3274. */
  3275. function addDir($params, $user_id, $courseInfo, $group_id, $session_id)
  3276. {
  3277. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3278. $user_id = intval($user_id);
  3279. $group_id = intval($group_id);
  3280. $session_id = intval($session_id);
  3281. $base_work_dir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work';
  3282. $course_id = $courseInfo['real_id'];
  3283. $directory = api_replace_dangerous_char($params['new_dir']);
  3284. $directory = disable_dangerous_file($directory);
  3285. $created_dir = create_unexisting_work_directory($base_work_dir, $directory);
  3286. if (!empty($created_dir)) {
  3287. $dirName = '/'.$created_dir;
  3288. $today = api_get_utc_datetime();
  3289. $sql = "INSERT INTO " . $work_table . " SET
  3290. c_id = $course_id,
  3291. url = '".Database::escape_string($dirName)."',
  3292. title = '".Database::escape_string($params['new_dir'])."',
  3293. description = '".Database::escape_string($params['description'])."',
  3294. author = '',
  3295. active = '1',
  3296. accepted = '1',
  3297. filetype = 'folder',
  3298. post_group_id = '" . $group_id . "',
  3299. sent_date = '" . $today . "',
  3300. qualification = '".($params['qualification'] != '' ? Database::escape_string($params['qualification']) : '') ."',
  3301. parent_id = '',
  3302. qualificator_id = '',
  3303. weight = '".Database::escape_string($params['weight'])."',
  3304. session_id = '".$session_id."',
  3305. allow_text_assignment = '".Database::escape_string($params['allow_text_assignment'])."',
  3306. contains_file = 0,
  3307. user_id = '".$user_id."'";
  3308. Database::query($sql);
  3309. // Add the directory
  3310. $id = Database::insert_id();
  3311. if ($id) {
  3312. $sql = "UPDATE $work_table SET id = iid WHERE iid = $id";
  3313. Database::query($sql);
  3314. // Folder created
  3315. api_item_property_update(
  3316. $courseInfo,
  3317. 'work',
  3318. $id,
  3319. 'DirectoryCreated',
  3320. $user_id,
  3321. $group_id
  3322. );
  3323. updatePublicationAssignment($id, $params, $courseInfo, $group_id);
  3324. if (api_get_course_setting('email_alert_students_on_new_homework') == 1) {
  3325. send_email_on_homework_creation(api_get_course_id());
  3326. }
  3327. return $id;
  3328. }
  3329. }
  3330. return false;
  3331. }
  3332. /**
  3333. * @param int $workId
  3334. * @param array $courseInfo
  3335. * @return int
  3336. */
  3337. function agendaExistsForWork($workId, $courseInfo)
  3338. {
  3339. $workTable = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3340. $courseId = $courseInfo['real_id'];
  3341. $workId = intval($workId);
  3342. $sql = "SELECT add_to_calendar FROM $workTable
  3343. WHERE c_id = $courseId AND publication_id = ".$workId;
  3344. $res = Database::query($sql);
  3345. if (Database::num_rows($res)) {
  3346. $row = Database::fetch_array($res, 'ASSOC');
  3347. if (!empty($row['add_to_calendar'])) {
  3348. return $row['add_to_calendar'];
  3349. }
  3350. }
  3351. return 0;
  3352. }
  3353. /**
  3354. * Update work description, qualification, weight, allow_text_assignment
  3355. * @param int $workId
  3356. * @param array $params
  3357. * @param array $courseInfo
  3358. * @param int $sessionId
  3359. */
  3360. function updateWork($workId, $params, $courseInfo, $sessionId = 0)
  3361. {
  3362. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3363. $filteredParams = array(
  3364. 'description' => $params['description'],
  3365. 'qualification' => $params['qualification'],
  3366. 'weight' => $params['weight'],
  3367. 'allow_text_assignment' => $params['allow_text_assignment']
  3368. );
  3369. Database::update(
  3370. $workTable,
  3371. $filteredParams,
  3372. array(
  3373. 'id = ? AND c_id = ? AND session_id = ? ' => array(
  3374. $workId, $courseInfo['real_id'], $sessionId
  3375. )
  3376. )
  3377. );
  3378. }
  3379. /**
  3380. * @param int $workId
  3381. * @param array $params
  3382. * @param array $courseInfo
  3383. * @param int $groupId
  3384. */
  3385. function updatePublicationAssignment($workId, $params, $courseInfo, $groupId)
  3386. {
  3387. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3388. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3389. $workId = intval($workId);
  3390. $time = api_get_utc_datetime();
  3391. $course_id = $courseInfo['real_id'];
  3392. // Insert into agenda
  3393. $agendaId = 0;
  3394. if (isset($params['add_to_calendar']) && $params['add_to_calendar'] == 1) {
  3395. require_once api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';
  3396. // Setting today date
  3397. $date = $end_date = $time;
  3398. if (isset($params['enableExpiryDate'])) {
  3399. $end_date = $params['expires_on'];
  3400. $date = $end_date;
  3401. }
  3402. $title = sprintf(get_lang('HandingOverOfTaskX'), $params['new_dir']);
  3403. $description = isset($params['description']) ? $params['description'] : '';
  3404. $content = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId.'">'
  3405. .$params['new_dir'].'</a>'.$description;
  3406. $agendaId = agendaExistsForWork($workId, $courseInfo);
  3407. // Add/edit agenda
  3408. $agenda = new Agenda();
  3409. $agenda->set_course($courseInfo);
  3410. $agenda->type = 'course';
  3411. if (empty($agendaId)) {
  3412. $agendaId = $agenda->addEvent(
  3413. $date,
  3414. $end_date,
  3415. 'false',
  3416. $title,
  3417. $content,
  3418. array('GROUP:'.$groupId)
  3419. );
  3420. } else {
  3421. $agenda->editEvent(
  3422. $agendaId,
  3423. $end_date,
  3424. $end_date,
  3425. 'false',
  3426. $title,
  3427. $content
  3428. );
  3429. }
  3430. }
  3431. $qualification = isset($params['qualification']) && !empty($params['qualification']) ? 1 : 0;
  3432. $expiryDate = isset($params['enableExpiryDate']) && $params['enableExpiryDate'] == 1 ? api_get_utc_datetime($params['expires_on']) : '';
  3433. $endDate = isset($params['enableEndDate']) && $params['enableEndDate'] == 1 ? api_get_utc_datetime($params['ends_on']) : '';
  3434. $data = get_work_assignment_by_id($workId, $course_id);
  3435. if (!empty($expiryDate)) {
  3436. $expiryDateCondition = "expires_on = '".Database::escape_string($expiryDate)."', ";
  3437. } else {
  3438. $expiryDateCondition = "expires_on = null, ";
  3439. }
  3440. if (!empty($endDate)) {
  3441. $endOnCondition = "ends_on = '".Database::escape_string($endDate)."', ";
  3442. } else {
  3443. $endOnCondition = "ends_on = null, ";
  3444. }
  3445. if (empty($data)) {
  3446. $sql = "INSERT INTO $table SET
  3447. c_id = $course_id ,
  3448. $expiryDateCondition
  3449. $endOnCondition
  3450. add_to_calendar = $agendaId,
  3451. enable_qualification = '$qualification',
  3452. publication_id = '$workId'";
  3453. Database::query($sql);
  3454. $my_last_id = Database::insert_id();
  3455. if ($my_last_id) {
  3456. $sql = "UPDATE $table SET
  3457. id = iid
  3458. WHERE iid = $my_last_id";
  3459. Database::query($sql);
  3460. $sql = "UPDATE $workTable SET
  3461. has_properties = $my_last_id,
  3462. view_properties = 1
  3463. WHERE c_id = $course_id AND id = $workId";
  3464. Database::query($sql);
  3465. }
  3466. } else {
  3467. $sql = "UPDATE $table SET
  3468. $expiryDateCondition
  3469. $endOnCondition
  3470. add_to_calendar = $agendaId,
  3471. enable_qualification = '".$qualification."'
  3472. WHERE
  3473. publication_id = $workId AND
  3474. c_id = $course_id AND
  3475. id = ".$data['id'];
  3476. Database::query($sql);
  3477. }
  3478. if (!empty($params['category_id'])) {
  3479. $link_info = GradebookUtils::is_resource_in_course_gradebook(
  3480. $courseInfo['code'],
  3481. LINK_STUDENTPUBLICATION,
  3482. $workId,
  3483. api_get_session_id()
  3484. );
  3485. $linkId = null;
  3486. if (!empty($link_info)) {
  3487. $linkId = $link_info['id'];
  3488. }
  3489. if (isset($params['make_calification']) &&
  3490. $params['make_calification'] == 1
  3491. ) {
  3492. if (empty($linkId)) {
  3493. GradebookUtils::add_resource_to_course_gradebook(
  3494. $params['category_id'],
  3495. $courseInfo['code'],
  3496. LINK_STUDENTPUBLICATION,
  3497. $workId,
  3498. $params['dir_name'],
  3499. (float)$params['weight'],
  3500. (float)$params['qualification'],
  3501. $params['description'],
  3502. 1,
  3503. api_get_session_id()
  3504. );
  3505. } else {
  3506. GradebookUtils::update_resource_from_course_gradebook(
  3507. $linkId,
  3508. $courseInfo['code'],
  3509. $params['weight']
  3510. );
  3511. }
  3512. } else {
  3513. // Delete everything of the gradebook for this $linkId
  3514. GradebookUtils::remove_resource_from_course_gradebook($linkId);
  3515. }
  3516. }
  3517. }
  3518. /**
  3519. * Delete all work by student
  3520. * @param int $userId
  3521. * @param array $courseInfo
  3522. * @return array return deleted items
  3523. */
  3524. function deleteAllWorkPerUser($userId, $courseInfo)
  3525. {
  3526. $deletedItems = array();
  3527. $workPerUser = getWorkPerUser($userId);
  3528. if (!empty($workPerUser)) {
  3529. foreach ($workPerUser as $work) {
  3530. $work = $work['work'];
  3531. foreach ($work->user_results as $userResult) {
  3532. $result = deleteWorkItem($userResult['id'], $courseInfo);
  3533. if ($result) {
  3534. $deletedItems[] = $userResult;
  3535. }
  3536. }
  3537. }
  3538. }
  3539. return $deletedItems;
  3540. }
  3541. /**
  3542. * @param int $item_id
  3543. * @param array course info
  3544. * @return bool
  3545. */
  3546. function deleteWorkItem($item_id, $courseInfo)
  3547. {
  3548. $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  3549. $TSTDPUBASG = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3550. $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
  3551. $is_allowed_to_edit = api_is_allowed_to_edit();
  3552. $file_deleted = false;
  3553. $item_id = intval($item_id);
  3554. $is_author = user_is_author($item_id);
  3555. $work_data = get_work_data_by_id($item_id);
  3556. $locked = api_resource_is_locked_by_gradebook($work_data['parent_id'], LINK_STUDENTPUBLICATION);
  3557. $course_id = $courseInfo['real_id'];
  3558. if (($is_allowed_to_edit && $locked == false) ||
  3559. (
  3560. $locked == false &&
  3561. $is_author &&
  3562. api_get_course_setting('student_delete_own_publication') == 1 &&
  3563. $work_data['qualificator_id'] == 0
  3564. )
  3565. ) {
  3566. // We found the current user is the author
  3567. $sql = "SELECT url, contains_file FROM $work_table
  3568. WHERE c_id = $course_id AND id = $item_id";
  3569. $result = Database::query($sql);
  3570. $row = Database::fetch_array($result);
  3571. if (Database::num_rows($result) > 0) {
  3572. $sql = "UPDATE $work_table SET active = 2
  3573. WHERE c_id = $course_id AND id = $item_id";
  3574. Database::query($sql);
  3575. $sql = "DELETE FROM $TSTDPUBASG
  3576. WHERE c_id = $course_id AND publication_id = $item_id";
  3577. Database::query($sql);
  3578. api_item_property_update(
  3579. $courseInfo,
  3580. 'work',
  3581. $item_id,
  3582. 'DocumentDeleted',
  3583. api_get_user_id()
  3584. );
  3585. $work = $row['url'];
  3586. if ($row['contains_file'] == 1) {
  3587. if (!empty($work)) {
  3588. if (api_get_setting('permanently_remove_deleted_files') == 'true') {
  3589. my_delete($currentCourseRepositorySys.'/'.$work);
  3590. $file_deleted = true;
  3591. } else {
  3592. $extension = pathinfo($work, PATHINFO_EXTENSION);
  3593. $new_dir = $work.'_DELETED_'.$item_id.'.'.$extension;
  3594. if (file_exists($currentCourseRepositorySys.'/'.$work)) {
  3595. rename($currentCourseRepositorySys.'/'.$work, $currentCourseRepositorySys.'/'.$new_dir);
  3596. $file_deleted = true;
  3597. }
  3598. }
  3599. }
  3600. } else {
  3601. $file_deleted = true;
  3602. }
  3603. }
  3604. }
  3605. return $file_deleted;
  3606. }
  3607. /**
  3608. * @param FormValidator $form
  3609. * @param array $defaults
  3610. * @return FormValidator
  3611. */
  3612. function getFormWork($form, $defaults = array())
  3613. {
  3614. if (!empty($defaults)) {
  3615. if (isset($defaults['submit'])) {
  3616. unset($defaults['submit']);
  3617. }
  3618. }
  3619. // Create the form that asks for the directory name
  3620. $form->addElement('text', 'new_dir', get_lang('AssignmentName'));
  3621. $form->addRule('new_dir', get_lang('ThisFieldIsRequired'), 'required');
  3622. $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
  3623. $form->addButtonAdvancedSettings('advanced_params', get_lang('AdvancedParameters'));
  3624. if (!empty($defaults) && (isset($defaults['enableEndDate']) || isset($defaults['enableExpiryDate']))) {
  3625. $form->addElement('html', '<div id="advanced_params_options" style="display:block">');
  3626. } else {
  3627. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  3628. }
  3629. // QualificationOfAssignment
  3630. $form->addElement('text', 'qualification', get_lang('QualificationNumeric'));
  3631. if ((api_get_session_id() != 0 && Gradebook::is_active()) || api_get_session_id() == 0) {
  3632. $form->addElement(
  3633. 'checkbox',
  3634. 'make_calification',
  3635. null,
  3636. get_lang('MakeQualifiable'),
  3637. array(
  3638. 'id' =>'make_calification_id',
  3639. 'onclick' => "javascript: if(this.checked) { document.getElementById('option1').style.display='block';}else{document.getElementById('option1').style.display='none';}"
  3640. )
  3641. );
  3642. } else {
  3643. // QualificationOfAssignment
  3644. $form->addElement('hidden', 'make_calification', false);
  3645. }
  3646. if (!empty($defaults) && isset($defaults['category_id'])) {
  3647. $form->addElement('html', '<div id=\'option1\' style="display:block">');
  3648. } else {
  3649. $form->addElement('html', '<div id=\'option1\' style="display:none">');
  3650. }
  3651. // Loading Gradebook select
  3652. GradebookUtils::load_gradebook_select_in_tool($form);
  3653. $form->addElement('text', 'weight', get_lang('WeightInTheGradebook'));
  3654. $form->addElement('html', '</div>');
  3655. $form->addElement('checkbox', 'enableExpiryDate', null, get_lang('EnableExpiryDate'), 'id="expiry_date"');
  3656. if (isset($defaults['enableExpiryDate']) && $defaults['enableExpiryDate']) {
  3657. $form->addElement('html', '<div id="option2" style="display: block;">');
  3658. } else {
  3659. $form->addElement('html', '<div id="option2" style="display: none;">');
  3660. }
  3661. $currentDate = substr(api_get_local_time(), 0, 10);
  3662. if (!isset($defaults['expires_on'])) {
  3663. $date = substr($currentDate, 0, 10);
  3664. $defaults['expires_on'] = $date.' 23:59';
  3665. }
  3666. if (!isset($defaults['ends_on'])) {
  3667. $date = substr($currentDate, 0, 10);
  3668. $defaults['ends_on'] = $date.' 23:59';
  3669. }
  3670. $form->addElement('date_time_picker', 'expires_on', get_lang('ExpiresAt'));
  3671. $form->addElement('html', '</div>');
  3672. $form->addElement('checkbox', 'enableEndDate', null, get_lang('EnableEndDate'), 'id="end_date"');
  3673. if (isset($defaults['enableEndDate']) && $defaults['enableEndDate']) {
  3674. $form->addElement('html', '<div id="option3" style="display: block;">');
  3675. } else {
  3676. $form->addElement('html', '<div id="option3" style="display: none;">');
  3677. }
  3678. $form->addElement('date_time_picker', 'ends_on', get_lang('EndsAt'));
  3679. $form->addElement('html', '</div>');
  3680. $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar'));
  3681. $form->addElement('select', 'allow_text_assignment', get_lang('DocumentType'), getUploadDocumentType());
  3682. $form->addElement('html', '</div>');
  3683. if (isset($defaults['enableExpiryDate']) && isset($defaults['enableEndDate'])) {
  3684. $form->addRule(array('expires_on', 'ends_on'), get_lang('DateExpiredNotBeLessDeadLine'), 'comparedate');
  3685. }
  3686. if (!empty($defaults)) {
  3687. $form->setDefaults($defaults);
  3688. }
  3689. return $form;
  3690. }
  3691. /**
  3692. * @return array
  3693. */
  3694. function getUploadDocumentType()
  3695. {
  3696. return array(
  3697. 0 => get_lang('AllowFileOrText'),
  3698. 1 => get_lang('AllowOnlyText'),
  3699. 2 => get_lang('AllowOnlyFiles')
  3700. );
  3701. }
  3702. /**
  3703. * @param array $courseInfo
  3704. * @param bool $showScore
  3705. * @param bool $studentDeleteOwnPublication
  3706. */
  3707. function updateSettings($courseInfo, $showScore, $studentDeleteOwnPublication)
  3708. {
  3709. $showScore = intval($showScore);
  3710. $courseId = api_get_course_int_id();
  3711. $main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  3712. $table_course_setting = Database :: get_course_table(TOOL_COURSE_SETTING);
  3713. $query = "UPDATE ".$main_course_table." SET show_score = '".$showScore."'
  3714. WHERE id = $courseId";
  3715. Database::query($query);
  3716. /**
  3717. * Course data are cached in session so we need to update both the database
  3718. * and the session data
  3719. */
  3720. $_course['show_score'] = $showScore;
  3721. Session::write('_course', $courseInfo);
  3722. // changing the tool setting: is a student allowed to delete his/her own document
  3723. // counting the number of occurrences of this setting (if 0 => add, if 1 => update)
  3724. $query = "SELECT * FROM " . $table_course_setting . "
  3725. WHERE c_id = $courseId AND variable = 'student_delete_own_publication'";
  3726. $result = Database::query($query);
  3727. $number_of_setting = Database::num_rows($result);
  3728. if ($number_of_setting == 1) {
  3729. $query = "UPDATE " . $table_course_setting . " SET
  3730. value='" . Database::escape_string($studentDeleteOwnPublication) . "'
  3731. WHERE variable = 'student_delete_own_publication' AND c_id = $courseId";
  3732. Database::query($query);
  3733. } else {
  3734. $query = "INSERT INTO " . $table_course_setting . " (c_id, variable, value, category) VALUES
  3735. ($courseId, 'student_delete_own_publication' , '".Database::escape_string($studentDeleteOwnPublication) . "','work')";
  3736. Database::query($query);
  3737. }
  3738. }
  3739. /**
  3740. * @param int $item_id
  3741. * @param array $course_info
  3742. */
  3743. function makeVisible($item_id, $course_info)
  3744. {
  3745. $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  3746. $course_id = $course_info['real_id'];
  3747. $item_id = intval($item_id);
  3748. $sql = "UPDATE $work_table SET accepted = 1
  3749. WHERE c_id = $course_id AND id = $item_id";
  3750. Database::query($sql);
  3751. api_item_property_update($course_info, 'work', $item_id, 'visible', api_get_user_id());
  3752. }
  3753. /**
  3754. * @param int $item_id
  3755. * @param array $course_info
  3756. */
  3757. function makeInvisible($item_id, $course_info)
  3758. {
  3759. $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  3760. $item_id = intval($item_id);
  3761. $course_id = $course_info['real_id'];
  3762. $sql = "UPDATE " . $work_table . "
  3763. SET accepted = 0
  3764. WHERE c_id = $course_id AND id = '" . $item_id . "'";
  3765. Database::query($sql);
  3766. api_item_property_update(
  3767. $course_info,
  3768. 'work',
  3769. $item_id,
  3770. 'invisible',
  3771. api_get_user_id()
  3772. );
  3773. }
  3774. /**
  3775. * @param int $item_id
  3776. * @param string $path
  3777. * @param array $courseInfo
  3778. * @param int $groupId
  3779. * @param int $sessionId
  3780. * @return string
  3781. */
  3782. function generateMoveForm($item_id, $path, $courseInfo, $groupId, $sessionId)
  3783. {
  3784. $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  3785. $courseId = $courseInfo['real_id'];
  3786. $folders = array();
  3787. $session_id = intval($sessionId);
  3788. $groupId = intval($groupId);
  3789. $sessionCondition = empty($sessionId) ? " AND session_id = 0 " : " AND session_id='".$session_id."'";
  3790. $sql = "SELECT id, url, title
  3791. FROM $work_table
  3792. WHERE
  3793. c_id = $courseId AND
  3794. active IN (0, 1) AND
  3795. url LIKE '/%' AND
  3796. post_group_id = $groupId
  3797. $sessionCondition";
  3798. $res = Database::query($sql);
  3799. while ($folder = Database::fetch_array($res)) {
  3800. $title = empty($folder['title']) ? basename($folder['url']) : $folder['title'];
  3801. $folders[$folder['id']] = $title;
  3802. }
  3803. return build_work_move_to_selector($folders, $path, $item_id);
  3804. }
  3805. /**
  3806. * @param int $workId
  3807. * @return string
  3808. */
  3809. function showStudentList($workId)
  3810. {
  3811. $columnModel = array(
  3812. array('name'=>'student', 'index'=>'student', 'width'=>'150', 'align'=>'left', 'sortable' => 'false'),
  3813. array('name'=>'works', 'index'=>'works', 'width'=>'50', 'align'=>'left', 'sortable' => 'false')
  3814. );
  3815. $token = null;
  3816. $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student_list_overview&work_id='.$workId.'&'.api_get_cidreq();
  3817. $columns = array(
  3818. get_lang('Students'),
  3819. get_lang('Works')
  3820. );
  3821. $order = api_is_western_name_order() ? 'firstname' : 'lastname';
  3822. $params = array(
  3823. 'autowidth' => 'true',
  3824. 'height' => 'auto',
  3825. 'rowNum' => 10,
  3826. 'sortname' => $order,
  3827. 'sortorder' => 'asc'
  3828. );
  3829. $html = '<script>
  3830. $(function() {
  3831. '.Display::grid_js('studentList', $url, $columns, $columnModel, $params, array(), null, true).'
  3832. $("#workList").jqGrid(
  3833. "navGrid",
  3834. "#studentList_pager",
  3835. { edit: false, add: false, del: false },
  3836. { height:280, reloadAfterSubmit:false }, // edit options
  3837. { height:280, reloadAfterSubmit:false }, // add options
  3838. { width:500 } // search options
  3839. );
  3840. });
  3841. </script>';
  3842. $html .= Display::grid_html('studentList');
  3843. return $html;
  3844. }
  3845. /**
  3846. * @param string $courseCode
  3847. * @param int $sessionId
  3848. * @param int $groupId
  3849. * @param int $start
  3850. * @param int $limit
  3851. * @param string $sidx
  3852. * @param string $sord
  3853. * @param $getCount
  3854. * @return array|int
  3855. */
  3856. function getWorkUserList($courseCode, $sessionId, $groupId, $start, $limit, $sidx, $sord, $getCount = false)
  3857. {
  3858. if (!empty($groupId)) {
  3859. $userList = GroupManager::get_users(
  3860. $groupId,
  3861. false,
  3862. $start,
  3863. $limit,
  3864. $getCount,
  3865. null,
  3866. $sidx,
  3867. $sord
  3868. );
  3869. } else {
  3870. $limitString = null;
  3871. if (!empty($start) && !empty($limit)) {
  3872. $start = intval($start);
  3873. $limit = intval($limit);
  3874. $limitString = " LIMIT $start, $limit";
  3875. }
  3876. $orderBy = null;
  3877. if (!empty($sidx) && !empty($sord)) {
  3878. if (in_array($sidx, array('firstname', 'lastname'))) {
  3879. $orderBy = "ORDER BY $sidx $sord";
  3880. }
  3881. }
  3882. if (empty($sessionId)) {
  3883. $userList = CourseManager::get_user_list_from_course_code(
  3884. $courseCode,
  3885. $sessionId,
  3886. $limitString,
  3887. $orderBy ,
  3888. STUDENT,
  3889. $getCount
  3890. );
  3891. } else {
  3892. $userList = CourseManager::get_user_list_from_course_code(
  3893. $courseCode,
  3894. $sessionId,
  3895. $limitString,
  3896. $orderBy,
  3897. 0,
  3898. $getCount
  3899. );
  3900. }
  3901. if ($getCount == false) {
  3902. $userList = array_keys($userList);
  3903. }
  3904. }
  3905. return $userList;
  3906. }
  3907. /**
  3908. * @param int $workId
  3909. * @param string $courseCode
  3910. * @param int $sessionId
  3911. * @param int $groupId
  3912. * @param int $start
  3913. * @param int $limit
  3914. * @param int $sidx
  3915. * @param string $sord
  3916. * @param bool $getCount
  3917. * @return array|int
  3918. */
  3919. function getWorkUserListData(
  3920. $workId,
  3921. $courseCode,
  3922. $sessionId,
  3923. $groupId,
  3924. $start,
  3925. $limit,
  3926. $sidx,
  3927. $sord,
  3928. $getCount = false
  3929. ) {
  3930. $my_folder_data = get_work_data_by_id($workId);
  3931. $workParents = array();
  3932. if (empty($my_folder_data)) {
  3933. $workParents = getWorkList($workId, $my_folder_data, null);
  3934. }
  3935. $workIdList = array();
  3936. if (!empty($workParents)) {
  3937. foreach ($workParents as $work) {
  3938. $workIdList[] = $work->id;
  3939. }
  3940. }
  3941. $courseInfo = api_get_course_info($courseCode);
  3942. $userList = getWorkUserList(
  3943. $courseCode,
  3944. $sessionId,
  3945. $groupId,
  3946. $start,
  3947. $limit,
  3948. $sidx,
  3949. $sord,
  3950. $getCount
  3951. );
  3952. if ($getCount) {
  3953. return $userList;
  3954. }
  3955. $results = array();
  3956. if (!empty($userList)) {
  3957. foreach ($userList as $userId) {
  3958. $user = api_get_user_info($userId);
  3959. $link = api_get_path(WEB_CODE_PATH).'work/student_work.php?'.api_get_cidreq().'&studentId='.$user['user_id'];
  3960. $url = Display::url(api_get_person_name($user['firstname'], $user['lastname']), $link);
  3961. $userWorks = 0;
  3962. if (!empty($workIdList)) {
  3963. $userWorks = getUniqueStudentAttempts(
  3964. $workIdList,
  3965. $groupId,
  3966. $courseInfo['real_id'],
  3967. $sessionId,
  3968. $user['user_id']
  3969. );
  3970. }
  3971. $works = $userWorks." / ".count($workParents);
  3972. $results[] = array('student' => $url, 'works' => $works);
  3973. }
  3974. }
  3975. return $results;
  3976. }
  3977. /**
  3978. * @param int $id
  3979. * @param array $course_info
  3980. * @param bool $isCorrection
  3981. *
  3982. * @return bool
  3983. */
  3984. function downloadFile($id, $course_info, $isCorrection)
  3985. {
  3986. return getFile($id, $course_info, true, $isCorrection);
  3987. }
  3988. /**
  3989. * @param int $id
  3990. * @param array $course_info
  3991. * @param bool $download
  3992. * @param bool $isCorrection
  3993. *
  3994. * @return bool
  3995. */
  3996. function getFile($id, $course_info, $download = true, $isCorrection = false)
  3997. {
  3998. $file = getFileContents($id, $course_info, 0, $isCorrection);
  3999. if (!empty($file) && is_array($file)) {
  4000. return DocumentManager::file_send_for_download(
  4001. $file['path'],
  4002. $download,
  4003. $file['title']
  4004. );
  4005. }
  4006. return false;
  4007. }
  4008. /**
  4009. * Get the file contents for an assigment
  4010. * @param int $id
  4011. * @param array $course_info
  4012. * @param int Session ID
  4013. * @param $correction
  4014. *
  4015. * @return array|bool
  4016. */
  4017. function getFileContents($id, $course_info, $sessionId = 0, $correction = false)
  4018. {
  4019. $id = intval($id);
  4020. if (empty($course_info) || empty($id)) {
  4021. return false;
  4022. }
  4023. if (empty($sessionId)) {
  4024. $sessionId = api_get_session_id();
  4025. }
  4026. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4027. if (!empty($course_info['real_id'])) {
  4028. $sql = 'SELECT *
  4029. FROM '.$table.'
  4030. WHERE c_id = '.$course_info['real_id'].' AND id = "'.$id.'"';
  4031. $result = Database::query($sql);
  4032. if ($result && Database::num_rows($result)) {
  4033. $row = Database::fetch_array($result, 'ASSOC');
  4034. if ($correction) {
  4035. $row['url'] = $row['url_correction'];
  4036. }
  4037. if (empty($row['url'])) {
  4038. return false;
  4039. }
  4040. $full_file_name = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$row['url'];
  4041. $item_info = api_get_item_property_info(
  4042. api_get_course_int_id(),
  4043. 'work',
  4044. $row['id'],
  4045. $sessionId
  4046. );
  4047. allowOnlySubscribedUser(
  4048. api_get_user_id(),
  4049. $row['parent_id'],
  4050. $course_info['real_id']
  4051. );
  4052. if (empty($item_info)) {
  4053. api_not_allowed();
  4054. }
  4055. /*
  4056. field show_score in table course :
  4057. 0 => New documents are visible for all users
  4058. 1 => New documents are only visible for the teacher(s)
  4059. field visibility in table item_property :
  4060. 0 => eye closed, invisible for all students
  4061. 1 => eye open
  4062. field accepted in table c_student_publication :
  4063. 0 => eye closed, invisible for all students
  4064. 1 => eye open
  4065. ( We should have visibility == accepted, otherwise there is an
  4066. inconsistency in the Database)
  4067. field value in table c_course_setting :
  4068. 0 => Allow learners to delete their own publications = NO
  4069. 1 => Allow learners to delete their own publications = YES
  4070. +------------------+-------------------------+------------------------+
  4071. |Can download work?| doc visible for all = 0 | doc visible for all = 1|
  4072. +------------------+-------------------------+------------------------+
  4073. | visibility = 0 | editor only | editor only |
  4074. | | | |
  4075. +------------------+-------------------------+------------------------+
  4076. | visibility = 1 | editor | editor |
  4077. | | + owner of the work | + any student |
  4078. +------------------+-------------------------+------------------------+
  4079. (editor = teacher + admin + anybody with right api_is_allowed_to_edit)
  4080. */
  4081. $work_is_visible = $item_info['visibility'] == 1 && $row['accepted'] == 1;
  4082. $doc_visible_for_all = ($course_info['show_score'] == 1);
  4083. $is_editor = api_is_allowed_to_edit(true, true, true);
  4084. $student_is_owner_of_work = user_is_author($row['id'], $row['user_id']);
  4085. if ($is_editor ||
  4086. ($student_is_owner_of_work) ||
  4087. ($doc_visible_for_all && $work_is_visible)
  4088. ) {
  4089. $title = $row['title'];
  4090. if ($correction) {
  4091. $title = $row['title_correction'];
  4092. }
  4093. if (array_key_exists('filename', $row) && !empty($row['filename'])) {
  4094. $title = $row['filename'];
  4095. }
  4096. $title = str_replace(' ', '_', $title);
  4097. Event::event_download($title);
  4098. if (Security::check_abs_path(
  4099. $full_file_name,
  4100. api_get_path(SYS_COURSE_PATH).api_get_course_path().'/')
  4101. ) {
  4102. return array(
  4103. 'path' => $full_file_name,
  4104. 'title' => $title,
  4105. 'title_correction' => $row['title_correction']
  4106. );
  4107. }
  4108. }
  4109. }
  4110. }
  4111. return false;
  4112. }
  4113. /**
  4114. * @param int $userId
  4115. * @param array $courseInfo
  4116. * @param string $format
  4117. * @return bool
  4118. */
  4119. function exportAllWork($userId, $courseInfo, $format = 'pdf')
  4120. {
  4121. $userInfo = api_get_user_info($userId);
  4122. if (empty($userInfo) || empty($courseInfo)) {
  4123. return false;
  4124. }
  4125. $workPerUser = getWorkPerUser($userId);
  4126. switch ($format) {
  4127. case 'pdf':
  4128. if (!empty($workPerUser)) {
  4129. $pdf = new PDF();
  4130. $content = null;
  4131. foreach ($workPerUser as $work) {
  4132. $work = $work['work'];
  4133. foreach ($work->user_results as $userResult) {
  4134. //var_dump($userResult);exit;
  4135. $content .= $userResult['title'];
  4136. // No need to use api_get_local_time()
  4137. $content .= $userResult['sent_date'];
  4138. $content .= $userResult['qualification'];
  4139. $content .= $userResult['description'];
  4140. //$content .= getWorkComments($userResult);
  4141. }
  4142. }
  4143. if (!empty($content)) {
  4144. $pdf->content_to_pdf(
  4145. $content,
  4146. null,
  4147. api_replace_dangerous_char($userInfo['complete_name']),
  4148. $courseInfo['code']
  4149. );
  4150. }
  4151. }
  4152. break;
  4153. }
  4154. }
  4155. /**
  4156. * @param int $workId
  4157. * @param array $courseInfo
  4158. * @param int $sessionId
  4159. * @param string $format
  4160. * @return bool
  4161. */
  4162. function exportAllStudentWorkFromPublication(
  4163. $workId,
  4164. $courseInfo,
  4165. $sessionId,
  4166. $format = 'pdf'
  4167. ) {
  4168. if (empty($courseInfo)) {
  4169. return false;
  4170. }
  4171. $workData = get_work_data_by_id($workId);
  4172. if (empty($workData)) {
  4173. return false;
  4174. }
  4175. $assignment = get_work_assignment_by_id($workId);
  4176. $courseCode = $courseInfo['code'];
  4177. $header = get_lang('Course').': '.$courseInfo['title'];
  4178. $teachers = CourseManager::get_teacher_list_from_course_code_to_string(
  4179. $courseCode
  4180. );
  4181. if (!empty($sessionId)) {
  4182. $sessionInfo = api_get_session_info($sessionId);
  4183. if (!empty($sessionInfo)) {
  4184. $header .= ' - ' . $sessionInfo['name'];
  4185. $header .= '<br />' . $sessionInfo['description'];
  4186. $teachers = SessionManager::getCoachesByCourseSessionToString(
  4187. $sessionId,
  4188. $courseInfo['real_id']
  4189. );
  4190. }
  4191. }
  4192. $header .= '<br />'.get_lang('Teachers').': '.$teachers.'<br />';
  4193. $header .= '<br />'.get_lang('Date').': '.api_get_local_time().'<br />';
  4194. $header .= '<br />'.get_lang('StudentPublication').': '.$workData['title'].'<br />';
  4195. $content = null;
  4196. $expiresOn = null;
  4197. if (!empty($assignment) && isset($assignment['expires_on'])) {
  4198. $content .= '<br /><strong>' . get_lang('ExpiryDate') . '</strong>: ' . api_get_local_time($assignment['expires_on']);
  4199. $expiresOn = api_get_local_time($assignment['expires_on']);
  4200. }
  4201. if (!empty($workData['description'])) {
  4202. $content .= '<br /><strong>' . get_lang('Description') . '</strong>: ' . $workData['description'];
  4203. }
  4204. $workList = get_work_user_list(null, null, null, null, $workId);
  4205. switch ($format) {
  4206. case 'pdf':
  4207. if (!empty($workList)) {
  4208. $table = new HTML_Table(array('class' => 'data_table'));
  4209. $headers = array(
  4210. get_lang('Name'),
  4211. get_lang('User'),
  4212. get_lang('HandOutDateLimit'),
  4213. get_lang('SentDate'),
  4214. get_lang('FileName'),
  4215. get_lang('Score'),
  4216. get_lang('Feedback')
  4217. );
  4218. $column = 0;
  4219. foreach($headers as $header) {
  4220. $table->setHeaderContents(0, $column, $header);
  4221. $column++;
  4222. }
  4223. $row = 1;
  4224. //$pdf->set_custom_header($header);
  4225. foreach ($workList as $work) {
  4226. $content .= '<hr />';
  4227. // getWorkComments need c_id
  4228. $work['c_id'] = $courseInfo['real_id'];
  4229. //$content .= get_lang('Date').': '.api_get_local_time($work['sent_date_from_db']).'<br />';
  4230. $score = null;
  4231. if (!empty($work['qualification_only'])) {
  4232. $score = $work['qualification_only'];
  4233. }
  4234. //$content .= get_lang('Description').': '.$work['description'].'<br />';
  4235. $comments = getWorkComments($work);
  4236. $feedback = null;
  4237. if (!empty($comments)) {
  4238. $content .= '<h4>'.get_lang('Feedback').': </h4>';
  4239. foreach ($comments as $comment) {
  4240. $feedback .= get_lang('User').': '.api_get_person_name(
  4241. $comment['firstname'],
  4242. $comment['lastname']
  4243. ).'<br />';
  4244. $feedback .= $comment['comment'].'<br />';
  4245. }
  4246. }
  4247. $table->setCellContents($row, 0, strip_tags($workData['title']));
  4248. $table->setCellContents($row, 1, api_get_person_name(strip_tags($work['firstname']), strip_tags($work['lastname'])));
  4249. $table->setCellContents($row, 2, $expiresOn);
  4250. $table->setCellContents($row, 3, api_get_local_time($work['sent_date_from_db']));
  4251. $table->setCellContents($row, 4, strip_tags($work['title']));
  4252. $table->setCellContents($row, 5, $score);
  4253. $table->setCellContents($row, 6, $feedback);
  4254. $row++;
  4255. }
  4256. $content = $table->toHtml();
  4257. if (!empty($content)) {
  4258. $params = array(
  4259. 'filename' => $workData['title'] . '_' . api_get_local_time(),
  4260. 'pdf_title' => api_replace_dangerous_char($workData['title']),
  4261. 'course_code' => $courseInfo['code'],
  4262. 'add_signatures' => false
  4263. );
  4264. $pdf = new PDF('A4', null, $params);
  4265. $pdf->html_to_pdf_with_template($content);
  4266. }
  4267. exit;
  4268. }
  4269. break;
  4270. }
  4271. }
  4272. /**
  4273. * Downloads all user files per user
  4274. * @param int $userId
  4275. * @param array $courseInfo
  4276. * @return bool
  4277. */
  4278. function downloadAllFilesPerUser($userId, $courseInfo)
  4279. {
  4280. $userInfo = api_get_user_info($userId);
  4281. if (empty($userInfo) || empty($courseInfo)) {
  4282. return false;
  4283. }
  4284. require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
  4285. $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
  4286. $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/';
  4287. $zip = new PclZip($tempZipFile);
  4288. $workPerUser = getWorkPerUser($userId);
  4289. if (!empty($workPerUser)) {
  4290. $files = array();
  4291. foreach ($workPerUser as $work) {
  4292. $work = $work['work'];
  4293. foreach ($work->user_results as $userResult) {
  4294. if (empty($userResult['url']) || empty($userResult['contains_file'])) {
  4295. continue;
  4296. }
  4297. $data = getFileContents($userResult['id'], $courseInfo);
  4298. if (!empty($data) && isset($data['path'])) {
  4299. $files[basename($data['path'])] = array(
  4300. 'title' => $data['title'],
  4301. 'path' => $data['path']
  4302. );
  4303. }
  4304. }
  4305. }
  4306. if (!empty($files)) {
  4307. Session::write('files', $files);
  4308. foreach ($files as $data) {
  4309. $zip->add(
  4310. $data['path'],
  4311. PCLZIP_OPT_REMOVE_PATH,
  4312. $coursePath,
  4313. PCLZIP_CB_PRE_ADD,
  4314. 'preAddAllWorkStudentCallback'
  4315. );
  4316. }
  4317. }
  4318. // Start download of created file
  4319. $name = basename(api_replace_dangerous_char($userInfo['complete_name'])).'.zip';
  4320. Event::event_download($name.'.zip (folder)');
  4321. if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
  4322. DocumentManager::file_send_for_download($tempZipFile, true, $name);
  4323. @unlink($tempZipFile);
  4324. exit;
  4325. }
  4326. }
  4327. exit;
  4328. }
  4329. /**
  4330. * @param $p_event
  4331. * @param array $p_header
  4332. * @return int
  4333. */
  4334. function preAddAllWorkStudentCallback($p_event, &$p_header)
  4335. {
  4336. $files = Session::read('files');
  4337. if (isset($files[basename($p_header['stored_filename'])])) {
  4338. $p_header['stored_filename'] = $files[basename($p_header['stored_filename'])]['title'];
  4339. return 1;
  4340. }
  4341. return 0;
  4342. }
  4343. /**
  4344. * Get all work created by a user
  4345. * @param int $user_id
  4346. * @param int $courseId
  4347. * @param int $sessionId
  4348. * @return array
  4349. */
  4350. function getWorkCreatedByUser($user_id, $courseId, $sessionId)
  4351. {
  4352. $items = api_get_item_property_list_by_tool_by_user(
  4353. $user_id,
  4354. 'work',
  4355. $courseId,
  4356. $sessionId
  4357. );
  4358. $forumList = array();
  4359. if (!empty($items)) {
  4360. foreach ($items as $forum) {
  4361. $item = get_work_data_by_id(
  4362. $forum['ref'],
  4363. $courseId,
  4364. $sessionId
  4365. );
  4366. $forumList[] = array(
  4367. $item['title'],
  4368. api_get_local_time($forum['insert_date']),
  4369. api_get_local_time($forum['lastedit_date'])
  4370. );
  4371. }
  4372. }
  4373. return $forumList;
  4374. }
  4375. /**
  4376. * @param array $courseInfo
  4377. * @param int $workId
  4378. * @return bool
  4379. */
  4380. function protectWork($courseInfo, $workId)
  4381. {
  4382. $userId = api_get_user_id();
  4383. $groupId = api_get_group_id();
  4384. $sessionId = api_get_session_id();
  4385. $workData = get_work_data_by_id($workId);
  4386. if (empty($workData) || empty($courseInfo)) {
  4387. api_not_allowed(true);
  4388. }
  4389. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  4390. return true;
  4391. }
  4392. $workId = $workData['id'];
  4393. if ($workData['active'] != 1) {
  4394. api_not_allowed(true);
  4395. }
  4396. $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $sessionId);
  4397. if ($visibility != 1) {
  4398. api_not_allowed(true);
  4399. }
  4400. allowOnlySubscribedUser($userId, $workId, $courseInfo['real_id']);
  4401. if (!empty($groupId)) {
  4402. $showWork = GroupManager::user_has_access(
  4403. $userId,
  4404. $groupId,
  4405. GroupManager::GROUP_TOOL_WORK
  4406. );
  4407. if (!$showWork) {
  4408. api_not_allowed(true);
  4409. }
  4410. }
  4411. }