work.lib.php 177 KB

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