work.lib.php 178 KB

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