work.lib.php 179 KB

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