work.lib.php 176 KB

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