work.lib.php 163 KB

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