work.lib.php 181 KB

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