work.lib.php 181 KB

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