work.lib.php 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573
  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 = intval($start);
  1086. $limit = intval($limit);
  1087. $groupIid = 0;
  1088. if ($group_id) {
  1089. $groupInfo = GroupManager::get_group_properties($group_id);
  1090. $groupIid = $groupInfo['iid'];
  1091. }
  1092. $groupIid = (int) $groupIid;
  1093. // Get list from database
  1094. if (!empty($groupIid)) {
  1095. $group_query = " WHERE w.c_id = $course_id AND post_group_id = $groupIid";
  1096. $subdirs_query = "AND parent_id = 0";
  1097. } else {
  1098. $group_query = " WHERE w.c_id = $course_id AND (post_group_id = '0' or post_group_id is NULL) ";
  1099. $subdirs_query = "AND parent_id = 0";
  1100. }
  1101. $active_condition = ' AND active IN (1, 0)';
  1102. if ($getCount) {
  1103. $select = "SELECT count(w.id) as count ";
  1104. } else {
  1105. $select = "SELECT w.*, a.expires_on, expires_on, ends_on, enable_qualification ";
  1106. }
  1107. $sql = "$select
  1108. FROM $workTable w
  1109. LEFT JOIN $workTableAssignment a
  1110. ON (a.publication_id = w.id AND a.c_id = w.c_id)
  1111. $group_query
  1112. $subdirs_query
  1113. $active_condition
  1114. $condition_session
  1115. $where_condition
  1116. ";
  1117. $sql .= " ORDER BY $column $direction ";
  1118. if (!empty($start) && !empty($limit)) {
  1119. $sql .= " LIMIT $start, $limit";
  1120. }
  1121. $result = Database::query($sql);
  1122. if ($getCount) {
  1123. $row = Database::fetch_array($result);
  1124. return $row['count'];
  1125. }
  1126. $works = [];
  1127. $url = api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq();
  1128. if ($isDrhOfCourse) {
  1129. $url = api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq();
  1130. }
  1131. $urlOthers = api_get_path(WEB_CODE_PATH).'work/work_list_others.php?'.api_get_cidreq().'&id=';
  1132. while ($work = Database::fetch_array($result, 'ASSOC')) {
  1133. $isSubscribed = userIsSubscribedToWork($userId, $work['id'], $course_id);
  1134. if ($isSubscribed == false) {
  1135. continue;
  1136. }
  1137. $visibility = api_get_item_visibility($courseInfo, 'work', $work['id'], $session_id);
  1138. if ($visibility != 1) {
  1139. continue;
  1140. }
  1141. $work['type'] = Display::return_icon('work.png');
  1142. $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
  1143. if (empty($work['title'])) {
  1144. $work['title'] = basename($work['url']);
  1145. }
  1146. $whereCondition = " AND u.user_id = ".intval($userId);
  1147. $workList = get_work_user_list(
  1148. 0,
  1149. 1000,
  1150. null,
  1151. null,
  1152. $work['id'],
  1153. $whereCondition
  1154. );
  1155. $count = getTotalWorkComment($workList, $courseInfo);
  1156. $lastWork = getLastWorkStudentFromParentByUser($userId, $work, $courseInfo);
  1157. if (!is_null($count) && !empty($count)) {
  1158. $urlView = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$lastWork['id'].'&'.api_get_cidreq();
  1159. $feedback = '&nbsp;'.Display::url(
  1160. Display::returnFontAwesomeIcon('comments-o'),
  1161. $urlView,
  1162. ['title' => get_lang('View')]
  1163. );
  1164. $work['feedback'] = ' '.Display::label($count.' '.get_lang('Feedback'), 'info').$feedback;
  1165. }
  1166. if (!empty($lastWork)) {
  1167. $work['last_upload'] = (!empty($lastWork['qualification'])) ? $lastWork['qualification_rounded'].' - ' : '';
  1168. $work['last_upload'] .= api_get_local_time($lastWork['sent_date']);
  1169. }
  1170. $work['title'] = Display::url($work['title'], $url.'&id='.$work['id']);
  1171. $work['others'] = Display::url(
  1172. Display::return_icon('group.png', get_lang('Others')),
  1173. $urlOthers.$work['id']
  1174. );
  1175. $works[] = $work;
  1176. }
  1177. return $works;
  1178. }
  1179. /**
  1180. * @param int $start
  1181. * @param int $limit
  1182. * @param string $column
  1183. * @param string $direction
  1184. * @param string $where_condition
  1185. * @param bool $getCount
  1186. *
  1187. * @return array
  1188. */
  1189. function getWorkListTeacher(
  1190. $start,
  1191. $limit,
  1192. $column,
  1193. $direction,
  1194. $where_condition,
  1195. $getCount = false
  1196. ) {
  1197. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1198. $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  1199. $courseInfo = api_get_course_info();
  1200. $course_id = api_get_course_int_id();
  1201. $session_id = api_get_session_id();
  1202. $condition_session = api_get_session_condition($session_id);
  1203. $group_id = api_get_group_id();
  1204. $groupIid = 0;
  1205. if ($group_id) {
  1206. $groupInfo = GroupManager::get_group_properties($group_id);
  1207. $groupIid = $groupInfo['iid'];
  1208. }
  1209. $groupIid = (int) $groupIid;
  1210. $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
  1211. if (!in_array($direction, ['asc', 'desc'])) {
  1212. $direction = 'desc';
  1213. }
  1214. if (!empty($where_condition)) {
  1215. $where_condition = ' AND '.$where_condition;
  1216. }
  1217. $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
  1218. $start = intval($start);
  1219. $limit = intval($limit);
  1220. $works = [];
  1221. // Get list from database
  1222. if ($is_allowed_to_edit) {
  1223. $active_condition = ' active IN (0, 1)';
  1224. if ($getCount) {
  1225. $select = " SELECT count(w.id) as count";
  1226. } else {
  1227. $select = " SELECT w.*, a.expires_on, expires_on, ends_on, enable_qualification ";
  1228. }
  1229. $sql = " $select
  1230. FROM $workTable w
  1231. LEFT JOIN $workTableAssignment a
  1232. ON (a.publication_id = w.id AND a.c_id = w.c_id)
  1233. WHERE
  1234. w.c_id = $course_id
  1235. $condition_session AND
  1236. $active_condition AND
  1237. parent_id = 0 AND
  1238. post_group_id = $groupIid
  1239. $where_condition
  1240. ORDER BY $column $direction
  1241. LIMIT $start, $limit";
  1242. $result = Database::query($sql);
  1243. if ($getCount) {
  1244. $row = Database::fetch_array($result);
  1245. return $row['count'];
  1246. }
  1247. $url = api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq();
  1248. $blockEdition = api_get_configuration_value('block_student_publication_edition');
  1249. while ($work = Database::fetch_array($result, 'ASSOC')) {
  1250. $workId = $work['id'];
  1251. $work['type'] = Display::return_icon('work.png');
  1252. $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
  1253. $countUniqueAttempts = getUniqueStudentAttemptsTotal(
  1254. $workId,
  1255. $group_id,
  1256. $course_id,
  1257. $session_id
  1258. );
  1259. $totalUsers = getStudentSubscribedToWork(
  1260. $workId,
  1261. $course_id,
  1262. $group_id,
  1263. $session_id,
  1264. true
  1265. );
  1266. $work['amount'] = Display::label(
  1267. $countUniqueAttempts.'/'.
  1268. $totalUsers,
  1269. 'success'
  1270. );
  1271. $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $session_id);
  1272. if ($visibility == 1) {
  1273. $icon = 'visible.png';
  1274. $text = get_lang('Visible');
  1275. $action = 'invisible';
  1276. $class = '';
  1277. } else {
  1278. $icon = 'invisible.png';
  1279. $text = get_lang('Invisible');
  1280. $action = 'visible';
  1281. $class = 'muted';
  1282. }
  1283. $visibilityLink = Display::url(
  1284. Display::return_icon($icon, $text, [], ICON_SIZE_SMALL),
  1285. api_get_path(WEB_CODE_PATH).'work/work.php?id='.$workId.'&action='.$action.'&'.api_get_cidreq()
  1286. );
  1287. if (empty($work['title'])) {
  1288. $work['title'] = basename($work['url']);
  1289. }
  1290. $work['title'] = Display::url($work['title'], $url.'&id='.$workId, ['class' => $class]);
  1291. $work['title'] .= ' '.Display::label(get_count_work($work['id']), 'success');
  1292. $work['sent_date'] = api_get_local_time($work['sent_date']);
  1293. if ($blockEdition && !api_is_platform_admin()) {
  1294. $editLink = '';
  1295. } else {
  1296. $editLink = Display::url(
  1297. Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL),
  1298. api_get_path(WEB_CODE_PATH).'work/edit_work.php?id='.$workId.'&'.api_get_cidreq()
  1299. );
  1300. }
  1301. $correctionLink = '&nbsp;'.Display::url(
  1302. Display::return_icon('upload_package.png', get_lang('UploadCorrections'), '', ICON_SIZE_SMALL),
  1303. api_get_path(WEB_CODE_PATH).'work/upload_corrections.php?'.api_get_cidreq().'&id='.$workId
  1304. ).'&nbsp;';
  1305. if ($countUniqueAttempts > 0) {
  1306. $downloadLink = Display::url(
  1307. Display::return_icon(
  1308. 'save_pack.png',
  1309. get_lang('Save'),
  1310. [],
  1311. ICON_SIZE_SMALL
  1312. ),
  1313. api_get_path(WEB_CODE_PATH).'work/downloadfolder.inc.php?id='.$workId.'&'.api_get_cidreq()
  1314. );
  1315. } else {
  1316. $downloadLink = Display::url(
  1317. Display::return_icon(
  1318. 'save_pack_na.png',
  1319. get_lang('Save'),
  1320. [],
  1321. ICON_SIZE_SMALL
  1322. ),
  1323. '#'
  1324. );
  1325. }
  1326. // Remove Delete Work Button from action List
  1327. // Because removeXSS "removes" the onClick JS Event to do the action (See model.ajax.php - Line 1639)
  1328. // But still can use the another jqgrid button to remove works (trash icon)
  1329. //
  1330. // $deleteUrl = api_get_path(WEB_CODE_PATH).'work/work.php?id='.$workId.'&action=delete_dir&'.api_get_cidreq();
  1331. // $deleteLink = '<a href="#" onclick="showConfirmationPopup(this, \'' . $deleteUrl . '\' ) " >' .
  1332. // Display::return_icon(
  1333. // 'delete.png',
  1334. // get_lang('Delete'),
  1335. // [],
  1336. // ICON_SIZE_SMALL
  1337. // ) . '</a>';
  1338. if (!api_is_allowed_to_edit()) {
  1339. // $deleteLink = null;
  1340. $editLink = null;
  1341. }
  1342. $work['actions'] = $visibilityLink.$correctionLink.$downloadLink.$editLink;
  1343. $works[] = $work;
  1344. }
  1345. }
  1346. return $works;
  1347. }
  1348. /**
  1349. * @param int $start
  1350. * @param int $limit
  1351. * @param string $column
  1352. * @param string $direction
  1353. * @param int $workId
  1354. * @param int $studentId
  1355. * @param string $whereCondition
  1356. * @param bool $getCount
  1357. *
  1358. * @return array
  1359. */
  1360. function get_work_user_list_from_documents(
  1361. $start,
  1362. $limit,
  1363. $column,
  1364. $direction,
  1365. $workId,
  1366. $studentId = null,
  1367. $whereCondition = '',
  1368. $getCount = false
  1369. ) {
  1370. if ($getCount) {
  1371. $select1 = " SELECT count(u.user_id) as count ";
  1372. $select2 = " SELECT count(u.user_id) as count ";
  1373. } else {
  1374. $select1 = " SELECT DISTINCT
  1375. u.firstname,
  1376. u.lastname,
  1377. u.user_id,
  1378. w.title,
  1379. w.parent_id,
  1380. w.document_id document_id,
  1381. w.id, qualification,
  1382. qualificator_id,
  1383. w.sent_date,
  1384. w.contains_file,
  1385. w.url
  1386. ";
  1387. $select2 = " SELECT DISTINCT
  1388. u.firstname, u.lastname,
  1389. u.user_id,
  1390. d.title,
  1391. w.parent_id,
  1392. d.id document_id,
  1393. 0,
  1394. 0,
  1395. 0,
  1396. w.sent_date,
  1397. w.contains_file,
  1398. w.url
  1399. ";
  1400. }
  1401. $documentTable = Database::get_course_table(TABLE_DOCUMENT);
  1402. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1403. $workRelDocument = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  1404. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  1405. $courseId = api_get_course_int_id();
  1406. $sessionId = api_get_session_id();
  1407. if (empty($studentId)) {
  1408. $studentId = api_get_user_id();
  1409. }
  1410. $studentId = intval($studentId);
  1411. $workId = intval($workId);
  1412. $userCondition = " AND u.user_id = $studentId ";
  1413. $sessionCondition = api_get_session_condition($sessionId, true, false, 'w.session_id');
  1414. $workCondition = " AND w_rel.work_id = $workId";
  1415. $workParentCondition = " AND w.parent_id = $workId";
  1416. $sql = "(
  1417. $select1 FROM $userTable u
  1418. INNER JOIN $workTable w
  1419. ON (u.user_id = w.user_id AND w.active IN (0, 1) AND w.filetype = 'file')
  1420. WHERE
  1421. w.c_id = $courseId
  1422. $userCondition
  1423. $sessionCondition
  1424. $whereCondition
  1425. $workParentCondition
  1426. ) UNION (
  1427. $select2 FROM $workTable w
  1428. INNER JOIN $workRelDocument w_rel
  1429. ON (w_rel.work_id = w.id AND w.active IN (0, 1) AND w_rel.c_id = w.c_id)
  1430. INNER JOIN $documentTable d
  1431. ON (w_rel.document_id = d.id AND d.c_id = w.c_id)
  1432. INNER JOIN $userTable u ON (u.user_id = $studentId)
  1433. WHERE
  1434. w.c_id = $courseId
  1435. $workCondition
  1436. $sessionCondition AND
  1437. d.id NOT IN (
  1438. SELECT w.document_id id
  1439. FROM $workTable w
  1440. WHERE
  1441. user_id = $studentId AND
  1442. c_id = $courseId AND
  1443. filetype = 'file' AND
  1444. active IN (0, 1)
  1445. $sessionCondition
  1446. $workParentCondition
  1447. )
  1448. )";
  1449. $start = intval($start);
  1450. $limit = intval($limit);
  1451. $direction = in_array(strtolower($direction), ['desc', 'asc']) ? $direction : 'desc';
  1452. $column = Database::escape_string($column);
  1453. if ($getCount) {
  1454. $result = Database::query($sql);
  1455. $result = Database::fetch_array($result);
  1456. return $result['count'];
  1457. }
  1458. $sql .= " ORDER BY $column $direction";
  1459. $sql .= " LIMIT $start, $limit";
  1460. $result = Database::query($sql);
  1461. $currentUserId = api_get_user_id();
  1462. $work_data = get_work_data_by_id($workId);
  1463. $qualificationExists = false;
  1464. if (!empty($work_data['qualification']) && intval($work_data['qualification']) > 0) {
  1465. $qualificationExists = true;
  1466. }
  1467. $urlAdd = api_get_path(WEB_CODE_PATH).'work/upload_from_template.php?'.api_get_cidreq();
  1468. $urlEdit = api_get_path(WEB_CODE_PATH).'work/edit.php?'.api_get_cidreq();
  1469. $urlDelete = api_get_path(WEB_CODE_PATH).'work/work_list.php?action=delete&'.api_get_cidreq();
  1470. $urlView = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq();
  1471. $urlDownload = api_get_path(WEB_CODE_PATH).'work/download.php?'.api_get_cidreq();
  1472. $editIcon = Display::return_icon('edit.png', get_lang('Edit'));
  1473. $addIcon = Display::return_icon('add.png', get_lang('Add'));
  1474. $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'));
  1475. $viewIcon = Display::return_icon('default.png', get_lang('View'));
  1476. $saveIcon = Display::return_icon(
  1477. 'save.png',
  1478. get_lang('Save'),
  1479. [],
  1480. ICON_SIZE_SMALL
  1481. );
  1482. $allowEdition = api_get_course_setting('student_delete_own_publication') == 1;
  1483. $workList = [];
  1484. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1485. $userId = $row['user_id'];
  1486. $documentId = $row['document_id'];
  1487. $itemId = $row['id'];
  1488. $addLinkShowed = false;
  1489. if (empty($documentId)) {
  1490. $url = $urlEdit.'&item_id='.$row['id'].'&id='.$workId;
  1491. $editLink = Display::url($editIcon, $url);
  1492. if ($allowEdition != 1) {
  1493. $editLink = null;
  1494. }
  1495. } else {
  1496. $documentToWork = getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId);
  1497. if (empty($documentToWork)) {
  1498. $url = $urlAdd.'&document_id='.$documentId.'&id='.$workId;
  1499. $editLink = Display::url($addIcon, $url);
  1500. $addLinkShowed = true;
  1501. } else {
  1502. $row['title'] = $documentToWork['title'];
  1503. $row['sent_date'] = $documentToWork['sent_date'];
  1504. $newWorkId = $documentToWork['id'];
  1505. $url = $urlEdit.'&item_id='.$newWorkId.'&id='.$workId;
  1506. $editLink = Display::url($editIcon, $url);
  1507. if ($allowEdition != 1) {
  1508. $editLink = '';
  1509. }
  1510. }
  1511. }
  1512. $downloadLink = '';
  1513. // If URL is present then there's a file to download keep BC.
  1514. if ($row['contains_file'] || !empty($row['url'])) {
  1515. $downloadLink = Display::url($saveIcon, $urlDownload.'&id='.$row['id']).'&nbsp;';
  1516. }
  1517. $viewLink = '';
  1518. if (!empty($itemId)) {
  1519. $viewLink = Display::url($viewIcon, $urlView.'&id='.$itemId);
  1520. }
  1521. $deleteLink = '';
  1522. if ($allowEdition == 1 && !empty($itemId)) {
  1523. $deleteLink = Display::url($deleteIcon, $urlDelete.'&item_id='.$itemId.'&id='.$workId);
  1524. }
  1525. $row['type'] = null;
  1526. if ($qualificationExists) {
  1527. if (empty($row['qualificator_id'])) {
  1528. $status = Display::label(get_lang('NotRevised'), 'warning');
  1529. } else {
  1530. $status = Display::label(get_lang('Revised'), 'success');
  1531. }
  1532. $row['qualificator_id'] = $status;
  1533. }
  1534. if (!empty($row['qualification'])) {
  1535. $row['qualification'] = Display::label($row['qualification'], 'info');
  1536. }
  1537. if (!empty($row['sent_date'])) {
  1538. $row['sent_date'] = Display::dateToStringAgoAndLongDate($row['sent_date']);
  1539. }
  1540. if ($userId == $currentUserId) {
  1541. $row['actions'] = $downloadLink.$viewLink.$editLink.$deleteLink;
  1542. }
  1543. if ($addLinkShowed) {
  1544. $row['qualification'] = '';
  1545. $row['qualificator_id'] = '';
  1546. }
  1547. $workList[] = $row;
  1548. }
  1549. return $workList;
  1550. }
  1551. /**
  1552. * @param int $start
  1553. * @param int $limit
  1554. * @param int $column
  1555. * @param string $direction
  1556. * @param int $work_id
  1557. * @param array $where_condition
  1558. * @param int $studentId
  1559. * @param bool $getCount
  1560. * @param int $courseId
  1561. * @param int $sessionId
  1562. *
  1563. * @return array
  1564. */
  1565. function get_work_user_list(
  1566. $start,
  1567. $limit,
  1568. $column,
  1569. $direction,
  1570. $work_id,
  1571. $where_condition = null,
  1572. $studentId = null,
  1573. $getCount = false,
  1574. $courseId = 0,
  1575. $sessionId = 0
  1576. ) {
  1577. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  1578. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1579. $session_id = $sessionId ? $sessionId : api_get_session_id();
  1580. $group_id = api_get_group_id();
  1581. $course_info = api_get_course_info();
  1582. $course_info = empty($course_info) ? api_get_course_info_by_id($courseId) : $course_info;
  1583. $course_id = isset($course_info['real_id']) ? $course_info['real_id'] : $courseId;
  1584. $work_id = intval($work_id);
  1585. $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
  1586. $start = intval($start);
  1587. $limit = intval($limit);
  1588. if (!in_array($direction, ['asc', 'desc'])) {
  1589. $direction = 'desc';
  1590. }
  1591. $work_data = get_work_data_by_id($work_id, $courseId, $sessionId);
  1592. $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
  1593. $condition_session = api_get_session_condition(
  1594. $session_id,
  1595. true,
  1596. false,
  1597. 'work.session_id'
  1598. );
  1599. $locked = api_resource_is_locked_by_gradebook(
  1600. $work_id,
  1601. LINK_STUDENTPUBLICATION,
  1602. $course_info['code']
  1603. );
  1604. $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
  1605. api_get_user_id(),
  1606. $course_info
  1607. );
  1608. $groupIid = 0;
  1609. if ($group_id) {
  1610. $groupInfo = GroupManager::get_group_properties($group_id);
  1611. $groupIid = $groupInfo['iid'];
  1612. }
  1613. if (!empty($work_data)) {
  1614. if (!empty($group_id)) {
  1615. $extra_conditions = " work.post_group_id = '".intval($groupIid)."' ";
  1616. // set to select only messages posted by the user's group
  1617. } else {
  1618. $extra_conditions = " (work.post_group_id = '0' OR work.post_group_id is NULL) ";
  1619. }
  1620. if ($is_allowed_to_edit || $isDrhOfCourse) {
  1621. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1622. } else {
  1623. if (isset($course_info['show_score']) &&
  1624. $course_info['show_score'] == 1
  1625. ) {
  1626. $extra_conditions .= " AND (u.user_id = ".api_get_user_id()." AND work.active IN (0, 1)) ";
  1627. } else {
  1628. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1629. }
  1630. }
  1631. $extra_conditions .= " AND parent_id = ".$work_id." ";
  1632. $select = 'SELECT DISTINCT
  1633. u.user_id,
  1634. work.id as id,
  1635. title as title,
  1636. description,
  1637. url,
  1638. sent_date,
  1639. contains_file,
  1640. has_properties,
  1641. view_properties,
  1642. qualification,
  1643. weight,
  1644. allow_text_assignment,
  1645. u.firstname,
  1646. u.lastname,
  1647. u.username,
  1648. parent_id,
  1649. accepted,
  1650. qualificator_id,
  1651. url_correction,
  1652. title_correction
  1653. ';
  1654. if ($getCount) {
  1655. $select = "SELECT DISTINCT count(u.user_id) as count ";
  1656. }
  1657. $work_assignment = get_work_assignment_by_id($work_id, $courseId);
  1658. if (!empty($studentId)) {
  1659. $where_condition .= " AND u.user_id = ".intval($studentId);
  1660. }
  1661. $sql = " $select
  1662. FROM $work_table work
  1663. INNER JOIN $user_table u
  1664. ON (work.user_id = u.user_id)
  1665. WHERE
  1666. work.c_id = $course_id AND
  1667. $extra_conditions
  1668. $where_condition
  1669. $condition_session
  1670. AND u.status != ".INVITEE."
  1671. ORDER BY $column $direction";
  1672. if (!empty($start) && !empty($limit)) {
  1673. $sql .= " LIMIT $start, $limit";
  1674. }
  1675. $result = Database::query($sql);
  1676. $works = [];
  1677. if ($getCount) {
  1678. $work = Database::fetch_array($result, 'ASSOC');
  1679. return $work['count'];
  1680. }
  1681. $url = api_get_path(WEB_CODE_PATH).'work/';
  1682. $unoconv = api_get_configuration_value('unoconv.binaries');
  1683. $loadingText = addslashes(get_lang('Loading'));
  1684. $uploadedText = addslashes(get_lang('Uploaded'));
  1685. $failsUploadText = addslashes(get_lang('UplNoFileUploaded'));
  1686. $failsUploadIcon = Display::return_icon(
  1687. 'closed-circle.png',
  1688. '',
  1689. [],
  1690. ICON_SIZE_TINY
  1691. );
  1692. $saveIcon = Display::return_icon(
  1693. 'save.png',
  1694. get_lang('Save'),
  1695. [],
  1696. ICON_SIZE_SMALL
  1697. );
  1698. $correctionIcon = Display::return_icon(
  1699. 'check-circle.png',
  1700. get_lang('Correction'),
  1701. null,
  1702. ICON_SIZE_SMALL
  1703. );
  1704. $correctionIconSmall = Display::return_icon(
  1705. 'check-circle.png',
  1706. get_lang('Correction'),
  1707. null,
  1708. ICON_SIZE_TINY
  1709. );
  1710. $rateIcon = Display::return_icon(
  1711. 'rate_work.png',
  1712. get_lang('CorrectAndRate'),
  1713. [],
  1714. ICON_SIZE_SMALL
  1715. );
  1716. $blockEdition = api_get_configuration_value('block_student_publication_edition');
  1717. $blockScoreEdition = api_get_configuration_value('block_student_publication_score_edition');
  1718. while ($work = Database::fetch_array($result, 'ASSOC')) {
  1719. $item_id = $work['id'];
  1720. // Get the author ID for that document from the item_property table
  1721. $is_author = false;
  1722. $can_read = false;
  1723. $owner_id = $work['user_id'];
  1724. /* Because a bug found when saving items using the api_item_property_update()
  1725. the field $item_property_data['insert_user_id'] is not reliable. */
  1726. if (!$is_allowed_to_edit && $owner_id == api_get_user_id()) {
  1727. $is_author = true;
  1728. }
  1729. if ($course_info['show_score'] == 0) {
  1730. $can_read = true;
  1731. }
  1732. $qualification_exists = false;
  1733. if (!empty($work_data['qualification']) &&
  1734. intval($work_data['qualification']) > 0
  1735. ) {
  1736. $qualification_exists = true;
  1737. }
  1738. $qualification_string = '';
  1739. if ($qualification_exists) {
  1740. if ($work['qualification'] == '') {
  1741. $qualification_string = Display::label('-');
  1742. } else {
  1743. $qualification_string = formatWorkScore($work['qualification'], $work_data['qualification']);
  1744. }
  1745. }
  1746. $work['qualification_score'] = $work['qualification'];
  1747. $add_string = '';
  1748. $time_expires = '';
  1749. if (!empty($work_assignment['expires_on'])) {
  1750. $time_expires = api_strtotime(
  1751. $work_assignment['expires_on'],
  1752. 'UTC'
  1753. );
  1754. }
  1755. if (!empty($work_assignment['expires_on']) &&
  1756. !empty($time_expires) && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) {
  1757. $add_string = Display::label(get_lang('Expired'), 'important').' - ';
  1758. }
  1759. if (($can_read && $work['accepted'] == '1') ||
  1760. ($is_author && in_array($work['accepted'], ['1', '0'])) ||
  1761. ($is_allowed_to_edit || api_is_drh())
  1762. ) {
  1763. // Firstname, lastname, username
  1764. $work['fullname'] = Display::div(
  1765. api_get_person_name($work['firstname'], $work['lastname']),
  1766. ['class' => 'work-name']
  1767. );
  1768. // Title
  1769. $work['title_clean'] = $work['title'];
  1770. $work['title'] = Security::remove_XSS($work['title']);
  1771. if (strlen($work['title']) > 30) {
  1772. $short_title = substr($work['title'], 0, 27).'...';
  1773. $work['title'] = Display::span($short_title, ['class' => 'work-title', 'title' => $work['title']]);
  1774. } else {
  1775. $work['title'] = Display::div($work['title'], ['class' => 'work-title']);
  1776. }
  1777. // Type.
  1778. $work['type'] = DocumentManager::build_document_icon_tag('file', $work['url']);
  1779. // File name.
  1780. $linkToDownload = '';
  1781. // If URL is present then there's a file to download keep BC.
  1782. if ($work['contains_file'] || !empty($work['url'])) {
  1783. $linkToDownload = '<a href="'.$url.'download.php?id='.$item_id.'&'.api_get_cidreq().'">'.$saveIcon.'</a> ';
  1784. }
  1785. $feedback = '';
  1786. $count = getWorkCommentCount($item_id, $course_info);
  1787. if (!is_null($count) && !empty($count)) {
  1788. if ($qualification_exists) {
  1789. $feedback .= ' ';
  1790. }
  1791. $feedback .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang(
  1792. 'View'
  1793. ).'">'.
  1794. $count.' '.Display::returnFontAwesomeIcon('comments-o').'</a> ';
  1795. }
  1796. $correction = '';
  1797. $hasCorrection = '';
  1798. if (!empty($work['url_correction'])) {
  1799. $hasCorrection = Display::url(
  1800. $correctionIcon,
  1801. api_get_path(WEB_CODE_PATH).'work/download.php?id='.$item_id.'&'.api_get_cidreq().'&correction=1'
  1802. );
  1803. }
  1804. if ($qualification_exists) {
  1805. $work['qualification'] = $qualification_string.$feedback;
  1806. } else {
  1807. $work['qualification'] = $qualification_string.$feedback.$hasCorrection;
  1808. }
  1809. $work['qualification_only'] = $qualification_string;
  1810. // Date.
  1811. $work_date = api_get_local_time($work['sent_date']);
  1812. $date = date_to_str_ago($work['sent_date']).' '.$work_date;
  1813. $work['formatted_date'] = $work_date.' '.$add_string;
  1814. $work['sent_date_from_db'] = $work['sent_date'];
  1815. $work['sent_date'] = '<div class="work-date" title="'.$date.'">'.
  1816. $add_string.' '.Display::dateToStringAgoAndLongDate($work['sent_date']).'</div>';
  1817. $work['status'] = $hasCorrection;
  1818. $work['has_correction'] = $hasCorrection;
  1819. // Actions.
  1820. $action = '';
  1821. if (api_is_allowed_to_edit()) {
  1822. if ($blockScoreEdition && !api_is_platform_admin() && !empty($work['qualification_score'])) {
  1823. $rateLink = '';
  1824. } else {
  1825. $rateLink = '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1826. $rateIcon.'</a> ';
  1827. }
  1828. $action .= $rateLink;
  1829. if ($unoconv && empty($work['contains_file'])) {
  1830. $action .= '<a f
  1831. href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=export_to_doc&item_id='.$item_id.'"
  1832. title="'.get_lang('ExportToDoc').'" >'.
  1833. Display::return_icon('export_doc.png', get_lang('ExportToDoc'), [], ICON_SIZE_SMALL).'</a> ';
  1834. }
  1835. $alreadyUploaded = '';
  1836. if (!empty($work['url_correction'])) {
  1837. $alreadyUploaded = '<br />'.$work['title_correction'].' '.$correctionIconSmall;
  1838. }
  1839. $correction = '
  1840. <form
  1841. id="file_upload_'.$item_id.'"
  1842. class="work_correction_file_upload file_upload_small fileinput-button"
  1843. action="'.api_get_path(WEB_AJAX_PATH).'work.ajax.php?'.api_get_cidreq().'&a=upload_correction_file&item_id='.$item_id.'" method="POST" enctype="multipart/form-data"
  1844. >
  1845. <div id="progress_'.$item_id.'" class="text-center button-load">
  1846. '.addslashes(get_lang('ClickOrDropOneFileHere')).'
  1847. '.Display::return_icon('upload_file.png', get_lang('Correction'), [], ICON_SIZE_TINY).'
  1848. '.$alreadyUploaded.'
  1849. </div>
  1850. <input id="file_'.$item_id.'" type="file" name="file" class="" multiple>
  1851. </form>
  1852. ';
  1853. $correction .= "<script>
  1854. $(function() {
  1855. $('.work_correction_file_upload').each(function () {
  1856. $(this).fileupload({
  1857. dropZone: $(this)
  1858. });
  1859. });
  1860. $('#file_upload_".$item_id."').fileupload({
  1861. add: function (e, data) {
  1862. $('#progress_$item_id').html();
  1863. //$('#file_$item_id').remove();
  1864. data.context = $('#progress_$item_id').html('$loadingText <br /> <em class=\"fa fa-spinner fa-pulse fa-fw\"></em>');
  1865. data.submit();
  1866. $(this).removeClass('hover');
  1867. },
  1868. dragover: function (e, data) {
  1869. $(this).addClass('hover');
  1870. },
  1871. done: function (e, data) {
  1872. if (data._response.result.name) {
  1873. $('#progress_$item_id').html('$uploadedText '+data._response.result.result+'<br />'+data._response.result.name);
  1874. } else {
  1875. $('#progress_$item_id').html('$failsUploadText $failsUploadIcon');
  1876. }
  1877. $(this).removeClass('hover');
  1878. }
  1879. });
  1880. $('#file_upload_".$item_id."').on('dragleave', function (e) {
  1881. // dragleave callback implementation
  1882. $(this).removeClass('hover');
  1883. });
  1884. });
  1885. </script>";
  1886. if ($locked) {
  1887. if ($qualification_exists) {
  1888. $action .= Display::return_icon(
  1889. 'edit_na.png',
  1890. get_lang('CorrectAndRate'),
  1891. [],
  1892. ICON_SIZE_SMALL
  1893. );
  1894. } else {
  1895. $action .= Display::return_icon('edit_na.png', get_lang('Comment'), [], ICON_SIZE_SMALL);
  1896. }
  1897. } else {
  1898. if ($blockEdition && !api_is_platform_admin()) {
  1899. $editLink = '';
  1900. } else {
  1901. if ($qualification_exists) {
  1902. $editLink = '<a href="'.$url.'edit.php?'.api_get_cidreq(
  1903. ).'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang(
  1904. 'Edit'
  1905. ).'" >'.
  1906. Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>';
  1907. } else {
  1908. $editLink = '<a href="'.$url.'edit.php?'.api_get_cidreq(
  1909. ).'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang(
  1910. 'Modify'
  1911. ).'">'.
  1912. Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>';
  1913. }
  1914. }
  1915. $action .= $editLink;
  1916. }
  1917. if ($work['contains_file']) {
  1918. if ($locked) {
  1919. $action .= Display::return_icon(
  1920. 'move_na.png',
  1921. get_lang('Move'),
  1922. [],
  1923. ICON_SIZE_SMALL
  1924. );
  1925. } else {
  1926. $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=move&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Move').'">'.
  1927. Display::return_icon('move.png', get_lang('Move'), [], ICON_SIZE_SMALL).'</a>';
  1928. }
  1929. }
  1930. if ($work['accepted'] == '1') {
  1931. $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=make_invisible&item_id='.$item_id.'" title="'.get_lang('Invisible').'" >'.
  1932. Display::return_icon('visible.png', get_lang('Invisible'), [], ICON_SIZE_SMALL).'</a>';
  1933. } else {
  1934. $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=make_visible&item_id='.$item_id.'" title="'.get_lang('Visible').'" >'.
  1935. Display::return_icon('invisible.png', get_lang('Visible'), [], ICON_SIZE_SMALL).'</a> ';
  1936. }
  1937. if ($locked) {
  1938. $action .= Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
  1939. } else {
  1940. $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=delete&item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'.
  1941. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
  1942. }
  1943. } elseif ($is_author && (empty($work['qualificator_id']) || $work['qualificator_id'] == 0)) {
  1944. $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1945. Display::return_icon('default.png', get_lang('View'), [], ICON_SIZE_SMALL).'</a>';
  1946. if (api_get_course_setting('student_delete_own_publication') == 1) {
  1947. if (api_is_allowed_to_session_edit(false, true)) {
  1948. $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'.
  1949. Display::return_icon('edit.png', get_lang('Comment'), [], ICON_SIZE_SMALL).'</a>';
  1950. }
  1951. $action .= ' <a href="'.$url.'work_list.php?'.api_get_cidreq().'&action=delete&item_id='.$item_id.'&id='.$work['parent_id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'.
  1952. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
  1953. }
  1954. } else {
  1955. $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1956. Display::return_icon('default.png', get_lang('View'), [], ICON_SIZE_SMALL).'</a>';
  1957. }
  1958. // Status.
  1959. if (empty($work['qualificator_id'])) {
  1960. $qualificator_id = Display::label(get_lang('NotRevised'), 'warning');
  1961. } else {
  1962. $qualificator_id = Display::label(get_lang('Revised'), 'success');
  1963. }
  1964. $work['qualificator_id'] = $qualificator_id.' '.$hasCorrection;
  1965. $work['actions'] = '<div class="work-action">'.$linkToDownload.$action.'</div>';
  1966. $work['correction'] = $correction;
  1967. $works[] = $work;
  1968. }
  1969. }
  1970. return $works;
  1971. }
  1972. }
  1973. /**
  1974. * Send reminder to users who have not given the task.
  1975. *
  1976. * @param int
  1977. *
  1978. * @return array
  1979. *
  1980. * @author cvargas carlos.vargas@beeznest.com cfasanando, christian.fasanado@beeznest.com
  1981. */
  1982. function send_reminder_users_without_publication($task_data)
  1983. {
  1984. $_course = api_get_course_info();
  1985. $task_id = $task_data['id'];
  1986. $task_title = !empty($task_data['title']) ? $task_data['title'] : basename($task_data['url']);
  1987. $subject = '['.api_get_setting('siteName').'] ';
  1988. // The body can be as long as you wish, and any combination of text and variables
  1989. $content = get_lang('ReminderToSubmitPendingTask')."\n".get_lang('CourseName').' : '.$_course['name']."\n";
  1990. $content .= get_lang('WorkName').' : '.$task_title."\n";
  1991. $list_users = get_list_users_without_publication($task_id);
  1992. $mails_sent_to = [];
  1993. foreach ($list_users as $user) {
  1994. $name_user = api_get_person_name($user[1], $user[0], null, PERSON_NAME_EMAIL_ADDRESS);
  1995. $dear_line = get_lang('Dear')." ".api_get_person_name($user[1], $user[0]).", \n\n";
  1996. $body = $dear_line.$content;
  1997. MessageManager::send_message($user[3], $subject, $body);
  1998. $mails_sent_to[] = $name_user;
  1999. }
  2000. return $mails_sent_to;
  2001. }
  2002. /**
  2003. * @param int $workId The work ID
  2004. * @param int $courseId The course ID
  2005. * @param int $sessionId Optional. The session ID
  2006. */
  2007. function sendEmailToDrhOnHomeworkCreation($workId, $courseId, $sessionId = 0)
  2008. {
  2009. $courseInfo = api_get_course_info_by_id($courseId);
  2010. $assignment = get_work_assignment_by_id($workId, $courseId);
  2011. $work = get_work_data_by_id($workId, $courseId, $sessionId);
  2012. $workInfo = array_merge($assignment, $work);
  2013. if (empty($sessionId)) {
  2014. $students = CourseManager::get_student_list_from_course_code($courseInfo['code']);
  2015. } else {
  2016. $students = CourseManager::get_student_list_from_course_code($courseInfo['code'], true, $sessionId);
  2017. }
  2018. $bodyView = new Template(null, false, false, false, false, false);
  2019. foreach ($students as $student) {
  2020. $studentInfo = api_get_user_info($student['user_id']);
  2021. if (empty($studentInfo)) {
  2022. continue;
  2023. }
  2024. $hrms = UserManager::getDrhListFromUser($student['id']);
  2025. foreach ($hrms as $hrm) {
  2026. $hrmName = api_get_person_name($hrm['firstname'], $hrm['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
  2027. $bodyView->assign('hrm_name', $hrmName);
  2028. $bodyView->assign('student', $studentInfo);
  2029. $bodyView->assign('course', $courseInfo);
  2030. $bodyView->assign('course_link', api_get_course_url($courseInfo['code'], $sessionId));
  2031. $bodyView->assign('work', $workInfo);
  2032. $bodyTemplate = $bodyView->get_template('mail/new_work_alert_hrm.tpl');
  2033. MessageManager::send_message(
  2034. $hrm['id'],
  2035. sprintf(
  2036. get_lang('StudentXHasBeenAssignedNewWorkInCourseY'),
  2037. $student['firstname'],
  2038. $courseInfo['title']
  2039. ),
  2040. $bodyView->fetch($bodyTemplate)
  2041. );
  2042. }
  2043. }
  2044. }
  2045. /**
  2046. * Sends an email to the students of a course when a homework is created.
  2047. *
  2048. * @param int $workId
  2049. * @param int $courseId
  2050. * @param int $sessionId
  2051. *
  2052. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  2053. * @author Julio Montoya <gugli100@gmail.com> Adding session support - 2011
  2054. */
  2055. function sendEmailToStudentsOnHomeworkCreation($workId, $courseId, $sessionId = 0)
  2056. {
  2057. $courseInfo = api_get_course_info_by_id($courseId);
  2058. $courseCode = $courseInfo['code'];
  2059. // Get the students of the course
  2060. if (empty($sessionId)) {
  2061. $students = CourseManager::get_student_list_from_course_code($courseCode);
  2062. } else {
  2063. $students = CourseManager::get_student_list_from_course_code($courseCode, true, $sessionId);
  2064. }
  2065. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('HomeworkCreated');
  2066. $currentUser = api_get_user_info(api_get_user_id());
  2067. if (!empty($students)) {
  2068. foreach ($students as $student) {
  2069. $user_info = api_get_user_info($student['user_id']);
  2070. if (!empty($user_info)) {
  2071. $link = api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId;
  2072. $emailbody = get_lang('Dear')." ".$user_info['complete_name'].",\n\n";
  2073. $emailbody .= get_lang('HomeworkHasBeenCreatedForTheCourse')." ".$courseCode.". "."\n\n".
  2074. '<a href="'.$link.'">'.get_lang('PleaseCheckHomeworkPage').'</a>';
  2075. $emailbody .= "\n\n".$currentUser['complete_name'];
  2076. $additionalParameters = [
  2077. 'smsType' => SmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE,
  2078. 'userId' => $student['user_id'],
  2079. 'courseTitle' => $courseCode,
  2080. 'link' => $link,
  2081. ];
  2082. MessageManager::send_message_simple(
  2083. $student['user_id'],
  2084. $emailsubject,
  2085. $emailbody,
  2086. null,
  2087. false,
  2088. false,
  2089. $additionalParameters,
  2090. false
  2091. );
  2092. }
  2093. }
  2094. }
  2095. }
  2096. /**
  2097. * @param string $url
  2098. *
  2099. * @return bool
  2100. */
  2101. function is_work_exist_by_url($url)
  2102. {
  2103. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2104. $url = Database::escape_string($url);
  2105. $sql = "SELECT id FROM $table WHERE url='$url'";
  2106. $result = Database::query($sql);
  2107. if (Database::num_rows($result) > 0) {
  2108. $row = Database::fetch_row($result);
  2109. if (empty($row)) {
  2110. return false;
  2111. } else {
  2112. return true;
  2113. }
  2114. } else {
  2115. return false;
  2116. }
  2117. }
  2118. /**
  2119. * Check if a user is the author of a work document.
  2120. *
  2121. * @param int $itemId
  2122. * @param int $userId
  2123. * @param int $courseId
  2124. * @param int $sessionId
  2125. *
  2126. * @return bool
  2127. */
  2128. function user_is_author($itemId, $userId = null, $courseId = 0, $sessionId = 0)
  2129. {
  2130. if (empty($itemId)) {
  2131. return false;
  2132. }
  2133. if (empty($userId)) {
  2134. $userId = api_get_user_id();
  2135. }
  2136. $isAuthor = false;
  2137. $is_allowed_to_edit = api_is_allowed_to_edit();
  2138. if ($is_allowed_to_edit) {
  2139. $isAuthor = true;
  2140. } else {
  2141. if (empty($courseId)) {
  2142. $courseId = api_get_course_int_id();
  2143. }
  2144. if (empty($sessionId)) {
  2145. $sessionId = api_get_session_id();
  2146. }
  2147. $data = api_get_item_property_info($courseId, 'work', $itemId, $sessionId);
  2148. if ($data['insert_user_id'] == $userId) {
  2149. $isAuthor = true;
  2150. }
  2151. $workData = get_work_data_by_id($itemId);
  2152. if ($workData['user_id'] == $userId) {
  2153. $isAuthor = true;
  2154. }
  2155. }
  2156. if (!$isAuthor) {
  2157. return false;
  2158. }
  2159. return $isAuthor;
  2160. }
  2161. /**
  2162. * Get list of users who have not given the task.
  2163. *
  2164. * @param int
  2165. * @param int
  2166. *
  2167. * @return array
  2168. *
  2169. * @author cvargas
  2170. * @author Julio Montoya <gugli100@gmail.com> Fixing query
  2171. */
  2172. function get_list_users_without_publication($task_id, $studentId = 0)
  2173. {
  2174. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2175. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2176. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2177. $session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2178. $users = getAllUserToWork($task_id, api_get_course_int_id());
  2179. $users = array_column($users, 'user_id');
  2180. // Condition for the session
  2181. $session_id = api_get_session_id();
  2182. $course_id = api_get_course_int_id();
  2183. $task_id = intval($task_id);
  2184. $sessionCondition = api_get_session_condition($session_id);
  2185. if ($session_id == 0) {
  2186. $sql = "SELECT user_id as id FROM $work_table
  2187. WHERE
  2188. c_id = $course_id AND
  2189. parent_id = '$task_id' AND
  2190. active IN (0, 1)";
  2191. } else {
  2192. $sql = "SELECT user_id as id FROM $work_table
  2193. WHERE
  2194. c_id = $course_id AND
  2195. parent_id = '$task_id' $sessionCondition AND
  2196. active IN (0, 1)";
  2197. }
  2198. $result = Database::query($sql);
  2199. $users_with_tasks = [];
  2200. while ($row = Database::fetch_array($result)) {
  2201. $users_with_tasks[] = $row['id'];
  2202. }
  2203. if ($session_id == 0) {
  2204. $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
  2205. FROM $table_course_user AS cu, $table_user AS u
  2206. WHERE u.status != 1 and cu.c_id='".$course_id."' AND u.user_id = cu.user_id";
  2207. } else {
  2208. $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
  2209. FROM $session_course_rel_user AS cu, $table_user AS u
  2210. WHERE
  2211. u.status != 1 AND
  2212. cu.c_id='".$course_id."' AND
  2213. u.user_id = cu.user_id AND
  2214. cu.session_id = '".$session_id."'";
  2215. }
  2216. if (!empty($studentId)) {
  2217. $sql_users .= " AND u.user_id = ".intval($studentId);
  2218. }
  2219. $group_id = api_get_group_id();
  2220. $new_group_user_list = [];
  2221. if ($group_id) {
  2222. $groupInfo = GroupManager::get_group_properties($group_id);
  2223. $group_user_list = GroupManager::get_subscribed_users($groupInfo);
  2224. if (!empty($group_user_list)) {
  2225. foreach ($group_user_list as $group_user) {
  2226. $new_group_user_list[] = $group_user['user_id'];
  2227. }
  2228. }
  2229. }
  2230. $result_users = Database::query($sql_users);
  2231. $users_without_tasks = [];
  2232. while ($rowUsers = Database::fetch_array($result_users)) {
  2233. $userId = $rowUsers['user_id'];
  2234. if (in_array($userId, $users_with_tasks)) {
  2235. continue;
  2236. }
  2237. if ($group_id && !in_array($userId, $new_group_user_list)) {
  2238. continue;
  2239. }
  2240. if (!empty($users)) {
  2241. if (!in_array($userId, $users)) {
  2242. continue;
  2243. }
  2244. }
  2245. $row_users = [];
  2246. $row_users[0] = $rowUsers['lastname'];
  2247. $row_users[1] = $rowUsers['firstname'];
  2248. $row_users[2] = Display::encrypted_mailto_link($rowUsers['email']);
  2249. $row_users[3] = $userId;
  2250. $users_without_tasks[] = $row_users;
  2251. }
  2252. return $users_without_tasks;
  2253. }
  2254. /**
  2255. * Display list of users who have not given the task.
  2256. *
  2257. * @param int task id
  2258. * @param int $studentId
  2259. *
  2260. * @author cvargas carlos.vargas@beeznest.com cfasanando, christian.fasanado@beeznest.com
  2261. * @author Julio Montoya <gugli100@gmail.com> Fixes
  2262. */
  2263. function display_list_users_without_publication($task_id, $studentId = null)
  2264. {
  2265. $origin = api_get_origin();
  2266. $table_header[] = [get_lang('LastName'), true];
  2267. $table_header[] = [get_lang('FirstName'), true];
  2268. $table_header[] = [get_lang('Email'), true];
  2269. $data = get_list_users_without_publication($task_id);
  2270. $sorting_options = [];
  2271. $sorting_options['column'] = 1;
  2272. $paging_options = [];
  2273. $my_params = [];
  2274. if (isset($_GET['edit_dir'])) {
  2275. $my_params['edit_dir'] = Security::remove_XSS($_GET['edit_dir']);
  2276. }
  2277. if (isset($_GET['list'])) {
  2278. $my_params['list'] = Security::remove_XSS($_GET['list']);
  2279. }
  2280. $my_params['origin'] = $origin;
  2281. $my_params['id'] = intval($_GET['id']);
  2282. //$column_show
  2283. $column_show[] = 1;
  2284. $column_show[] = 1;
  2285. $column_show[] = 1;
  2286. Display::display_sortable_config_table(
  2287. 'work',
  2288. $table_header,
  2289. $data,
  2290. $sorting_options,
  2291. $paging_options,
  2292. $my_params,
  2293. $column_show
  2294. );
  2295. }
  2296. /**
  2297. * @param int $documentId
  2298. * @param int $workId
  2299. * @param int $courseId
  2300. */
  2301. function addDocumentToWork($documentId, $workId, $courseId)
  2302. {
  2303. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2304. $params = [
  2305. 'document_id' => $documentId,
  2306. 'work_id' => $workId,
  2307. 'c_id' => $courseId,
  2308. ];
  2309. Database::insert($table, $params);
  2310. }
  2311. /**
  2312. * @param int $documentId
  2313. * @param int $workId
  2314. * @param int $courseId
  2315. *
  2316. * @return array
  2317. */
  2318. function getDocumentToWork($documentId, $workId, $courseId)
  2319. {
  2320. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2321. $params = [
  2322. 'document_id = ? and work_id = ? and c_id = ?' => [$documentId, $workId, $courseId],
  2323. ];
  2324. return Database::select('*', $table, ['where' => $params]);
  2325. }
  2326. /**
  2327. * @param int $documentId
  2328. * @param int $workId
  2329. * @param int $courseId
  2330. * @param int $sessionId
  2331. * @param int $userId
  2332. * @param int $active
  2333. *
  2334. * @return array
  2335. */
  2336. function getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId, $active = 1)
  2337. {
  2338. $workRel = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2339. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2340. $documentId = intval($documentId);
  2341. $workId = intval($workId);
  2342. $courseId = intval($courseId);
  2343. $userId = intval($userId);
  2344. $sessionId = intval($sessionId);
  2345. $active = intval($active);
  2346. $sessionCondition = api_get_session_condition($sessionId);
  2347. $sql = "SELECT w.* FROM $work w
  2348. INNER JOIN $workRel rel
  2349. ON (w.parent_id = rel.work_id)
  2350. WHERE
  2351. w.document_id = $documentId AND
  2352. w.parent_id = $workId AND
  2353. w.c_id = $courseId
  2354. $sessionCondition AND
  2355. user_id = $userId AND
  2356. active = $active
  2357. ";
  2358. $result = Database::query($sql);
  2359. $workInfo = [];
  2360. if (Database::num_rows($result)) {
  2361. $workInfo = Database::fetch_array($result, 'ASSOC');
  2362. }
  2363. return $workInfo;
  2364. }
  2365. /**
  2366. * @param int $workId
  2367. * @param int $courseId
  2368. *
  2369. * @return array
  2370. */
  2371. function getAllDocumentToWork($workId, $courseId)
  2372. {
  2373. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2374. $params = [
  2375. 'work_id = ? and c_id = ?' => [$workId, $courseId],
  2376. ];
  2377. return Database::select('*', $table, ['where' => $params]);
  2378. }
  2379. /**
  2380. * @param int $documentId
  2381. * @param int $workId
  2382. * @param int $courseId
  2383. */
  2384. function deleteDocumentToWork($documentId, $workId, $courseId)
  2385. {
  2386. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2387. $params = [
  2388. 'document_id = ? and work_id = ? and c_id = ?' => [$documentId, $workId, $courseId],
  2389. ];
  2390. Database::delete($table, $params);
  2391. }
  2392. /**
  2393. * @param int $userId
  2394. * @param int $workId
  2395. * @param int $courseId
  2396. */
  2397. function addUserToWork($userId, $workId, $courseId)
  2398. {
  2399. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2400. $params = [
  2401. 'user_id' => $userId,
  2402. 'work_id' => $workId,
  2403. 'c_id' => $courseId,
  2404. ];
  2405. Database::insert($table, $params);
  2406. }
  2407. /**
  2408. * @param int $userId
  2409. * @param int $workId
  2410. * @param int $courseId
  2411. *
  2412. * @return array
  2413. */
  2414. function getUserToWork($userId, $workId, $courseId)
  2415. {
  2416. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2417. $params = [
  2418. 'user_id = ? and work_id = ? and c_id = ?' => [$userId, $workId, $courseId],
  2419. ];
  2420. return Database::select('*', $table, ['where' => $params]);
  2421. }
  2422. /**
  2423. * @param int $workId
  2424. * @param int $courseId
  2425. * @param bool $getCount
  2426. *
  2427. * @return array|int
  2428. */
  2429. function getAllUserToWork($workId, $courseId, $getCount = false)
  2430. {
  2431. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2432. $params = [
  2433. 'work_id = ? and c_id = ?' => [$workId, $courseId],
  2434. ];
  2435. if ($getCount) {
  2436. $count = 0;
  2437. $result = Database::select(
  2438. 'count(user_id) as count',
  2439. $table,
  2440. ['where' => $params],
  2441. 'simple'
  2442. );
  2443. if (!empty($result)) {
  2444. $count = intval($result['count']);
  2445. }
  2446. return $count;
  2447. } else {
  2448. return Database::select('*', $table, ['where' => $params]);
  2449. }
  2450. }
  2451. /**
  2452. * @param int $userId
  2453. * @param int $workId
  2454. * @param int $courseId
  2455. */
  2456. function deleteUserToWork($userId, $workId, $courseId)
  2457. {
  2458. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2459. $params = [
  2460. 'user_id = ? and work_id = ? and c_id = ?' => [$userId, $workId, $courseId],
  2461. ];
  2462. Database::delete($table, $params);
  2463. }
  2464. /**
  2465. * @param int $userId
  2466. * @param int $workId
  2467. * @param int $courseId
  2468. *
  2469. * @return bool
  2470. */
  2471. function userIsSubscribedToWork($userId, $workId, $courseId)
  2472. {
  2473. $subscribedUsers = getAllUserToWork($workId, $courseId);
  2474. if (empty($subscribedUsers)) {
  2475. return true;
  2476. } else {
  2477. $subscribedUsersList = [];
  2478. foreach ($subscribedUsers as $item) {
  2479. $subscribedUsersList[] = $item['user_id'];
  2480. }
  2481. if (in_array($userId, $subscribedUsersList)) {
  2482. return true;
  2483. }
  2484. }
  2485. return false;
  2486. }
  2487. /**
  2488. * Get the list of students that have to submit their work.
  2489. *
  2490. * @param int $workId The internal ID of the assignment
  2491. * @param int $courseId The course ID
  2492. * @param int $groupId The group ID, if any
  2493. * @param int $sessionId The session ID, if any
  2494. * @param bool $getCount Whether we want just the amount or the full result
  2495. *
  2496. * @return array|int An integer (if we just asked for the count) or an array of users
  2497. */
  2498. function getStudentSubscribedToWork(
  2499. $workId,
  2500. $courseId,
  2501. $groupId = null,
  2502. $sessionId = null,
  2503. $getCount = false
  2504. ) {
  2505. $usersInWork = null;
  2506. $usersInCourse = null;
  2507. if (empty($groupId)) {
  2508. $courseInfo = api_get_course_info_by_id($courseId);
  2509. $status = STUDENT;
  2510. if (!empty($sessionId)) {
  2511. $status = 0;
  2512. }
  2513. $usersInCourse = CourseManager::get_user_list_from_course_code(
  2514. $courseInfo['code'],
  2515. $sessionId,
  2516. null,
  2517. null,
  2518. $status,
  2519. $getCount
  2520. );
  2521. } else {
  2522. $usersInCourse = GroupManager::get_users(
  2523. $groupId,
  2524. false,
  2525. null,
  2526. null,
  2527. $getCount,
  2528. $courseId
  2529. );
  2530. }
  2531. $usersInWork = getAllUserToWork($workId, $courseId, $getCount);
  2532. if (empty($usersInWork)) {
  2533. return $usersInCourse;
  2534. } else {
  2535. return $usersInWork;
  2536. }
  2537. }
  2538. /**
  2539. * @param int $userId
  2540. * @param int $workId
  2541. * @param int $courseId
  2542. * @param bool $forceAccessForCourseAdmins
  2543. *
  2544. * @return bool
  2545. */
  2546. function allowOnlySubscribedUser($userId, $workId, $courseId, $forceAccessForCourseAdmins = false)
  2547. {
  2548. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  2549. return true;
  2550. }
  2551. if ($forceAccessForCourseAdmins) {
  2552. if (api_is_course_admin() || api_is_coach()) {
  2553. return true;
  2554. }
  2555. }
  2556. return userIsSubscribedToWork($userId, $workId, $courseId);
  2557. }
  2558. /**
  2559. * @param int $workId
  2560. * @param array $courseInfo
  2561. * @param int $documentId
  2562. *
  2563. * @return array
  2564. */
  2565. function getDocumentTemplateFromWork($workId, $courseInfo, $documentId)
  2566. {
  2567. $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
  2568. if (!empty($documents)) {
  2569. foreach ($documents as $doc) {
  2570. if ($documentId != $doc['document_id']) {
  2571. continue;
  2572. }
  2573. $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
  2574. $fileInfo = pathinfo($docData['path']);
  2575. if ($fileInfo['extension'] == 'html') {
  2576. if (file_exists($docData['absolute_path']) && is_file($docData['absolute_path'])) {
  2577. $docData['file_content'] = file_get_contents($docData['absolute_path']);
  2578. return $docData;
  2579. }
  2580. }
  2581. }
  2582. }
  2583. return [];
  2584. }
  2585. /**
  2586. * @param int $workId
  2587. * @param array $courseInfo
  2588. *
  2589. * @return string
  2590. */
  2591. function getAllDocumentsFromWorkToString($workId, $courseInfo)
  2592. {
  2593. $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
  2594. $content = null;
  2595. if (!empty($documents)) {
  2596. $content .= '<ul class="nav nav-list well">';
  2597. $content .= '<li class="nav-header">'.get_lang('Documents').'</li>';
  2598. foreach ($documents as $doc) {
  2599. $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
  2600. if ($docData) {
  2601. $content .= '<li><a target="_blank" href="'.$docData['url'].'">'.$docData['title'].'</a></li>';
  2602. }
  2603. }
  2604. $content .= '</ul><br />';
  2605. }
  2606. return $content;
  2607. }
  2608. /**
  2609. * Returns fck editor toolbar.
  2610. *
  2611. * @return array
  2612. */
  2613. function getWorkDescriptionToolbar()
  2614. {
  2615. return [
  2616. 'ToolbarStartExpanded' => 'true',
  2617. 'ToolbarSet' => 'Work',
  2618. 'Width' => '100%',
  2619. 'Height' => '400',
  2620. ];
  2621. }
  2622. /**
  2623. * @param array $work
  2624. *
  2625. * @return array
  2626. */
  2627. function getWorkComments($work)
  2628. {
  2629. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2630. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  2631. $courseId = intval($work['c_id']);
  2632. $workId = intval($work['id']);
  2633. if (empty($courseId) || empty($workId)) {
  2634. return [];
  2635. }
  2636. $sql = "SELECT
  2637. c.id,
  2638. c.user_id
  2639. FROM $commentTable c
  2640. INNER JOIN $userTable u
  2641. ON (u.id = c.user_id)
  2642. WHERE c_id = $courseId AND work_id = $workId
  2643. ORDER BY sent_at
  2644. ";
  2645. $result = Database::query($sql);
  2646. $comments = Database::store_result($result, 'ASSOC');
  2647. if (!empty($comments)) {
  2648. foreach ($comments as &$comment) {
  2649. $userInfo = api_get_user_info($comment['user_id']);
  2650. $comment['picture'] = $userInfo['avatar'];
  2651. $comment['complete_name'] = $userInfo['complete_name_with_username'];
  2652. $commentInfo = getWorkComment($comment['id']);
  2653. if (!empty($commentInfo)) {
  2654. $comment = array_merge($comment, $commentInfo);
  2655. }
  2656. }
  2657. }
  2658. return $comments;
  2659. }
  2660. /**
  2661. * Get total score from a work list.
  2662. *
  2663. * @param $workList
  2664. *
  2665. * @return int|null
  2666. */
  2667. function getTotalWorkScore($workList)
  2668. {
  2669. $count = 0;
  2670. foreach ($workList as $data) {
  2671. $count += $data['qualification_score'];
  2672. }
  2673. return $count;
  2674. }
  2675. /**
  2676. * Get comment count from a work list (docs sent by students).
  2677. *
  2678. * @param array $workList
  2679. * @param array $courseInfo
  2680. *
  2681. * @return int|null
  2682. */
  2683. function getTotalWorkComment($workList, $courseInfo = [])
  2684. {
  2685. if (empty($courseInfo)) {
  2686. $courseInfo = api_get_course_info();
  2687. }
  2688. $count = 0;
  2689. foreach ($workList as $data) {
  2690. $count += getWorkCommentCount($data['id'], $courseInfo);
  2691. }
  2692. return $count;
  2693. }
  2694. /**
  2695. * Get comment count for a specific work sent by a student.
  2696. *
  2697. * @param int $id
  2698. * @param array $courseInfo
  2699. *
  2700. * @return int
  2701. */
  2702. function getWorkCommentCount($id, $courseInfo = [])
  2703. {
  2704. if (empty($courseInfo)) {
  2705. $courseInfo = api_get_course_info();
  2706. }
  2707. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2708. $id = intval($id);
  2709. $sql = "SELECT count(*) as count
  2710. FROM $commentTable
  2711. WHERE work_id = $id AND c_id = ".$courseInfo['real_id'];
  2712. $result = Database::query($sql);
  2713. if (Database::num_rows($result)) {
  2714. $comment = Database::fetch_array($result);
  2715. return $comment['count'];
  2716. }
  2717. return 0;
  2718. }
  2719. /**
  2720. * Get comment count for a specific parent.
  2721. *
  2722. * @param int $parentId
  2723. * @param array $courseInfo
  2724. * @param int $sessionId
  2725. *
  2726. * @return int
  2727. */
  2728. function getWorkCommentCountFromParent(
  2729. $parentId,
  2730. $courseInfo = [],
  2731. $sessionId = 0
  2732. ) {
  2733. if (empty($courseInfo)) {
  2734. $courseInfo = api_get_course_info();
  2735. }
  2736. if (empty($sessionId)) {
  2737. $sessionId = api_get_session_id();
  2738. } else {
  2739. $sessionId = intval($sessionId);
  2740. }
  2741. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2742. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2743. $parentId = intval($parentId);
  2744. $sessionCondition = api_get_session_condition($sessionId, false, false, 'w.session_id');
  2745. $sql = "SELECT count(*) as count
  2746. FROM $commentTable c INNER JOIN $work w
  2747. ON c.c_id = w.c_id AND w.id = c.work_id
  2748. WHERE
  2749. $sessionCondition AND
  2750. parent_id = $parentId AND
  2751. w.c_id = ".$courseInfo['real_id'];
  2752. $result = Database::query($sql);
  2753. if (Database::num_rows($result)) {
  2754. $comment = Database::fetch_array($result);
  2755. return $comment['count'];
  2756. }
  2757. return 0;
  2758. }
  2759. /**
  2760. * Get last work information from parent.
  2761. *
  2762. * @param int $parentId
  2763. * @param array $courseInfo
  2764. * @param int $sessionId
  2765. *
  2766. * @return int
  2767. */
  2768. function getLastWorkStudentFromParent(
  2769. $parentId,
  2770. $courseInfo = [],
  2771. $sessionId = 0
  2772. ) {
  2773. if (empty($courseInfo)) {
  2774. $courseInfo = api_get_course_info();
  2775. }
  2776. if (empty($sessionId)) {
  2777. $sessionId = api_get_session_id();
  2778. } else {
  2779. $sessionId = intval($sessionId);
  2780. }
  2781. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2782. $sessionCondition = api_get_session_condition($sessionId, false);
  2783. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2784. $parentId = intval($parentId);
  2785. $sql = "SELECT w.*
  2786. FROM $commentTable c INNER JOIN $work w
  2787. ON c.c_id = w.c_id AND w.id = c.work_id
  2788. WHERE
  2789. $sessionCondition AND
  2790. parent_id = $parentId AND
  2791. w.c_id = ".$courseInfo['real_id']."
  2792. ORDER BY w.sent_date
  2793. LIMIT 1
  2794. ";
  2795. $result = Database::query($sql);
  2796. if (Database::num_rows($result)) {
  2797. $comment = Database::fetch_array($result, 'ASSOC');
  2798. return $comment;
  2799. }
  2800. return [];
  2801. }
  2802. /**
  2803. * Get last work information from parent.
  2804. *
  2805. * @param int $userId
  2806. * @param array $parentInfo
  2807. * @param array $courseInfo
  2808. * @param int $sessionId
  2809. *
  2810. * @return int
  2811. */
  2812. function getLastWorkStudentFromParentByUser(
  2813. $userId,
  2814. $parentInfo,
  2815. $courseInfo = [],
  2816. $sessionId = 0
  2817. ) {
  2818. if (empty($courseInfo)) {
  2819. $courseInfo = api_get_course_info();
  2820. }
  2821. if (empty($sessionId)) {
  2822. $sessionId = api_get_session_id();
  2823. } else {
  2824. $sessionId = intval($sessionId);
  2825. }
  2826. $userId = intval($userId);
  2827. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2828. if (empty($parentInfo)) {
  2829. return false;
  2830. }
  2831. $parentId = $parentInfo['id'];
  2832. $sessionCondition = api_get_session_condition($sessionId);
  2833. $sql = "SELECT *
  2834. FROM $work
  2835. WHERE
  2836. user_id = $userId
  2837. $sessionCondition AND
  2838. parent_id = $parentId AND
  2839. c_id = ".$courseInfo['real_id']."
  2840. ORDER BY sent_date DESC
  2841. LIMIT 1
  2842. ";
  2843. $result = Database::query($sql);
  2844. if (Database::num_rows($result)) {
  2845. $work = Database::fetch_array($result, 'ASSOC');
  2846. $work['qualification_rounded'] = formatWorkScore($work['qualification'], $parentInfo['qualification']);
  2847. return $work;
  2848. }
  2849. return [];
  2850. }
  2851. /**
  2852. * @param float $score
  2853. * @param int $weight
  2854. *
  2855. * @return string
  2856. */
  2857. function formatWorkScore($score, $weight)
  2858. {
  2859. $label = 'info';
  2860. $weight = (int) $weight;
  2861. $relativeScore = 0;
  2862. if (!empty($weight)) {
  2863. $relativeScore = $score / $weight;
  2864. }
  2865. if ($relativeScore < 0.5) {
  2866. $label = 'important';
  2867. } elseif ($relativeScore < 0.75) {
  2868. $label = 'warning';
  2869. }
  2870. $scoreBasedInModel = ExerciseLib::convertScoreToModel($relativeScore * 100);
  2871. if (empty($scoreBasedInModel)) {
  2872. $finalScore = api_number_format($score, 1).' / '.$weight;
  2873. return Display::label(
  2874. $finalScore,
  2875. $label
  2876. );
  2877. } else {
  2878. $finalScore = $scoreBasedInModel;
  2879. return $finalScore;
  2880. }
  2881. }
  2882. /**
  2883. * @param int $id comment id
  2884. * @param array $courseInfo
  2885. *
  2886. * @return string
  2887. */
  2888. function getWorkComment($id, $courseInfo = [])
  2889. {
  2890. if (empty($courseInfo)) {
  2891. $courseInfo = api_get_course_info();
  2892. }
  2893. if (empty($courseInfo['real_id'])) {
  2894. return [];
  2895. }
  2896. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2897. $id = intval($id);
  2898. $sql = "SELECT * FROM $commentTable
  2899. WHERE id = $id AND c_id = ".$courseInfo['real_id'];
  2900. $result = Database::query($sql);
  2901. $comment = [];
  2902. if (Database::num_rows($result)) {
  2903. $comment = Database::fetch_array($result, 'ASSOC');
  2904. $filePath = null;
  2905. $fileUrl = null;
  2906. $deleteUrl = null;
  2907. $fileName = null;
  2908. if (!empty($comment['file'])) {
  2909. $work = get_work_data_by_id($comment['work_id']);
  2910. $workParent = get_work_data_by_id($work['parent_id']);
  2911. $filePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/'.$workParent['url'].'/'.$comment['file'];
  2912. $fileUrl = api_get_path(WEB_CODE_PATH).'work/download_comment_file.php?comment_id='.$id.'&'.api_get_cidreq();
  2913. $deleteUrl = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$comment['work_id'].'&action=delete_attachment&comment_id='.$id;
  2914. $fileParts = explode('_', $comment['file']);
  2915. $fileName = str_replace($fileParts[0].'_'.$fileParts[1].'_', '', $comment['file']);
  2916. }
  2917. $comment['delete_file_url'] = $deleteUrl;
  2918. $comment['file_path'] = $filePath;
  2919. $comment['file_url'] = $fileUrl;
  2920. $comment['file_name_to_show'] = $fileName;
  2921. $comment['sent_at_with_label'] = Display::dateToStringAgoAndLongDate($comment['sent_at']);
  2922. }
  2923. return $comment;
  2924. }
  2925. /**
  2926. * @param int $id
  2927. * @param array $courseInfo
  2928. */
  2929. function deleteCommentFile($id, $courseInfo = [])
  2930. {
  2931. $workComment = getWorkComment($id, $courseInfo);
  2932. if (isset($workComment['file']) && !empty($workComment['file'])) {
  2933. if (file_exists($workComment['file_path'])) {
  2934. $result = my_delete($workComment['file_path']);
  2935. if ($result) {
  2936. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2937. $params = ['file' => ''];
  2938. Database::update(
  2939. $commentTable,
  2940. $params,
  2941. ['id = ? AND c_id = ? ' => [$workComment['id'], $workComment['c_id']]]
  2942. );
  2943. }
  2944. }
  2945. }
  2946. }
  2947. /**
  2948. * Adds a comments to the work document.
  2949. *
  2950. * @param array $courseInfo
  2951. * @param int $userId
  2952. * @param array $parentWork
  2953. * @param array $work
  2954. * @param array $data
  2955. *
  2956. * @return int
  2957. */
  2958. function addWorkComment($courseInfo, $userId, $parentWork, $work, $data)
  2959. {
  2960. $fileData = isset($data['attachment']) ? $data['attachment'] : null;
  2961. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2962. // If no attachment and no comment then don't save comment
  2963. if (empty($fileData['name']) && empty($data['comment'])) {
  2964. return false;
  2965. }
  2966. $params = [
  2967. 'work_id' => $work['id'],
  2968. 'c_id' => $work['c_id'],
  2969. 'user_id' => $userId,
  2970. 'comment' => $data['comment'],
  2971. 'sent_at' => api_get_utc_datetime(),
  2972. ];
  2973. $commentId = Database::insert($commentTable, $params);
  2974. if ($commentId) {
  2975. Display::addFlash(
  2976. Display::return_message(get_lang('CommentAdded'))
  2977. );
  2978. $sql = "UPDATE $commentTable SET id = iid WHERE iid = $commentId";
  2979. Database::query($sql);
  2980. }
  2981. $userIdListToSend = [];
  2982. if (api_is_allowed_to_edit()) {
  2983. if (isset($data['send_email']) && $data['send_email']) {
  2984. // Teacher sends a feedback
  2985. $userIdListToSend = [$work['user_id']];
  2986. }
  2987. } else {
  2988. $sessionId = api_get_session_id();
  2989. if (empty($sessionId)) {
  2990. $teachers = CourseManager::get_teacher_list_from_course_code(
  2991. $courseInfo['code']
  2992. );
  2993. if (!empty($teachers)) {
  2994. $userIdListToSend = array_keys($teachers);
  2995. }
  2996. } else {
  2997. $teachers = SessionManager::getCoachesByCourseSession(
  2998. $sessionId,
  2999. $courseInfo['real_id']
  3000. );
  3001. if (!empty($teachers)) {
  3002. $userIdListToSend = array_values($teachers);
  3003. }
  3004. }
  3005. $sendNotification = api_get_course_setting('email_to_teachers_on_new_work_feedback', api_get_course_id());
  3006. if ($sendNotification != 1) {
  3007. $userIdListToSend = [];
  3008. }
  3009. }
  3010. $url = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$work['id'];
  3011. $subject = sprintf(get_lang('ThereIsANewWorkFeedback'), $parentWork['title']);
  3012. $content = sprintf(get_lang('ThereIsANewWorkFeedbackInWorkXHere'), $work['title'], $url);
  3013. if (!empty($data['comment'])) {
  3014. $content .= '<br /><b>'.get_lang('Comment').':</b><br />'.$data['comment'];
  3015. }
  3016. if (!empty($userIdListToSend)) {
  3017. foreach ($userIdListToSend as $userIdToSend) {
  3018. MessageManager::send_message_simple(
  3019. $userIdToSend,
  3020. $subject,
  3021. $content
  3022. );
  3023. }
  3024. }
  3025. if (!empty($commentId) && !empty($fileData)) {
  3026. $workParent = get_work_data_by_id($work['parent_id']);
  3027. if (!empty($workParent)) {
  3028. $uploadDir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work'.$workParent['url'];
  3029. $newFileName = 'comment_'.$commentId.'_'.php2phps(api_replace_dangerous_char($fileData['name']));
  3030. $newFilePath = $uploadDir.'/'.$newFileName;
  3031. $result = move_uploaded_file($fileData['tmp_name'], $newFilePath);
  3032. if ($result) {
  3033. $params = ['file' => $newFileName];
  3034. Database::update(
  3035. $commentTable,
  3036. $params,
  3037. ['id = ? AND c_id = ? ' => [$commentId, $work['c_id']]]
  3038. );
  3039. }
  3040. }
  3041. }
  3042. }
  3043. /**
  3044. * @param array $work
  3045. * @param array $workParent
  3046. *
  3047. * @return string
  3048. */
  3049. function getWorkCommentForm($work, $workParent)
  3050. {
  3051. $url = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$work['id'].'&action=send_comment&'.api_get_cidreq();
  3052. $form = new FormValidator(
  3053. 'work_comment',
  3054. 'post',
  3055. $url,
  3056. '',
  3057. ['enctype' => "multipart/form-data"]
  3058. );
  3059. $qualification = $workParent['qualification'];
  3060. if (api_is_allowed_to_edit()) {
  3061. if (!empty($qualification) && intval($qualification) > 0) {
  3062. $model = ExerciseLib::getCourseScoreModel();
  3063. if (empty($model)) {
  3064. $form->addFloat(
  3065. 'qualification',
  3066. [get_lang('Qualification'), " / ".$qualification],
  3067. false,
  3068. [],
  3069. false,
  3070. 0,
  3071. $qualification
  3072. );
  3073. } else {
  3074. ExerciseLib::addScoreModelInput(
  3075. $form,
  3076. 'qualification',
  3077. $qualification,
  3078. $work['qualification']
  3079. );
  3080. }
  3081. $form->addFile('file', get_lang('Correction'));
  3082. $form->setDefaults(['qualification' => $work['qualification']]);
  3083. }
  3084. }
  3085. Skill::addSkillsToUserForm($form, ITEM_TYPE_STUDENT_PUBLICATION, $workParent['id'], $work['user_id'], $work['id']);
  3086. $form->addHtmlEditor('comment', get_lang('Comment'), false);
  3087. $form->addFile('attachment', get_lang('Attachment'));
  3088. $form->addElement('hidden', 'id', $work['id']);
  3089. if (api_is_allowed_to_edit()) {
  3090. $form->addCheckBox(
  3091. 'send_email',
  3092. null,
  3093. get_lang('SendMailToStudent')
  3094. );
  3095. }
  3096. $form->addButtonSend(get_lang('Send'), 'button');
  3097. return $form->returnForm();
  3098. }
  3099. /**
  3100. * @param array $homework result of get_work_assignment_by_id()
  3101. *
  3102. * @return array
  3103. */
  3104. function getWorkDateValidationStatus($homework)
  3105. {
  3106. $message = null;
  3107. $has_expired = false;
  3108. $has_ended = false;
  3109. if (!empty($homework)) {
  3110. if (!empty($homework['expires_on']) || !empty($homework['ends_on'])) {
  3111. $time_now = time();
  3112. if (!empty($homework['expires_on'])) {
  3113. $time_expires = api_strtotime($homework['expires_on'], 'UTC');
  3114. $difference = $time_expires - $time_now;
  3115. if ($difference < 0) {
  3116. $has_expired = true;
  3117. }
  3118. }
  3119. if (empty($homework['expires_on'])) {
  3120. $has_expired = false;
  3121. }
  3122. if (!empty($homework['ends_on'])) {
  3123. $time_ends = api_strtotime($homework['ends_on'], 'UTC');
  3124. $difference2 = $time_ends - $time_now;
  3125. if ($difference2 < 0) {
  3126. $has_ended = true;
  3127. }
  3128. }
  3129. $ends_on = api_convert_and_format_date($homework['ends_on']);
  3130. $expires_on = api_convert_and_format_date($homework['expires_on']);
  3131. }
  3132. if ($has_ended) {
  3133. $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
  3134. } elseif ($has_expired) {
  3135. $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
  3136. } else {
  3137. if ($has_expired) {
  3138. $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
  3139. }
  3140. }
  3141. }
  3142. return [
  3143. 'message' => $message,
  3144. 'has_ended' => $has_ended,
  3145. 'has_expired' => $has_expired,
  3146. ];
  3147. }
  3148. /**
  3149. * @param FormValidator $form
  3150. * @param int $uploadFormType
  3151. */
  3152. function setWorkUploadForm($form, $uploadFormType = 0)
  3153. {
  3154. $form->addHeader(get_lang('UploadADocument'));
  3155. $form->addHidden('contains_file', 0, ['id' => 'contains_file_id']);
  3156. $form->addHidden('active', 1);
  3157. $form->addHidden('accepted', 1);
  3158. $form->addElement('text', 'title', get_lang('Title'), ['id' => 'file_upload']);
  3159. $form->addElement(
  3160. 'text',
  3161. 'extension',
  3162. get_lang('FileExtension'),
  3163. ['id' => 'file_extension', 'readonly' => 'readonly']
  3164. );
  3165. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  3166. switch ($uploadFormType) {
  3167. case 0:
  3168. // File and text.
  3169. $form->addElement(
  3170. 'file',
  3171. 'file',
  3172. get_lang('UploadADocument'),
  3173. 'size="40" onchange="updateDocumentTitle(this.value)"'
  3174. );
  3175. $form->addProgress();
  3176. $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
  3177. break;
  3178. case 1:
  3179. // Only text.
  3180. $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
  3181. $form->addRule('description', get_lang('ThisFieldIsRequired'), 'required');
  3182. break;
  3183. case 2:
  3184. // Only file.
  3185. $form->addElement(
  3186. 'file',
  3187. 'file',
  3188. get_lang('UploadADocument'),
  3189. 'size="40" onchange="updateDocumentTitle(this.value)"'
  3190. );
  3191. $form->addProgress();
  3192. $form->addRule('file', get_lang('ThisFieldIsRequired'), 'required');
  3193. break;
  3194. }
  3195. $form->addButtonUpload(get_lang('Upload'), 'submitWork');
  3196. }
  3197. /**
  3198. * @param array $my_folder_data
  3199. * @param array $_course
  3200. * @param bool $isCorrection
  3201. * @param array $workInfo
  3202. * @param array $file
  3203. *
  3204. * @return array
  3205. */
  3206. function uploadWork($my_folder_data, $_course, $isCorrection = false, $workInfo = [], $file = [])
  3207. {
  3208. if (isset($_FILES['file']) && !empty($_FILES['file'])) {
  3209. $file = $_FILES['file'];
  3210. }
  3211. if (empty($file['size'])) {
  3212. return [
  3213. 'error' => Display:: return_message(
  3214. get_lang('UplUploadFailedSizeIsZero'),
  3215. 'error'
  3216. ),
  3217. ];
  3218. }
  3219. $updir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work/'; //directory path to upload
  3220. // Try to add an extension to the file if it has'nt one
  3221. $filename = add_ext_on_mime(stripslashes($file['name']), $file['type']);
  3222. // Replace dangerous characters
  3223. $filename = api_replace_dangerous_char($filename);
  3224. // Transform any .php file in .phps fo security
  3225. $filename = php2phps($filename);
  3226. $filesize = filesize($file['tmp_name']);
  3227. if (empty($filesize)) {
  3228. return [
  3229. 'error' => Display::return_message(
  3230. get_lang('UplUploadFailedSizeIsZero'),
  3231. 'error'
  3232. ),
  3233. ];
  3234. } elseif (!filter_extension($new_file_name)) {
  3235. return [
  3236. 'error' => Display::return_message(
  3237. get_lang('UplUnableToSaveFileFilteredExtension'),
  3238. 'error'
  3239. ),
  3240. ];
  3241. }
  3242. $totalSpace = DocumentManager::documents_total_space($_course['real_id']);
  3243. $course_max_space = DocumentManager::get_course_quota($_course['code']);
  3244. $total_size = $filesize + $totalSpace;
  3245. if ($total_size > $course_max_space) {
  3246. return [
  3247. 'error' => Display::return_message(get_lang('NoSpace'), 'error'),
  3248. ];
  3249. }
  3250. // Compose a unique file name to avoid any conflict
  3251. $new_file_name = api_get_unique_id();
  3252. if ($isCorrection) {
  3253. if (!empty($workInfo['url'])) {
  3254. $new_file_name = basename($workInfo['url']).'_correction';
  3255. } else {
  3256. $new_file_name = $new_file_name.'_correction';
  3257. }
  3258. }
  3259. $curdirpath = basename($my_folder_data['url']);
  3260. // If we come from the group tools the groupid will be saved in $work_table
  3261. if (is_dir($updir.$curdirpath) || empty($curdirpath)) {
  3262. $result = move_uploaded_file(
  3263. $file['tmp_name'],
  3264. $updir.$curdirpath.'/'.$new_file_name
  3265. );
  3266. } else {
  3267. return [
  3268. 'error' => Display :: return_message(
  3269. get_lang('FolderDoesntExistsInFileSystem'),
  3270. 'error'
  3271. ),
  3272. ];
  3273. }
  3274. if ($result) {
  3275. $url = 'work/'.$curdirpath.'/'.$new_file_name;
  3276. } else {
  3277. return false;
  3278. }
  3279. return [
  3280. 'url' => $url,
  3281. 'filename' => $filename,
  3282. 'filesize' => $filesize,
  3283. 'error' => '',
  3284. ];
  3285. }
  3286. /**
  3287. * Send an e-mail to users related to this work (course teachers, usually, but
  3288. * might include other group members).
  3289. *
  3290. * @param int $workId
  3291. * @param array $courseInfo
  3292. * @param int $sessionId
  3293. */
  3294. function sendAlertToUsers($workId, $courseInfo, $sessionId)
  3295. {
  3296. $sessionId = (int) $sessionId;
  3297. $workData = get_work_data_by_id($workId, $courseInfo['real_id'], $sessionId);
  3298. // last value is to check this is not "just" an edit
  3299. // YW Tis part serve to send a e-mail to the tutors when a new file is sent
  3300. $send = api_get_course_setting('email_alert_manager_on_new_doc');
  3301. $userList = [];
  3302. if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_TEACHERS) {
  3303. // Lets predefine some variables. Be sure to change the from address!
  3304. if (empty($sessionId)) {
  3305. // Teachers
  3306. $userList = CourseManager::get_user_list_from_course_code(
  3307. api_get_course_id(),
  3308. null,
  3309. null,
  3310. null,
  3311. COURSEMANAGER
  3312. );
  3313. } else {
  3314. // Coaches
  3315. $userList = CourseManager::get_user_list_from_course_code(
  3316. api_get_course_id(),
  3317. $sessionId,
  3318. null,
  3319. null,
  3320. 2
  3321. );
  3322. }
  3323. }
  3324. if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_STUDENTS) {
  3325. // Send mail only to sender
  3326. $studentList = [[
  3327. 'user_id' => api_get_user_id(),
  3328. ]];
  3329. $userList = array_merge($userList, $studentList);
  3330. }
  3331. if ($send) {
  3332. $subject = "[".api_get_setting('siteName')."] ".get_lang('SendMailBody')."\n ".get_lang('CourseName').": ".$courseInfo['name']." ";
  3333. foreach ($userList as $user_data) {
  3334. $to_user_id = $user_data['user_id'];
  3335. $user_info = api_get_user_info($to_user_id);
  3336. $message = get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$courseInfo['name']."\n";
  3337. $message .= get_lang('UserName')." : ".$user_info['complete_name']."\n";
  3338. $message .= get_lang('DateSent')." : ".api_format_date(api_get_local_time())."\n";
  3339. $url = api_get_path(WEB_CODE_PATH)."work/work.php?cidReq=".$courseInfo['code']."&id_session=".$sessionId."&id=".$workData['id'];
  3340. $message .= get_lang('WorkName')." : ".$workData['title']."\n\n".'<a href="'.$url.'">'.get_lang('DownloadLink')."</a>\n";
  3341. MessageManager::send_message_simple(
  3342. $to_user_id,
  3343. $subject,
  3344. $message,
  3345. 0,
  3346. false,
  3347. false,
  3348. [],
  3349. false
  3350. );
  3351. }
  3352. }
  3353. }
  3354. /**
  3355. * Check if the current uploaded work filename already exists in the current assement.
  3356. *
  3357. * @param string $filename
  3358. * @param int $workId
  3359. *
  3360. * @return array
  3361. */
  3362. function checkExistingWorkFileName($filename, $workId)
  3363. {
  3364. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3365. $filename = Database::escape_string($filename);
  3366. $workId = (int) $workId;
  3367. $sql = "SELECT title FROM $table
  3368. WHERE parent_id = $workId AND title = '$filename' AND active = 1";
  3369. $result = Database::query($sql);
  3370. return Database::fetch_assoc($result);
  3371. }
  3372. /**
  3373. * @param array $workInfo
  3374. * @param array $values
  3375. * @param array $courseInfo
  3376. * @param int $sessionId
  3377. * @param int $groupId
  3378. * @param int $userId
  3379. * @param array $file
  3380. * @param bool $checkDuplicated
  3381. * @param bool $showFlashMessage
  3382. *
  3383. * @return string|null
  3384. */
  3385. function processWorkForm(
  3386. $workInfo,
  3387. $values,
  3388. $courseInfo,
  3389. $sessionId,
  3390. $groupId,
  3391. $userId,
  3392. $file = [],
  3393. $checkDuplicated = false,
  3394. $showFlashMessage = true
  3395. ) {
  3396. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3397. $courseId = $courseInfo['real_id'];
  3398. $groupId = (int) $groupId;
  3399. $sessionId = (int) $sessionId;
  3400. $userId = (int) $userId;
  3401. $extension = '';
  3402. if (isset($values['extension'])) {
  3403. $extension = $values['extension'];
  3404. } else {
  3405. $fileInfo = pathinfo($values['title']);
  3406. if (isset($fileInfo['extension']) && !empty($fileInfo['extension'])) {
  3407. $extension = '.'.$fileInfo['extension'];
  3408. $values['title'] = $fileInfo['filename'];
  3409. }
  3410. }
  3411. $title = $values['title'].$extension;
  3412. $description = isset($values['description']) ? $values['description'] : '';
  3413. $containsFile = isset($values['contains_file']) && !empty($values['contains_file']) ? (int) $values['contains_file'] : 0;
  3414. $saveWork = true;
  3415. $filename = null;
  3416. $url = null;
  3417. $filesize = null;
  3418. $workData = [];
  3419. $message = null;
  3420. if ($containsFile) {
  3421. $saveWork = false;
  3422. if ($checkDuplicated) {
  3423. if (checkExistingWorkFileName($file['name'], $workInfo['id'])) {
  3424. $saveWork = false;
  3425. $result['error'] = get_lang('YouAlreadySentThisFile');
  3426. $workData['error'] = get_lang('UplAlreadyExists');
  3427. } else {
  3428. $result = uploadWork($workInfo, $courseInfo, false, [], $file);
  3429. }
  3430. } else {
  3431. $result = uploadWork($workInfo, $courseInfo, false, [], $file);
  3432. }
  3433. if (isset($result['error'])) {
  3434. $saveWork = false;
  3435. if ($showFlashMessage) {
  3436. $message = $result['error'];
  3437. }
  3438. if (empty($result['error']) && isset($result['url']) && !empty($result['url'])) {
  3439. $saveWork = true;
  3440. }
  3441. }
  3442. }
  3443. if ($saveWork) {
  3444. $filename = isset($result['filename']) ? $result['filename'] : null;
  3445. if (empty($title)) {
  3446. $title = isset($result['title']) && !empty($result['title']) ? $result['title'] : get_lang('Untitled');
  3447. }
  3448. $filesize = isset($result['filesize']) ? $result['filesize'] : null;
  3449. $url = isset($result['url']) ? $result['url'] : null;
  3450. }
  3451. if (empty($title)) {
  3452. $title = get_lang('Untitled');
  3453. }
  3454. $groupIid = 0;
  3455. $groupInfo = [];
  3456. if ($groupId) {
  3457. $groupInfo = GroupManager::get_group_properties($groupId);
  3458. $groupIid = $groupInfo['iid'];
  3459. }
  3460. if ($saveWork) {
  3461. $active = '1';
  3462. $params = [
  3463. 'c_id' => $courseId,
  3464. 'url' => $url,
  3465. 'filetype' => 'file',
  3466. 'title' => $title,
  3467. 'description' => $description,
  3468. 'contains_file' => $containsFile,
  3469. 'active' => $active,
  3470. 'accepted' => '1',
  3471. 'qualificator_id' => 0,
  3472. 'document_id' => 0,
  3473. 'weight' => 0,
  3474. 'allow_text_assignment' => 0,
  3475. 'post_group_id' => $groupIid,
  3476. 'sent_date' => api_get_utc_datetime(),
  3477. 'parent_id' => $workInfo['id'],
  3478. 'session_id' => $sessionId ? $sessionId : null,
  3479. 'user_id' => $userId,
  3480. 'has_properties' => 0,
  3481. 'qualification' => 0,
  3482. //'filesize' => $filesize
  3483. ];
  3484. $workId = Database::insert($work_table, $params);
  3485. if ($workId) {
  3486. $sql = "UPDATE $work_table SET id = iid WHERE iid = $workId ";
  3487. Database::query($sql);
  3488. if (array_key_exists('filename', $workInfo) && !empty($filename)) {
  3489. $filename = Database::escape_string($filename);
  3490. $sql = "UPDATE $work_table SET
  3491. filename = '$filename'
  3492. WHERE iid = $workId";
  3493. Database::query($sql);
  3494. }
  3495. if (array_key_exists('document_id', $workInfo)) {
  3496. $documentId = isset($values['document_id']) ? (int) $values['document_id'] : 0;
  3497. $sql = "UPDATE $work_table SET
  3498. document_id = '$documentId'
  3499. WHERE iid = $workId";
  3500. Database::query($sql);
  3501. }
  3502. api_item_property_update(
  3503. $courseInfo,
  3504. 'work',
  3505. $workId,
  3506. 'DocumentAdded',
  3507. $userId,
  3508. $groupInfo
  3509. );
  3510. sendAlertToUsers($workId, $courseInfo, $sessionId);
  3511. Event::event_upload($workId);
  3512. // The following feature requires the creation of a work-type
  3513. // extra_field and the following setting in the configuration file
  3514. // (until moved to the database). It allows te teacher to set a
  3515. // "considered work time", meaning the time we assume a student
  3516. // would have spent, approximately, to prepare the task before
  3517. // handing it in Chamilo, adding this time to the student total
  3518. // course use time, as a register of time spent *before* his
  3519. // connection to the platform to hand the work in.
  3520. $consideredWorkingTime = api_get_configuration_value('considered_working_time');
  3521. if (!empty($consideredWorkingTime)) {
  3522. // Get the "considered work time" defined for this work
  3523. $fieldValue = new ExtraFieldValue('work');
  3524. $resultExtra = $fieldValue->getAllValuesForAnItem(
  3525. $workInfo['iid'], //the ID of the work *folder*, not the document uploaded by the student
  3526. true
  3527. );
  3528. $workingTime = null;
  3529. foreach ($resultExtra as $field) {
  3530. $field = $field['value'];
  3531. if ($consideredWorkingTime == $field->getField()->getVariable()) {
  3532. $workingTime = $field->getValue();
  3533. }
  3534. }
  3535. // If no time was defined, or a time of "0" was set, do nothing
  3536. if (!empty($workingTime)) {
  3537. // If some time is set, get the list of docs handed in by
  3538. // this student (to make sure we count the time only once)
  3539. $userWorks = get_work_user_list(
  3540. 0,
  3541. 100,
  3542. null,
  3543. null,
  3544. $workInfo['id'],
  3545. null,
  3546. $userId,
  3547. false,
  3548. $courseId,
  3549. $sessionId
  3550. );
  3551. if (count($userWorks) == 1) {
  3552. // The student only uploaded one doc so far, so add the
  3553. // considered work time to his course connection time
  3554. Event::eventAddVirtualCourseTime($courseId, $userId, $sessionId, $workingTime);
  3555. }
  3556. }
  3557. }
  3558. $workData = get_work_data_by_id($workId);
  3559. if ($workData && $showFlashMessage) {
  3560. Display::addFlash(Display::return_message(get_lang('DocAdd')));
  3561. }
  3562. }
  3563. } else {
  3564. if ($showFlashMessage) {
  3565. Display::addFlash(
  3566. Display::return_message(
  3567. $message ? $message : get_lang('ImpossibleToSaveTheDocument'),
  3568. 'error'
  3569. )
  3570. );
  3571. }
  3572. }
  3573. return $workData;
  3574. }
  3575. /**
  3576. * Creates a new task (directory) in the assignment tool.
  3577. *
  3578. * @param array $formValues
  3579. * @param int $user_id
  3580. * @param array $courseInfo
  3581. * @param int $groupId
  3582. * @param int $sessionId
  3583. *
  3584. * @return bool|int
  3585. * @note $params can have the following elements, but should at least have the 2 first ones: (
  3586. * 'new_dir' => 'some-name',
  3587. * 'description' => 'some-desc',
  3588. * 'qualification' => 20 (e.g. 20),
  3589. * 'weight' => 50 (percentage) to add to gradebook (e.g. 50),
  3590. * 'allow_text_assignment' => 0/1/2,
  3591. *
  3592. * @todo Rename createAssignment or createWork, or something like that
  3593. */
  3594. function addDir($formValues, $user_id, $courseInfo, $groupId, $sessionId = 0)
  3595. {
  3596. $em = Database::getManager();
  3597. $user_id = (int) $user_id;
  3598. $groupId = (int) $groupId;
  3599. $sessionId = (int) $sessionId;
  3600. $groupIid = 0;
  3601. $groupInfo = [];
  3602. if (!empty($groupId)) {
  3603. $groupInfo = GroupManager::get_group_properties($groupId);
  3604. $groupIid = $groupInfo['iid'];
  3605. }
  3606. $session = $em->find('ChamiloCoreBundle:Session', $sessionId);
  3607. $base_work_dir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work';
  3608. $course_id = $courseInfo['real_id'];
  3609. $directory = api_replace_dangerous_char($formValues['new_dir']);
  3610. $directory = disable_dangerous_file($directory);
  3611. $created_dir = create_unexisting_work_directory($base_work_dir, $directory);
  3612. if (empty($created_dir)) {
  3613. return false;
  3614. }
  3615. $enableEndDate = isset($formValues['enableEndDate']) ? true : false;
  3616. $enableExpiryDate = isset($formValues['enableExpiryDate']) ? true : false;
  3617. if ($enableEndDate && $enableExpiryDate) {
  3618. if ($formValues['expires_on'] > $formValues['ends_on']) {
  3619. Display::addFlash(
  3620. Display::return_message(
  3621. get_lang('DateExpiredNotBeLessDeadLine'),
  3622. 'warning'
  3623. )
  3624. );
  3625. return false;
  3626. }
  3627. }
  3628. $dirName = '/'.$created_dir;
  3629. $today = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  3630. $title = isset($formValues['work_title']) ? $formValues['work_title'] : $formValues['new_dir'];
  3631. $workTable = new CStudentPublication();
  3632. $workTable
  3633. ->setCId($course_id)
  3634. ->setUrl($dirName)
  3635. ->setTitle($title)
  3636. ->setDescription($formValues['description'])
  3637. ->setActive(true)
  3638. ->setAccepted(true)
  3639. ->setFiletype('folder')
  3640. ->setPostGroupId($groupIid)
  3641. ->setSentDate($today)
  3642. ->setQualification($formValues['qualification'] != '' ? $formValues['qualification'] : 0)
  3643. ->setParentId(0)
  3644. ->setQualificatorId(0)
  3645. ->setWeight(!empty($formValues['weight']) ? $formValues['weight'] : 0)
  3646. ->setSession($session)
  3647. ->setAllowTextAssignment($formValues['allow_text_assignment'])
  3648. ->setContainsFile(0)
  3649. ->setUserId($user_id)
  3650. ->setHasProperties(0)
  3651. ->setDocumentId(0);
  3652. $em->persist($workTable);
  3653. $em->flush();
  3654. $workTable->setId($workTable->getIid());
  3655. $em->merge($workTable);
  3656. $em->flush();
  3657. // Folder created
  3658. api_item_property_update(
  3659. $courseInfo,
  3660. 'work',
  3661. $workTable->getIid(),
  3662. 'DirectoryCreated',
  3663. $user_id,
  3664. $groupInfo
  3665. );
  3666. updatePublicationAssignment(
  3667. $workTable->getIid(),
  3668. $formValues,
  3669. $courseInfo,
  3670. $groupIid
  3671. );
  3672. // Added the new Work ID to the extra field values
  3673. $formValues['item_id'] = $workTable->getIid();
  3674. $workFieldValue = new ExtraFieldValue('work');
  3675. $workFieldValue->saveFieldValues($formValues);
  3676. $sendEmailAlert = api_get_course_setting('email_alert_students_on_new_homework');
  3677. switch ($sendEmailAlert) {
  3678. case 1:
  3679. sendEmailToStudentsOnHomeworkCreation(
  3680. $workTable->getIid(),
  3681. $course_id,
  3682. $sessionId
  3683. );
  3684. //no break
  3685. case 2:
  3686. sendEmailToDrhOnHomeworkCreation(
  3687. $workTable->getIid(),
  3688. $course_id,
  3689. $sessionId
  3690. );
  3691. break;
  3692. }
  3693. return $workTable->getIid();
  3694. }
  3695. /**
  3696. * @param int $workId
  3697. * @param array $courseInfo
  3698. *
  3699. * @return int
  3700. */
  3701. function agendaExistsForWork($workId, $courseInfo)
  3702. {
  3703. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3704. $courseId = $courseInfo['real_id'];
  3705. $workId = intval($workId);
  3706. $sql = "SELECT add_to_calendar FROM $workTable
  3707. WHERE c_id = $courseId AND publication_id = ".$workId;
  3708. $res = Database::query($sql);
  3709. if (Database::num_rows($res)) {
  3710. $row = Database::fetch_array($res, 'ASSOC');
  3711. if (!empty($row['add_to_calendar'])) {
  3712. return $row['add_to_calendar'];
  3713. }
  3714. }
  3715. return 0;
  3716. }
  3717. /**
  3718. * Update work description, qualification, weight, allow_text_assignment.
  3719. *
  3720. * @param int $workId (iid)
  3721. * @param array $params
  3722. * @param array $courseInfo
  3723. * @param int $sessionId
  3724. */
  3725. function updateWork($workId, $params, $courseInfo, $sessionId = 0)
  3726. {
  3727. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3728. $filteredParams = [
  3729. 'description' => $params['description'],
  3730. 'qualification' => $params['qualification'],
  3731. 'weight' => $params['weight'],
  3732. 'allow_text_assignment' => $params['allow_text_assignment'],
  3733. ];
  3734. Database::update(
  3735. $workTable,
  3736. $filteredParams,
  3737. [
  3738. 'iid = ? AND c_id = ?' => [
  3739. $workId,
  3740. $courseInfo['real_id'],
  3741. ],
  3742. ]
  3743. );
  3744. $workFieldValue = new ExtraFieldValue('work');
  3745. $workFieldValue->saveFieldValues($params);
  3746. }
  3747. /**
  3748. * @param int $workId
  3749. * @param array $params
  3750. * @param array $courseInfo
  3751. * @param int $groupId
  3752. */
  3753. function updatePublicationAssignment($workId, $params, $courseInfo, $groupId)
  3754. {
  3755. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3756. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3757. $workId = intval($workId);
  3758. $now = api_get_utc_datetime();
  3759. $course_id = $courseInfo['real_id'];
  3760. // Insert into agenda
  3761. $agendaId = 0;
  3762. if (isset($params['add_to_calendar']) && $params['add_to_calendar'] == 1) {
  3763. // Setting today date
  3764. $date = $end_date = $now;
  3765. if (isset($params['enableExpiryDate'])) {
  3766. $end_date = $params['expires_on'];
  3767. $date = $end_date;
  3768. }
  3769. $title = sprintf(get_lang('HandingOverOfTaskX'), $params['new_dir']);
  3770. $description = isset($params['description']) ? $params['description'] : '';
  3771. $content = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId.'">'
  3772. .$params['new_dir'].'</a>'.$description;
  3773. $agendaId = agendaExistsForWork($workId, $courseInfo);
  3774. // Add/edit agenda
  3775. $agenda = new Agenda('course');
  3776. $agenda->set_course($courseInfo);
  3777. if (!empty($agendaId)) {
  3778. // add_to_calendar is set but it doesnt exists then invalidate
  3779. $eventInfo = $agenda->get_event($agendaId);
  3780. if (empty($eventInfo)) {
  3781. $agendaId = 0;
  3782. }
  3783. }
  3784. $eventColor = $agenda->eventStudentPublicationColor;
  3785. if (empty($agendaId)) {
  3786. $agendaId = $agenda->addEvent(
  3787. $date,
  3788. $end_date,
  3789. 'false',
  3790. $title,
  3791. $content,
  3792. ['GROUP:'.$groupId],
  3793. false,
  3794. null,
  3795. [],
  3796. [],
  3797. null,
  3798. $eventColor
  3799. );
  3800. } else {
  3801. $agenda->editEvent(
  3802. $agendaId,
  3803. $end_date,
  3804. $end_date,
  3805. 'false',
  3806. $title,
  3807. $content,
  3808. [],
  3809. [],
  3810. [],
  3811. null,
  3812. $eventColor
  3813. );
  3814. }
  3815. }
  3816. $qualification = isset($params['qualification']) && !empty($params['qualification']) ? 1 : 0;
  3817. $expiryDate = isset($params['enableExpiryDate']) && (int) $params['enableExpiryDate'] == 1 ? api_get_utc_datetime($params['expires_on']) : '';
  3818. $endDate = isset($params['enableEndDate']) && (int) $params['enableEndDate'] == 1 ? api_get_utc_datetime($params['ends_on']) : '';
  3819. $data = get_work_assignment_by_id($workId, $course_id);
  3820. if (!empty($expiryDate)) {
  3821. $expiryDateCondition = "expires_on = '".Database::escape_string($expiryDate)."', ";
  3822. } else {
  3823. $expiryDateCondition = "expires_on = null, ";
  3824. }
  3825. if (!empty($endDate)) {
  3826. $endOnCondition = "ends_on = '".Database::escape_string($endDate)."', ";
  3827. } else {
  3828. $endOnCondition = "ends_on = null, ";
  3829. }
  3830. if (empty($data)) {
  3831. $sql = "INSERT INTO $table SET
  3832. c_id = $course_id ,
  3833. $expiryDateCondition
  3834. $endOnCondition
  3835. add_to_calendar = $agendaId,
  3836. enable_qualification = '$qualification',
  3837. publication_id = '$workId'";
  3838. Database::query($sql);
  3839. $my_last_id = Database::insert_id();
  3840. if ($my_last_id) {
  3841. $sql = "UPDATE $table SET
  3842. id = iid
  3843. WHERE iid = $my_last_id";
  3844. Database::query($sql);
  3845. $sql = "UPDATE $workTable SET
  3846. has_properties = $my_last_id,
  3847. view_properties = 1
  3848. WHERE c_id = $course_id AND id = $workId";
  3849. Database::query($sql);
  3850. }
  3851. } else {
  3852. $sql = "UPDATE $table SET
  3853. $expiryDateCondition
  3854. $endOnCondition
  3855. add_to_calendar = $agendaId,
  3856. enable_qualification = '".$qualification."'
  3857. WHERE
  3858. publication_id = $workId AND
  3859. c_id = $course_id AND
  3860. iid = ".$data['iid'];
  3861. Database::query($sql);
  3862. }
  3863. if (!empty($params['category_id'])) {
  3864. $link_info = GradebookUtils::isResourceInCourseGradebook(
  3865. $courseInfo['code'],
  3866. LINK_STUDENTPUBLICATION,
  3867. $workId,
  3868. api_get_session_id()
  3869. );
  3870. $linkId = null;
  3871. if (!empty($link_info)) {
  3872. $linkId = $link_info['id'];
  3873. }
  3874. if (isset($params['make_calification']) &&
  3875. $params['make_calification'] == 1
  3876. ) {
  3877. if (empty($linkId)) {
  3878. GradebookUtils::add_resource_to_course_gradebook(
  3879. $params['category_id'],
  3880. $courseInfo['code'],
  3881. LINK_STUDENTPUBLICATION,
  3882. $workId,
  3883. $params['new_dir'],
  3884. api_float_val($params['weight']),
  3885. api_float_val($params['qualification']),
  3886. $params['description'],
  3887. 1,
  3888. api_get_session_id()
  3889. );
  3890. } else {
  3891. GradebookUtils::updateResourceFromCourseGradebook(
  3892. $linkId,
  3893. $courseInfo['code'],
  3894. $params['weight']
  3895. );
  3896. }
  3897. } else {
  3898. // Delete everything of the gradebook for this $linkId
  3899. GradebookUtils::remove_resource_from_course_gradebook($linkId);
  3900. }
  3901. }
  3902. }
  3903. /**
  3904. * Delete all work by student.
  3905. *
  3906. * @param int $userId
  3907. * @param array $courseInfo
  3908. *
  3909. * @return array return deleted items
  3910. */
  3911. function deleteAllWorkPerUser($userId, $courseInfo)
  3912. {
  3913. $deletedItems = [];
  3914. $workPerUser = getWorkPerUser($userId);
  3915. if (!empty($workPerUser)) {
  3916. foreach ($workPerUser as $work) {
  3917. $work = $work['work'];
  3918. foreach ($work->user_results as $userResult) {
  3919. $result = deleteWorkItem($userResult['id'], $courseInfo);
  3920. if ($result) {
  3921. $deletedItems[] = $userResult;
  3922. }
  3923. }
  3924. }
  3925. }
  3926. return $deletedItems;
  3927. }
  3928. /**
  3929. * @param int $item_id
  3930. * @param array course info
  3931. *
  3932. * @return bool
  3933. */
  3934. function deleteWorkItem($item_id, $courseInfo)
  3935. {
  3936. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3937. $TSTDPUBASG = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3938. $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
  3939. $is_allowed_to_edit = api_is_allowed_to_edit();
  3940. $file_deleted = false;
  3941. $item_id = intval($item_id);
  3942. $is_author = user_is_author($item_id);
  3943. $work_data = get_work_data_by_id($item_id);
  3944. $locked = api_resource_is_locked_by_gradebook($work_data['parent_id'], LINK_STUDENTPUBLICATION);
  3945. $course_id = $courseInfo['real_id'];
  3946. if (($is_allowed_to_edit && $locked == false) ||
  3947. (
  3948. $locked == false &&
  3949. $is_author &&
  3950. api_get_course_setting('student_delete_own_publication') == 1 &&
  3951. $work_data['qualificator_id'] == 0
  3952. )
  3953. ) {
  3954. // We found the current user is the author
  3955. $sql = "SELECT url, contains_file, user_id, session_id, parent_id
  3956. FROM $work_table
  3957. WHERE c_id = $course_id AND id = $item_id";
  3958. $result = Database::query($sql);
  3959. $row = Database::fetch_array($result);
  3960. $count = Database::num_rows($result);
  3961. if ($count > 0) {
  3962. // If the "considered_working_time" option is enabled, check
  3963. // whether some time should be removed from track_e_course_access
  3964. $consideredWorkingTime = api_get_configuration_value('considered_working_time');
  3965. if ($consideredWorkingTime) {
  3966. $userWorks = get_work_user_list(
  3967. 0,
  3968. 100,
  3969. null,
  3970. null,
  3971. $row['parent_id'],
  3972. null,
  3973. $row['user_id'],
  3974. false,
  3975. $course_id,
  3976. $row['session_id']
  3977. );
  3978. // We're only interested in deleting the time if this is the latest work sent
  3979. if (count($userWorks) == 1) {
  3980. // Get the "considered work time" defined for this work
  3981. $fieldValue = new ExtraFieldValue('work');
  3982. $resultExtra = $fieldValue->getAllValuesForAnItem(
  3983. $row['parent_id'],
  3984. true
  3985. );
  3986. $workingTime = null;
  3987. foreach ($resultExtra as $field) {
  3988. $field = $field['value'];
  3989. if ($consideredWorkingTime == $field->getField()->getVariable()) {
  3990. $workingTime = $field->getValue();
  3991. }
  3992. }
  3993. // If no time was defined, or a time of "0" was set, do nothing
  3994. if (!empty($workingTime)) {
  3995. $sessionId = empty($row['session_id']) ? 0 : $row['session_id'];
  3996. // Getting false from the following call would mean the
  3997. // time record
  3998. Event::eventRemoveVirtualCourseTime(
  3999. $course_id,
  4000. $row['user_id'],
  4001. $sessionId,
  4002. $workingTime
  4003. );
  4004. }
  4005. }
  4006. } // end of considered_working_time check section
  4007. $sql = "UPDATE $work_table SET active = 2
  4008. WHERE c_id = $course_id AND id = $item_id";
  4009. Database::query($sql);
  4010. $sql = "DELETE FROM $TSTDPUBASG
  4011. WHERE c_id = $course_id AND publication_id = $item_id";
  4012. Database::query($sql);
  4013. api_item_property_update(
  4014. $courseInfo,
  4015. 'work',
  4016. $item_id,
  4017. 'DocumentDeleted',
  4018. api_get_user_id()
  4019. );
  4020. Event::addEvent(
  4021. LOG_WORK_FILE_DELETE,
  4022. LOG_WORK_DATA,
  4023. [
  4024. 'id' => $work_data['id'],
  4025. 'url' => $work_data['url'],
  4026. 'title' => $work_data['title'],
  4027. ],
  4028. null,
  4029. api_get_user_id(),
  4030. api_get_course_int_id(),
  4031. api_get_session_id()
  4032. );
  4033. $work = $row['url'];
  4034. if ($row['contains_file'] == 1) {
  4035. if (!empty($work)) {
  4036. if (api_get_setting('permanently_remove_deleted_files') === 'true') {
  4037. my_delete($currentCourseRepositorySys.'/'.$work);
  4038. $file_deleted = true;
  4039. } else {
  4040. $extension = pathinfo($work, PATHINFO_EXTENSION);
  4041. $new_dir = $work.'_DELETED_'.$item_id.'.'.$extension;
  4042. if (file_exists($currentCourseRepositorySys.'/'.$work)) {
  4043. rename($currentCourseRepositorySys.'/'.$work, $currentCourseRepositorySys.'/'.$new_dir);
  4044. $file_deleted = true;
  4045. }
  4046. }
  4047. }
  4048. } else {
  4049. $file_deleted = true;
  4050. }
  4051. }
  4052. }
  4053. return $file_deleted;
  4054. }
  4055. /**
  4056. * @param FormValidator $form
  4057. * @param array $defaults
  4058. * @param int $workId
  4059. *
  4060. * @return FormValidator
  4061. */
  4062. function getFormWork($form, $defaults = [], $workId = 0)
  4063. {
  4064. $sessionId = api_get_session_id();
  4065. if (!empty($defaults)) {
  4066. if (isset($defaults['submit'])) {
  4067. unset($defaults['submit']);
  4068. }
  4069. }
  4070. // Create the form that asks for the directory name
  4071. $form->addText('new_dir', get_lang('AssignmentName'));
  4072. $form->addHtmlEditor(
  4073. 'description',
  4074. get_lang('Description'),
  4075. false,
  4076. false,
  4077. getWorkDescriptionToolbar()
  4078. );
  4079. $form->addButtonAdvancedSettings('advanced_params', get_lang('AdvancedParameters'));
  4080. if (!empty($defaults) && (isset($defaults['enableEndDate']) || isset($defaults['enableExpiryDate']))) {
  4081. $form->addHtml('<div id="advanced_params_options" style="display:block">');
  4082. } else {
  4083. $form->addHtml('<div id="advanced_params_options" style="display:none">');
  4084. }
  4085. // QualificationOfAssignment
  4086. $form->addElement('text', 'qualification', get_lang('QualificationNumeric'));
  4087. if (($sessionId != 0 && Gradebook::is_active()) || $sessionId == 0) {
  4088. $form->addElement(
  4089. 'checkbox',
  4090. 'make_calification',
  4091. null,
  4092. get_lang('MakeQualifiable'),
  4093. [
  4094. 'id' => 'make_calification_id',
  4095. 'onclick' => "javascript: if(this.checked) { document.getElementById('option1').style.display='block';}else{document.getElementById('option1').style.display='none';}",
  4096. ]
  4097. );
  4098. } else {
  4099. // QualificationOfAssignment
  4100. $form->addElement('hidden', 'make_calification', false);
  4101. }
  4102. if (!empty($defaults) && isset($defaults['category_id'])) {
  4103. $form->addHtml('<div id=\'option1\' style="display:block">');
  4104. } else {
  4105. $form->addHtml('<div id=\'option1\' style="display:none">');
  4106. }
  4107. // Loading Gradebook select
  4108. GradebookUtils::load_gradebook_select_in_tool($form);
  4109. $form->addElement('text', 'weight', get_lang('WeightInTheGradebook'));
  4110. $form->addHtml('</div>');
  4111. $form->addElement('checkbox', 'enableExpiryDate', null, get_lang('EnableExpiryDate'), 'id="expiry_date"');
  4112. if (isset($defaults['enableExpiryDate']) && $defaults['enableExpiryDate']) {
  4113. $form->addHtml('<div id="option2" style="display: block;">');
  4114. } else {
  4115. $form->addHtml('<div id="option2" style="display: none;">');
  4116. }
  4117. $timeNextWeek = time() + 86400 * 7;
  4118. $nextWeek = substr(api_get_local_time($timeNextWeek), 0, 10);
  4119. if (!isset($defaults['expires_on'])) {
  4120. $date = substr($nextWeek, 0, 10);
  4121. $defaults['expires_on'] = $date.' 23:59';
  4122. }
  4123. $form->addElement('date_time_picker', 'expires_on', get_lang('ExpiresAt'));
  4124. $form->addHtml('</div>');
  4125. $form->addElement('checkbox', 'enableEndDate', null, get_lang('EnableEndDate'), 'id="end_date"');
  4126. if (!isset($defaults['ends_on'])) {
  4127. $nextDay = substr(api_get_local_time($timeNextWeek + 86400), 0, 10);
  4128. $date = substr($nextDay, 0, 10);
  4129. $defaults['ends_on'] = $date.' 23:59';
  4130. }
  4131. if (isset($defaults['enableEndDate']) && $defaults['enableEndDate']) {
  4132. $form->addHtml('<div id="option3" style="display: block;">');
  4133. } else {
  4134. $form->addHtml('<div id="option3" style="display: none;">');
  4135. }
  4136. $form->addElement('date_time_picker', 'ends_on', get_lang('EndsAt'));
  4137. $form->addHtml('</div>');
  4138. $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar'));
  4139. $form->addElement('select', 'allow_text_assignment', get_lang('DocumentType'), getUploadDocumentType());
  4140. // Extra fields
  4141. $extraField = new ExtraField('work');
  4142. $extra = $extraField->addElements($form, $workId);
  4143. $htmlHeadXtra[] = '
  4144. <script>
  4145. $(function() {
  4146. '.$extra['jquery_ready_content'].'
  4147. });
  4148. </script>';
  4149. $form->addHtml('</div>');
  4150. $skillList = Skill::addSkillsToForm($form, ITEM_TYPE_STUDENT_PUBLICATION, $workId);
  4151. if (!empty($defaults)) {
  4152. $defaults['skills'] = array_keys($skillList);
  4153. $form->setDefaults($defaults);
  4154. }
  4155. return $form;
  4156. }
  4157. /**
  4158. * @return array
  4159. */
  4160. function getUploadDocumentType()
  4161. {
  4162. return [
  4163. 0 => get_lang('AllowFileOrText'),
  4164. 1 => get_lang('AllowOnlyText'),
  4165. 2 => get_lang('AllowOnlyFiles'),
  4166. ];
  4167. }
  4168. /**
  4169. * @param int $item_id
  4170. * @param array $course_info
  4171. *
  4172. * @return bool
  4173. */
  4174. function makeVisible($item_id, $course_info)
  4175. {
  4176. if (empty($course_info) || empty($item_id)) {
  4177. return false;
  4178. }
  4179. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4180. $course_id = $course_info['real_id'];
  4181. $item_id = intval($item_id);
  4182. $sql = "UPDATE $work_table SET accepted = 1
  4183. WHERE c_id = $course_id AND id = $item_id";
  4184. Database::query($sql);
  4185. api_item_property_update($course_info, 'work', $item_id, 'visible', api_get_user_id());
  4186. return true;
  4187. }
  4188. /**
  4189. * @param int $item_id
  4190. * @param array $course_info
  4191. *
  4192. * @return int
  4193. */
  4194. function makeInvisible($item_id, $course_info)
  4195. {
  4196. if (empty($course_info) || empty($item_id)) {
  4197. return false;
  4198. }
  4199. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4200. $item_id = intval($item_id);
  4201. $course_id = $course_info['real_id'];
  4202. $sql = "UPDATE $table
  4203. SET accepted = 0
  4204. WHERE c_id = $course_id AND id = '".$item_id."'";
  4205. Database::query($sql);
  4206. api_item_property_update(
  4207. $course_info,
  4208. 'work',
  4209. $item_id,
  4210. 'invisible',
  4211. api_get_user_id()
  4212. );
  4213. return true;
  4214. }
  4215. /**
  4216. * @param int $item_id
  4217. * @param string $path
  4218. * @param array $courseInfo
  4219. * @param int $groupId iid
  4220. * @param int $sessionId
  4221. *
  4222. * @return string
  4223. */
  4224. function generateMoveForm($item_id, $path, $courseInfo, $groupId, $sessionId)
  4225. {
  4226. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4227. $courseId = $courseInfo['real_id'];
  4228. $folders = [];
  4229. $session_id = intval($sessionId);
  4230. $groupId = intval($groupId);
  4231. $sessionCondition = empty($sessionId) ? " AND (session_id = 0 OR session_id IS NULL) " : " AND session_id='".$session_id."'";
  4232. $groupIid = 0;
  4233. if ($groupId) {
  4234. $groupInfo = GroupManager::get_group_properties($groupId);
  4235. $groupIid = $groupInfo['iid'];
  4236. }
  4237. $sql = "SELECT id, url, title
  4238. FROM $work_table
  4239. WHERE
  4240. c_id = $courseId AND
  4241. active IN (0, 1) AND
  4242. url LIKE '/%' AND
  4243. post_group_id = $groupIid
  4244. $sessionCondition";
  4245. $res = Database::query($sql);
  4246. while ($folder = Database::fetch_array($res)) {
  4247. $title = empty($folder['title']) ? basename($folder['url']) : $folder['title'];
  4248. $folders[$folder['id']] = $title;
  4249. }
  4250. return build_work_move_to_selector($folders, $path, $item_id);
  4251. }
  4252. /**
  4253. * @param int $workId
  4254. *
  4255. * @return string
  4256. */
  4257. function showStudentList($workId)
  4258. {
  4259. $columnModel = [
  4260. [
  4261. 'name' => 'student',
  4262. 'index' => 'student',
  4263. 'width' => '350px',
  4264. 'align' => 'left',
  4265. 'sortable' => 'false',
  4266. ],
  4267. [
  4268. 'name' => 'works',
  4269. 'index' => 'works',
  4270. 'align' => 'center',
  4271. 'sortable' => 'false',
  4272. ],
  4273. ];
  4274. $token = null;
  4275. $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student_list_overview&work_id='.$workId.'&'.api_get_cidreq();
  4276. $columns = [
  4277. get_lang('Students'),
  4278. get_lang('Works'),
  4279. ];
  4280. $order = api_is_western_name_order() ? 'firstname' : 'lastname';
  4281. $params = [
  4282. 'autowidth' => 'true',
  4283. 'height' => 'auto',
  4284. 'rowNum' => 5,
  4285. 'sortname' => $order,
  4286. 'sortorder' => 'asc',
  4287. ];
  4288. $html = '<script>
  4289. $(function() {
  4290. '.Display::grid_js('studentList', $url, $columns, $columnModel, $params, [], null, true).'
  4291. $("#workList").jqGrid(
  4292. "navGrid",
  4293. "#studentList_pager",
  4294. { edit: false, add: false, del: false },
  4295. { height:280, reloadAfterSubmit:false }, // edit options
  4296. { height:280, reloadAfterSubmit:false }, // add options
  4297. { width:500 } // search options
  4298. );
  4299. });
  4300. </script>';
  4301. $html .= Display::grid_html('studentList');
  4302. return $html;
  4303. }
  4304. /**
  4305. * @param string $courseCode
  4306. * @param int $sessionId
  4307. * @param int $groupId
  4308. * @param int $start
  4309. * @param int $limit
  4310. * @param string $sidx
  4311. * @param string $sord
  4312. * @param $getCount
  4313. *
  4314. * @return array|int
  4315. */
  4316. function getWorkUserList($courseCode, $sessionId, $groupId, $start, $limit, $sidx, $sord, $getCount = false)
  4317. {
  4318. if (!empty($groupId)) {
  4319. $userList = GroupManager::get_users(
  4320. $groupId,
  4321. false,
  4322. $start,
  4323. $limit,
  4324. $getCount,
  4325. null,
  4326. $sidx,
  4327. $sord
  4328. );
  4329. } else {
  4330. $limitString = null;
  4331. if (!empty($start) && !empty($limit)) {
  4332. $start = intval($start);
  4333. $limit = intval($limit);
  4334. $limitString = " LIMIT $start, $limit";
  4335. }
  4336. $orderBy = null;
  4337. if (!empty($sidx) && !empty($sord)) {
  4338. if (in_array($sidx, ['firstname', 'lastname'])) {
  4339. $orderBy = "ORDER BY $sidx $sord";
  4340. }
  4341. }
  4342. if (empty($sessionId)) {
  4343. $userList = CourseManager::get_user_list_from_course_code(
  4344. $courseCode,
  4345. $sessionId,
  4346. $limitString,
  4347. $orderBy,
  4348. STUDENT,
  4349. $getCount
  4350. );
  4351. } else {
  4352. $userList = CourseManager::get_user_list_from_course_code(
  4353. $courseCode,
  4354. $sessionId,
  4355. $limitString,
  4356. $orderBy,
  4357. 0,
  4358. $getCount
  4359. );
  4360. }
  4361. if ($getCount == false) {
  4362. $userList = array_keys($userList);
  4363. }
  4364. }
  4365. return $userList;
  4366. }
  4367. /**
  4368. * @param int $workId
  4369. * @param string $courseCode
  4370. * @param int $sessionId
  4371. * @param int $groupId
  4372. * @param int $start
  4373. * @param int $limit
  4374. * @param int $sidx
  4375. * @param string $sord
  4376. * @param bool $getCount
  4377. *
  4378. * @return array|int
  4379. */
  4380. function getWorkUserListData(
  4381. $workId,
  4382. $courseCode,
  4383. $sessionId,
  4384. $groupId,
  4385. $start,
  4386. $limit,
  4387. $sidx,
  4388. $sord,
  4389. $getCount = false
  4390. ) {
  4391. $my_folder_data = get_work_data_by_id($workId);
  4392. $workParents = [];
  4393. if (empty($my_folder_data)) {
  4394. $workParents = getWorkList($workId, $my_folder_data, null);
  4395. }
  4396. $workIdList = [];
  4397. if (!empty($workParents)) {
  4398. foreach ($workParents as $work) {
  4399. $workIdList[] = $work->id;
  4400. }
  4401. }
  4402. $courseInfo = api_get_course_info($courseCode);
  4403. $userList = getWorkUserList(
  4404. $courseCode,
  4405. $sessionId,
  4406. $groupId,
  4407. $start,
  4408. $limit,
  4409. $sidx,
  4410. $sord,
  4411. $getCount
  4412. );
  4413. if ($getCount) {
  4414. return $userList;
  4415. }
  4416. $results = [];
  4417. if (!empty($userList)) {
  4418. foreach ($userList as $userId) {
  4419. $user = api_get_user_info($userId);
  4420. $link = api_get_path(WEB_CODE_PATH).'work/student_work.php?'.api_get_cidreq().'&studentId='.$user['user_id'];
  4421. $url = Display::url(api_get_person_name($user['firstname'], $user['lastname']), $link);
  4422. $userWorks = 0;
  4423. if (!empty($workIdList)) {
  4424. $userWorks = getUniqueStudentAttempts(
  4425. $workIdList,
  4426. $groupId,
  4427. $courseInfo['real_id'],
  4428. $sessionId,
  4429. $user['user_id']
  4430. );
  4431. }
  4432. $works = $userWorks." / ".count($workParents);
  4433. $results[] = [
  4434. 'student' => $url,
  4435. 'works' => Display::url($works, $link),
  4436. ];
  4437. }
  4438. }
  4439. return $results;
  4440. }
  4441. /**
  4442. * @param int $id
  4443. * @param array $course_info
  4444. * @param bool $isCorrection
  4445. *
  4446. * @return bool
  4447. */
  4448. function downloadFile($id, $course_info, $isCorrection)
  4449. {
  4450. return getFile($id, $course_info, true, $isCorrection, true);
  4451. }
  4452. /**
  4453. * @param int $id
  4454. * @param array $course_info
  4455. * @param bool $download
  4456. * @param bool $isCorrection
  4457. * @param bool $forceAccessForCourseAdmins
  4458. *
  4459. * @return bool
  4460. */
  4461. function getFile($id, $course_info, $download = true, $isCorrection = false, $forceAccessForCourseAdmins = false)
  4462. {
  4463. $file = getFileContents($id, $course_info, 0, $isCorrection, $forceAccessForCourseAdmins);
  4464. if (!empty($file) && is_array($file)) {
  4465. return DocumentManager::file_send_for_download(
  4466. $file['path'],
  4467. $download,
  4468. $file['title']
  4469. );
  4470. }
  4471. return false;
  4472. }
  4473. /**
  4474. * Get the file contents for an assigment.
  4475. *
  4476. * @param int $id
  4477. * @param array $courseInfo
  4478. * @param int $sessionId
  4479. * @param bool $correction
  4480. * @param bool $forceAccessForCourseAdmins
  4481. *
  4482. * @return array|bool
  4483. */
  4484. function getFileContents($id, $courseInfo, $sessionId = 0, $correction = false, $forceAccessForCourseAdmins = false)
  4485. {
  4486. $id = (int) $id;
  4487. if (empty($courseInfo) || empty($id)) {
  4488. return false;
  4489. }
  4490. if (empty($sessionId)) {
  4491. $sessionId = api_get_session_id();
  4492. }
  4493. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4494. if (!empty($courseInfo['real_id'])) {
  4495. $sql = "SELECT *
  4496. FROM $table
  4497. WHERE c_id = ".$courseInfo['real_id']." AND id = $id";
  4498. $result = Database::query($sql);
  4499. if ($result && Database::num_rows($result)) {
  4500. $row = Database::fetch_array($result, 'ASSOC');
  4501. if ($correction) {
  4502. $row['url'] = $row['url_correction'];
  4503. }
  4504. if (empty($row['url'])) {
  4505. return false;
  4506. }
  4507. $full_file_name = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$row['url'];
  4508. $item_info = api_get_item_property_info(
  4509. api_get_course_int_id(),
  4510. 'work',
  4511. $row['id'],
  4512. $sessionId
  4513. );
  4514. if (empty($item_info)) {
  4515. return false;
  4516. }
  4517. $isAllow = allowOnlySubscribedUser(
  4518. api_get_user_id(),
  4519. $row['parent_id'],
  4520. $courseInfo['real_id'],
  4521. $forceAccessForCourseAdmins
  4522. );
  4523. if (empty($isAllow)) {
  4524. return false;
  4525. }
  4526. /*
  4527. field show_score in table course :
  4528. 0 => New documents are visible for all users
  4529. 1 => New documents are only visible for the teacher(s)
  4530. field visibility in table item_property :
  4531. 0 => eye closed, invisible for all students
  4532. 1 => eye open
  4533. field accepted in table c_student_publication :
  4534. 0 => eye closed, invisible for all students
  4535. 1 => eye open
  4536. ( We should have visibility == accepted, otherwise there is an
  4537. inconsistency in the Database)
  4538. field value in table c_course_setting :
  4539. 0 => Allow learners to delete their own publications = NO
  4540. 1 => Allow learners to delete their own publications = YES
  4541. +------------------+-------------------------+------------------------+
  4542. |Can download work?| doc visible for all = 0 | doc visible for all = 1|
  4543. +------------------+-------------------------+------------------------+
  4544. | visibility = 0 | editor only | editor only |
  4545. | | | |
  4546. +------------------+-------------------------+------------------------+
  4547. | visibility = 1 | editor | editor |
  4548. | | + owner of the work | + any student |
  4549. +------------------+-------------------------+------------------------+
  4550. (editor = teacher + admin + anybody with right api_is_allowed_to_edit)
  4551. */
  4552. $work_is_visible = $item_info['visibility'] == 1 && $row['accepted'] == 1;
  4553. $doc_visible_for_all = (int) $courseInfo['show_score'] === 0;
  4554. $is_editor = api_is_allowed_to_edit(true, true, true);
  4555. $student_is_owner_of_work = user_is_author($row['id'], api_get_user_id());
  4556. if (($forceAccessForCourseAdmins && $isAllow) ||
  4557. $is_editor ||
  4558. $student_is_owner_of_work ||
  4559. ($doc_visible_for_all && $work_is_visible)
  4560. ) {
  4561. $title = $row['title'];
  4562. if ($correction) {
  4563. $title = $row['title_correction'];
  4564. }
  4565. if (array_key_exists('filename', $row) && !empty($row['filename'])) {
  4566. $title = $row['filename'];
  4567. }
  4568. $title = str_replace(' ', '_', $title);
  4569. if ($correction == false) {
  4570. $userInfo = api_get_user_info($row['user_id']);
  4571. if ($userInfo) {
  4572. $date = api_get_local_time($row['sent_date']);
  4573. $date = str_replace([':', '-', ' '], '_', $date);
  4574. $title = $date.'_'.$userInfo['username'].'_'.$title;
  4575. }
  4576. }
  4577. if (Security::check_abs_path(
  4578. $full_file_name,
  4579. api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'
  4580. )) {
  4581. Event::event_download($title);
  4582. return [
  4583. 'path' => $full_file_name,
  4584. 'title' => $title,
  4585. 'title_correction' => $row['title_correction'],
  4586. ];
  4587. }
  4588. }
  4589. }
  4590. }
  4591. return false;
  4592. }
  4593. /**
  4594. * @param int $userId
  4595. * @param array $courseInfo
  4596. * @param string $format
  4597. *
  4598. * @return bool
  4599. */
  4600. function exportAllWork($userId, $courseInfo, $format = 'pdf')
  4601. {
  4602. $userInfo = api_get_user_info($userId);
  4603. if (empty($userInfo) || empty($courseInfo)) {
  4604. return false;
  4605. }
  4606. $workPerUser = getWorkPerUser($userId);
  4607. switch ($format) {
  4608. case 'pdf':
  4609. if (!empty($workPerUser)) {
  4610. $pdf = new PDF();
  4611. $content = null;
  4612. foreach ($workPerUser as $work) {
  4613. $work = $work['work'];
  4614. foreach ($work->user_results as $userResult) {
  4615. $content .= $userResult['title'];
  4616. // No need to use api_get_local_time()
  4617. $content .= $userResult['sent_date'];
  4618. $content .= $userResult['qualification'];
  4619. $content .= $userResult['description'];
  4620. }
  4621. }
  4622. if (!empty($content)) {
  4623. $pdf->content_to_pdf(
  4624. $content,
  4625. null,
  4626. api_replace_dangerous_char($userInfo['complete_name']),
  4627. $courseInfo['code']
  4628. );
  4629. }
  4630. }
  4631. break;
  4632. }
  4633. }
  4634. /**
  4635. * @param int $workId
  4636. * @param array $courseInfo
  4637. * @param int $sessionId
  4638. * @param string $format
  4639. *
  4640. * @return bool
  4641. */
  4642. function exportAllStudentWorkFromPublication(
  4643. $workId,
  4644. $courseInfo,
  4645. $sessionId,
  4646. $format = 'pdf'
  4647. ) {
  4648. if (empty($courseInfo)) {
  4649. return false;
  4650. }
  4651. $workData = get_work_data_by_id($workId);
  4652. if (empty($workData)) {
  4653. return false;
  4654. }
  4655. $assignment = get_work_assignment_by_id($workId);
  4656. $courseCode = $courseInfo['code'];
  4657. $header = get_lang('Course').': '.$courseInfo['title'];
  4658. $teachers = CourseManager::getTeacherListFromCourseCodeToString(
  4659. $courseCode
  4660. );
  4661. if (!empty($sessionId)) {
  4662. $sessionInfo = api_get_session_info($sessionId);
  4663. if (!empty($sessionInfo)) {
  4664. $header .= ' - '.$sessionInfo['name'];
  4665. $header .= '<br />'.$sessionInfo['description'];
  4666. $teachers = SessionManager::getCoachesByCourseSessionToString(
  4667. $sessionId,
  4668. $courseInfo['real_id']
  4669. );
  4670. }
  4671. }
  4672. $header .= '<br />'.get_lang('Teachers').': '.$teachers.'<br />';
  4673. $header .= '<br />'.get_lang('Date').': '.api_get_local_time().'<br />';
  4674. $header .= '<br />'.get_lang('WorkName').': '.$workData['title'].'<br />';
  4675. $content = null;
  4676. $expiresOn = null;
  4677. if (!empty($assignment) && isset($assignment['expires_on'])) {
  4678. $content .= '<br /><strong>'.get_lang('PostedExpirationDate').'</strong>: '.api_get_local_time($assignment['expires_on']);
  4679. $expiresOn = api_get_local_time($assignment['expires_on']);
  4680. }
  4681. if (!empty($workData['description'])) {
  4682. $content .= '<br /><strong>'.get_lang('Description').'</strong>: '.$workData['description'];
  4683. }
  4684. $workList = get_work_user_list(null, null, null, null, $workId);
  4685. switch ($format) {
  4686. case 'pdf':
  4687. if (!empty($workList)) {
  4688. $table = new HTML_Table(['class' => 'data_table']);
  4689. $headers = [
  4690. get_lang('Name'),
  4691. get_lang('User'),
  4692. get_lang('HandOutDateLimit'),
  4693. get_lang('SentDate'),
  4694. get_lang('FileName'),
  4695. get_lang('Score'),
  4696. get_lang('Feedback'),
  4697. ];
  4698. $column = 0;
  4699. foreach ($headers as $header) {
  4700. $table->setHeaderContents(0, $column, $header);
  4701. $column++;
  4702. }
  4703. $row = 1;
  4704. //$pdf->set_custom_header($header);
  4705. foreach ($workList as $work) {
  4706. $content .= '<hr />';
  4707. // getWorkComments need c_id
  4708. $work['c_id'] = $courseInfo['real_id'];
  4709. //$content .= get_lang('Date').': '.api_get_local_time($work['sent_date_from_db']).'<br />';
  4710. $score = null;
  4711. if (!empty($work['qualification_only'])) {
  4712. $score = $work['qualification_only'];
  4713. }
  4714. $comments = getWorkComments($work);
  4715. $feedback = null;
  4716. if (!empty($comments)) {
  4717. $content .= '<h4>'.get_lang('Feedback').': </h4>';
  4718. foreach ($comments as $comment) {
  4719. $feedback .= get_lang('User').': '.$comment['complete_name'].
  4720. '<br />';
  4721. $feedback .= $comment['comment'].'<br />';
  4722. }
  4723. }
  4724. $table->setCellContents($row, 0, strip_tags($workData['title']));
  4725. $table->setCellContents($row, 1, strip_tags($work['fullname']));
  4726. $table->setCellContents($row, 2, $expiresOn);
  4727. $table->setCellContents($row, 3, api_get_local_time($work['sent_date_from_db']));
  4728. $table->setCellContents($row, 4, strip_tags($work['title']));
  4729. $table->setCellContents($row, 5, $score);
  4730. $table->setCellContents($row, 6, $feedback);
  4731. $row++;
  4732. }
  4733. $content = $table->toHtml();
  4734. if (!empty($content)) {
  4735. $params = [
  4736. 'filename' => $workData['title'].'_'.api_get_local_time(),
  4737. 'pdf_title' => api_replace_dangerous_char($workData['title']),
  4738. 'course_code' => $courseInfo['code'],
  4739. ];
  4740. $pdf = new PDF('A4', null, $params);
  4741. $pdf->html_to_pdf_with_template($content);
  4742. }
  4743. exit;
  4744. }
  4745. break;
  4746. }
  4747. }
  4748. /**
  4749. * Downloads all user files per user.
  4750. *
  4751. * @param int $userId
  4752. * @param array $courseInfo
  4753. *
  4754. * @return bool
  4755. */
  4756. function downloadAllFilesPerUser($userId, $courseInfo)
  4757. {
  4758. $userInfo = api_get_user_info($userId);
  4759. if (empty($userInfo) || empty($courseInfo)) {
  4760. return false;
  4761. }
  4762. $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
  4763. $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/';
  4764. $zip = new PclZip($tempZipFile);
  4765. $workPerUser = getWorkPerUser($userId);
  4766. if (!empty($workPerUser)) {
  4767. $files = [];
  4768. foreach ($workPerUser as $work) {
  4769. $work = $work['work'];
  4770. foreach ($work->user_results as $userResult) {
  4771. if (empty($userResult['url']) || empty($userResult['contains_file'])) {
  4772. continue;
  4773. }
  4774. $data = getFileContents($userResult['id'], $courseInfo);
  4775. if (!empty($data) && isset($data['path'])) {
  4776. $files[basename($data['path'])] = [
  4777. 'title' => $data['title'],
  4778. 'path' => $data['path'],
  4779. ];
  4780. }
  4781. }
  4782. }
  4783. if (!empty($files)) {
  4784. Session::write('files', $files);
  4785. foreach ($files as $data) {
  4786. $zip->add(
  4787. $data['path'],
  4788. PCLZIP_OPT_REMOVE_PATH,
  4789. $coursePath,
  4790. PCLZIP_CB_PRE_ADD,
  4791. 'preAddAllWorkStudentCallback'
  4792. );
  4793. }
  4794. }
  4795. // Start download of created file
  4796. $name = basename(api_replace_dangerous_char($userInfo['complete_name'])).'.zip';
  4797. Event::event_download($name.'.zip (folder)');
  4798. if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
  4799. DocumentManager::file_send_for_download($tempZipFile, true, $name);
  4800. @unlink($tempZipFile);
  4801. exit;
  4802. }
  4803. }
  4804. exit;
  4805. }
  4806. /**
  4807. * @param $p_event
  4808. * @param array $p_header
  4809. *
  4810. * @return int
  4811. */
  4812. function preAddAllWorkStudentCallback($p_event, &$p_header)
  4813. {
  4814. $files = Session::read('files');
  4815. if (isset($files[basename($p_header['stored_filename'])])) {
  4816. $p_header['stored_filename'] = $files[basename($p_header['stored_filename'])]['title'];
  4817. return 1;
  4818. }
  4819. return 0;
  4820. }
  4821. /**
  4822. * Get all work created by a user.
  4823. *
  4824. * @param int $user_id
  4825. * @param int $courseId
  4826. * @param int $sessionId
  4827. *
  4828. * @return array
  4829. */
  4830. function getWorkCreatedByUser($user_id, $courseId, $sessionId)
  4831. {
  4832. $items = api_get_item_property_list_by_tool_by_user(
  4833. $user_id,
  4834. 'work',
  4835. $courseId,
  4836. $sessionId
  4837. );
  4838. $list = [];
  4839. if (!empty($items)) {
  4840. foreach ($items as $work) {
  4841. $item = get_work_data_by_id(
  4842. $work['ref'],
  4843. $courseId,
  4844. $sessionId
  4845. );
  4846. if (!empty($item)) {
  4847. $list[] = [
  4848. $item['title'],
  4849. api_get_local_time($work['insert_date']),
  4850. api_get_local_time($work['lastedit_date']),
  4851. ];
  4852. }
  4853. }
  4854. }
  4855. return $list;
  4856. }
  4857. /**
  4858. * @param array $courseInfo
  4859. * @param int $workId
  4860. *
  4861. * @return bool
  4862. */
  4863. function protectWork($courseInfo, $workId)
  4864. {
  4865. $userId = api_get_user_id();
  4866. $groupId = api_get_group_id();
  4867. $sessionId = api_get_session_id();
  4868. $workData = get_work_data_by_id($workId);
  4869. if (empty($workData) || empty($courseInfo)) {
  4870. api_not_allowed(true);
  4871. }
  4872. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  4873. return true;
  4874. }
  4875. $workId = $workData['id'];
  4876. if ($workData['active'] != 1) {
  4877. api_not_allowed(true);
  4878. }
  4879. $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $sessionId);
  4880. if ($visibility != 1) {
  4881. api_not_allowed(true);
  4882. }
  4883. $isAllow = allowOnlySubscribedUser($userId, $workId, $courseInfo['real_id']);
  4884. if (empty($isAllow)) {
  4885. api_not_allowed(true);
  4886. }
  4887. $groupInfo = GroupManager::get_group_properties($groupId);
  4888. if (!empty($groupId)) {
  4889. $showWork = GroupManager::user_has_access(
  4890. $userId,
  4891. $groupInfo['iid'],
  4892. GroupManager::GROUP_TOOL_WORK
  4893. );
  4894. if (!$showWork) {
  4895. api_not_allowed(true);
  4896. }
  4897. }
  4898. }
  4899. /**
  4900. * @param array $courseInfo
  4901. * @param array $work
  4902. */
  4903. function deleteCorrection($courseInfo, $work)
  4904. {
  4905. if (isset($work['url_correction']) && !empty($work['url_correction']) && isset($work['iid'])) {
  4906. $id = $work['iid'];
  4907. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4908. $sql = "UPDATE $table SET
  4909. url_correction = '',
  4910. title_correction = ''
  4911. WHERE iid = $id";
  4912. Database::query($sql);
  4913. $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
  4914. if (file_exists($coursePath.$work['url_correction'])) {
  4915. if (Security::check_abs_path($coursePath.$work['url_correction'], $coursePath)) {
  4916. unlink($coursePath.$work['url_correction']);
  4917. }
  4918. }
  4919. }
  4920. }
  4921. /**
  4922. * @param int $workId
  4923. *
  4924. * @return string
  4925. */
  4926. function workGetExtraFieldData($workId)
  4927. {
  4928. $sessionField = new ExtraField('work');
  4929. $extraFieldData = $sessionField->getDataAndFormattedValues($workId);
  4930. $result = '';
  4931. if (!empty($extraFieldData)) {
  4932. $result .= '<div class="well">';
  4933. foreach ($extraFieldData as $data) {
  4934. $result .= $data['text'].': <b>'.$data['value'].'</b>';
  4935. }
  4936. $result .= '</div>';
  4937. }
  4938. return $result;
  4939. }