work.lib.php 177 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581
  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. $(document).ready(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 = intval($start);
  1086. $limit = intval($limit);
  1087. $groupIid = 0;
  1088. if ($group_id) {
  1089. $groupInfo = GroupManager::get_group_properties($group_id);
  1090. $groupIid = $groupInfo['iid'];
  1091. }
  1092. $groupIid = (int) $groupIid;
  1093. // Get list from database
  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 = ".intval($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 array $where_condition
  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. $where_condition = null,
  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 = intval($work_id);
  1585. $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
  1586. $start = intval($start);
  1587. $limit = intval($limit);
  1588. if (!in_array($direction, ['asc', 'desc'])) {
  1589. $direction = 'desc';
  1590. }
  1591. $work_data = get_work_data_by_id($work_id, $courseId, $sessionId);
  1592. $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
  1593. $condition_session = api_get_session_condition(
  1594. $session_id,
  1595. true,
  1596. false,
  1597. 'work.session_id'
  1598. );
  1599. $locked = api_resource_is_locked_by_gradebook(
  1600. $work_id,
  1601. LINK_STUDENTPUBLICATION,
  1602. $course_info['code']
  1603. );
  1604. $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
  1605. api_get_user_id(),
  1606. $course_info
  1607. );
  1608. $groupIid = 0;
  1609. if ($group_id) {
  1610. $groupInfo = GroupManager::get_group_properties($group_id);
  1611. $groupIid = $groupInfo['iid'];
  1612. }
  1613. if (!empty($work_data)) {
  1614. if (!empty($group_id)) {
  1615. $extra_conditions = " work.post_group_id = '".intval($groupIid)."' ";
  1616. // set to select only messages posted by the user's group
  1617. } else {
  1618. $extra_conditions = " (work.post_group_id = '0' OR work.post_group_id is NULL) ";
  1619. }
  1620. if ($is_allowed_to_edit || $isDrhOfCourse) {
  1621. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1622. } else {
  1623. if (isset($course_info['show_score']) &&
  1624. $course_info['show_score'] == 1
  1625. ) {
  1626. $extra_conditions .= " AND (u.user_id = ".api_get_user_id()." AND work.active IN (0, 1)) ";
  1627. } else {
  1628. $extra_conditions .= ' AND work.active IN (0, 1) ';
  1629. }
  1630. }
  1631. $extra_conditions .= " AND parent_id = ".$work_id." ";
  1632. $select = 'SELECT DISTINCT
  1633. u.user_id,
  1634. work.id as id,
  1635. title as title,
  1636. description,
  1637. url,
  1638. sent_date,
  1639. contains_file,
  1640. has_properties,
  1641. view_properties,
  1642. qualification,
  1643. weight,
  1644. allow_text_assignment,
  1645. u.firstname,
  1646. u.lastname,
  1647. u.username,
  1648. parent_id,
  1649. accepted,
  1650. qualificator_id,
  1651. url_correction,
  1652. title_correction
  1653. ';
  1654. if ($getCount) {
  1655. $select = "SELECT DISTINCT count(u.user_id) as count ";
  1656. }
  1657. $work_assignment = get_work_assignment_by_id($work_id, $courseId);
  1658. if (!empty($studentId)) {
  1659. $where_condition .= " AND u.user_id = ".intval($studentId);
  1660. }
  1661. $sql = " $select
  1662. FROM $work_table work
  1663. INNER JOIN $user_table u
  1664. ON (work.user_id = u.user_id)
  1665. WHERE
  1666. work.c_id = $course_id AND
  1667. $extra_conditions
  1668. $where_condition
  1669. $condition_session
  1670. AND u.status != ".INVITEE."
  1671. ORDER BY $column $direction";
  1672. if (!empty($start) && !empty($limit)) {
  1673. $sql .= " LIMIT $start, $limit";
  1674. }
  1675. $result = Database::query($sql);
  1676. $works = [];
  1677. if ($getCount) {
  1678. $work = Database::fetch_array($result, 'ASSOC');
  1679. return $work['count'];
  1680. }
  1681. $url = api_get_path(WEB_CODE_PATH).'work/';
  1682. $unoconv = api_get_configuration_value('unoconv.binaries');
  1683. $loadingText = addslashes(get_lang('Loading'));
  1684. $uploadedText = addslashes(get_lang('Uploaded'));
  1685. $failsUploadText = addslashes(get_lang('UplNoFileUploaded'));
  1686. $failsUploadIcon = Display::return_icon(
  1687. 'closed-circle.png',
  1688. '',
  1689. [],
  1690. ICON_SIZE_TINY
  1691. );
  1692. $saveIcon = Display::return_icon(
  1693. 'save.png',
  1694. get_lang('Save'),
  1695. [],
  1696. ICON_SIZE_SMALL
  1697. );
  1698. $correctionIcon = Display::return_icon(
  1699. 'check-circle.png',
  1700. get_lang('Correction'),
  1701. null,
  1702. ICON_SIZE_SMALL
  1703. );
  1704. $correctionIconSmall = Display::return_icon(
  1705. 'check-circle.png',
  1706. get_lang('Correction'),
  1707. null,
  1708. ICON_SIZE_TINY
  1709. );
  1710. $rateIcon = Display::return_icon(
  1711. 'rate_work.png',
  1712. get_lang('CorrectAndRate'),
  1713. [],
  1714. ICON_SIZE_SMALL
  1715. );
  1716. $blockEdition = api_get_configuration_value('block_student_publication_edition');
  1717. $blockScoreEdition = api_get_configuration_value('block_student_publication_score_edition');
  1718. while ($work = Database::fetch_array($result, 'ASSOC')) {
  1719. $item_id = $work['id'];
  1720. // Get the author ID for that document from the item_property table
  1721. $is_author = false;
  1722. $can_read = false;
  1723. $owner_id = $work['user_id'];
  1724. /* Because a bug found when saving items using the api_item_property_update()
  1725. the field $item_property_data['insert_user_id'] is not reliable. */
  1726. if (!$is_allowed_to_edit && $owner_id == api_get_user_id()) {
  1727. $is_author = true;
  1728. }
  1729. if ($course_info['show_score'] == 0) {
  1730. $can_read = true;
  1731. }
  1732. $qualification_exists = false;
  1733. if (!empty($work_data['qualification']) &&
  1734. intval($work_data['qualification']) > 0
  1735. ) {
  1736. $qualification_exists = true;
  1737. }
  1738. $qualification_string = '';
  1739. if ($qualification_exists) {
  1740. if ($work['qualification'] == '') {
  1741. $qualification_string = Display::label('-');
  1742. } else {
  1743. $qualification_string = formatWorkScore($work['qualification'], $work_data['qualification']);
  1744. }
  1745. }
  1746. $work['qualification_score'] = $work['qualification'];
  1747. $add_string = '';
  1748. $time_expires = '';
  1749. if (!empty($work_assignment['expires_on'])) {
  1750. $time_expires = api_strtotime(
  1751. $work_assignment['expires_on'],
  1752. 'UTC'
  1753. );
  1754. }
  1755. if (!empty($work_assignment['expires_on']) &&
  1756. !empty($time_expires) && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) {
  1757. $add_string = Display::label(get_lang('Expired'), 'important').' - ';
  1758. }
  1759. if (($can_read && $work['accepted'] == '1') ||
  1760. ($is_author && in_array($work['accepted'], ['1', '0'])) ||
  1761. ($is_allowed_to_edit || api_is_drh())
  1762. ) {
  1763. // Firstname, lastname, username
  1764. $work['fullname'] = Display::div(
  1765. api_get_person_name($work['firstname'], $work['lastname']),
  1766. ['class' => 'work-name']
  1767. );
  1768. // Title
  1769. $work['title_clean'] = $work['title'];
  1770. $work['title'] = Security::remove_XSS($work['title']);
  1771. if (strlen($work['title']) > 30) {
  1772. $short_title = substr($work['title'], 0, 27).'...';
  1773. $work['title'] = Display::span($short_title, ['class' => 'work-title', 'title' => $work['title']]);
  1774. } else {
  1775. $work['title'] = Display::div($work['title'], ['class' => 'work-title']);
  1776. }
  1777. // Type.
  1778. $work['type'] = DocumentManager::build_document_icon_tag('file', $work['url']);
  1779. // File name.
  1780. $linkToDownload = '';
  1781. // If URL is present then there's a file to download keep BC.
  1782. if ($work['contains_file'] || !empty($work['url'])) {
  1783. $linkToDownload = '<a href="'.$url.'download.php?id='.$item_id.'&'.api_get_cidreq().'">'.$saveIcon.'</a> ';
  1784. }
  1785. $feedback = '';
  1786. $count = getWorkCommentCount($item_id, $course_info);
  1787. if (!is_null($count) && !empty($count)) {
  1788. if ($qualification_exists) {
  1789. $feedback .= ' ';
  1790. }
  1791. $feedback .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang(
  1792. 'View'
  1793. ).'">'.
  1794. $count.' '.Display::returnFontAwesomeIcon('comments-o').'</a> ';
  1795. }
  1796. $correction = '';
  1797. $hasCorrection = '';
  1798. if (!empty($work['url_correction'])) {
  1799. $hasCorrection = Display::url(
  1800. $correctionIcon,
  1801. api_get_path(WEB_CODE_PATH).'work/download.php?id='.$item_id.'&'.api_get_cidreq().'&correction=1'
  1802. );
  1803. }
  1804. if ($qualification_exists) {
  1805. $work['qualification'] = $qualification_string.$feedback;
  1806. } else {
  1807. $work['qualification'] = $qualification_string.$feedback.$hasCorrection;
  1808. }
  1809. $work['qualification_only'] = $qualification_string;
  1810. // Date.
  1811. $work_date = api_get_local_time($work['sent_date']);
  1812. $date = date_to_str_ago($work['sent_date']).' '.$work_date;
  1813. $work['formatted_date'] = $work_date.' '.$add_string;
  1814. $work['sent_date_from_db'] = $work['sent_date'];
  1815. $work['sent_date'] = '<div class="work-date" title="'.$date.'">'.
  1816. $add_string.' '.Display::dateToStringAgoAndLongDate($work['sent_date']).'</div>';
  1817. $work['status'] = $hasCorrection;
  1818. $work['has_correction'] = $hasCorrection;
  1819. // Actions.
  1820. $action = '';
  1821. if (api_is_allowed_to_edit()) {
  1822. if ($blockScoreEdition && !api_is_platform_admin() && !empty($work['qualification_score'])) {
  1823. $rateLink = '';
  1824. } else {
  1825. $rateLink = '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1826. $rateIcon.'</a> ';
  1827. }
  1828. $action .= $rateLink;
  1829. if ($unoconv && empty($work['contains_file'])) {
  1830. $action .= '<a f
  1831. href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=export_to_doc&item_id='.$item_id.'"
  1832. title="'.get_lang('ExportToDoc').'" >'.
  1833. Display::return_icon('export_doc.png', get_lang('ExportToDoc'), [], ICON_SIZE_SMALL).'</a> ';
  1834. }
  1835. $alreadyUploaded = '';
  1836. if (!empty($work['url_correction'])) {
  1837. $alreadyUploaded = '<br />'.$work['title_correction'].' '.$correctionIconSmall;
  1838. }
  1839. $correction = '
  1840. <form
  1841. id="file_upload_'.$item_id.'"
  1842. class="work_correction_file_upload file_upload_small fileinput-button"
  1843. 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"
  1844. >
  1845. <div id="progress_'.$item_id.'" class="text-center button-load">
  1846. '.addslashes(get_lang('ClickOrDropOneFileHere')).'
  1847. '.Display::return_icon('upload_file.png', get_lang('Correction'), [], ICON_SIZE_TINY).'
  1848. '.$alreadyUploaded.'
  1849. </div>
  1850. <input id="file_'.$item_id.'" type="file" name="file" class="" multiple>
  1851. </form>
  1852. ';
  1853. $correction .= "<script>
  1854. $(document).ready(function() {
  1855. $('.work_correction_file_upload').each(function () {
  1856. $(this).fileupload({
  1857. dropZone: $(this)
  1858. });
  1859. });
  1860. $('#file_upload_".$item_id."').fileupload({
  1861. add: function (e, data) {
  1862. $('#progress_$item_id').html();
  1863. //$('#file_$item_id').remove();
  1864. data.context = $('#progress_$item_id').html('$loadingText <br /> <em class=\"fa fa-spinner fa-pulse fa-fw\"></em>');
  1865. data.submit();
  1866. $(this).removeClass('hover');
  1867. },
  1868. dragover: function (e, data) {
  1869. $(this).addClass('hover');
  1870. },
  1871. done: function (e, data) {
  1872. if (data._response.result.name) {
  1873. $('#progress_$item_id').html('$uploadedText '+data._response.result.result+'<br />'+data._response.result.name);
  1874. } else {
  1875. $('#progress_$item_id').html('$failsUploadText $failsUploadIcon');
  1876. }
  1877. $(this).removeClass('hover');
  1878. }
  1879. });
  1880. $('#file_upload_".$item_id."').on('dragleave', function (e) {
  1881. // dragleave callback implementation
  1882. $(this).removeClass('hover');
  1883. });
  1884. });
  1885. </script>";
  1886. if ($locked) {
  1887. if ($qualification_exists) {
  1888. $action .= Display::return_icon(
  1889. 'edit_na.png',
  1890. get_lang('CorrectAndRate'),
  1891. [],
  1892. ICON_SIZE_SMALL
  1893. );
  1894. } else {
  1895. $action .= Display::return_icon('edit_na.png', get_lang('Comment'), [], ICON_SIZE_SMALL);
  1896. }
  1897. } else {
  1898. if ($blockEdition && !api_is_platform_admin()) {
  1899. $editLink = '';
  1900. } else {
  1901. if ($qualification_exists) {
  1902. $editLink = '<a href="'.$url.'edit.php?'.api_get_cidreq(
  1903. ).'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang(
  1904. 'Edit'
  1905. ).'" >'.
  1906. Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>';
  1907. } else {
  1908. $editLink = '<a href="'.$url.'edit.php?'.api_get_cidreq(
  1909. ).'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang(
  1910. 'Modify'
  1911. ).'">'.
  1912. Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>';
  1913. }
  1914. }
  1915. $action .= $editLink;
  1916. }
  1917. if ($work['contains_file']) {
  1918. if ($locked) {
  1919. $action .= Display::return_icon(
  1920. 'move_na.png',
  1921. get_lang('Move'),
  1922. [],
  1923. ICON_SIZE_SMALL
  1924. );
  1925. } else {
  1926. $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=move&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Move').'">'.
  1927. Display::return_icon('move.png', get_lang('Move'), [], ICON_SIZE_SMALL).'</a>';
  1928. }
  1929. }
  1930. if ($work['accepted'] == '1') {
  1931. $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').'" >'.
  1932. Display::return_icon('visible.png', get_lang('Invisible'), [], ICON_SIZE_SMALL).'</a>';
  1933. } else {
  1934. $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').'" >'.
  1935. Display::return_icon('invisible.png', get_lang('Visible'), [], ICON_SIZE_SMALL).'</a> ';
  1936. }
  1937. if ($locked) {
  1938. $action .= Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
  1939. } else {
  1940. $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').'" >'.
  1941. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
  1942. }
  1943. } elseif ($is_author && (empty($work['qualificator_id']) || $work['qualificator_id'] == 0)) {
  1944. $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
  1945. Display::return_icon('default.png', get_lang('View'), [], ICON_SIZE_SMALL).'</a>';
  1946. if (api_get_course_setting('student_delete_own_publication') == 1) {
  1947. if (api_is_allowed_to_session_edit(false, true)) {
  1948. $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'.
  1949. Display::return_icon('edit.png', get_lang('Comment'), [], ICON_SIZE_SMALL).'</a>';
  1950. }
  1951. $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').'" >'.
  1952. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
  1953. }
  1954. } else {
  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. }
  1958. // Status.
  1959. if (empty($work['qualificator_id'])) {
  1960. $qualificator_id = Display::label(get_lang('NotRevised'), 'warning');
  1961. } else {
  1962. $qualificator_id = Display::label(get_lang('Revised'), 'success');
  1963. }
  1964. $work['qualificator_id'] = $qualificator_id.' '.$hasCorrection;
  1965. $work['actions'] = '<div class="work-action">'.$linkToDownload.$action.'</div>';
  1966. $work['correction'] = $correction;
  1967. $works[] = $work;
  1968. }
  1969. }
  1970. return $works;
  1971. }
  1972. }
  1973. /**
  1974. * Send reminder to users who have not given the task.
  1975. *
  1976. * @param int
  1977. *
  1978. * @return array
  1979. *
  1980. * @author cvargas carlos.vargas@beeznest.com cfasanando, christian.fasanado@beeznest.com
  1981. */
  1982. function send_reminder_users_without_publication($task_data)
  1983. {
  1984. $_course = api_get_course_info();
  1985. $task_id = $task_data['id'];
  1986. $task_title = !empty($task_data['title']) ? $task_data['title'] : basename($task_data['url']);
  1987. $subject = '['.api_get_setting('siteName').'] ';
  1988. // The body can be as long as you wish, and any combination of text and variables
  1989. $content = get_lang('ReminderToSubmitPendingTask')."\n".get_lang('CourseName').' : '.$_course['name']."\n";
  1990. $content .= get_lang('WorkName').' : '.$task_title."\n";
  1991. $list_users = get_list_users_without_publication($task_id);
  1992. $mails_sent_to = [];
  1993. foreach ($list_users as $user) {
  1994. $name_user = api_get_person_name($user[1], $user[0], null, PERSON_NAME_EMAIL_ADDRESS);
  1995. $dear_line = get_lang('Dear')." ".api_get_person_name($user[1], $user[0]).", \n\n";
  1996. $body = $dear_line.$content;
  1997. MessageManager::send_message($user[3], $subject, $body);
  1998. $mails_sent_to[] = $name_user;
  1999. }
  2000. return $mails_sent_to;
  2001. }
  2002. /**
  2003. * @param int $workId The work ID
  2004. * @param int $courseId The course ID
  2005. * @param int $sessionId Optional. The session ID
  2006. */
  2007. function sendEmailToDrhOnHomeworkCreation($workId, $courseId, $sessionId = 0)
  2008. {
  2009. $courseInfo = api_get_course_info_by_id($courseId);
  2010. $assignment = get_work_assignment_by_id($workId, $courseId);
  2011. $work = get_work_data_by_id($workId, $courseId, $sessionId);
  2012. $workInfo = array_merge($assignment, $work);
  2013. if (empty($sessionId)) {
  2014. $students = CourseManager::get_student_list_from_course_code($courseInfo['code']);
  2015. } else {
  2016. $students = CourseManager::get_student_list_from_course_code($courseInfo['code'], true, $sessionId);
  2017. }
  2018. $bodyView = new Template(null, false, false, false, false, false);
  2019. foreach ($students as $student) {
  2020. $studentInfo = api_get_user_info($student['user_id']);
  2021. if (empty($studentInfo)) {
  2022. continue;
  2023. }
  2024. $hrms = UserManager::getDrhListFromUser($student['id']);
  2025. foreach ($hrms as $hrm) {
  2026. $hrmName = api_get_person_name($hrm['firstname'], $hrm['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
  2027. $bodyView->assign('hrm_name', $hrmName);
  2028. $bodyView->assign('student', $studentInfo);
  2029. $bodyView->assign('course', $courseInfo);
  2030. $bodyView->assign('course_link', api_get_course_url($courseInfo['code'], $sessionId));
  2031. $bodyView->assign('work', $workInfo);
  2032. $bodyTemplate = $bodyView->get_template('mail/new_work_alert_hrm.tpl');
  2033. MessageManager::send_message(
  2034. $hrm['id'],
  2035. sprintf(
  2036. get_lang('StudentXHasBeenAssignedNewWorkInCourseY'),
  2037. $student['firstname'],
  2038. $courseInfo['title']
  2039. ),
  2040. $bodyView->fetch($bodyTemplate)
  2041. );
  2042. }
  2043. }
  2044. }
  2045. /**
  2046. * Sends an email to the students of a course when a homework is created.
  2047. *
  2048. * @param int $workId
  2049. * @param int $courseId
  2050. * @param int $sessionId
  2051. *
  2052. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  2053. * @author Julio Montoya <gugli100@gmail.com> Adding session support - 2011
  2054. */
  2055. function sendEmailToStudentsOnHomeworkCreation($workId, $courseId, $sessionId = 0)
  2056. {
  2057. $courseInfo = api_get_course_info_by_id($courseId);
  2058. $courseCode = $courseInfo['code'];
  2059. // Get the students of the course
  2060. if (empty($sessionId)) {
  2061. $students = CourseManager::get_student_list_from_course_code($courseCode);
  2062. } else {
  2063. $students = CourseManager::get_student_list_from_course_code($courseCode, true, $sessionId);
  2064. }
  2065. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('HomeworkCreated');
  2066. $currentUser = api_get_user_info(api_get_user_id());
  2067. if (!empty($students)) {
  2068. foreach ($students as $student) {
  2069. $user_info = api_get_user_info($student['user_id']);
  2070. if (!empty($user_info)) {
  2071. $link = api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId;
  2072. $emailbody = get_lang('Dear')." ".$user_info['complete_name'].",\n\n";
  2073. $emailbody .= get_lang('HomeworkHasBeenCreatedForTheCourse')." ".$courseCode.". "."\n\n".
  2074. '<a href="'.$link.'">'.get_lang('PleaseCheckHomeworkPage').'</a>';
  2075. $emailbody .= "\n\n".$currentUser['complete_name'];
  2076. $additionalParameters = [
  2077. 'smsType' => SmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE,
  2078. 'userId' => $student['user_id'],
  2079. 'courseTitle' => $courseCode,
  2080. 'link' => $link,
  2081. ];
  2082. MessageManager::send_message_simple(
  2083. $student['user_id'],
  2084. $emailsubject,
  2085. $emailbody,
  2086. null,
  2087. false,
  2088. false,
  2089. $additionalParameters,
  2090. false
  2091. );
  2092. }
  2093. }
  2094. }
  2095. }
  2096. /**
  2097. * @param string $url
  2098. *
  2099. * @return bool
  2100. */
  2101. function is_work_exist_by_url($url)
  2102. {
  2103. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2104. $url = Database::escape_string($url);
  2105. $sql = "SELECT id FROM $table WHERE url='$url'";
  2106. $result = Database::query($sql);
  2107. if (Database::num_rows($result) > 0) {
  2108. $row = Database::fetch_row($result);
  2109. if (empty($row)) {
  2110. return false;
  2111. } else {
  2112. return true;
  2113. }
  2114. } else {
  2115. return false;
  2116. }
  2117. }
  2118. /**
  2119. * Check if a user is the author of a work document.
  2120. *
  2121. * @param int $itemId
  2122. * @param int $userId
  2123. * @param int $courseId
  2124. * @param int $sessionId
  2125. *
  2126. * @return bool
  2127. */
  2128. function user_is_author($itemId, $userId = null, $courseId = 0, $sessionId = 0)
  2129. {
  2130. if (empty($itemId)) {
  2131. return false;
  2132. }
  2133. if (empty($userId)) {
  2134. $userId = api_get_user_id();
  2135. }
  2136. $isAuthor = false;
  2137. $is_allowed_to_edit = api_is_allowed_to_edit();
  2138. if ($is_allowed_to_edit) {
  2139. $isAuthor = true;
  2140. } else {
  2141. if (empty($courseId)) {
  2142. $courseId = api_get_course_int_id();
  2143. }
  2144. if (empty($sessionId)) {
  2145. $sessionId = api_get_session_id();
  2146. }
  2147. $data = api_get_item_property_info($courseId, 'work', $itemId, $sessionId);
  2148. if ($data['insert_user_id'] == $userId) {
  2149. $isAuthor = true;
  2150. }
  2151. $workData = get_work_data_by_id($itemId);
  2152. if ($workData['user_id'] == $userId) {
  2153. $isAuthor = true;
  2154. }
  2155. }
  2156. if (!$isAuthor) {
  2157. return false;
  2158. }
  2159. return $isAuthor;
  2160. }
  2161. /**
  2162. * Get list of users who have not given the task.
  2163. *
  2164. * @param int
  2165. * @param int
  2166. *
  2167. * @return array
  2168. *
  2169. * @author cvargas
  2170. * @author Julio Montoya <gugli100@gmail.com> Fixing query
  2171. */
  2172. function get_list_users_without_publication($task_id, $studentId = 0)
  2173. {
  2174. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2175. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2176. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2177. $session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2178. $users = getAllUserToWork($task_id, api_get_course_int_id());
  2179. $users = array_column($users, 'user_id');
  2180. // Condition for the session
  2181. $session_id = api_get_session_id();
  2182. $course_id = api_get_course_int_id();
  2183. $task_id = intval($task_id);
  2184. $sessionCondition = api_get_session_condition($session_id);
  2185. if ($session_id == 0) {
  2186. $sql = "SELECT user_id as id FROM $work_table
  2187. WHERE
  2188. c_id = $course_id AND
  2189. parent_id = '$task_id' AND
  2190. active IN (0, 1)";
  2191. } else {
  2192. $sql = "SELECT user_id as id FROM $work_table
  2193. WHERE
  2194. c_id = $course_id AND
  2195. parent_id = '$task_id' $sessionCondition AND
  2196. active IN (0, 1)";
  2197. }
  2198. $result = Database::query($sql);
  2199. $users_with_tasks = [];
  2200. while ($row = Database::fetch_array($result)) {
  2201. $users_with_tasks[] = $row['id'];
  2202. }
  2203. if ($session_id == 0) {
  2204. $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
  2205. FROM $table_course_user AS cu, $table_user AS u
  2206. WHERE u.status != 1 and cu.c_id='".$course_id."' AND u.user_id = cu.user_id";
  2207. } else {
  2208. $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
  2209. FROM $session_course_rel_user AS cu, $table_user AS u
  2210. WHERE
  2211. u.status != 1 AND
  2212. cu.c_id='".$course_id."' AND
  2213. u.user_id = cu.user_id AND
  2214. cu.session_id = '".$session_id."'";
  2215. }
  2216. if (!empty($studentId)) {
  2217. $sql_users .= " AND u.user_id = ".intval($studentId);
  2218. }
  2219. $group_id = api_get_group_id();
  2220. $new_group_user_list = [];
  2221. if ($group_id) {
  2222. $groupInfo = GroupManager::get_group_properties($group_id);
  2223. $group_user_list = GroupManager::get_subscribed_users($groupInfo);
  2224. if (!empty($group_user_list)) {
  2225. foreach ($group_user_list as $group_user) {
  2226. $new_group_user_list[] = $group_user['user_id'];
  2227. }
  2228. }
  2229. }
  2230. $result_users = Database::query($sql_users);
  2231. $users_without_tasks = [];
  2232. while ($rowUsers = Database::fetch_array($result_users)) {
  2233. $userId = $rowUsers['user_id'];
  2234. if (in_array($userId, $users_with_tasks)) {
  2235. continue;
  2236. }
  2237. if ($group_id && !in_array($userId, $new_group_user_list)) {
  2238. continue;
  2239. }
  2240. if (!empty($users)) {
  2241. if (!in_array($userId, $users)) {
  2242. continue;
  2243. }
  2244. }
  2245. $row_users = [];
  2246. $row_users[0] = $rowUsers['lastname'];
  2247. $row_users[1] = $rowUsers['firstname'];
  2248. $row_users[2] = Display::encrypted_mailto_link($rowUsers['email']);
  2249. $row_users[3] = $userId;
  2250. $users_without_tasks[] = $row_users;
  2251. }
  2252. return $users_without_tasks;
  2253. }
  2254. /**
  2255. * Display list of users who have not given the task.
  2256. *
  2257. * @param int task id
  2258. * @param int $studentId
  2259. *
  2260. * @author cvargas carlos.vargas@beeznest.com cfasanando, christian.fasanado@beeznest.com
  2261. * @author Julio Montoya <gugli100@gmail.com> Fixes
  2262. */
  2263. function display_list_users_without_publication($task_id, $studentId = null)
  2264. {
  2265. $origin = api_get_origin();
  2266. $table_header[] = [get_lang('LastName'), true];
  2267. $table_header[] = [get_lang('FirstName'), true];
  2268. $table_header[] = [get_lang('Email'), true];
  2269. $data = get_list_users_without_publication($task_id);
  2270. $sorting_options = [];
  2271. $sorting_options['column'] = 1;
  2272. $paging_options = [];
  2273. $my_params = [];
  2274. if (isset($_GET['edit_dir'])) {
  2275. $my_params['edit_dir'] = Security::remove_XSS($_GET['edit_dir']);
  2276. }
  2277. if (isset($_GET['list'])) {
  2278. $my_params['list'] = Security::remove_XSS($_GET['list']);
  2279. }
  2280. $my_params['origin'] = $origin;
  2281. $my_params['id'] = intval($_GET['id']);
  2282. //$column_show
  2283. $column_show[] = 1;
  2284. $column_show[] = 1;
  2285. $column_show[] = 1;
  2286. Display::display_sortable_config_table(
  2287. 'work',
  2288. $table_header,
  2289. $data,
  2290. $sorting_options,
  2291. $paging_options,
  2292. $my_params,
  2293. $column_show
  2294. );
  2295. }
  2296. /**
  2297. * @param int $documentId
  2298. * @param int $workId
  2299. * @param int $courseId
  2300. */
  2301. function addDocumentToWork($documentId, $workId, $courseId)
  2302. {
  2303. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2304. $params = [
  2305. 'document_id' => $documentId,
  2306. 'work_id' => $workId,
  2307. 'c_id' => $courseId,
  2308. ];
  2309. Database::insert($table, $params);
  2310. }
  2311. /**
  2312. * @param int $documentId
  2313. * @param int $workId
  2314. * @param int $courseId
  2315. *
  2316. * @return array
  2317. */
  2318. function getDocumentToWork($documentId, $workId, $courseId)
  2319. {
  2320. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2321. $params = [
  2322. 'document_id = ? and work_id = ? and c_id = ?' => [$documentId, $workId, $courseId],
  2323. ];
  2324. return Database::select('*', $table, ['where' => $params]);
  2325. }
  2326. /**
  2327. * @param int $documentId
  2328. * @param int $workId
  2329. * @param int $courseId
  2330. * @param int $sessionId
  2331. * @param int $userId
  2332. * @param int $active
  2333. *
  2334. * @return array
  2335. */
  2336. function getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId, $active = 1)
  2337. {
  2338. $workRel = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2339. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2340. $documentId = intval($documentId);
  2341. $workId = intval($workId);
  2342. $courseId = intval($courseId);
  2343. $userId = intval($userId);
  2344. $sessionId = intval($sessionId);
  2345. $active = intval($active);
  2346. $sessionCondition = api_get_session_condition($sessionId);
  2347. $sql = "SELECT w.* FROM $work w
  2348. INNER JOIN $workRel rel
  2349. ON (w.parent_id = rel.work_id)
  2350. WHERE
  2351. w.document_id = $documentId AND
  2352. w.parent_id = $workId AND
  2353. w.c_id = $courseId
  2354. $sessionCondition AND
  2355. user_id = $userId AND
  2356. active = $active
  2357. ";
  2358. $result = Database::query($sql);
  2359. $workInfo = [];
  2360. if (Database::num_rows($result)) {
  2361. $workInfo = Database::fetch_array($result, 'ASSOC');
  2362. }
  2363. return $workInfo;
  2364. }
  2365. /**
  2366. * @param int $workId
  2367. * @param int $courseId
  2368. *
  2369. * @return array
  2370. */
  2371. function getAllDocumentToWork($workId, $courseId)
  2372. {
  2373. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2374. $params = [
  2375. 'work_id = ? and c_id = ?' => [$workId, $courseId],
  2376. ];
  2377. return Database::select('*', $table, ['where' => $params]);
  2378. }
  2379. /**
  2380. * @param int $documentId
  2381. * @param int $workId
  2382. * @param int $courseId
  2383. */
  2384. function deleteDocumentToWork($documentId, $workId, $courseId)
  2385. {
  2386. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
  2387. $params = [
  2388. 'document_id = ? and work_id = ? and c_id = ?' => [$documentId, $workId, $courseId],
  2389. ];
  2390. Database::delete($table, $params);
  2391. }
  2392. /**
  2393. * @param int $userId
  2394. * @param int $workId
  2395. * @param int $courseId
  2396. */
  2397. function addUserToWork($userId, $workId, $courseId)
  2398. {
  2399. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2400. $params = [
  2401. 'user_id' => $userId,
  2402. 'work_id' => $workId,
  2403. 'c_id' => $courseId,
  2404. ];
  2405. Database::insert($table, $params);
  2406. }
  2407. /**
  2408. * @param int $userId
  2409. * @param int $workId
  2410. * @param int $courseId
  2411. *
  2412. * @return array
  2413. */
  2414. function getUserToWork($userId, $workId, $courseId)
  2415. {
  2416. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2417. $params = [
  2418. 'user_id = ? and work_id = ? and c_id = ?' => [$userId, $workId, $courseId],
  2419. ];
  2420. return Database::select('*', $table, ['where' => $params]);
  2421. }
  2422. /**
  2423. * @param int $workId
  2424. * @param int $courseId
  2425. * @param bool $getCount
  2426. *
  2427. * @return array|int
  2428. */
  2429. function getAllUserToWork($workId, $courseId, $getCount = false)
  2430. {
  2431. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2432. $params = [
  2433. 'work_id = ? and c_id = ?' => [$workId, $courseId],
  2434. ];
  2435. if ($getCount) {
  2436. $count = 0;
  2437. $result = Database::select(
  2438. 'count(user_id) as count',
  2439. $table,
  2440. ['where' => $params],
  2441. 'simple'
  2442. );
  2443. if (!empty($result)) {
  2444. $count = intval($result['count']);
  2445. }
  2446. return $count;
  2447. } else {
  2448. return Database::select('*', $table, ['where' => $params]);
  2449. }
  2450. }
  2451. /**
  2452. * @param int $userId
  2453. * @param int $workId
  2454. * @param int $courseId
  2455. */
  2456. function deleteUserToWork($userId, $workId, $courseId)
  2457. {
  2458. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
  2459. $params = [
  2460. 'user_id = ? and work_id = ? and c_id = ?' => [$userId, $workId, $courseId],
  2461. ];
  2462. Database::delete($table, $params);
  2463. }
  2464. /**
  2465. * @param int $userId
  2466. * @param int $workId
  2467. * @param int $courseId
  2468. *
  2469. * @return bool
  2470. */
  2471. function userIsSubscribedToWork($userId, $workId, $courseId)
  2472. {
  2473. $subscribedUsers = getAllUserToWork($workId, $courseId);
  2474. if (empty($subscribedUsers)) {
  2475. return true;
  2476. } else {
  2477. $subscribedUsersList = [];
  2478. foreach ($subscribedUsers as $item) {
  2479. $subscribedUsersList[] = $item['user_id'];
  2480. }
  2481. if (in_array($userId, $subscribedUsersList)) {
  2482. return true;
  2483. }
  2484. }
  2485. return false;
  2486. }
  2487. /**
  2488. * Get the list of students that have to submit their work.
  2489. *
  2490. * @param int $workId The internal ID of the assignment
  2491. * @param int $courseId The course ID
  2492. * @param int $groupId The group ID, if any
  2493. * @param int $sessionId The session ID, if any
  2494. * @param bool $getCount Whether we want just the amount or the full result
  2495. *
  2496. * @return array|int An integer (if we just asked for the count) or an array of users
  2497. */
  2498. function getStudentSubscribedToWork(
  2499. $workId,
  2500. $courseId,
  2501. $groupId = null,
  2502. $sessionId = null,
  2503. $getCount = false
  2504. ) {
  2505. $usersInWork = null;
  2506. $usersInCourse = null;
  2507. if (empty($groupId)) {
  2508. $courseInfo = api_get_course_info_by_id($courseId);
  2509. $status = STUDENT;
  2510. if (!empty($sessionId)) {
  2511. $status = 0;
  2512. }
  2513. $usersInCourse = CourseManager::get_user_list_from_course_code(
  2514. $courseInfo['code'],
  2515. $sessionId,
  2516. null,
  2517. null,
  2518. $status,
  2519. $getCount
  2520. );
  2521. } else {
  2522. $usersInCourse = GroupManager::get_users(
  2523. $groupId,
  2524. false,
  2525. null,
  2526. null,
  2527. $getCount,
  2528. $courseId
  2529. );
  2530. }
  2531. $usersInWork = getAllUserToWork($workId, $courseId, $getCount);
  2532. if (empty($usersInWork)) {
  2533. return $usersInCourse;
  2534. } else {
  2535. return $usersInWork;
  2536. }
  2537. }
  2538. /**
  2539. * @param int $userId
  2540. * @param int $workId
  2541. * @param int $courseId
  2542. * @param bool $forceAccessForCourseAdmins
  2543. *
  2544. * @return bool
  2545. */
  2546. function allowOnlySubscribedUser($userId, $workId, $courseId, $forceAccessForCourseAdmins = false)
  2547. {
  2548. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  2549. return true;
  2550. }
  2551. if ($forceAccessForCourseAdmins) {
  2552. if (api_is_course_admin() || api_is_coach()) {
  2553. return true;
  2554. }
  2555. }
  2556. return userIsSubscribedToWork($userId, $workId, $courseId);
  2557. }
  2558. /**
  2559. * @param int $workId
  2560. * @param array $courseInfo
  2561. * @param int $documentId
  2562. *
  2563. * @return array
  2564. */
  2565. function getDocumentTemplateFromWork($workId, $courseInfo, $documentId)
  2566. {
  2567. $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
  2568. if (!empty($documents)) {
  2569. foreach ($documents as $doc) {
  2570. if ($documentId != $doc['document_id']) {
  2571. continue;
  2572. }
  2573. $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
  2574. $fileInfo = pathinfo($docData['path']);
  2575. if ($fileInfo['extension'] == 'html') {
  2576. if (file_exists($docData['absolute_path']) && is_file($docData['absolute_path'])) {
  2577. $docData['file_content'] = file_get_contents($docData['absolute_path']);
  2578. return $docData;
  2579. }
  2580. }
  2581. }
  2582. }
  2583. return [];
  2584. }
  2585. /**
  2586. * @param int $workId
  2587. * @param array $courseInfo
  2588. *
  2589. * @return string
  2590. */
  2591. function getAllDocumentsFromWorkToString($workId, $courseInfo)
  2592. {
  2593. $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
  2594. $content = null;
  2595. if (!empty($documents)) {
  2596. $content .= '<ul class="nav nav-list well">';
  2597. $content .= '<li class="nav-header">'.get_lang('Documents').'</li>';
  2598. foreach ($documents as $doc) {
  2599. $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
  2600. if ($docData) {
  2601. $content .= '<li><a target="_blank" href="'.$docData['url'].'">'.$docData['title'].'</a></li>';
  2602. }
  2603. }
  2604. $content .= '</ul><br />';
  2605. }
  2606. return $content;
  2607. }
  2608. /**
  2609. * Returns fck editor toolbar.
  2610. *
  2611. * @return array
  2612. */
  2613. function getWorkDescriptionToolbar()
  2614. {
  2615. return [
  2616. 'ToolbarStartExpanded' => 'true',
  2617. 'ToolbarSet' => 'Work',
  2618. 'Width' => '100%',
  2619. 'Height' => '400',
  2620. ];
  2621. }
  2622. /**
  2623. * @param array $work
  2624. *
  2625. * @return array
  2626. */
  2627. function getWorkComments($work)
  2628. {
  2629. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2630. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  2631. $courseId = intval($work['c_id']);
  2632. $workId = intval($work['id']);
  2633. if (empty($courseId) || empty($workId)) {
  2634. return [];
  2635. }
  2636. $sql = "SELECT
  2637. c.id,
  2638. c.user_id
  2639. FROM $commentTable c
  2640. INNER JOIN $userTable u
  2641. ON (u.id = c.user_id)
  2642. WHERE c_id = $courseId AND work_id = $workId
  2643. ORDER BY sent_at
  2644. ";
  2645. $result = Database::query($sql);
  2646. $comments = Database::store_result($result, 'ASSOC');
  2647. if (!empty($comments)) {
  2648. foreach ($comments as &$comment) {
  2649. $userInfo = api_get_user_info($comment['user_id']);
  2650. $comment['picture'] = $userInfo['avatar'];
  2651. $comment['complete_name'] = $userInfo['complete_name_with_username'];
  2652. $commentInfo = getWorkComment($comment['id']);
  2653. if (!empty($commentInfo)) {
  2654. $comment = array_merge($comment, $commentInfo);
  2655. }
  2656. }
  2657. }
  2658. return $comments;
  2659. }
  2660. /**
  2661. * Get total score from a work list.
  2662. *
  2663. * @param $workList
  2664. *
  2665. * @return int|null
  2666. */
  2667. function getTotalWorkScore($workList)
  2668. {
  2669. $count = 0;
  2670. foreach ($workList as $data) {
  2671. $count += $data['qualification_score'];
  2672. }
  2673. return $count;
  2674. }
  2675. /**
  2676. * Get comment count from a work list (docs sent by students).
  2677. *
  2678. * @param array $workList
  2679. * @param array $courseInfo
  2680. *
  2681. * @return int|null
  2682. */
  2683. function getTotalWorkComment($workList, $courseInfo = [])
  2684. {
  2685. if (empty($courseInfo)) {
  2686. $courseInfo = api_get_course_info();
  2687. }
  2688. $count = 0;
  2689. foreach ($workList as $data) {
  2690. $count += getWorkCommentCount($data['id'], $courseInfo);
  2691. }
  2692. return $count;
  2693. }
  2694. /**
  2695. * Get comment count for a specific work sent by a student.
  2696. *
  2697. * @param int $id
  2698. * @param array $courseInfo
  2699. *
  2700. * @return int
  2701. */
  2702. function getWorkCommentCount($id, $courseInfo = [])
  2703. {
  2704. if (empty($courseInfo)) {
  2705. $courseInfo = api_get_course_info();
  2706. }
  2707. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2708. $id = intval($id);
  2709. $sql = "SELECT count(*) as count
  2710. FROM $commentTable
  2711. WHERE work_id = $id AND c_id = ".$courseInfo['real_id'];
  2712. $result = Database::query($sql);
  2713. if (Database::num_rows($result)) {
  2714. $comment = Database::fetch_array($result);
  2715. return $comment['count'];
  2716. }
  2717. return 0;
  2718. }
  2719. /**
  2720. * Get comment count for a specific parent.
  2721. *
  2722. * @param int $parentId
  2723. * @param array $courseInfo
  2724. * @param int $sessionId
  2725. *
  2726. * @return int
  2727. */
  2728. function getWorkCommentCountFromParent(
  2729. $parentId,
  2730. $courseInfo = [],
  2731. $sessionId = 0
  2732. ) {
  2733. if (empty($courseInfo)) {
  2734. $courseInfo = api_get_course_info();
  2735. }
  2736. if (empty($sessionId)) {
  2737. $sessionId = api_get_session_id();
  2738. } else {
  2739. $sessionId = intval($sessionId);
  2740. }
  2741. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2742. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2743. $parentId = intval($parentId);
  2744. $sessionCondition = api_get_session_condition($sessionId, false, false, 'w.session_id');
  2745. $sql = "SELECT count(*) as count
  2746. FROM $commentTable c INNER JOIN $work w
  2747. ON c.c_id = w.c_id AND w.id = c.work_id
  2748. WHERE
  2749. $sessionCondition AND
  2750. parent_id = $parentId AND
  2751. w.c_id = ".$courseInfo['real_id'];
  2752. $result = Database::query($sql);
  2753. if (Database::num_rows($result)) {
  2754. $comment = Database::fetch_array($result);
  2755. return $comment['count'];
  2756. }
  2757. return 0;
  2758. }
  2759. /**
  2760. * Get last work information from parent.
  2761. *
  2762. * @param int $parentId
  2763. * @param array $courseInfo
  2764. * @param int $sessionId
  2765. *
  2766. * @return int
  2767. */
  2768. function getLastWorkStudentFromParent(
  2769. $parentId,
  2770. $courseInfo = [],
  2771. $sessionId = 0
  2772. ) {
  2773. if (empty($courseInfo)) {
  2774. $courseInfo = api_get_course_info();
  2775. }
  2776. if (empty($sessionId)) {
  2777. $sessionId = api_get_session_id();
  2778. } else {
  2779. $sessionId = intval($sessionId);
  2780. }
  2781. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2782. $sessionCondition = api_get_session_condition($sessionId, false);
  2783. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2784. $parentId = intval($parentId);
  2785. $sql = "SELECT w.*
  2786. FROM $commentTable c INNER JOIN $work w
  2787. ON c.c_id = w.c_id AND w.id = c.work_id
  2788. WHERE
  2789. $sessionCondition AND
  2790. parent_id = $parentId AND
  2791. w.c_id = ".$courseInfo['real_id']."
  2792. ORDER BY w.sent_date
  2793. LIMIT 1
  2794. ";
  2795. $result = Database::query($sql);
  2796. if (Database::num_rows($result)) {
  2797. $comment = Database::fetch_array($result, 'ASSOC');
  2798. return $comment;
  2799. }
  2800. return [];
  2801. }
  2802. /**
  2803. * Get last work information from parent.
  2804. *
  2805. * @param int $userId
  2806. * @param array $parentInfo
  2807. * @param array $courseInfo
  2808. * @param int $sessionId
  2809. *
  2810. * @return int
  2811. */
  2812. function getLastWorkStudentFromParentByUser(
  2813. $userId,
  2814. $parentInfo,
  2815. $courseInfo = [],
  2816. $sessionId = 0
  2817. ) {
  2818. if (empty($courseInfo)) {
  2819. $courseInfo = api_get_course_info();
  2820. }
  2821. if (empty($sessionId)) {
  2822. $sessionId = api_get_session_id();
  2823. } else {
  2824. $sessionId = intval($sessionId);
  2825. }
  2826. $userId = intval($userId);
  2827. $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  2828. if (empty($parentInfo)) {
  2829. return false;
  2830. }
  2831. $parentId = $parentInfo['id'];
  2832. $sessionCondition = api_get_session_condition($sessionId);
  2833. $sql = "SELECT *
  2834. FROM $work
  2835. WHERE
  2836. user_id = $userId
  2837. $sessionCondition AND
  2838. parent_id = $parentId AND
  2839. c_id = ".$courseInfo['real_id']."
  2840. ORDER BY sent_date DESC
  2841. LIMIT 1
  2842. ";
  2843. $result = Database::query($sql);
  2844. if (Database::num_rows($result)) {
  2845. $work = Database::fetch_array($result, 'ASSOC');
  2846. $work['qualification_rounded'] = formatWorkScore($work['qualification'], $parentInfo['qualification']);
  2847. return $work;
  2848. }
  2849. return [];
  2850. }
  2851. /**
  2852. * @param float $score
  2853. * @param int $weight
  2854. *
  2855. * @return string
  2856. */
  2857. function formatWorkScore($score, $weight)
  2858. {
  2859. $label = 'info';
  2860. $weight = (int) $weight;
  2861. $relativeScore = 0;
  2862. if (!empty($weight)) {
  2863. $relativeScore = $score / $weight;
  2864. }
  2865. if ($relativeScore < 0.5) {
  2866. $label = 'important';
  2867. } elseif ($relativeScore < 0.75) {
  2868. $label = 'warning';
  2869. }
  2870. $scoreBasedInModel = ExerciseLib::convertScoreToModel($relativeScore * 100);
  2871. if (empty($scoreBasedInModel)) {
  2872. $finalScore = api_number_format($score, 1).' / '.$weight;
  2873. return Display::label(
  2874. $finalScore,
  2875. $label
  2876. );
  2877. } else {
  2878. $finalScore = $scoreBasedInModel;
  2879. return $finalScore;
  2880. }
  2881. }
  2882. /**
  2883. * @param int $id comment id
  2884. * @param array $courseInfo
  2885. *
  2886. * @return string
  2887. */
  2888. function getWorkComment($id, $courseInfo = [])
  2889. {
  2890. if (empty($courseInfo)) {
  2891. $courseInfo = api_get_course_info();
  2892. }
  2893. if (empty($courseInfo['real_id'])) {
  2894. return [];
  2895. }
  2896. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2897. $id = intval($id);
  2898. $sql = "SELECT * FROM $commentTable
  2899. WHERE id = $id AND c_id = ".$courseInfo['real_id'];
  2900. $result = Database::query($sql);
  2901. $comment = [];
  2902. if (Database::num_rows($result)) {
  2903. $comment = Database::fetch_array($result, 'ASSOC');
  2904. $filePath = null;
  2905. $fileUrl = null;
  2906. $deleteUrl = null;
  2907. $fileName = null;
  2908. if (!empty($comment['file'])) {
  2909. $work = get_work_data_by_id($comment['work_id']);
  2910. $workParent = get_work_data_by_id($work['parent_id']);
  2911. $filePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/'.$workParent['url'].'/'.$comment['file'];
  2912. $fileUrl = api_get_path(WEB_CODE_PATH).'work/download_comment_file.php?comment_id='.$id.'&'.api_get_cidreq();
  2913. $deleteUrl = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$comment['work_id'].'&action=delete_attachment&comment_id='.$id;
  2914. $fileParts = explode('_', $comment['file']);
  2915. $fileName = str_replace($fileParts[0].'_'.$fileParts[1].'_', '', $comment['file']);
  2916. }
  2917. $comment['delete_file_url'] = $deleteUrl;
  2918. $comment['file_path'] = $filePath;
  2919. $comment['file_url'] = $fileUrl;
  2920. $comment['file_name_to_show'] = $fileName;
  2921. $comment['sent_at_with_label'] = Display::dateToStringAgoAndLongDate($comment['sent_at']);
  2922. }
  2923. return $comment;
  2924. }
  2925. /**
  2926. * @param int $id
  2927. * @param array $courseInfo
  2928. */
  2929. function deleteCommentFile($id, $courseInfo = [])
  2930. {
  2931. $workComment = getWorkComment($id, $courseInfo);
  2932. if (isset($workComment['file']) && !empty($workComment['file'])) {
  2933. if (file_exists($workComment['file_path'])) {
  2934. $result = my_delete($workComment['file_path']);
  2935. if ($result) {
  2936. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2937. $params = ['file' => ''];
  2938. Database::update(
  2939. $commentTable,
  2940. $params,
  2941. ['id = ? AND c_id = ? ' => [$workComment['id'], $workComment['c_id']]]
  2942. );
  2943. }
  2944. }
  2945. }
  2946. }
  2947. /**
  2948. * Adds a comments to the work document.
  2949. *
  2950. * @param array $courseInfo
  2951. * @param int $userId
  2952. * @param array $parentWork
  2953. * @param array $work
  2954. * @param array $data
  2955. *
  2956. * @return int
  2957. */
  2958. function addWorkComment($courseInfo, $userId, $parentWork, $work, $data)
  2959. {
  2960. $fileData = isset($data['attachment']) ? $data['attachment'] : null;
  2961. $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
  2962. // If no attachment and no comment then don't save comment
  2963. if (empty($fileData['name']) && empty($data['comment'])) {
  2964. return false;
  2965. }
  2966. $params = [
  2967. 'work_id' => $work['id'],
  2968. 'c_id' => $work['c_id'],
  2969. 'user_id' => $userId,
  2970. 'comment' => $data['comment'],
  2971. 'sent_at' => api_get_utc_datetime(),
  2972. ];
  2973. $commentId = Database::insert($commentTable, $params);
  2974. if ($commentId) {
  2975. Display::addFlash(
  2976. Display::return_message(get_lang('CommentAdded'))
  2977. );
  2978. $sql = "UPDATE $commentTable SET id = iid WHERE iid = $commentId";
  2979. Database::query($sql);
  2980. }
  2981. $userIdListToSend = [];
  2982. if (api_is_allowed_to_edit()) {
  2983. if (isset($data['send_email']) && $data['send_email']) {
  2984. // Teacher sends a feedback
  2985. $userIdListToSend = [$work['user_id']];
  2986. }
  2987. } else {
  2988. $sessionId = api_get_session_id();
  2989. if (empty($sessionId)) {
  2990. $teachers = CourseManager::get_teacher_list_from_course_code(
  2991. $courseInfo['code']
  2992. );
  2993. if (!empty($teachers)) {
  2994. $userIdListToSend = array_keys($teachers);
  2995. }
  2996. } else {
  2997. $teachers = SessionManager::getCoachesByCourseSession(
  2998. $sessionId,
  2999. $courseInfo['real_id']
  3000. );
  3001. if (!empty($teachers)) {
  3002. $userIdListToSend = array_values($teachers);
  3003. }
  3004. }
  3005. $sendNotification = api_get_course_setting('email_to_teachers_on_new_work_feedback', api_get_course_id());
  3006. if ($sendNotification != 1) {
  3007. $userIdListToSend = [];
  3008. }
  3009. }
  3010. $url = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$work['id'];
  3011. $subject = sprintf(get_lang('ThereIsANewWorkFeedback'), $parentWork['title']);
  3012. $content = sprintf(get_lang('ThereIsANewWorkFeedbackInWorkXHere'), $work['title'], $url);
  3013. if (!empty($data['comment'])) {
  3014. $content .= '<br /><b>'.get_lang('Comment').':</b><br />'.$data['comment'];
  3015. }
  3016. if (!empty($userIdListToSend)) {
  3017. foreach ($userIdListToSend as $userIdToSend) {
  3018. MessageManager::send_message_simple(
  3019. $userIdToSend,
  3020. $subject,
  3021. $content
  3022. );
  3023. }
  3024. }
  3025. if (!empty($commentId) && !empty($fileData)) {
  3026. $workParent = get_work_data_by_id($work['parent_id']);
  3027. if (!empty($workParent)) {
  3028. $uploadDir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work'.$workParent['url'];
  3029. $newFileName = 'comment_'.$commentId.'_'.php2phps(api_replace_dangerous_char($fileData['name']));
  3030. $newFilePath = $uploadDir.'/'.$newFileName;
  3031. $result = move_uploaded_file($fileData['tmp_name'], $newFilePath);
  3032. if ($result) {
  3033. $params = ['file' => $newFileName];
  3034. Database::update(
  3035. $commentTable,
  3036. $params,
  3037. ['id = ? AND c_id = ? ' => [$commentId, $work['c_id']]]
  3038. );
  3039. }
  3040. }
  3041. }
  3042. }
  3043. /**
  3044. * @param array $work
  3045. * @param array $workParent
  3046. *
  3047. * @return string
  3048. */
  3049. function getWorkCommentForm($work, $workParent)
  3050. {
  3051. $url = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$work['id'].'&action=send_comment&'.api_get_cidreq();
  3052. $form = new FormValidator(
  3053. 'work_comment',
  3054. 'post',
  3055. $url,
  3056. '',
  3057. ['enctype' => "multipart/form-data"]
  3058. );
  3059. $qualification = $workParent['qualification'];
  3060. if (api_is_allowed_to_edit()) {
  3061. if (!empty($qualification) && intval($qualification) > 0) {
  3062. $model = ExerciseLib::getCourseScoreModel();
  3063. if (empty($model)) {
  3064. $form->addFloat(
  3065. 'qualification',
  3066. [get_lang('Qualification'), " / ".$qualification],
  3067. false,
  3068. [],
  3069. false,
  3070. 0,
  3071. $qualification
  3072. );
  3073. } else {
  3074. ExerciseLib::addScoreModelInput(
  3075. $form,
  3076. 'qualification',
  3077. $qualification,
  3078. $work['qualification']
  3079. );
  3080. }
  3081. $form->addFile('file', get_lang('Correction'));
  3082. $form->setDefaults(['qualification' => $work['qualification']]);
  3083. }
  3084. }
  3085. Skill::addSkillsToUserForm($form, ITEM_TYPE_STUDENT_PUBLICATION, $workParent['id'], $work['user_id'], $work['id']);
  3086. $form->addHtmlEditor('comment', get_lang('Comment'), false);
  3087. $form->addFile('attachment', get_lang('Attachment'));
  3088. $form->addElement('hidden', 'id', $work['id']);
  3089. if (api_is_allowed_to_edit()) {
  3090. $form->addCheckBox(
  3091. 'send_email',
  3092. null,
  3093. get_lang('SendMailToStudent')
  3094. );
  3095. }
  3096. $form->addButtonSend(get_lang('Send'), 'button');
  3097. return $form->returnForm();
  3098. }
  3099. /**
  3100. * @param array $homework result of get_work_assignment_by_id()
  3101. *
  3102. * @return array
  3103. */
  3104. function getWorkDateValidationStatus($homework)
  3105. {
  3106. $message = null;
  3107. $has_expired = false;
  3108. $has_ended = false;
  3109. if (!empty($homework)) {
  3110. if (!empty($homework['expires_on']) || !empty($homework['ends_on'])) {
  3111. $time_now = time();
  3112. if (!empty($homework['expires_on'])) {
  3113. $time_expires = api_strtotime($homework['expires_on'], 'UTC');
  3114. $difference = $time_expires - $time_now;
  3115. if ($difference < 0) {
  3116. $has_expired = true;
  3117. }
  3118. }
  3119. if (empty($homework['expires_on'])) {
  3120. $has_expired = false;
  3121. }
  3122. if (!empty($homework['ends_on'])) {
  3123. $time_ends = api_strtotime($homework['ends_on'], 'UTC');
  3124. $difference2 = $time_ends - $time_now;
  3125. if ($difference2 < 0) {
  3126. $has_ended = true;
  3127. }
  3128. }
  3129. $ends_on = api_convert_and_format_date($homework['ends_on']);
  3130. $expires_on = api_convert_and_format_date($homework['expires_on']);
  3131. }
  3132. if ($has_ended) {
  3133. $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
  3134. } elseif ($has_expired) {
  3135. $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
  3136. } else {
  3137. if ($has_expired) {
  3138. $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
  3139. }
  3140. }
  3141. }
  3142. return [
  3143. 'message' => $message,
  3144. 'has_ended' => $has_ended,
  3145. 'has_expired' => $has_expired,
  3146. ];
  3147. }
  3148. /**
  3149. * @param FormValidator $form
  3150. * @param int $uploadFormType
  3151. */
  3152. function setWorkUploadForm($form, $uploadFormType = 0)
  3153. {
  3154. $form->addHeader(get_lang('UploadADocument'));
  3155. $form->addHidden('contains_file', 0, ['id' => 'contains_file_id']);
  3156. $form->addHidden('active', 1);
  3157. $form->addHidden('accepted', 1);
  3158. $form->addElement('text', 'title', get_lang('Title'), ['id' => 'file_upload']);
  3159. $form->addElement(
  3160. 'text',
  3161. 'extension',
  3162. get_lang('FileExtension'),
  3163. ['id' => 'file_extension', 'readonly' => 'readonly']
  3164. );
  3165. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  3166. switch ($uploadFormType) {
  3167. case 0:
  3168. // File and text.
  3169. $form->addElement(
  3170. 'file',
  3171. 'file',
  3172. get_lang('UploadADocument'),
  3173. 'size="40" onchange="updateDocumentTitle(this.value)"'
  3174. );
  3175. $form->addProgress();
  3176. $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
  3177. break;
  3178. case 1:
  3179. // Only text.
  3180. $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
  3181. $form->addRule('description', get_lang('ThisFieldIsRequired'), 'required');
  3182. break;
  3183. case 2:
  3184. // Only file.
  3185. $form->addElement(
  3186. 'file',
  3187. 'file',
  3188. get_lang('UploadADocument'),
  3189. 'size="40" onchange="updateDocumentTitle(this.value)"'
  3190. );
  3191. $form->addProgress();
  3192. $form->addRule('file', get_lang('ThisFieldIsRequired'), 'required');
  3193. break;
  3194. }
  3195. $form->addButtonUpload(get_lang('Upload'), 'submitWork');
  3196. }
  3197. /**
  3198. * @param array $my_folder_data
  3199. * @param array $_course
  3200. * @param bool $isCorrection
  3201. * @param array $workInfo
  3202. * @param array $file
  3203. *
  3204. * @return array
  3205. */
  3206. function uploadWork($my_folder_data, $_course, $isCorrection = false, $workInfo = [], $file = [])
  3207. {
  3208. if (isset($_FILES['file']) && !empty($_FILES['file'])) {
  3209. $file = $_FILES['file'];
  3210. }
  3211. if (empty($file['size'])) {
  3212. return [
  3213. 'error' => Display:: return_message(
  3214. get_lang('UplUploadFailedSizeIsZero'),
  3215. 'error'
  3216. ),
  3217. ];
  3218. }
  3219. $updir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work/'; //directory path to upload
  3220. // Try to add an extension to the file if it has'nt one
  3221. $filename = add_ext_on_mime(stripslashes($file['name']), $file['type']);
  3222. // Replace dangerous characters
  3223. $filename = api_replace_dangerous_char($filename);
  3224. // Transform any .php file in .phps fo security
  3225. $filename = php2phps($filename);
  3226. $filesize = filesize($file['tmp_name']);
  3227. if (empty($filesize)) {
  3228. return [
  3229. 'error' => Display::return_message(
  3230. get_lang('UplUploadFailedSizeIsZero'),
  3231. 'error'
  3232. ),
  3233. ];
  3234. } elseif (!filter_extension($new_file_name)) {
  3235. return [
  3236. 'error' => Display::return_message(
  3237. get_lang('UplUnableToSaveFileFilteredExtension'),
  3238. 'error'
  3239. ),
  3240. ];
  3241. }
  3242. $totalSpace = DocumentManager::documents_total_space($_course['real_id']);
  3243. $course_max_space = DocumentManager::get_course_quota($_course['code']);
  3244. $total_size = $filesize + $totalSpace;
  3245. if ($total_size > $course_max_space) {
  3246. return [
  3247. 'error' => Display::return_message(get_lang('NoSpace'), 'error'),
  3248. ];
  3249. }
  3250. // Compose a unique file name to avoid any conflict
  3251. $new_file_name = api_get_unique_id();
  3252. if ($isCorrection) {
  3253. if (!empty($workInfo['url'])) {
  3254. $new_file_name = basename($workInfo['url']).'_correction';
  3255. } else {
  3256. $new_file_name = $new_file_name.'_correction';
  3257. }
  3258. }
  3259. $curdirpath = basename($my_folder_data['url']);
  3260. // If we come from the group tools the groupid will be saved in $work_table
  3261. if (is_dir($updir.$curdirpath) || empty($curdirpath)) {
  3262. $result = move_uploaded_file(
  3263. $file['tmp_name'],
  3264. $updir.$curdirpath.'/'.$new_file_name
  3265. );
  3266. } else {
  3267. return [
  3268. 'error' => Display :: return_message(
  3269. get_lang('FolderDoesntExistsInFileSystem'),
  3270. 'error'
  3271. ),
  3272. ];
  3273. }
  3274. if ($result) {
  3275. $url = 'work/'.$curdirpath.'/'.$new_file_name;
  3276. } else {
  3277. return false;
  3278. }
  3279. return [
  3280. 'url' => $url,
  3281. 'filename' => $filename,
  3282. 'filesize' => $filesize,
  3283. 'error' => '',
  3284. ];
  3285. }
  3286. /**
  3287. * Send an e-mail to users related to this work (course teachers, usually, but
  3288. * might include other group members).
  3289. *
  3290. * @param int $workId
  3291. * @param array $courseInfo
  3292. * @param int $session_id
  3293. */
  3294. function sendAlertToUsers($workId, $courseInfo, $session_id)
  3295. {
  3296. $user_list = [];
  3297. $workData = get_work_data_by_id($workId, $courseInfo['real_id'], $session_id);
  3298. // last value is to check this is not "just" an edit
  3299. // YW Tis part serve to send a e-mail to the tutors when a new file is sent
  3300. $send = api_get_course_setting('email_alert_manager_on_new_doc');
  3301. if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_TEACHERS) {
  3302. // Lets predefine some variables. Be sure to change the from address!
  3303. if (empty($session_id)) {
  3304. //Teachers
  3305. $user_list = CourseManager::get_user_list_from_course_code(
  3306. api_get_course_id(),
  3307. null,
  3308. null,
  3309. null,
  3310. COURSEMANAGER
  3311. );
  3312. } else {
  3313. // Coaches
  3314. $user_list = CourseManager::get_user_list_from_course_code(
  3315. api_get_course_id(),
  3316. $session_id,
  3317. null,
  3318. null,
  3319. 2
  3320. );
  3321. }
  3322. }
  3323. if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_STUDENTS) {
  3324. if (!$session_id) {
  3325. $session_id = null;
  3326. }
  3327. $student = CourseManager::get_user_list_from_course_code(
  3328. api_get_course_id(),
  3329. $session_id,
  3330. null,
  3331. null,
  3332. STUDENT,
  3333. null,
  3334. null,
  3335. null,
  3336. null,
  3337. null,
  3338. [api_get_user_id()]
  3339. );
  3340. $user_list = array_merge($user_list, $student);
  3341. }
  3342. if ($send) {
  3343. $subject = "[".api_get_setting('siteName')."] ".get_lang('SendMailBody')."\n ".get_lang('CourseName').": ".$courseInfo['name']." ";
  3344. foreach ($user_list as $user_data) {
  3345. $to_user_id = $user_data['user_id'];
  3346. $user_info = api_get_user_info($to_user_id);
  3347. $message = get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$courseInfo['name']."\n";
  3348. $message .= get_lang('UserName')." : ".$user_info['complete_name']."\n";
  3349. $message .= get_lang('DateSent')." : ".api_format_date(api_get_local_time())."\n";
  3350. $url = api_get_path(WEB_CODE_PATH)."work/work.php?cidReq=".$courseInfo['code']."&id_session=".$session_id."&id=".$workData['id'];
  3351. $message .= get_lang('WorkName')." : ".$workData['title']."\n\n".'<a href="'.$url.'">'.get_lang('DownloadLink')."</a>\n";
  3352. MessageManager::send_message_simple(
  3353. $to_user_id,
  3354. $subject,
  3355. $message,
  3356. 0,
  3357. false,
  3358. false,
  3359. [],
  3360. false
  3361. );
  3362. }
  3363. }
  3364. }
  3365. /**
  3366. * Check if the current uploaded work filename already exists in the current assement.
  3367. *
  3368. * @param string $filename
  3369. * @param int $workId
  3370. *
  3371. * @return array
  3372. */
  3373. function checkExistingWorkFileName($filename, $workId)
  3374. {
  3375. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3376. $filename = Database::escape_string($filename);
  3377. $workId = (int) $workId;
  3378. $sql = "SELECT title FROM $table
  3379. WHERE parent_id = $workId AND title = '$filename' AND active = 1";
  3380. $result = Database::query($sql);
  3381. return Database::fetch_assoc($result);
  3382. }
  3383. /**
  3384. * @param array $workInfo
  3385. * @param array $values
  3386. * @param array $courseInfo
  3387. * @param int $sessionId
  3388. * @param int $groupId
  3389. * @param int $userId
  3390. * @param array $file
  3391. * @param bool $checkDuplicated
  3392. * @param bool $showFlashMessage
  3393. *
  3394. * @return string|null
  3395. */
  3396. function processWorkForm(
  3397. $workInfo,
  3398. $values,
  3399. $courseInfo,
  3400. $sessionId,
  3401. $groupId,
  3402. $userId,
  3403. $file = [],
  3404. $checkDuplicated = false,
  3405. $showFlashMessage = true
  3406. ) {
  3407. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3408. $courseId = $courseInfo['real_id'];
  3409. $groupId = (int) $groupId;
  3410. $sessionId = (int) $sessionId;
  3411. $userId = (int) $userId;
  3412. $extension = '';
  3413. if (isset($values['extension'])) {
  3414. $extension = $values['extension'];
  3415. } else {
  3416. $fileInfo = pathinfo($values['title']);
  3417. if (isset($fileInfo['extension']) && !empty($fileInfo['extension'])) {
  3418. $extension = '.'.$fileInfo['extension'];
  3419. $values['title'] = $fileInfo['filename'];
  3420. }
  3421. }
  3422. $title = $values['title'].$extension;
  3423. $description = isset($values['description']) ? $values['description'] : '';
  3424. $containsFile = isset($values['contains_file']) && !empty($values['contains_file']) ? (int) $values['contains_file'] : 0;
  3425. $saveWork = true;
  3426. $filename = null;
  3427. $url = null;
  3428. $filesize = null;
  3429. $workData = [];
  3430. $message = null;
  3431. if ($containsFile) {
  3432. $saveWork = false;
  3433. if ($checkDuplicated) {
  3434. if (checkExistingWorkFileName($file['name'], $workInfo['id'])) {
  3435. $saveWork = false;
  3436. $result['error'] = get_lang('YouAlreadySentThisFile');
  3437. $workData['error'] = get_lang('UplAlreadyExists');
  3438. } else {
  3439. $result = uploadWork($workInfo, $courseInfo, false, [], $file);
  3440. }
  3441. } else {
  3442. $result = uploadWork($workInfo, $courseInfo, false, [], $file);
  3443. }
  3444. if (isset($result['error'])) {
  3445. $saveWork = false;
  3446. if ($showFlashMessage) {
  3447. $message = $result['error'];
  3448. }
  3449. if (empty($result['error']) && isset($result['url']) && !empty($result['url'])) {
  3450. $saveWork = true;
  3451. }
  3452. }
  3453. }
  3454. if ($saveWork) {
  3455. $filename = isset($result['filename']) ? $result['filename'] : null;
  3456. if (empty($title)) {
  3457. $title = isset($result['title']) && !empty($result['title']) ? $result['title'] : get_lang('Untitled');
  3458. }
  3459. $filesize = isset($result['filesize']) ? $result['filesize'] : null;
  3460. $url = isset($result['url']) ? $result['url'] : null;
  3461. }
  3462. if (empty($title)) {
  3463. $title = get_lang('Untitled');
  3464. }
  3465. $groupIid = 0;
  3466. $groupInfo = [];
  3467. if ($groupId) {
  3468. $groupInfo = GroupManager::get_group_properties($groupId);
  3469. $groupIid = $groupInfo['iid'];
  3470. }
  3471. if ($saveWork) {
  3472. $active = '1';
  3473. $params = [
  3474. 'c_id' => $courseId,
  3475. 'url' => $url,
  3476. 'filetype' => 'file',
  3477. 'title' => $title,
  3478. 'description' => $description,
  3479. 'contains_file' => $containsFile,
  3480. 'active' => $active,
  3481. 'accepted' => '1',
  3482. 'qualificator_id' => 0,
  3483. 'document_id' => 0,
  3484. 'weight' => 0,
  3485. 'allow_text_assignment' => 0,
  3486. 'post_group_id' => $groupIid,
  3487. 'sent_date' => api_get_utc_datetime(),
  3488. 'parent_id' => $workInfo['id'],
  3489. 'session_id' => $sessionId ? $sessionId : null,
  3490. 'user_id' => $userId,
  3491. 'has_properties' => 0,
  3492. 'qualification' => 0,
  3493. //'filesize' => $filesize
  3494. ];
  3495. $workId = Database::insert($work_table, $params);
  3496. if ($workId) {
  3497. $sql = "UPDATE $work_table SET id = iid WHERE iid = $workId ";
  3498. Database::query($sql);
  3499. if (array_key_exists('filename', $workInfo) && !empty($filename)) {
  3500. $filename = Database::escape_string($filename);
  3501. $sql = "UPDATE $work_table SET
  3502. filename = '$filename'
  3503. WHERE iid = $workId";
  3504. Database::query($sql);
  3505. }
  3506. if (array_key_exists('document_id', $workInfo)) {
  3507. $documentId = isset($values['document_id']) ? intval($values['document_id']) : 0;
  3508. $sql = "UPDATE $work_table SET
  3509. document_id = '$documentId'
  3510. WHERE iid = $workId";
  3511. Database::query($sql);
  3512. }
  3513. api_item_property_update(
  3514. $courseInfo,
  3515. 'work',
  3516. $workId,
  3517. 'DocumentAdded',
  3518. $userId,
  3519. $groupInfo
  3520. );
  3521. sendAlertToUsers($workId, $courseInfo, $sessionId);
  3522. Event::event_upload($workId);
  3523. // The following feature requires the creation of a work-type
  3524. // extra_field and the following setting in the configuration file
  3525. // (until moved to the database). It allows te teacher to set a
  3526. // "considered work time", meaning the time we assume a student
  3527. // would have spent, approximately, to prepare the task before
  3528. // handing it in Chamilo, adding this time to the student total
  3529. // course use time, as a register of time spent *before* his
  3530. // connection to the platform to hand the work in.
  3531. $consideredWorkingTime = api_get_configuration_value('considered_working_time');
  3532. if (!empty($consideredWorkingTime)) {
  3533. // Get the "considered work time" defined for this work
  3534. $fieldValue = new ExtraFieldValue('work');
  3535. $resultExtra = $fieldValue->getAllValuesForAnItem(
  3536. $workInfo['iid'], //the ID of the work *folder*, not the document uploaded by the student
  3537. true
  3538. );
  3539. $workingTime = null;
  3540. foreach ($resultExtra as $field) {
  3541. $field = $field['value'];
  3542. if ($consideredWorkingTime == $field->getField()->getVariable()) {
  3543. $workingTime = $field->getValue();
  3544. }
  3545. }
  3546. // If no time was defined, or a time of "0" was set, do nothing
  3547. if (!empty($workingTime)) {
  3548. // If some time is set, get the list of docs handed in by
  3549. // this student (to make sure we count the time only once)
  3550. $userWorks = get_work_user_list(
  3551. 0,
  3552. 100,
  3553. null,
  3554. null,
  3555. $workInfo['id'],
  3556. null,
  3557. $userId,
  3558. false,
  3559. $courseId,
  3560. $sessionId
  3561. );
  3562. if (count($userWorks) == 1) {
  3563. // The student only uploaded one doc so far, so add the
  3564. // considered work time to his course connection time
  3565. Event::eventAddVirtualCourseTime($courseId, $userId, $sessionId, $workingTime);
  3566. }
  3567. }
  3568. }
  3569. $workData = get_work_data_by_id($workId);
  3570. if ($workData && $showFlashMessage) {
  3571. Display::addFlash(Display::return_message(get_lang('DocAdd')));
  3572. }
  3573. }
  3574. } else {
  3575. if ($showFlashMessage) {
  3576. Display::addFlash(
  3577. Display::return_message(
  3578. $message ? $message : get_lang('ImpossibleToSaveTheDocument'),
  3579. 'error'
  3580. )
  3581. );
  3582. }
  3583. }
  3584. return $workData;
  3585. }
  3586. /**
  3587. * Creates a new task (directory) in the assignment tool.
  3588. *
  3589. * @param array $formValues
  3590. * @param int $user_id
  3591. * @param array $courseInfo
  3592. * @param int $groupId
  3593. * @param int $sessionId
  3594. *
  3595. * @return bool|int
  3596. * @note $params can have the following elements, but should at least have the 2 first ones: (
  3597. * 'new_dir' => 'some-name',
  3598. * 'description' => 'some-desc',
  3599. * 'qualification' => 20 (e.g. 20),
  3600. * 'weight' => 50 (percentage) to add to gradebook (e.g. 50),
  3601. * 'allow_text_assignment' => 0/1/2,
  3602. *
  3603. * @todo Rename createAssignment or createWork, or something like that
  3604. */
  3605. function addDir($formValues, $user_id, $courseInfo, $groupId, $sessionId = 0)
  3606. {
  3607. $em = Database::getManager();
  3608. $user_id = (int) $user_id;
  3609. $groupId = (int) $groupId;
  3610. $sessionId = (int) $sessionId;
  3611. $groupIid = 0;
  3612. $groupInfo = [];
  3613. if (!empty($groupId)) {
  3614. $groupInfo = GroupManager::get_group_properties($groupId);
  3615. $groupIid = $groupInfo['iid'];
  3616. }
  3617. $session = $em->find('ChamiloCoreBundle:Session', $sessionId);
  3618. $base_work_dir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work';
  3619. $course_id = $courseInfo['real_id'];
  3620. $directory = api_replace_dangerous_char($formValues['new_dir']);
  3621. $directory = disable_dangerous_file($directory);
  3622. $created_dir = create_unexisting_work_directory($base_work_dir, $directory);
  3623. if (empty($created_dir)) {
  3624. return false;
  3625. }
  3626. $enableEndDate = isset($formValues['enableEndDate']) ? true : false;
  3627. $enableExpiryDate = isset($formValues['enableExpiryDate']) ? true : false;
  3628. if ($enableEndDate && $enableExpiryDate) {
  3629. if ($formValues['expires_on'] > $formValues['ends_on']) {
  3630. Display::addFlash(
  3631. Display::return_message(
  3632. get_lang('DateExpiredNotBeLessDeadLine'),
  3633. 'warning'
  3634. )
  3635. );
  3636. return false;
  3637. }
  3638. }
  3639. $dirName = '/'.$created_dir;
  3640. $today = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  3641. $title = isset($formValues['work_title']) ? $formValues['work_title'] : $formValues['new_dir'];
  3642. $workTable = new CStudentPublication();
  3643. $workTable
  3644. ->setCId($course_id)
  3645. ->setUrl($dirName)
  3646. ->setTitle($title)
  3647. ->setDescription($formValues['description'])
  3648. ->setActive(true)
  3649. ->setAccepted(true)
  3650. ->setFiletype('folder')
  3651. ->setPostGroupId($groupIid)
  3652. ->setSentDate($today)
  3653. ->setQualification($formValues['qualification'] != '' ? $formValues['qualification'] : 0)
  3654. ->setParentId(0)
  3655. ->setQualificatorId(0)
  3656. ->setWeight(!empty($formValues['weight']) ? $formValues['weight'] : 0)
  3657. ->setSession($session)
  3658. ->setAllowTextAssignment($formValues['allow_text_assignment'])
  3659. ->setContainsFile(0)
  3660. ->setUserId($user_id)
  3661. ->setHasProperties(0)
  3662. ->setDocumentId(0);
  3663. $em->persist($workTable);
  3664. $em->flush();
  3665. $workTable->setId($workTable->getIid());
  3666. $em->merge($workTable);
  3667. $em->flush();
  3668. // Folder created
  3669. api_item_property_update(
  3670. $courseInfo,
  3671. 'work',
  3672. $workTable->getIid(),
  3673. 'DirectoryCreated',
  3674. $user_id,
  3675. $groupInfo
  3676. );
  3677. updatePublicationAssignment(
  3678. $workTable->getIid(),
  3679. $formValues,
  3680. $courseInfo,
  3681. $groupIid
  3682. );
  3683. // Added the new Work ID to the extra field values
  3684. $formValues['item_id'] = $workTable->getIid();
  3685. $workFieldValue = new ExtraFieldValue('work');
  3686. $workFieldValue->saveFieldValues($formValues);
  3687. $sendEmailAlert = api_get_course_setting('email_alert_students_on_new_homework');
  3688. switch ($sendEmailAlert) {
  3689. case 1:
  3690. sendEmailToStudentsOnHomeworkCreation(
  3691. $workTable->getIid(),
  3692. $course_id,
  3693. $sessionId
  3694. );
  3695. //no break
  3696. case 2:
  3697. sendEmailToDrhOnHomeworkCreation(
  3698. $workTable->getIid(),
  3699. $course_id,
  3700. $sessionId
  3701. );
  3702. break;
  3703. }
  3704. return $workTable->getIid();
  3705. }
  3706. /**
  3707. * @param int $workId
  3708. * @param array $courseInfo
  3709. *
  3710. * @return int
  3711. */
  3712. function agendaExistsForWork($workId, $courseInfo)
  3713. {
  3714. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3715. $courseId = $courseInfo['real_id'];
  3716. $workId = intval($workId);
  3717. $sql = "SELECT add_to_calendar FROM $workTable
  3718. WHERE c_id = $courseId AND publication_id = ".$workId;
  3719. $res = Database::query($sql);
  3720. if (Database::num_rows($res)) {
  3721. $row = Database::fetch_array($res, 'ASSOC');
  3722. if (!empty($row['add_to_calendar'])) {
  3723. return $row['add_to_calendar'];
  3724. }
  3725. }
  3726. return 0;
  3727. }
  3728. /**
  3729. * Update work description, qualification, weight, allow_text_assignment.
  3730. *
  3731. * @param int $workId (iid)
  3732. * @param array $params
  3733. * @param array $courseInfo
  3734. * @param int $sessionId
  3735. */
  3736. function updateWork($workId, $params, $courseInfo, $sessionId = 0)
  3737. {
  3738. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3739. $filteredParams = [
  3740. 'description' => $params['description'],
  3741. 'qualification' => $params['qualification'],
  3742. 'weight' => $params['weight'],
  3743. 'allow_text_assignment' => $params['allow_text_assignment'],
  3744. ];
  3745. Database::update(
  3746. $workTable,
  3747. $filteredParams,
  3748. [
  3749. 'iid = ? AND c_id = ?' => [
  3750. $workId,
  3751. $courseInfo['real_id'],
  3752. ],
  3753. ]
  3754. );
  3755. $workFieldValue = new ExtraFieldValue('work');
  3756. $workFieldValue->saveFieldValues($params);
  3757. }
  3758. /**
  3759. * @param int $workId
  3760. * @param array $params
  3761. * @param array $courseInfo
  3762. * @param int $groupId
  3763. */
  3764. function updatePublicationAssignment($workId, $params, $courseInfo, $groupId)
  3765. {
  3766. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3767. $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3768. $workId = intval($workId);
  3769. $now = api_get_utc_datetime();
  3770. $course_id = $courseInfo['real_id'];
  3771. // Insert into agenda
  3772. $agendaId = 0;
  3773. if (isset($params['add_to_calendar']) && $params['add_to_calendar'] == 1) {
  3774. // Setting today date
  3775. $date = $end_date = $now;
  3776. if (isset($params['enableExpiryDate'])) {
  3777. $end_date = $params['expires_on'];
  3778. $date = $end_date;
  3779. }
  3780. $title = sprintf(get_lang('HandingOverOfTaskX'), $params['new_dir']);
  3781. $description = isset($params['description']) ? $params['description'] : '';
  3782. $content = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId.'">'
  3783. .$params['new_dir'].'</a>'.$description;
  3784. $agendaId = agendaExistsForWork($workId, $courseInfo);
  3785. // Add/edit agenda
  3786. $agenda = new Agenda('course');
  3787. $agenda->set_course($courseInfo);
  3788. if (!empty($agendaId)) {
  3789. // add_to_calendar is set but it doesnt exists then invalidate
  3790. $eventInfo = $agenda->get_event($agendaId);
  3791. if (empty($eventInfo)) {
  3792. $agendaId = 0;
  3793. }
  3794. }
  3795. $eventColor = $agenda->eventStudentPublicationColor;
  3796. if (empty($agendaId)) {
  3797. $agendaId = $agenda->addEvent(
  3798. $date,
  3799. $end_date,
  3800. 'false',
  3801. $title,
  3802. $content,
  3803. ['GROUP:'.$groupId],
  3804. false,
  3805. null,
  3806. [],
  3807. [],
  3808. null,
  3809. $eventColor
  3810. );
  3811. } else {
  3812. $agenda->editEvent(
  3813. $agendaId,
  3814. $end_date,
  3815. $end_date,
  3816. 'false',
  3817. $title,
  3818. $content,
  3819. [],
  3820. [],
  3821. [],
  3822. null,
  3823. $eventColor
  3824. );
  3825. }
  3826. }
  3827. $qualification = isset($params['qualification']) && !empty($params['qualification']) ? 1 : 0;
  3828. $expiryDate = isset($params['enableExpiryDate']) && (int) $params['enableExpiryDate'] == 1 ? api_get_utc_datetime($params['expires_on']) : '';
  3829. $endDate = isset($params['enableEndDate']) && (int) $params['enableEndDate'] == 1 ? api_get_utc_datetime($params['ends_on']) : '';
  3830. $data = get_work_assignment_by_id($workId, $course_id);
  3831. if (!empty($expiryDate)) {
  3832. $expiryDateCondition = "expires_on = '".Database::escape_string($expiryDate)."', ";
  3833. } else {
  3834. $expiryDateCondition = "expires_on = null, ";
  3835. }
  3836. if (!empty($endDate)) {
  3837. $endOnCondition = "ends_on = '".Database::escape_string($endDate)."', ";
  3838. } else {
  3839. $endOnCondition = "ends_on = null, ";
  3840. }
  3841. if (empty($data)) {
  3842. $sql = "INSERT INTO $table SET
  3843. c_id = $course_id ,
  3844. $expiryDateCondition
  3845. $endOnCondition
  3846. add_to_calendar = $agendaId,
  3847. enable_qualification = '$qualification',
  3848. publication_id = '$workId'";
  3849. Database::query($sql);
  3850. $my_last_id = Database::insert_id();
  3851. if ($my_last_id) {
  3852. $sql = "UPDATE $table SET
  3853. id = iid
  3854. WHERE iid = $my_last_id";
  3855. Database::query($sql);
  3856. $sql = "UPDATE $workTable SET
  3857. has_properties = $my_last_id,
  3858. view_properties = 1
  3859. WHERE c_id = $course_id AND id = $workId";
  3860. Database::query($sql);
  3861. }
  3862. } else {
  3863. $sql = "UPDATE $table SET
  3864. $expiryDateCondition
  3865. $endOnCondition
  3866. add_to_calendar = $agendaId,
  3867. enable_qualification = '".$qualification."'
  3868. WHERE
  3869. publication_id = $workId AND
  3870. c_id = $course_id AND
  3871. iid = ".$data['iid'];
  3872. Database::query($sql);
  3873. }
  3874. if (!empty($params['category_id'])) {
  3875. $link_info = GradebookUtils::isResourceInCourseGradebook(
  3876. $courseInfo['code'],
  3877. LINK_STUDENTPUBLICATION,
  3878. $workId,
  3879. api_get_session_id()
  3880. );
  3881. $linkId = null;
  3882. if (!empty($link_info)) {
  3883. $linkId = $link_info['id'];
  3884. }
  3885. if (isset($params['make_calification']) &&
  3886. $params['make_calification'] == 1
  3887. ) {
  3888. if (empty($linkId)) {
  3889. GradebookUtils::add_resource_to_course_gradebook(
  3890. $params['category_id'],
  3891. $courseInfo['code'],
  3892. LINK_STUDENTPUBLICATION,
  3893. $workId,
  3894. $params['new_dir'],
  3895. api_float_val($params['weight']),
  3896. api_float_val($params['qualification']),
  3897. $params['description'],
  3898. 1,
  3899. api_get_session_id()
  3900. );
  3901. } else {
  3902. GradebookUtils::updateResourceFromCourseGradebook(
  3903. $linkId,
  3904. $courseInfo['code'],
  3905. $params['weight']
  3906. );
  3907. }
  3908. } else {
  3909. // Delete everything of the gradebook for this $linkId
  3910. GradebookUtils::remove_resource_from_course_gradebook($linkId);
  3911. }
  3912. }
  3913. }
  3914. /**
  3915. * Delete all work by student.
  3916. *
  3917. * @param int $userId
  3918. * @param array $courseInfo
  3919. *
  3920. * @return array return deleted items
  3921. */
  3922. function deleteAllWorkPerUser($userId, $courseInfo)
  3923. {
  3924. $deletedItems = [];
  3925. $workPerUser = getWorkPerUser($userId);
  3926. if (!empty($workPerUser)) {
  3927. foreach ($workPerUser as $work) {
  3928. $work = $work['work'];
  3929. foreach ($work->user_results as $userResult) {
  3930. $result = deleteWorkItem($userResult['id'], $courseInfo);
  3931. if ($result) {
  3932. $deletedItems[] = $userResult;
  3933. }
  3934. }
  3935. }
  3936. }
  3937. return $deletedItems;
  3938. }
  3939. /**
  3940. * @param int $item_id
  3941. * @param array course info
  3942. *
  3943. * @return bool
  3944. */
  3945. function deleteWorkItem($item_id, $courseInfo)
  3946. {
  3947. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3948. $TSTDPUBASG = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
  3949. $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
  3950. $is_allowed_to_edit = api_is_allowed_to_edit();
  3951. $file_deleted = false;
  3952. $item_id = intval($item_id);
  3953. $is_author = user_is_author($item_id);
  3954. $work_data = get_work_data_by_id($item_id);
  3955. $locked = api_resource_is_locked_by_gradebook($work_data['parent_id'], LINK_STUDENTPUBLICATION);
  3956. $course_id = $courseInfo['real_id'];
  3957. if (($is_allowed_to_edit && $locked == false) ||
  3958. (
  3959. $locked == false &&
  3960. $is_author &&
  3961. api_get_course_setting('student_delete_own_publication') == 1 &&
  3962. $work_data['qualificator_id'] == 0
  3963. )
  3964. ) {
  3965. // We found the current user is the author
  3966. $sql = "SELECT url, contains_file, user_id, session_id, parent_id
  3967. FROM $work_table
  3968. WHERE c_id = $course_id AND id = $item_id";
  3969. $result = Database::query($sql);
  3970. $row = Database::fetch_array($result);
  3971. $count = Database::num_rows($result);
  3972. if ($count > 0) {
  3973. // If the "considered_working_time" option is enabled, check
  3974. // whether some time should be removed from track_e_course_access
  3975. $consideredWorkingTime = api_get_configuration_value('considered_working_time');
  3976. if ($consideredWorkingTime) {
  3977. $userWorks = get_work_user_list(
  3978. 0,
  3979. 100,
  3980. null,
  3981. null,
  3982. $row['parent_id'],
  3983. null,
  3984. $row['user_id'],
  3985. false,
  3986. $course_id,
  3987. $row['session_id']
  3988. );
  3989. // We're only interested in deleting the time if this is the latest work sent
  3990. if (count($userWorks) == 1) {
  3991. // Get the "considered work time" defined for this work
  3992. $fieldValue = new ExtraFieldValue('work');
  3993. $resultExtra = $fieldValue->getAllValuesForAnItem(
  3994. $row['parent_id'],
  3995. true
  3996. );
  3997. $workingTime = null;
  3998. foreach ($resultExtra as $field) {
  3999. $field = $field['value'];
  4000. if ($consideredWorkingTime == $field->getField()->getVariable()) {
  4001. $workingTime = $field->getValue();
  4002. }
  4003. }
  4004. // If no time was defined, or a time of "0" was set, do nothing
  4005. if (!empty($workingTime)) {
  4006. $sessionId = empty($row['session_id']) ? 0 : $row['session_id'];
  4007. // Getting false from the following call would mean the
  4008. // time record
  4009. Event::eventRemoveVirtualCourseTime(
  4010. $course_id,
  4011. $row['user_id'],
  4012. $sessionId,
  4013. $workingTime
  4014. );
  4015. }
  4016. }
  4017. } // end of considered_working_time check section
  4018. $sql = "UPDATE $work_table SET active = 2
  4019. WHERE c_id = $course_id AND id = $item_id";
  4020. Database::query($sql);
  4021. $sql = "DELETE FROM $TSTDPUBASG
  4022. WHERE c_id = $course_id AND publication_id = $item_id";
  4023. Database::query($sql);
  4024. api_item_property_update(
  4025. $courseInfo,
  4026. 'work',
  4027. $item_id,
  4028. 'DocumentDeleted',
  4029. api_get_user_id()
  4030. );
  4031. Event::addEvent(
  4032. LOG_WORK_FILE_DELETE,
  4033. LOG_WORK_DATA,
  4034. [
  4035. 'id' => $work_data['id'],
  4036. 'url' => $work_data['url'],
  4037. 'title' => $work_data['title'],
  4038. ],
  4039. null,
  4040. api_get_user_id(),
  4041. api_get_course_int_id(),
  4042. api_get_session_id()
  4043. );
  4044. $work = $row['url'];
  4045. if ($row['contains_file'] == 1) {
  4046. if (!empty($work)) {
  4047. if (api_get_setting('permanently_remove_deleted_files') === 'true') {
  4048. my_delete($currentCourseRepositorySys.'/'.$work);
  4049. $file_deleted = true;
  4050. } else {
  4051. $extension = pathinfo($work, PATHINFO_EXTENSION);
  4052. $new_dir = $work.'_DELETED_'.$item_id.'.'.$extension;
  4053. if (file_exists($currentCourseRepositorySys.'/'.$work)) {
  4054. rename($currentCourseRepositorySys.'/'.$work, $currentCourseRepositorySys.'/'.$new_dir);
  4055. $file_deleted = true;
  4056. }
  4057. }
  4058. }
  4059. } else {
  4060. $file_deleted = true;
  4061. }
  4062. }
  4063. }
  4064. return $file_deleted;
  4065. }
  4066. /**
  4067. * @param FormValidator $form
  4068. * @param array $defaults
  4069. * @param int $workId
  4070. *
  4071. * @return FormValidator
  4072. */
  4073. function getFormWork($form, $defaults = [], $workId = 0)
  4074. {
  4075. $sessionId = api_get_session_id();
  4076. if (!empty($defaults)) {
  4077. if (isset($defaults['submit'])) {
  4078. unset($defaults['submit']);
  4079. }
  4080. }
  4081. // Create the form that asks for the directory name
  4082. $form->addText('new_dir', get_lang('AssignmentName'));
  4083. $form->addHtmlEditor(
  4084. 'description',
  4085. get_lang('Description'),
  4086. false,
  4087. false,
  4088. getWorkDescriptionToolbar()
  4089. );
  4090. $form->addButtonAdvancedSettings('advanced_params', get_lang('AdvancedParameters'));
  4091. if (!empty($defaults) && (isset($defaults['enableEndDate']) || isset($defaults['enableExpiryDate']))) {
  4092. $form->addHtml('<div id="advanced_params_options" style="display:block">');
  4093. } else {
  4094. $form->addHtml('<div id="advanced_params_options" style="display:none">');
  4095. }
  4096. // QualificationOfAssignment
  4097. $form->addElement('text', 'qualification', get_lang('QualificationNumeric'));
  4098. if (($sessionId != 0 && Gradebook::is_active()) || $sessionId == 0) {
  4099. $form->addElement(
  4100. 'checkbox',
  4101. 'make_calification',
  4102. null,
  4103. get_lang('MakeQualifiable'),
  4104. [
  4105. 'id' => 'make_calification_id',
  4106. 'onclick' => "javascript: if(this.checked) { document.getElementById('option1').style.display='block';}else{document.getElementById('option1').style.display='none';}",
  4107. ]
  4108. );
  4109. } else {
  4110. // QualificationOfAssignment
  4111. $form->addElement('hidden', 'make_calification', false);
  4112. }
  4113. if (!empty($defaults) && isset($defaults['category_id'])) {
  4114. $form->addHtml('<div id=\'option1\' style="display:block">');
  4115. } else {
  4116. $form->addHtml('<div id=\'option1\' style="display:none">');
  4117. }
  4118. // Loading Gradebook select
  4119. GradebookUtils::load_gradebook_select_in_tool($form);
  4120. $form->addElement('text', 'weight', get_lang('WeightInTheGradebook'));
  4121. $form->addHtml('</div>');
  4122. $form->addElement('checkbox', 'enableExpiryDate', null, get_lang('EnableExpiryDate'), 'id="expiry_date"');
  4123. if (isset($defaults['enableExpiryDate']) && $defaults['enableExpiryDate']) {
  4124. $form->addHtml('<div id="option2" style="display: block;">');
  4125. } else {
  4126. $form->addHtml('<div id="option2" style="display: none;">');
  4127. }
  4128. $timeNextWeek = time() + 86400 * 7;
  4129. $nextWeek = substr(api_get_local_time($timeNextWeek), 0, 10);
  4130. if (!isset($defaults['expires_on'])) {
  4131. $date = substr($nextWeek, 0, 10);
  4132. $defaults['expires_on'] = $date.' 23:59';
  4133. }
  4134. $form->addElement('date_time_picker', 'expires_on', get_lang('ExpiresAt'));
  4135. $form->addHtml('</div>');
  4136. $form->addElement('checkbox', 'enableEndDate', null, get_lang('EnableEndDate'), 'id="end_date"');
  4137. if (!isset($defaults['ends_on'])) {
  4138. $nextDay = substr(api_get_local_time($timeNextWeek + 86400), 0, 10);
  4139. $date = substr($nextDay, 0, 10);
  4140. $defaults['ends_on'] = $date.' 23:59';
  4141. }
  4142. if (isset($defaults['enableEndDate']) && $defaults['enableEndDate']) {
  4143. $form->addHtml('<div id="option3" style="display: block;">');
  4144. } else {
  4145. $form->addHtml('<div id="option3" style="display: none;">');
  4146. }
  4147. $form->addElement('date_time_picker', 'ends_on', get_lang('EndsAt'));
  4148. $form->addHtml('</div>');
  4149. $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar'));
  4150. $form->addElement('select', 'allow_text_assignment', get_lang('DocumentType'), getUploadDocumentType());
  4151. // Extra fields
  4152. $extraField = new ExtraField('work');
  4153. $extra = $extraField->addElements($form, $workId);
  4154. $htmlHeadXtra[] = '
  4155. <script>
  4156. $(function() {
  4157. '.$extra['jquery_ready_content'].'
  4158. });
  4159. </script>';
  4160. $form->addHtml('</div>');
  4161. $skillList = Skill::addSkillsToForm($form, ITEM_TYPE_STUDENT_PUBLICATION, $workId);
  4162. if (!empty($defaults)) {
  4163. $defaults['skills'] = array_keys($skillList);
  4164. $form->setDefaults($defaults);
  4165. }
  4166. return $form;
  4167. }
  4168. /**
  4169. * @return array
  4170. */
  4171. function getUploadDocumentType()
  4172. {
  4173. return [
  4174. 0 => get_lang('AllowFileOrText'),
  4175. 1 => get_lang('AllowOnlyText'),
  4176. 2 => get_lang('AllowOnlyFiles'),
  4177. ];
  4178. }
  4179. /**
  4180. * @param int $item_id
  4181. * @param array $course_info
  4182. *
  4183. * @return bool
  4184. */
  4185. function makeVisible($item_id, $course_info)
  4186. {
  4187. if (empty($course_info) || empty($item_id)) {
  4188. return false;
  4189. }
  4190. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4191. $course_id = $course_info['real_id'];
  4192. $item_id = intval($item_id);
  4193. $sql = "UPDATE $work_table SET accepted = 1
  4194. WHERE c_id = $course_id AND id = $item_id";
  4195. Database::query($sql);
  4196. api_item_property_update($course_info, 'work', $item_id, 'visible', api_get_user_id());
  4197. return true;
  4198. }
  4199. /**
  4200. * @param int $item_id
  4201. * @param array $course_info
  4202. *
  4203. * @return int
  4204. */
  4205. function makeInvisible($item_id, $course_info)
  4206. {
  4207. if (empty($course_info) || empty($item_id)) {
  4208. return false;
  4209. }
  4210. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4211. $item_id = intval($item_id);
  4212. $course_id = $course_info['real_id'];
  4213. $sql = "UPDATE $table
  4214. SET accepted = 0
  4215. WHERE c_id = $course_id AND id = '".$item_id."'";
  4216. Database::query($sql);
  4217. api_item_property_update(
  4218. $course_info,
  4219. 'work',
  4220. $item_id,
  4221. 'invisible',
  4222. api_get_user_id()
  4223. );
  4224. return true;
  4225. }
  4226. /**
  4227. * @param int $item_id
  4228. * @param string $path
  4229. * @param array $courseInfo
  4230. * @param int $groupId iid
  4231. * @param int $sessionId
  4232. *
  4233. * @return string
  4234. */
  4235. function generateMoveForm($item_id, $path, $courseInfo, $groupId, $sessionId)
  4236. {
  4237. $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4238. $courseId = $courseInfo['real_id'];
  4239. $folders = [];
  4240. $session_id = intval($sessionId);
  4241. $groupId = intval($groupId);
  4242. $sessionCondition = empty($sessionId) ? " AND (session_id = 0 OR session_id IS NULL) " : " AND session_id='".$session_id."'";
  4243. $groupIid = 0;
  4244. if ($groupId) {
  4245. $groupInfo = GroupManager::get_group_properties($groupId);
  4246. $groupIid = $groupInfo['iid'];
  4247. }
  4248. $sql = "SELECT id, url, title
  4249. FROM $work_table
  4250. WHERE
  4251. c_id = $courseId AND
  4252. active IN (0, 1) AND
  4253. url LIKE '/%' AND
  4254. post_group_id = $groupIid
  4255. $sessionCondition";
  4256. $res = Database::query($sql);
  4257. while ($folder = Database::fetch_array($res)) {
  4258. $title = empty($folder['title']) ? basename($folder['url']) : $folder['title'];
  4259. $folders[$folder['id']] = $title;
  4260. }
  4261. return build_work_move_to_selector($folders, $path, $item_id);
  4262. }
  4263. /**
  4264. * @param int $workId
  4265. *
  4266. * @return string
  4267. */
  4268. function showStudentList($workId)
  4269. {
  4270. $columnModel = [
  4271. [
  4272. 'name' => 'student',
  4273. 'index' => 'student',
  4274. 'width' => '350px',
  4275. 'align' => 'left',
  4276. 'sortable' => 'false',
  4277. ],
  4278. [
  4279. 'name' => 'works',
  4280. 'index' => 'works',
  4281. 'align' => 'center',
  4282. 'sortable' => 'false',
  4283. ],
  4284. ];
  4285. $token = null;
  4286. $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student_list_overview&work_id='.$workId.'&'.api_get_cidreq();
  4287. $columns = [
  4288. get_lang('Students'),
  4289. get_lang('Works'),
  4290. ];
  4291. $order = api_is_western_name_order() ? 'firstname' : 'lastname';
  4292. $params = [
  4293. 'autowidth' => 'true',
  4294. 'height' => 'auto',
  4295. 'rowNum' => 5,
  4296. 'sortname' => $order,
  4297. 'sortorder' => 'asc',
  4298. ];
  4299. $html = '<script>
  4300. $(function() {
  4301. '.Display::grid_js('studentList', $url, $columns, $columnModel, $params, [], null, true).'
  4302. $("#workList").jqGrid(
  4303. "navGrid",
  4304. "#studentList_pager",
  4305. { edit: false, add: false, del: false },
  4306. { height:280, reloadAfterSubmit:false }, // edit options
  4307. { height:280, reloadAfterSubmit:false }, // add options
  4308. { width:500 } // search options
  4309. );
  4310. });
  4311. </script>';
  4312. $html .= Display::grid_html('studentList');
  4313. return $html;
  4314. }
  4315. /**
  4316. * @param string $courseCode
  4317. * @param int $sessionId
  4318. * @param int $groupId
  4319. * @param int $start
  4320. * @param int $limit
  4321. * @param string $sidx
  4322. * @param string $sord
  4323. * @param $getCount
  4324. *
  4325. * @return array|int
  4326. */
  4327. function getWorkUserList($courseCode, $sessionId, $groupId, $start, $limit, $sidx, $sord, $getCount = false)
  4328. {
  4329. if (!empty($groupId)) {
  4330. $userList = GroupManager::get_users(
  4331. $groupId,
  4332. false,
  4333. $start,
  4334. $limit,
  4335. $getCount,
  4336. null,
  4337. $sidx,
  4338. $sord
  4339. );
  4340. } else {
  4341. $limitString = null;
  4342. if (!empty($start) && !empty($limit)) {
  4343. $start = intval($start);
  4344. $limit = intval($limit);
  4345. $limitString = " LIMIT $start, $limit";
  4346. }
  4347. $orderBy = null;
  4348. if (!empty($sidx) && !empty($sord)) {
  4349. if (in_array($sidx, ['firstname', 'lastname'])) {
  4350. $orderBy = "ORDER BY $sidx $sord";
  4351. }
  4352. }
  4353. if (empty($sessionId)) {
  4354. $userList = CourseManager::get_user_list_from_course_code(
  4355. $courseCode,
  4356. $sessionId,
  4357. $limitString,
  4358. $orderBy,
  4359. STUDENT,
  4360. $getCount
  4361. );
  4362. } else {
  4363. $userList = CourseManager::get_user_list_from_course_code(
  4364. $courseCode,
  4365. $sessionId,
  4366. $limitString,
  4367. $orderBy,
  4368. 0,
  4369. $getCount
  4370. );
  4371. }
  4372. if ($getCount == false) {
  4373. $userList = array_keys($userList);
  4374. }
  4375. }
  4376. return $userList;
  4377. }
  4378. /**
  4379. * @param int $workId
  4380. * @param string $courseCode
  4381. * @param int $sessionId
  4382. * @param int $groupId
  4383. * @param int $start
  4384. * @param int $limit
  4385. * @param int $sidx
  4386. * @param string $sord
  4387. * @param bool $getCount
  4388. *
  4389. * @return array|int
  4390. */
  4391. function getWorkUserListData(
  4392. $workId,
  4393. $courseCode,
  4394. $sessionId,
  4395. $groupId,
  4396. $start,
  4397. $limit,
  4398. $sidx,
  4399. $sord,
  4400. $getCount = false
  4401. ) {
  4402. $my_folder_data = get_work_data_by_id($workId);
  4403. $workParents = [];
  4404. if (empty($my_folder_data)) {
  4405. $workParents = getWorkList($workId, $my_folder_data, null);
  4406. }
  4407. $workIdList = [];
  4408. if (!empty($workParents)) {
  4409. foreach ($workParents as $work) {
  4410. $workIdList[] = $work->id;
  4411. }
  4412. }
  4413. $courseInfo = api_get_course_info($courseCode);
  4414. $userList = getWorkUserList(
  4415. $courseCode,
  4416. $sessionId,
  4417. $groupId,
  4418. $start,
  4419. $limit,
  4420. $sidx,
  4421. $sord,
  4422. $getCount
  4423. );
  4424. if ($getCount) {
  4425. return $userList;
  4426. }
  4427. $results = [];
  4428. if (!empty($userList)) {
  4429. foreach ($userList as $userId) {
  4430. $user = api_get_user_info($userId);
  4431. $link = api_get_path(WEB_CODE_PATH).'work/student_work.php?'.api_get_cidreq().'&studentId='.$user['user_id'];
  4432. $url = Display::url(api_get_person_name($user['firstname'], $user['lastname']), $link);
  4433. $userWorks = 0;
  4434. if (!empty($workIdList)) {
  4435. $userWorks = getUniqueStudentAttempts(
  4436. $workIdList,
  4437. $groupId,
  4438. $courseInfo['real_id'],
  4439. $sessionId,
  4440. $user['user_id']
  4441. );
  4442. }
  4443. $works = $userWorks." / ".count($workParents);
  4444. $results[] = [
  4445. 'student' => $url,
  4446. 'works' => Display::url($works, $link),
  4447. ];
  4448. }
  4449. }
  4450. return $results;
  4451. }
  4452. /**
  4453. * @param int $id
  4454. * @param array $course_info
  4455. * @param bool $isCorrection
  4456. *
  4457. * @return bool
  4458. */
  4459. function downloadFile($id, $course_info, $isCorrection)
  4460. {
  4461. return getFile($id, $course_info, true, $isCorrection, true);
  4462. }
  4463. /**
  4464. * @param int $id
  4465. * @param array $course_info
  4466. * @param bool $download
  4467. * @param bool $isCorrection
  4468. * @param bool $forceAccessForCourseAdmins
  4469. *
  4470. * @return bool
  4471. */
  4472. function getFile($id, $course_info, $download = true, $isCorrection = false, $forceAccessForCourseAdmins = false)
  4473. {
  4474. $file = getFileContents($id, $course_info, 0, $isCorrection, $forceAccessForCourseAdmins);
  4475. if (!empty($file) && is_array($file)) {
  4476. return DocumentManager::file_send_for_download(
  4477. $file['path'],
  4478. $download,
  4479. $file['title']
  4480. );
  4481. }
  4482. return false;
  4483. }
  4484. /**
  4485. * Get the file contents for an assigment.
  4486. *
  4487. * @param int $id
  4488. * @param array $courseInfo
  4489. * @param int $sessionId
  4490. * @param bool $correction
  4491. * @param bool $forceAccessForCourseAdmins
  4492. *
  4493. * @return array|bool
  4494. */
  4495. function getFileContents($id, $courseInfo, $sessionId = 0, $correction = false, $forceAccessForCourseAdmins = false)
  4496. {
  4497. $id = (int) $id;
  4498. if (empty($courseInfo) || empty($id)) {
  4499. return false;
  4500. }
  4501. if (empty($sessionId)) {
  4502. $sessionId = api_get_session_id();
  4503. }
  4504. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4505. if (!empty($courseInfo['real_id'])) {
  4506. $sql = "SELECT *
  4507. FROM $table
  4508. WHERE c_id = ".$courseInfo['real_id']." AND id = $id";
  4509. $result = Database::query($sql);
  4510. if ($result && Database::num_rows($result)) {
  4511. $row = Database::fetch_array($result, 'ASSOC');
  4512. if ($correction) {
  4513. $row['url'] = $row['url_correction'];
  4514. }
  4515. if (empty($row['url'])) {
  4516. return false;
  4517. }
  4518. $full_file_name = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$row['url'];
  4519. $item_info = api_get_item_property_info(
  4520. api_get_course_int_id(),
  4521. 'work',
  4522. $row['id'],
  4523. $sessionId
  4524. );
  4525. if (empty($item_info)) {
  4526. return false;
  4527. }
  4528. $isAllow = allowOnlySubscribedUser(
  4529. api_get_user_id(),
  4530. $row['parent_id'],
  4531. $courseInfo['real_id'],
  4532. $forceAccessForCourseAdmins
  4533. );
  4534. if (empty($isAllow)) {
  4535. return false;
  4536. }
  4537. /*
  4538. field show_score in table course :
  4539. 0 => New documents are visible for all users
  4540. 1 => New documents are only visible for the teacher(s)
  4541. field visibility in table item_property :
  4542. 0 => eye closed, invisible for all students
  4543. 1 => eye open
  4544. field accepted in table c_student_publication :
  4545. 0 => eye closed, invisible for all students
  4546. 1 => eye open
  4547. ( We should have visibility == accepted, otherwise there is an
  4548. inconsistency in the Database)
  4549. field value in table c_course_setting :
  4550. 0 => Allow learners to delete their own publications = NO
  4551. 1 => Allow learners to delete their own publications = YES
  4552. +------------------+-------------------------+------------------------+
  4553. |Can download work?| doc visible for all = 0 | doc visible for all = 1|
  4554. +------------------+-------------------------+------------------------+
  4555. | visibility = 0 | editor only | editor only |
  4556. | | | |
  4557. +------------------+-------------------------+------------------------+
  4558. | visibility = 1 | editor | editor |
  4559. | | + owner of the work | + any student |
  4560. +------------------+-------------------------+------------------------+
  4561. (editor = teacher + admin + anybody with right api_is_allowed_to_edit)
  4562. */
  4563. $work_is_visible = $item_info['visibility'] == 1 && $row['accepted'] == 1;
  4564. $doc_visible_for_all = (int) $courseInfo['show_score'] === 0;
  4565. $is_editor = api_is_allowed_to_edit(true, true, true);
  4566. $student_is_owner_of_work = user_is_author($row['id'], api_get_user_id());
  4567. if (($forceAccessForCourseAdmins && $isAllow) ||
  4568. $is_editor ||
  4569. $student_is_owner_of_work ||
  4570. ($doc_visible_for_all && $work_is_visible)
  4571. ) {
  4572. $title = $row['title'];
  4573. if ($correction) {
  4574. $title = $row['title_correction'];
  4575. }
  4576. if (array_key_exists('filename', $row) && !empty($row['filename'])) {
  4577. $title = $row['filename'];
  4578. }
  4579. $title = str_replace(' ', '_', $title);
  4580. if ($correction == false) {
  4581. $userInfo = api_get_user_info($row['user_id']);
  4582. if ($userInfo) {
  4583. $date = api_get_local_time($row['sent_date']);
  4584. $date = str_replace([':', '-', ' '], '_', $date);
  4585. $title = $date.'_'.$userInfo['username'].'_'.$title;
  4586. }
  4587. }
  4588. if (Security::check_abs_path(
  4589. $full_file_name,
  4590. api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'
  4591. )) {
  4592. Event::event_download($title);
  4593. return [
  4594. 'path' => $full_file_name,
  4595. 'title' => $title,
  4596. 'title_correction' => $row['title_correction'],
  4597. ];
  4598. }
  4599. }
  4600. }
  4601. }
  4602. return false;
  4603. }
  4604. /**
  4605. * @param int $userId
  4606. * @param array $courseInfo
  4607. * @param string $format
  4608. *
  4609. * @return bool
  4610. */
  4611. function exportAllWork($userId, $courseInfo, $format = 'pdf')
  4612. {
  4613. $userInfo = api_get_user_info($userId);
  4614. if (empty($userInfo) || empty($courseInfo)) {
  4615. return false;
  4616. }
  4617. $workPerUser = getWorkPerUser($userId);
  4618. switch ($format) {
  4619. case 'pdf':
  4620. if (!empty($workPerUser)) {
  4621. $pdf = new PDF();
  4622. $content = null;
  4623. foreach ($workPerUser as $work) {
  4624. $work = $work['work'];
  4625. foreach ($work->user_results as $userResult) {
  4626. $content .= $userResult['title'];
  4627. // No need to use api_get_local_time()
  4628. $content .= $userResult['sent_date'];
  4629. $content .= $userResult['qualification'];
  4630. $content .= $userResult['description'];
  4631. }
  4632. }
  4633. if (!empty($content)) {
  4634. $pdf->content_to_pdf(
  4635. $content,
  4636. null,
  4637. api_replace_dangerous_char($userInfo['complete_name']),
  4638. $courseInfo['code']
  4639. );
  4640. }
  4641. }
  4642. break;
  4643. }
  4644. }
  4645. /**
  4646. * @param int $workId
  4647. * @param array $courseInfo
  4648. * @param int $sessionId
  4649. * @param string $format
  4650. *
  4651. * @return bool
  4652. */
  4653. function exportAllStudentWorkFromPublication(
  4654. $workId,
  4655. $courseInfo,
  4656. $sessionId,
  4657. $format = 'pdf'
  4658. ) {
  4659. if (empty($courseInfo)) {
  4660. return false;
  4661. }
  4662. $workData = get_work_data_by_id($workId);
  4663. if (empty($workData)) {
  4664. return false;
  4665. }
  4666. $assignment = get_work_assignment_by_id($workId);
  4667. $courseCode = $courseInfo['code'];
  4668. $header = get_lang('Course').': '.$courseInfo['title'];
  4669. $teachers = CourseManager::getTeacherListFromCourseCodeToString(
  4670. $courseCode
  4671. );
  4672. if (!empty($sessionId)) {
  4673. $sessionInfo = api_get_session_info($sessionId);
  4674. if (!empty($sessionInfo)) {
  4675. $header .= ' - '.$sessionInfo['name'];
  4676. $header .= '<br />'.$sessionInfo['description'];
  4677. $teachers = SessionManager::getCoachesByCourseSessionToString(
  4678. $sessionId,
  4679. $courseInfo['real_id']
  4680. );
  4681. }
  4682. }
  4683. $header .= '<br />'.get_lang('Teachers').': '.$teachers.'<br />';
  4684. $header .= '<br />'.get_lang('Date').': '.api_get_local_time().'<br />';
  4685. $header .= '<br />'.get_lang('WorkName').': '.$workData['title'].'<br />';
  4686. $content = null;
  4687. $expiresOn = null;
  4688. if (!empty($assignment) && isset($assignment['expires_on'])) {
  4689. $content .= '<br /><strong>'.get_lang('PostedExpirationDate').'</strong>: '.api_get_local_time($assignment['expires_on']);
  4690. $expiresOn = api_get_local_time($assignment['expires_on']);
  4691. }
  4692. if (!empty($workData['description'])) {
  4693. $content .= '<br /><strong>'.get_lang('Description').'</strong>: '.$workData['description'];
  4694. }
  4695. $workList = get_work_user_list(null, null, null, null, $workId);
  4696. switch ($format) {
  4697. case 'pdf':
  4698. if (!empty($workList)) {
  4699. $table = new HTML_Table(['class' => 'data_table']);
  4700. $headers = [
  4701. get_lang('Name'),
  4702. get_lang('User'),
  4703. get_lang('HandOutDateLimit'),
  4704. get_lang('SentDate'),
  4705. get_lang('FileName'),
  4706. get_lang('Score'),
  4707. get_lang('Feedback'),
  4708. ];
  4709. $column = 0;
  4710. foreach ($headers as $header) {
  4711. $table->setHeaderContents(0, $column, $header);
  4712. $column++;
  4713. }
  4714. $row = 1;
  4715. //$pdf->set_custom_header($header);
  4716. foreach ($workList as $work) {
  4717. $content .= '<hr />';
  4718. // getWorkComments need c_id
  4719. $work['c_id'] = $courseInfo['real_id'];
  4720. //$content .= get_lang('Date').': '.api_get_local_time($work['sent_date_from_db']).'<br />';
  4721. $score = null;
  4722. if (!empty($work['qualification_only'])) {
  4723. $score = $work['qualification_only'];
  4724. }
  4725. $comments = getWorkComments($work);
  4726. $feedback = null;
  4727. if (!empty($comments)) {
  4728. $content .= '<h4>'.get_lang('Feedback').': </h4>';
  4729. foreach ($comments as $comment) {
  4730. $feedback .= get_lang('User').': '.$comment['complete_name'].
  4731. '<br />';
  4732. $feedback .= $comment['comment'].'<br />';
  4733. }
  4734. }
  4735. $table->setCellContents($row, 0, strip_tags($workData['title']));
  4736. $table->setCellContents($row, 1, strip_tags($work['fullname']));
  4737. $table->setCellContents($row, 2, $expiresOn);
  4738. $table->setCellContents($row, 3, api_get_local_time($work['sent_date_from_db']));
  4739. $table->setCellContents($row, 4, strip_tags($work['title']));
  4740. $table->setCellContents($row, 5, $score);
  4741. $table->setCellContents($row, 6, $feedback);
  4742. $row++;
  4743. }
  4744. $content = $table->toHtml();
  4745. if (!empty($content)) {
  4746. $params = [
  4747. 'filename' => $workData['title'].'_'.api_get_local_time(),
  4748. 'pdf_title' => api_replace_dangerous_char($workData['title']),
  4749. 'course_code' => $courseInfo['code'],
  4750. ];
  4751. $pdf = new PDF('A4', null, $params);
  4752. $pdf->html_to_pdf_with_template($content);
  4753. }
  4754. exit;
  4755. }
  4756. break;
  4757. }
  4758. }
  4759. /**
  4760. * Downloads all user files per user.
  4761. *
  4762. * @param int $userId
  4763. * @param array $courseInfo
  4764. *
  4765. * @return bool
  4766. */
  4767. function downloadAllFilesPerUser($userId, $courseInfo)
  4768. {
  4769. $userInfo = api_get_user_info($userId);
  4770. if (empty($userInfo) || empty($courseInfo)) {
  4771. return false;
  4772. }
  4773. $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
  4774. $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/';
  4775. $zip = new PclZip($tempZipFile);
  4776. $workPerUser = getWorkPerUser($userId);
  4777. if (!empty($workPerUser)) {
  4778. $files = [];
  4779. foreach ($workPerUser as $work) {
  4780. $work = $work['work'];
  4781. foreach ($work->user_results as $userResult) {
  4782. if (empty($userResult['url']) || empty($userResult['contains_file'])) {
  4783. continue;
  4784. }
  4785. $data = getFileContents($userResult['id'], $courseInfo);
  4786. if (!empty($data) && isset($data['path'])) {
  4787. $files[basename($data['path'])] = [
  4788. 'title' => $data['title'],
  4789. 'path' => $data['path'],
  4790. ];
  4791. }
  4792. }
  4793. }
  4794. if (!empty($files)) {
  4795. Session::write('files', $files);
  4796. foreach ($files as $data) {
  4797. $zip->add(
  4798. $data['path'],
  4799. PCLZIP_OPT_REMOVE_PATH,
  4800. $coursePath,
  4801. PCLZIP_CB_PRE_ADD,
  4802. 'preAddAllWorkStudentCallback'
  4803. );
  4804. }
  4805. }
  4806. // Start download of created file
  4807. $name = basename(api_replace_dangerous_char($userInfo['complete_name'])).'.zip';
  4808. Event::event_download($name.'.zip (folder)');
  4809. if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
  4810. DocumentManager::file_send_for_download($tempZipFile, true, $name);
  4811. @unlink($tempZipFile);
  4812. exit;
  4813. }
  4814. }
  4815. exit;
  4816. }
  4817. /**
  4818. * @param $p_event
  4819. * @param array $p_header
  4820. *
  4821. * @return int
  4822. */
  4823. function preAddAllWorkStudentCallback($p_event, &$p_header)
  4824. {
  4825. $files = Session::read('files');
  4826. if (isset($files[basename($p_header['stored_filename'])])) {
  4827. $p_header['stored_filename'] = $files[basename($p_header['stored_filename'])]['title'];
  4828. return 1;
  4829. }
  4830. return 0;
  4831. }
  4832. /**
  4833. * Get all work created by a user.
  4834. *
  4835. * @param int $user_id
  4836. * @param int $courseId
  4837. * @param int $sessionId
  4838. *
  4839. * @return array
  4840. */
  4841. function getWorkCreatedByUser($user_id, $courseId, $sessionId)
  4842. {
  4843. $items = api_get_item_property_list_by_tool_by_user(
  4844. $user_id,
  4845. 'work',
  4846. $courseId,
  4847. $sessionId
  4848. );
  4849. $list = [];
  4850. if (!empty($items)) {
  4851. foreach ($items as $work) {
  4852. $item = get_work_data_by_id(
  4853. $work['ref'],
  4854. $courseId,
  4855. $sessionId
  4856. );
  4857. if (!empty($item)) {
  4858. $list[] = [
  4859. $item['title'],
  4860. api_get_local_time($work['insert_date']),
  4861. api_get_local_time($work['lastedit_date']),
  4862. ];
  4863. }
  4864. }
  4865. }
  4866. return $list;
  4867. }
  4868. /**
  4869. * @param array $courseInfo
  4870. * @param int $workId
  4871. *
  4872. * @return bool
  4873. */
  4874. function protectWork($courseInfo, $workId)
  4875. {
  4876. $userId = api_get_user_id();
  4877. $groupId = api_get_group_id();
  4878. $sessionId = api_get_session_id();
  4879. $workData = get_work_data_by_id($workId);
  4880. if (empty($workData) || empty($courseInfo)) {
  4881. api_not_allowed(true);
  4882. }
  4883. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  4884. return true;
  4885. }
  4886. $workId = $workData['id'];
  4887. if ($workData['active'] != 1) {
  4888. api_not_allowed(true);
  4889. }
  4890. $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $sessionId);
  4891. if ($visibility != 1) {
  4892. api_not_allowed(true);
  4893. }
  4894. $isAllow = allowOnlySubscribedUser($userId, $workId, $courseInfo['real_id']);
  4895. if (empty($isAllow)) {
  4896. api_not_allowed(true);
  4897. }
  4898. $groupInfo = GroupManager::get_group_properties($groupId);
  4899. if (!empty($groupId)) {
  4900. $showWork = GroupManager::user_has_access(
  4901. $userId,
  4902. $groupInfo['iid'],
  4903. GroupManager::GROUP_TOOL_WORK
  4904. );
  4905. if (!$showWork) {
  4906. api_not_allowed(true);
  4907. }
  4908. }
  4909. }
  4910. /**
  4911. * @param array $courseInfo
  4912. * @param array $work
  4913. */
  4914. function deleteCorrection($courseInfo, $work)
  4915. {
  4916. if (isset($work['url_correction']) && !empty($work['url_correction']) && isset($work['iid'])) {
  4917. $id = $work['iid'];
  4918. $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  4919. $sql = "UPDATE $table SET
  4920. url_correction = '',
  4921. title_correction = ''
  4922. WHERE iid = $id";
  4923. Database::query($sql);
  4924. $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
  4925. if (file_exists($coursePath.$work['url_correction'])) {
  4926. if (Security::check_abs_path($coursePath.$work['url_correction'], $coursePath)) {
  4927. unlink($coursePath.$work['url_correction']);
  4928. }
  4929. }
  4930. }
  4931. }
  4932. /**
  4933. * @param int $workId
  4934. *
  4935. * @return string
  4936. */
  4937. function workGetExtraFieldData($workId)
  4938. {
  4939. $sessionField = new ExtraField('work');
  4940. $extraFieldData = $sessionField->getDataAndFormattedValues($workId);
  4941. $result = '';
  4942. if (!empty($extraFieldData)) {
  4943. $result .= '<div class="well">';
  4944. foreach ($extraFieldData as $data) {
  4945. $result .= $data['text'].': <b>'.$data['value'].'</b>';
  4946. }
  4947. $result .= '</div>';
  4948. }
  4949. return $result;
  4950. }