work.lib.php 165 KB

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