work.lib.php 164 KB

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