work.lib.php 163 KB

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