work.lib.php 178 KB

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