work.lib.php 176 KB

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