work.lib.php 184 KB

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