work.lib.php 178 KB

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