work.lib.php 179 KB

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