work.lib.php 162 KB

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