work.lib.php 165 KB

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