work.lib.php 166 KB

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