work.lib.php 166 KB

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