work.lib.php 179 KB

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