TableAjax.php 205 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818
  1. <?php
  2. Lib::loadClass('ViewAjax');
  3. Lib::loadClass('TableAjaxMap');
  4. Lib::loadClass('Typespecial');
  5. Lib::loadClass('SE_Layout');
  6. Lib::loadClass('FoldersConfig');
  7. Lib::loadClass('FileUploader');
  8. Lib::loadClass('UserProfile');
  9. class TableAjax extends ViewAjax {
  10. private $_cnf = '';// Column
  11. private $_htmlID = '';
  12. private $_rowFunctions = array();
  13. private $_pageSize = 10;
  14. private $_pageSizes = array();
  15. private $_filterInit = null;
  16. private $_forceFilterInit = null;
  17. private $_showProcesInit = true;
  18. public function __construct($tblAcl) {
  19. $this->_tbl = $tblAcl->getName();
  20. $this->_acl = $tblAcl;
  21. $this->_zasobID = $tblAcl->getID();
  22. $this->_pageSize = 10;
  23. {
  24. UserProfile::load();
  25. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  26. $this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
  27. }
  28. $this->_pageSizes = array(10, 20, 50, 100);// default page sizes
  29. $this->_filterInit = new stdClass();
  30. $hash = V::get('_hash', '', $_GET);
  31. if ($hash) {
  32. $this->_htmlID = $hash;
  33. $this->_readState();
  34. } else {
  35. $this->_htmlID = $this->generateHtmlID();
  36. $this->_readState();
  37. }
  38. }
  39. public function showProcesInit($bool = true) {
  40. $this->_showProcesInit = $bool;
  41. }
  42. private function _hasStateFilterInit() {
  43. return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
  44. }
  45. // TODO: read state from cache by key $this->_htmlID
  46. // TODO: load filters and state: table, edit, add, etc.
  47. // TODO: save this data in Workspace 1, 2, 3, etc.
  48. // TODO: default filters in VIEWTABLE_AJAX
  49. // $tbl->setLabel($zasobObj->OPIS);
  50. // $tbl->setFilterInit($filterInit);
  51. // $tbl->addRowFunction('edit');
  52. // $tbl->addRowFunction('hist');
  53. // $tbl->addRowFunction('files');
  54. // $tbl->addRowFunction('cp');
  55. private function _readState() {
  56. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  57. $_SESSION['TableAjax_Cache'] = array();
  58. }
  59. //trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
  60. //trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
  61. if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  62. foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
  63. //trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
  64. switch ($k) {
  65. case '_label':
  66. $this->_label = $v;
  67. break;
  68. case '_filterInit':
  69. $this->_filterInit = $v;
  70. break;
  71. case '_rowFunctions':
  72. $this->_rowFunctions = $v;
  73. break;
  74. default:
  75. }
  76. }
  77. }
  78. }
  79. protected function _saveState($key = null) {
  80. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  81. $_SESSION['TableAjax_Cache'] = array();
  82. }
  83. if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  84. $_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
  85. }
  86. if (!$key) {
  87. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  88. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  89. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  90. } else if ($key == '_label') {
  91. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  92. } else if ($key == '_filterInit') {
  93. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  94. } else if ($key == '_rowFunctions') {
  95. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  96. }
  97. }
  98. public function setPageSizes($pageSizes) {
  99. $this->_pageSizes = $pageSizes;
  100. }
  101. public function setFilterInit($filterInit) {
  102. if ($this->_hasStateFilterInit()) {
  103. return;
  104. }
  105. $this->_filterInit = (object)$filterInit;
  106. $this->_saveState();
  107. }
  108. /**
  109. * @param array $forceFilterInit
  110. */
  111. public function setForceFilterInit($forceFilterInit) {
  112. $this->_forceFilterInit = (object)$forceFilterInit;
  113. }
  114. private function setFilters($filterInit) {
  115. $this->_filterInit = (object)$filterInit;
  116. $this->_saveState();
  117. }
  118. public function addRowFunction($funName, $funParams = array()) {
  119. $defaultRowFunction = array();
  120. //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="glyphicon glyphicon-pencil" title="Edytuj rekord"></a>';
  121. //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="glyphicon glyphicon-book" title="Historia"></a>';
  122. //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="glyphicon glyphicon-folder-open" title="Pliki"></a>';
  123. //$defaultRowFunction['cp'] = '<a href="#" class="glyphicon glyphicon-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
  124. $defaultRowFunction['edit'] = array('href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord');
  125. $defaultRowFunction['hist'] = array('href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia');
  126. $defaultRowFunction['files'] = array('href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki');
  127. $defaultRowFunction['cp'] = array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  128. if (array_key_exists($funName, $defaultRowFunction)) {
  129. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  130. }
  131. else {
  132. $this->_rowFunctions[$funName] = $funParams;
  133. }
  134. $this->_saveState('_rowFunctions');
  135. }
  136. private function _parseRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
  137. $rowFunctions = array();
  138. foreach ($this->_rowFunctions as $kFunName => $vParams) {
  139. if (in_array($kFunName, $pomin)) continue;
  140. //$rowFunctionsOut .= str_replace('{0}', $recordID, $vUrl);
  141. $attrs = array();
  142. // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  143. $label = '';
  144. $ico = '';
  145. foreach ($vParams as $kParamName => $v) {
  146. if ($kParamName == 'ico') {
  147. $ico = '<span class="' . $v . '"></span>';
  148. continue;
  149. }
  150. $attr = $v;
  151. if ($recordID > 0) {
  152. $attr = str_replace('{0}', $recordID, $attr);
  153. }
  154. if ($showLabel && $kParamName == 'title') {
  155. $label = $attr;
  156. }
  157. $attr = $kParamName . '="' . $attr . '"';
  158. $attrs[] = $attr;
  159. }
  160. $rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico} {$label} " . '</a>';
  161. }
  162. return $rowFunctions;
  163. }
  164. private function _showRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
  165. $rowFunctionsOut = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
  166. $rowFunctionsOut = implode('', $rowFunctionsOut);
  167. return $rowFunctionsOut;
  168. }
  169. private function _showRowFunctionsJson($recordID = null, $pomin = array(), $showLabel = false) {
  170. $rowFunctions = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
  171. $rowFunctions = (object)$rowFunctions;
  172. return $rowFunctions;
  173. }
  174. private function _showExportFieldsJson() {
  175. $exportFields = $this->_acl->getExportFieldList();
  176. return $exportFields;
  177. }
  178. private function getProcesInitSelected() {
  179. $userAcl = User::getAcl();
  180. return $userAcl->getPermsFiltrProcesId();
  181. }
  182. public function allowTreeView() {
  183. if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
  184. if ($this->_tbl == 'CRM_PROCES') return true;
  185. return false;
  186. }
  187. public function hasGeomFields() {
  188. $hasGeomFields = false;
  189. $fieldsList = $this->_acl->getFields();
  190. foreach ($fieldsList as $kID => $vCol) {
  191. if ($this->_acl->isGeomField($vCol['name'])) {
  192. if ($this->_acl->hasFieldPerm($kID, 'R')) {
  193. $hasGeomFields = true;
  194. break;
  195. }
  196. }
  197. }
  198. return $hasGeomFields;
  199. }
  200. public function render() {
  201. $hasGeomFlds = $this->hasGeomFields();
  202. $tblAjaxMap = null;
  203. if ($hasGeomFlds) {
  204. $tblAjaxMap = new TableAjaxMap($this->_acl, 512, 400);
  205. }
  206. $hasPermCreate = $this->_acl->hasCreatePerms();
  207. $jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
  208. ob_start();
  209. ?>
  210. <div class="container">
  211. <?php SE_Layout::showMessagesForTable($this->_tbl); ?>
  212. </div>
  213. <?php if ($tblAjaxMap) $tblAjaxMap->printCSS(); ?>
  214. <?php if ($tblAjaxMap) $tblAjaxMap->printJS(); ?>
  215. <script src="stuff/jquery-ui-1.10.4.custom.min.js"></script>
  216. <link rel="stylesheet" type="text/css" href="stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css">
  217. <style type="text/css">
  218. .AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
  219. .AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
  220. .AjaxTable *,
  221. .AjaxTable.table {white-space:nowrap; width:auto;}
  222. .AjaxTable .popover * {white-space:normal;}
  223. .AjaxTable p {margin:0;}
  224. .AjaxTable td, .AjaxTable th {line-height:18px;}
  225. .AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
  226. .AjaxTable span.filter {background-color:#999;}
  227. .AjaxTable .indeterminate {opacity: 0.4;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";filter:alpha(opacity=40);}
  228. .AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
  229. .AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
  230. .AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
  231. .AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
  232. .AjaxTable input[type=text].filter {margin:0;padding:0 5px;box-shadow:none;width:100%;background:#eee;color:#000;}
  233. .AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
  234. .AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
  235. .AjaxTable .date-wrap {width:100%;min-width:115px;}
  236. .AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
  237. .AjaxTableCont .dropdown-menu {max-height:250px;padding:0 20px 0 0;overflow:auto;}
  238. .AjaxTable .actions a {padding:0;margin:0;}
  239. .AjaxTableCont .text-right {text-align:right}
  240. .AjaxTableCont .breadcrumb em {color:#bbb;}
  241. .AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
  242. .AjaxTable-loading .loading-info,
  243. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
  244. .AjaxTableCont .loading-info {display:none;}
  245. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block;}
  246. .AjaxTableCont .table {margin-bottom:0px;}
  247. .AjaxTableCont .stickyCol1 a { color:#333; }
  248. .AjaxTableCont .stickyCol1 a:hover { color:#337AB7; text-decoration:none; }
  249. .AjaxTableTaskCnt {padding:0 10px 10px 10px;}
  250. .AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
  251. .AjaxTable .tbl-short-txt span{display:block; height:18px;}
  252. .AjaxTable .tooltip-inner{white-space:normal;}
  253. .AjaxTable thead .sort .ta-ordering {cursor:pointer;}
  254. .AjaxTable thead .sort .ta-ordering span {margin:0 10px 0 0; padding:0; background-repeat:no-repeat; background-position:right top;}
  255. .AjaxTable thead .sort .ta-ordering-down span:after{content:"\e252";font-family:"Glyphicons Halflings";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  256. .AjaxTable thead .sort .ta-ordering-up span:after{content:"\e253";font-family:"Glyphicons Halflings";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  257. .AjaxTable thead .sort .ta-ordering {position:relative;}
  258. .AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
  259. .AjaxTable thead .sort th .hover-show{display:none;}
  260. .AjaxTable thead .sort th:hover .hover-show{display:inline;}
  261. .AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none; color:#f00;}
  262. .AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}
  263. .AjaxTableCont .pagination { margin:0; }
  264. .AjaxTableCont .pagination a { line-height:16px; }
  265. .AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
  266. .AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
  267. .AjaxTableCont .AjaxTableEdit .show-last-value .button-appendBack .glyphicon,
  268. .AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .button-appendBack .glyphicon {display:none;}
  269. .AjaxTableHist em {color:silver;}
  270. .AjaxTableCont .foot * { font-size:12px !important; }
  271. .AjaxTableCont .foot { margin:10px; }
  272. .AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
  273. .AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
  274. .AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
  275. .tblAjax__head__specialFilter {margin:0;padding:4px 4px 4px 127px;}
  276. .tblAjax__head__specialFilter .btn-group {margin:0 4px;padding:0;}
  277. .tblAjax__head__specialFilter .btn-group .glyphicon-remove {color:#f00;}
  278. .tblAjax__head__specialFilter .btn-group button.disabled .glyphicon-remove {color:#bbb;}
  279. /* overwrite bootstrap table border */
  280. .AjaxTable, .AjaxTableEdit,
  281. .AjaxTable td, .AjaxTableEdit td,
  282. .AjaxTable th, .AjaxTableEdit th { border-color:#999; }
  283. /* cell A_STATUS */
  284. .AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
  285. .AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
  286. .AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
  287. .AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
  288. .AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
  289. .AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
  290. .AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }
  291. /* cell Status */
  292. .AjaxTable .cell-Status-U { background:rgb(0,176,80); color:#000; text-align:center; }
  293. .AjaxTable .cell-Status-NU { background:#f00; color:#000; text-align:center; }
  294. .AjaxTable .cell-Status-P { background:rgb(112,48,160); color:#000; text-align:center; }
  295. .AjaxTable .cell-Status-PT { background:rgb(127,127,127); color:#000; text-align:center; }
  296. .AjaxTable .cell-Status-O { background:rgb(0,176,240); color:#000; text-align:center; }
  297. .AjaxTable .cell-Status-DZ { background:rgb(0,112,192); color:#000; text-align:center; }
  298. .AjaxTable .cell-Status-Z {}
  299. /* map */
  300. .AjaxTable .cell-mapfld { cursor:pointer; }
  301. .AjaxTable .cell-mapfld:hover { opacity:1; }
  302. .AjaxTable .cell-mapfld-remove { display:none; }
  303. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-select { color:#f00; }
  304. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-remove { display:inline-block; }
  305. .AjaxTableCont .mapEditor { position:absolute; bottom:0; right:6px; width:512px; height:318px; overflow:hidden; color:#eee; border:1px solid #999; }
  306. .AjaxTableCont .mapEditor-panel { height:16px; padding:0 6px; background:#999; border-bottom:1px solid #eee; }
  307. .AjaxTableCont .mapEditor-panel a { display:block; float:right; padding:0 6px; font-weight:bold; font-size:12px; line-height:16px; color:#fff; }
  308. .AjaxTableCont .mapEditor-panel a:hover { color:#006CD7; text-decoration:none; }
  309. .AjaxTableCont .mapEditor-panel a.mapEditor-panel-close:hover { color:#f00; }
  310. .AjaxTableCont .mapEditor-map { background:#fff; height:400px; }
  311. .AjaxTableCont-mapEditorContainer .mapEditor-map { border:1px solid #999; overflow:hidden; }
  312. /* .mapEditor-btnBackToWindow "olControlSave",overview_replacement */
  313. .olControlEditingToolbar .mapEditor-btnBackToWindowItemInactive,
  314. .olControlEditingToolbar .mapEditor-btnBackToWindowItemActive {
  315. background-image: url(icon/map.window.png);
  316. background-position: 0 0;
  317. background-repeat: no-repeat;
  318. }
  319. /*
  320. .mapEditor-btnBackToWindowItemInactive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  321. .mapEditor-btnBackToWindowItemActive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  322. */
  323. .ui-dialog-content .mapEditor-btnBackToWindowItemInactive,
  324. .ui-dialog-content .mapEditor-btnBackToWindowItemActive { display:none; }
  325. .AjaxTableCont .valign-btns-bottom a { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
  326. .ui-resizable-s { bottom:0; }
  327. .ui-resizable-e { right:0; }
  328. .AjaxTableCont-mapEditorContainer .ui-resizable-s { background-color:#ddd; }
  329. .AjaxTableCont-mapEditorContainer .ui-resizable-s:hover { background-color:#888; }
  330. </style>
  331. <div class="AjaxTableCont">
  332. <ul class="breadcrumb">
  333. <li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>
  334. <!-- TODO: if has perm 'C' then add btn to create new record -->
  335. <?php if ($hasPermCreate) : ?>
  336. <li><a title="Dodaj nowy rekord"
  337. class=""
  338. href="#CREATE"><span class="glyphicon glyphicon-plus"></span> Dodaj nowy rekord</a></li>
  339. <?php endif; ?>
  340. <?php if ($this->_showProcesInit) : ?>
  341. <div class="btn-group pull-right">
  342. <a class="btn btn-xs btn-info dropdown-toggle"
  343. data-toggle="dropdown"
  344. href="#"
  345. title="Uruchom filtr procesu powiązanego z tabelą <?php echo $this->getLabel(); ?>"
  346. onclick="return <?php echo $jsToogleFiltrProcesuFunctionName; ?>(this);">
  347. Filtr procesu <span class="caret"></span>
  348. </a>
  349. <ul class="dropdown-menu pull-left">
  350. <li class="disabled"><a href="#" onclick="return false;"> loading ... </a></li>
  351. </ul>
  352. </div>
  353. <?php endif; ?>
  354. <?php if ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') : ?>
  355. <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=TREEJS&ZASOB_ID={$this->_zasobID}"; ?>"><i class="glyphicon glyphicon-eye-open"></i> Drzewo</a>
  356. <?php elseif ($this->allowTreeView()) : ?>
  357. <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=VIEWTREE_AJAX&ZASOB_ID={$this->_zasobID}"; ?>"><i class="glyphicon glyphicon-eye-open"></i> Drzewo</a>
  358. <?php endif; ?>
  359. </ul>
  360. <div id="<?php echo $this->_htmlID; ?>"></div>
  361. </div>
  362. <script>
  363. (function($) {
  364. var TableAjaxGeomField = function() {
  365. var priv = {}; //private api
  366. var publ = {}; //public api
  367. priv.options = {};
  368. var defaults = {
  369. recordID: '',
  370. fieldValue: '',
  371. hasValueClassName: 'TableAjaxGeomField-hasValue',
  372. linkClassNamePrefix: 'TableAjaxGeomField',
  373. linkSelectClassName: 'select',
  374. linkSelectAddClassNames: '', // 'glyphicon glyphicon-map-marker'
  375. linkRemoveClassName: 'remove',
  376. linkRemoveAddClassNames: '', // 'glyphicon glyphicon-remove'
  377. removeUrl: '',
  378. onSelect: null,
  379. onRemove: null,
  380. debug: false
  381. };
  382. priv.init = function() {
  383. priv.render();
  384. };
  385. priv.render = function() {
  386. var state = priv.options;
  387. var cellMapSelect = jQuery('<i title="Pokaż/utwórz obiekt na mapie"></i>');
  388. cellMapSelect.addClass(state.linkClassNamePrefix + '-' + state.linkSelectClassName);
  389. if (state.linkSelectAddClassNames) {
  390. cellMapSelect.addClass(state.linkSelectAddClassNames);
  391. }
  392. cellMapSelect.on('click', {recordID: priv.options.recordID, fieldValue: priv.options.fieldValue}, function(e) {
  393. if (typeof state.onSelect == "function") {
  394. state.onSelect.call(this, e.data.recordID, e.data.fieldValue);
  395. }
  396. });
  397. var cellMapRemove = jQuery('<i title="Usuń obiekt z mapy"></i>');
  398. cellMapRemove.addClass(state.linkClassNamePrefix + '-' + state.linkRemoveClassName);
  399. if (state.linkRemoveAddClassNames) {
  400. cellMapRemove.addClass(state.linkRemoveAddClassNames);
  401. }
  402. cellMapRemove.on('click', {recordID: state.recordID, fieldValue: state.fieldValue}, function(e) {
  403. if (typeof state.onRemove == "function") {
  404. state.onRemove.call(this, publ, e.data.recordID, e.data.fieldValue);
  405. }
  406. });
  407. var node = $(state.id);
  408. node.empty();
  409. node.addClass(state.linkClassNamePrefix);
  410. node.removeClass(state.hasValueClassName);
  411. if (state.fieldValue) {
  412. node.addClass(state.hasValueClassName);
  413. }
  414. node.append(cellMapSelect);
  415. node.append(cellMapRemove);
  416. };
  417. publ.setValue = function(value) {
  418. if (priv.options.debug) console.log('TEST setValue: ', value, 'this', this);
  419. priv.options.fieldValue = value;
  420. priv.render();
  421. };
  422. publ.init = function(options) {
  423. if (priv.options.debug) console.log('TableAjaxGeomField initialization...', options);
  424. //merge supplied options with defaults
  425. $.extend(priv.options, defaults, options);
  426. priv.init();
  427. return publ;
  428. };
  429. return publ;
  430. };
  431. $.fn.TableAjaxGeomFieldSetValue = function(value) {
  432. return this.each(function() {
  433. var tblAjaxMapGeomFld = $(this).data('TableAjaxGeomField');
  434. if (tblAjaxMapGeomFld) {
  435. tblAjaxMapGeomFld.setValue(value);
  436. }
  437. });
  438. return this;
  439. };
  440. $.fn.TableAjaxGeomField = function(options) {
  441. options = options || {};
  442. return this.each(function() {
  443. options.id = this;
  444. if (!$(this).data('TableAjaxGeomField')) {
  445. $(this).data('TableAjaxGeomField', new TableAjaxGeomField().init(options));
  446. }
  447. });
  448. return this;
  449. };
  450. }(jQuery));
  451. (function($, undefined) {
  452. var TableAjax = function () {
  453. var priv = {}; //private api
  454. var publ = {}; //public api
  455. priv.options = {};
  456. var defaults = {
  457. url: '', //webservice url
  458. urlData: '', //webservice params
  459. urlPost: false, //use POST instead of GET
  460. debug: false, //prints debug info to console
  461. filter: false, //show filter row
  462. filterInit: false,// init filters data
  463. forceFilterInit: false,
  464. columnPicker: false, //show columnpicker
  465. checkboxes: false, //show body checkboxes
  466. actions: '', //holds action links
  467. pageSize: 10, //current pagesize
  468. pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
  469. hidePagerOnEmpty: false, //removes pager if no rows
  470. types: { //type specific options
  471. string: {},
  472. number: {},
  473. bool: {},
  474. date: {}
  475. },
  476. rowFunctions: false,
  477. tblFunctions: false,
  478. specialFilterFunctions: false,
  479. filtersClean: false,
  480. router: false,
  481. longDesc: false,
  482. exportFields: [],
  483. mapEditor: false, // mapEditor visible or not
  484. mapEditorContainer: 'window' // 'window' or 'dock'
  485. };
  486. var _uiNodeCont; // container holding table
  487. var _uiNode$Table; // the table node
  488. var _head; // table header
  489. var _headSort; // table header sorting row
  490. var _headFilter; // table header columns filter row
  491. var _headSpecialFilter; // table header special filter row
  492. var _bodyNode; // table body
  493. var _body; // TODO: table body need render?
  494. var _foot; // table footer
  495. var _inlineEditBox; // inline edit box with form
  496. var _popoverCell; // inline popover cell
  497. var _popoverCellCurrent; // inline popover cell
  498. var _popoverCellAjaxXhr;
  499. var _mapEditor; // map editor node
  500. var _mapEditorWrap; // map editor wrapper node
  501. var _mapEditorDialog; // map editor jquery ui dialog node
  502. var _state = {};// state - to replace variables below (date, ...)
  503. var _data; //columns and rows
  504. var _totalPages; // total pages
  505. var _currDpOp; // clicked datetimepicker operator
  506. var _filterFields = {}; // array with filter DOM elements
  507. var _filterTimeout; // timer for delayed filtering
  508. var _uniqueCols = {}; // array with checked rows /// TODO: mv to _state.
  509. var _checkToggleChecked = false; // check-all toggle state
  510. var _exportFieldsSelect = {};
  511. var _tableWidth;
  512. /*
  513. initialize the plugin.
  514. */
  515. priv.init = function () {
  516. _uiNodeCont = priv.options.id;
  517. _state = {};// init state
  518. _state.page = 1;
  519. _state.specialFilters = {};
  520. _state.filters = {};
  521. _state.filters.currSortCol = '';
  522. _state.filters.currSortFlip = false;
  523. _state.filters.filterCols = {};
  524. priv.initEvents();
  525. priv.initialRender();// set up _uiNode$...
  526. priv.options.types.string = ((priv.options.types || {}).string || {});
  527. priv.options.types.number = ((priv.options.types || {}).number || {});
  528. priv.options.types.bool = ((priv.options.types || {}).bool || {});
  529. priv.options.types.date = ((priv.options.types || {}).date || {});
  530. if (priv.options.mapEditorContainer != 'dock'
  531. && priv.options.mapEditorContainer != 'window') {
  532. priv.options.mapEditorContainer = 'window';
  533. }
  534. if (priv.options.filterInit) {
  535. priv.setStateFilters(priv.options.filterInit);
  536. }
  537. $.each(priv.options.exportFields, function(ind, col) {
  538. _exportFieldsSelect[col] = true;
  539. });
  540. //try call webservice for data
  541. priv.update(priv.options.router);
  542. if (typeof priv.options.router == "function") {
  543. $(window).bind('hashchange', function() {
  544. priv.options.router.apply(this);
  545. });
  546. }
  547. };
  548. priv.initEvents = function () {
  549. jQuery(_uiNodeCont).on('TableAjax:render', priv.onRender);
  550. };
  551. priv.onRender = function(e) {
  552. if (priv.options.debug) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
  553. if (arguments.length > 1) {
  554. for (var i=1; i<arguments.length; i++) {
  555. switch (arguments[i]) {
  556. case 'head': _head = undefined; break;
  557. case 'body': _body = undefined; break;
  558. case 'foot': _foot = undefined; break;
  559. case 'foot_pagination': {
  560. priv.renderFooterInfo();
  561. priv.renderFooterPagination();
  562. priv.renderFooterPageSizes();
  563. }
  564. break;
  565. case 'footer__toolbar__info': priv.renderFooterInfo(); break;
  566. case 'footer__toolbar__pagination': priv.renderFooterPagination(); break;
  567. case 'footer__toolbar__pagesizes': priv.renderFooterPageSizes(); break;
  568. case 'foot__columnPicker': priv.renderFooterColumnPicker(); break;
  569. case 'head__specialFilters': priv.renderHeadSpecialFilters(); break;
  570. }
  571. }
  572. priv.renderTable();
  573. }
  574. };
  575. priv.initialRender = function () {
  576. _uiNode$Table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_uiNodeCont);
  577. _head = $('<thead></thead>').prependTo(_uiNode$Table);
  578. _headSort = $('<tr class="sort tblAjax__head__sort"></tr>').prependTo(_head);
  579. _headFilter = $('<tr class="filter tblAjax__head__filter"></tr>').appendTo(_head);
  580. _bodyNode = $('<tbody></tbody>').insertAfter(_head);
  581. $('<tfoot></tfoot>').insertAfter(_bodyNode);
  582. _foot = $('<div class="foot tblAjax__footer"></div>').insertAfter(_uiNodeCont);
  583. var footToolbar = $('<div class="btn-toolbar tblAjax__footer__toolbar"></div>').appendTo(_foot);
  584. $('<span class="tblAjax__footer__toolbar__info"></span>').appendTo(footToolbar);
  585. $('<span class="tblAjax__footer__toolbar__pagination"></span>').appendTo(footToolbar);
  586. $('<span class="tblAjax__footer__toolbar__pagesizes"></span>').appendTo(footToolbar);
  587. $('<span class="tblAjax__footer__toolbar__columnPicker"></span>').appendTo(footToolbar);
  588. $('<span class="tblAjax__footer__toolbar__functions"></span>').appendTo(footToolbar);
  589. $('<span class="tblAjax__footer__toolbar__export"></span>').appendTo(footToolbar);
  590. _mapEditorWrap = $('<div class="mapEditor" style="display:none"></div>').insertAfter(_foot);
  591. _mapEditor = $('<div class="mapEditor-map"></div>').appendTo(_mapEditorWrap);
  592. _popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
  593. $('<div class="tblAjax__inlineEditBox"></div>').insertAfter(_foot);
  594. $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>').insertBefore(_uiNodeCont);
  595. priv.renderInlineEditBox();// .tblAjax__inlineEditBox
  596. _foot = _head = _body = _headSort = _headFilter = undefined;// TODO: refactor
  597. /// console.log('L.<?php echo __LINE__; ?> priv.initialRender, _uiNode$Table: ', _uiNode$Table.html())
  598. }
  599. /*
  600. creates the table with all its parts and handlers.
  601. note that only the parts we need is created.
  602. (yeah, the function is huge)
  603. */
  604. priv.renderTable = function () {
  605. //create table itself
  606. /// console.log('renderTable:: _data', _data);//TODO:DBG:RMME
  607. /// console.log('renderTable:: _uiNode$Table', _uiNode$Table);//TODO:DBG:RMME
  608. //create the header which will later hold both sorting and filtering
  609. /// console.log('L.<?php echo __LINE__; ?> renderTable:: _head', _head);//TODO:DBG:RMME
  610. if (!_head) {
  611. _headSort = _headFilter = _headSpecialFilter = undefined;
  612. //_head = $('<thead></thead>');
  613. // $('<tr class="sort"></tr>').prependTo(_head);
  614. //_uiNode$Table.find('thead').replaceWith(_head);
  615. _head = _uiNode$Table.find('thead');
  616. }
  617. //create the header sorting row
  618. if (!_headSort) {
  619. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadSort...');//TODO:DBG:RMME
  620. priv.renderTableTheadSort();
  621. }
  622. //create the header filtering row
  623. if (!_headFilter && priv.options.filter) {
  624. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
  625. priv.renderTableTheadFilter();
  626. _headFilter = true;
  627. }
  628. //create the header special filters row
  629. if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
  630. priv.renderHeadSpecialFilters();
  631. _headSpecialFilter = true;
  632. }
  633. //create the body
  634. if (!_body) {
  635. _uiNode$Table.find('tbody').remove();
  636. _bodyNode = $('<tbody></tbody>').insertAfter(_head);
  637. //_bodyNode.on('change', '.unique', priv.rowChecked);
  638. //find out what rows to show next...
  639. var rowsAdded = 0;
  640. //slice out the chunk of data we need and create rows
  641. $.each(_data.rows, function (index, props) {
  642. var rowNode = priv.renderRow(props);
  643. if (rowNode) rowNode.appendTo(_bodyNode);
  644. rowsAdded++;
  645. //enough rows created?
  646. if (rowsAdded >= priv.options.pageSize) {
  647. return false;
  648. }
  649. });
  650. if (_state.page == 1) {
  651. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  652. }
  653. //pad with empty rows if we're at last page.
  654. if (_state.page == _totalPages) {
  655. while (rowsAdded < priv.options.pageSize) {
  656. var rowNode = priv.renderRowEmptyNode();
  657. if (rowNode) rowNode.appendTo(_bodyNode);
  658. rowsAdded++;
  659. }
  660. }
  661. }
  662. //create the footer
  663. if (!_foot) {
  664. priv.renderTableTfoot();
  665. priv.renderFooter();
  666. }
  667. _foot = $(_uiNodeCont).next('.foot');
  668. var stickyCol1Width = (12 + 3) * 4 + 2 * 5 + 1;
  669. var stickyCol2Width = 50 + 2 * 5 + 1;
  670. if (undefined === _tableWidth) {
  671. _tableWidth = true;
  672. var contW = jQuery(_uiNodeCont).width();
  673. var th1 = _uiNode$Table.find('.stickyCol1:first');
  674. var th2 = th1.next();
  675. var th1W = th1.innerWidth();
  676. var th2W = 50 + 2 * 5;//th2.innerWidth();
  677. var colsW = stickyCol1Width + stickyCol2Width;
  678. jQuery(_uiNodeCont).css({width:'' + (contW - colsW) + 'px', marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
  679. }
  680. _uiNode$Table.find('.stickyCol1').css({position:'absolute',
  681. left:'0',
  682. top:'auto',
  683. width:'' + stickyCol1Width + 'px',
  684. });
  685. //_uiNode$Table.find('.filter').find('.stickyCol1').css({height:'34px'});
  686. var sortStickyColHeight = _uiNode$Table.find('.sort').find('th:last').outerHeight();
  687. _uiNode$Table.find('.sort').find('.stickyCol1').css({height: sortStickyColHeight + 'px'});
  688. _uiNode$Table.find('.sort').find('.stickyCol2').css({height: sortStickyColHeight + 'px'});
  689. _uiNode$Table.find('.stickyCol2').css({position:'absolute',
  690. left:'' + (stickyCol1Width) + 'px',
  691. top:'auto',
  692. width:'' + stickyCol2Width + 'px',
  693. borderRight: '1px solid silver'
  694. });
  695. if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
  696. $('.btn-toolbar', _foot).remove();
  697. }
  698. if (priv.options.debug) console.log('table created L.<?php echo __LINE__; ?>');
  699. if (typeof priv.options.tableCreated == 'function') {
  700. priv.options.tableCreated.call(_uiNode$Table.get(0), {table: _uiNode$Table.get(0)});
  701. }
  702. };
  703. priv.renderRow = function(props) {
  704. var rowNode = $('<tr></tr>'),
  705. uniqueColName = _state.uniqueCol,
  706. rowPK = (uniqueColName in props)? props[uniqueColName] : null,
  707. cellNode
  708. ;
  709. if (priv.options.rowFunctions || priv.options.filtersClean) {
  710. cellNode = priv.renderCellRowFunctions(priv.options.rowFunctions, rowPK, props);
  711. cellNode.addClass('text-right stickyCol1');
  712. cellNode.appendTo(rowNode);
  713. }
  714. //create checkbox
  715. if (_state.uniqueCol && priv.options.checkboxes) {
  716. var check = _uniqueCols[props[_state.uniqueCol]] != undefined ? 'checked' : '';
  717. var checkable = props['checkable'] === false ? 'disabled' : '';
  718. cellNode = $('<td></td>').appendTo(rowNode);
  719. $('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cellNode);
  720. }
  721. if (uniqueColName) rowNode.data('unique', rowPK);
  722. //create cells
  723. for (var i = 0; i < _state.colsSorted.length; i++) {
  724. var columnName = _state.colsSorted[i],
  725. columnProps = _data.cols[columnName],
  726. val = '',
  727. cellNode,
  728. cellCnt,
  729. format,
  730. showTooltip
  731. ;
  732. if (!columnProps) continue;
  733. if (columnProps.hidden) continue;// TODO: "unique" is hidden
  734. val = props[columnName];
  735. cellNode = $('<td></td>').appendTo(rowNode);
  736. if (columnName !== uniqueColName) {
  737. cellNode.on('dblclick', {id:rowPK, col:columnName}, priv.rowDblClicked);
  738. }
  739. if (i == 1) {// primaryKey(ID)
  740. cellCnt = $('<div></div>').appendTo(cellNode);// fix dblclick for copy
  741. cellNode.addClass('stickyCol2');
  742. } else {
  743. cellCnt = $('<span></span>').appendTo(cellNode);
  744. }
  745. cellNode.data('column', columnName);
  746. if (val === undefined) continue;
  747. format = props[columnName + 'Format'] || columnProps.format || '{0}';
  748. showTooltip = true;
  749. switch (columnProps.type) {
  750. case "string":
  751. cellCnt.html(format.f(val));
  752. break;
  753. case "number":
  754. val = Number(val);
  755. var forceDecimals = !isNaN(columnProps.decimals);
  756. if (forceDecimals) cellCnt.html(format.f(val.toFixed(columnProps.decimals)));
  757. else {
  758. (val || 0) % 1 === 0
  759. ? cellCnt.html(format.f(val))
  760. : cellCnt.html(format.f(val.toFixed(priv.options.types.number.decimals || 2)));
  761. }
  762. break;
  763. case "date":
  764. cellCnt.html(format.f(val));
  765. break;
  766. case "bool":
  767. $('<input type="checkbox" {0} disabled />'.f(val ? "checked" : "")).appendTo(cellCnt);
  768. break;
  769. case "special":
  770. cellCnt.html(format.f(val));
  771. break;
  772. case "simpleLink":
  773. var valLink = String(val);
  774. if (undefined !== columnProps._tsRetId
  775. && (0 === columnProps._tsRetId || '0' === columnProps._tsRetId)
  776. && undefined !== columnProps._tsSimpleLink) {
  777. valLink = columnProps._tsSimpleLink.format;
  778. $.each(columnProps._tsSimpleLink.aliasMap, function (i, v) {
  779. //console.log('simpleLink aliasMap columnName:', columnName, 'i:', i, 'v:', v, 'props['+v+']', props[v], 'val', val, 'typeof val', typeof val);
  780. if (undefined !== props[v]) {
  781. valLink = valLink.replace(new RegExp('\{' + i + '\}', 'g'), props[v]);
  782. }
  783. });
  784. }
  785. cellCnt.html(format.f(valLink));
  786. break;
  787. case "geom":
  788. cellCnt.TableAjaxGeomField({
  789. recordID: rowPK,
  790. fieldValue: val,
  791. hasValueClassName: 'cell-mapfld-hasValue',
  792. //removeUrl: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + rowPK,
  793. linkClassNamePrefix: 'cell-mapfld',
  794. linkSelectClassName: 'select',
  795. linkSelectAddClassNames: 'glyphicon glyphicon-map-marker',
  796. linkRemoveClassName: 'remove',
  797. linkRemoveAddClassNames: 'glyphicon glyphicon-remove',
  798. onSelect: function(recordID, geomShape) {
  799. if (priv.options.debug) console.log('recordID:', recordID, 'geomShape:', geomShape);
  800. priv.mapEditorShow();
  801. _mapEditor.TableAjaxMapSelectRecord(recordID, geomShape);
  802. },
  803. onRemove: function(geomField, recordID, geomShape) {
  804. if (confirm('Czy usunąć obiekt z mapy dla rekordu ' + recordID + '?')) {
  805. if (!recordID) return;
  806. var selectedRecordId = recordID;
  807. function notifyAjaxCallback(data) {
  808. var notify = {};
  809. notify.type = (data && data.type)? data.type : '';
  810. notify.msg = (data && data.msg)? data.msg : '';
  811. switch (notify.type) {
  812. case 'success':
  813. if (!notify.msg) notify.msg = 'Usunięto obiekt z mapy dla rekordu ' + selectedRecordId;
  814. break;
  815. case 'info':
  816. if (!notify.msg) notify.msg = 'Rekord nie był powiązany z żadnym obiektem na mapie';
  817. break;
  818. case 'error':
  819. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  820. break;
  821. case 'warning':
  822. notify.type = 'warn';
  823. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  824. break;
  825. default:
  826. notify.msg = 'Nieznany błąd';
  827. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  828. notify.type = '';
  829. }
  830. jQuery.notify(notify.msg, notify.type);
  831. }
  832. $.ajax({
  833. data: {},
  834. dataType: 'json',
  835. type: "POST",
  836. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + recordID
  837. })
  838. .done(function(data, textStatus, jqXHR){
  839. notifyAjaxCallback(data);
  840. if (priv.options.debug) console.log('data.record.the_geom:', data.record.the_geom);
  841. if (data && data.record && data.record.the_geom) {
  842. if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
  843. geomField.setValue(data.record.the_geom);
  844. }
  845. else if (data && data.record) {
  846. if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
  847. geomField.setValue(data.record.the_geom);
  848. }
  849. _mapEditor.TableAjaxMapRefresh();
  850. })
  851. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  852. if (jqXHR.responseJSON) {
  853. notifyAjaxCallback(jqXHR.responseJSON);
  854. }
  855. else {
  856. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  857. if (jqXHR.status == 404) {
  858. jQuery.notify(jqXHR.responseText, 'error');
  859. } else {
  860. jQuery.notify(jqXHR.responseText, 'warn');
  861. }
  862. }
  863. });
  864. }
  865. }
  866. });
  867. break;
  868. }
  869. if (columnProps._tsRetId) {
  870. showTooltip = false;
  871. if (columnProps._tsRetId > 0) {
  872. cellCnt.on('click', {id:rowPK, col:columnName, friendly:columnProps.friendly, value:format.f(val)}, priv.popoverCellTypeSpecial);
  873. }
  874. }
  875. if (i > 1 && priv.options.longDesc) {// TODO: use better check for columns: functions and pk
  876. cellNode.addClass('tbl-short-txt');
  877. if (showTooltip) {
  878. cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
  879. }
  880. }
  881. }
  882. return rowNode;
  883. };
  884. priv.renderCellRowFunctions = function(rowFunctions, rowPK, rowProps) {
  885. var cellNode = $('<td></td>'),
  886. keys = Object.keys(rowFunctions),
  887. total = keys.length,
  888. moreFuncBtnNode,
  889. moreFunctions = [],
  890. idx
  891. ;
  892. idx = keys.indexOf('hist');
  893. if (idx !== -1) {
  894. histFunc = keys.splice(idx, 1);
  895. keys.push('hist');
  896. }
  897. moreFunctions = keys.splice(3);
  898. keys.forEach(function(key) {
  899. var funObj = rowFunctions[key];
  900. $(funObj.f(rowPK)).appendTo(cellNode);
  901. });
  902. moreFuncBtnNode = $('<a href="#" style="text-decoration:none" title="Więcej funkcji" class="glyphicon glyphicon-menu-hamburger"> </a>');
  903. moreFuncBtnNode.on('click', {rowPK: rowPK, rowFunctions: rowFunctions, more: moreFunctions}, priv.popoverCellMoreFunctions);
  904. moreFuncBtnNode.appendTo(cellNode);
  905. return cellNode;
  906. };
  907. priv.popoverCellMoreFunctions = function (e) {
  908. e.preventDefault();
  909. e.stopPropagation();
  910. console.log('priv.popoverCellMoreFunctions::rowPK', e.data.rowPK, 'moreFunctions', e.data.more, 'rowFunctions', e.data.rowFunctions);
  911. if ('rowPK' in e.data && e.data.rowPK > 0) {
  912. var lastId = _popoverCell.data('rowid'),
  913. lastCol = _popoverCell.data('col'),
  914. rowPK = e.data.rowPK,
  915. moreFuncHtml = 'TODO: moreFunctions=['+e.data.more.join(',')+']';
  916. if (lastId == e.data.rowPK && lastCol == 'moreFunctions') {
  917. //_popoverCellCurrent.popover('toggle');
  918. }
  919. else {
  920. if (_popoverCellCurrent) {
  921. _popoverCellCurrent.popover('destroy');
  922. }
  923. _popoverCell.data('rowid', rowPK);
  924. _popoverCell.data('col', 'rowFunctions');
  925. _popoverCell.html(moreFuncHtml + '<div class="popoverCellContent" style="white-space:normal"></div>');
  926. _popoverCellCurrent = jQuery(e.currentTarget);
  927. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  928. var opts = {
  929. placement: 'right',
  930. trigger: 'click',
  931. template: '',
  932. html: true,
  933. content: _popoverCell.html()
  934. }
  935. opts.template += '<div class="popover" role="tooltip">';
  936. {
  937. opts.template += '<div class="arrow"></div>';
  938. //opts.template += '<h3 class="popover-title"></h3>';
  939. opts.template += '<div style="width:300px;display:block;position:relative;padding:0 20px 0 0;">';
  940. {
  941. opts.template += '<div class="popover-title">';
  942. opts.template += '</div>';
  943. opts.template += '<button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>';
  944. }
  945. opts.template += '</div>';
  946. opts.template += '<div class="popover-content"></div>';
  947. }
  948. opts.template += '</div>';
  949. _popoverCellCurrent.popover(opts);
  950. _popoverCellCurrent.on('shown.bs.popover', function(e) {
  951. if (_popoverCellCurrent) {
  952. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  953. if (popoverNodeId) {
  954. jQuery('#' + popoverNodeId).css({maxWidth:'400px', width:'300px'});
  955. }
  956. }
  957. priv.ajaxLoadMoreFunctionsCell(rowPK);
  958. });
  959. _popoverCellCurrent.popover('show');
  960. }
  961. } else {
  962. if (priv.options.debug) console.log('NO data');
  963. return false;
  964. }
  965. return;
  966. };
  967. priv.ajaxLoadMoreFunctionsCell = function(rowPK) {
  968. if (_popoverCellAjaxXhr) {
  969. _popoverCellAjaxXhr.abort();
  970. }
  971. var addHtml = '<p>TODO: more functions for ' + rowPK + '</p>';
  972. _popoverCell.append(addHtml);
  973. _popoverCell.find('.popoverCellContent').append(addHtml);
  974. _popoverCellAjaxXhr = $.ajax({
  975. type: 'GET',
  976. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=MORE_FUNCTIONS_CELL&ID=' + rowPK,
  977. dataType: 'json',
  978. contentType: "application/json; charset=utf-8",
  979. data: '',
  980. success: function(data) {
  981. if (data && 'success' === data.type) {
  982. var addHtml = '';
  983. addHtml += 'TODO: ...';
  984. //_popoverCell.append(addHtml);// cache
  985. if (_popoverCellCurrent) {
  986. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  987. if (popoverNodeId) {
  988. jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
  989. }
  990. }
  991. }
  992. }
  993. });
  994. };
  995. priv.renderRowEmptyNode = function() {
  996. var rowNode = $('<tr></tr>');
  997. if (priv.options.rowFunctions || priv.options.filtersClean) {
  998. $('<td class="text-right stickyCol1">&nbsp;</td>').appendTo(rowNode);
  999. }
  1000. if (_state.uniqueCol && priv.options.checkboxes) {
  1001. $('<td><input disabled type="checkbox" /></td>').appendTo(rowNode);
  1002. }
  1003. for (var i = 0; i < _state.colsSorted.length; i++) {
  1004. var columnName = _state.colsSorted[i],
  1005. columnProps = _data.cols[columnName]
  1006. ;
  1007. if (!columnProps) return;
  1008. if (columnProps.hidden) continue;// "unique" is hidden - TODO: rm "unique" from _state.colsSorted ?
  1009. if (i == 1) {// TODO: 1 is pk - use better check
  1010. $('<td class="stickyCol2">&nbsp;</td>').appendTo(rowNode);
  1011. } else {
  1012. $('<td>&nbsp;</td>').appendTo(rowNode);
  1013. }
  1014. }
  1015. return rowNode;
  1016. };
  1017. priv.renderTableTheadSort = function() {
  1018. var nodeClass = 'tblAjax__' + 'head__sort',
  1019. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  1020. node;
  1021. // currentNode.find('i').tooltip('hide');
  1022. node = $('<tr class="sort ' + nodeClass + '"></tr>');
  1023. //create the functions column
  1024. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1025. var headCell = $('<th class="text-right head-info stickyCol1"></th>').appendTo(node);
  1026. $.map(priv.options.tblFunctions, function(funObj, funName){
  1027. var funHtml = $('<a></a>');
  1028. funHtml.attr('href', funObj.href || '#');
  1029. if (funObj.title) funHtml.attr('title', funObj.title);
  1030. if (funObj.icon) funHtml.html('<span class="glyphicon glyphicon-' + funObj.icon + '"></span> ');
  1031. if (funObj.method && priv[funObj.method] && typeof priv[funObj.method] == 'function') {
  1032. funHtml.on('click', priv[funObj.method]);
  1033. }
  1034. funHtml.appendTo(headCell);
  1035. });
  1036. }
  1037. //create the checkall toggle
  1038. if (_state.uniqueCol && priv.options.checkboxes) {
  1039. var checked = _checkToggleChecked ? 'checked' : '';
  1040. var headCell = $('<th></th>').appendTo(node);
  1041. var elem = $('<input {0} class="checkToggle" type="checkbox" />'.f(checked)).appendTo(headCell);
  1042. elem.on('change', priv.checkToggleChanged);
  1043. }
  1044. //create the sortable headers
  1045. for (var i = 0; i < _state.colsSorted.length; i++) {
  1046. var column = _state.colsSorted[i];
  1047. var props = _data.cols[column];
  1048. if (!props.hidden) {
  1049. var headCell = $('<th class="ta-ordering"></th>').appendTo(node);
  1050. if (i == 1) headCell.addClass('stickyCol2');
  1051. if (false) {// TODO: old way
  1052. var link = $('<a class="pull-left" href="#">{0}</a>'.f(props.friendly || column));
  1053. link.on('click', {column: column}, priv.columnClicked).appendTo(headCell);
  1054. if (props.tooltip) {
  1055. $('<i class="glyphicon glyphicon-info-sign"></i>').tooltip({
  1056. title: props.tooltip.trim(),
  1057. html: true,
  1058. container: 'body',
  1059. placement: "top",
  1060. delay: {
  1061. show: 500,
  1062. hide: 100
  1063. }
  1064. }).appendTo(link);
  1065. }
  1066. //Add sort arrow
  1067. if (column == _state.filters.currSortCol) {
  1068. if (_state.filters.currSortFlip) $('<i class="glyphicon glyphicon-chevron-down pull-right"></i>').appendTo(headCell);
  1069. else $('<i class="glyphicon glyphicon-chevron-up pull-right"></i>').appendTo(headCell);
  1070. }
  1071. //Add hide btn
  1072. if (column != 'ID') {
  1073. var hideColBtn = $('<i class="glyphicon glyphicon-remove pull-right hover-show"></i>');
  1074. hideColBtn.on('click', {column: column}, priv.columnHideClicked);
  1075. hideColBtn.appendTo(headCell);
  1076. }
  1077. }
  1078. if (props.type != 'special' && props.type != 'geom') {
  1079. headCell.on('click', {column: column}, priv.columnClicked);
  1080. }
  1081. var colTitle = column;
  1082. if (props.description && props.description.length > 0) {
  1083. colTitle = props.description;
  1084. colTitle += ' (' + column + ')';
  1085. }
  1086. else if (props._tsRetId > 0) {
  1087. colTitle = 'Kliknij na pole i przejdź do powiązanych rekordów (' + colTitle + ')';
  1088. }
  1089. if (props.friendly) {
  1090. var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(props.friendly, colTitle));
  1091. } else {
  1092. var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(column, colTitle));
  1093. }
  1094. headCnt.appendTo(headCell);
  1095. //Add sort arrow
  1096. if (column == _state.filters.currSortCol) {
  1097. if (_state.filters.currSortFlip) headCell.addClass('ta-ordering-down');
  1098. else headCell.addClass('ta-ordering-up');
  1099. }
  1100. if (column != 'ID') {
  1101. var hideColBtn = $('<i class="glyphicon glyphicon-remove remove-cell"></i>');
  1102. hideColBtn.on('click', {column: column}, priv.columnHideClicked);
  1103. hideColBtn.appendTo(headCell);
  1104. }
  1105. }
  1106. }
  1107. currentNode.replaceWith(node);
  1108. };
  1109. priv.renderHeadSpecialFilters = function() {
  1110. var nodeClass = 'tblAjax__' + 'head__specialFilter',
  1111. currentNode = $(_uiNodeCont).prev('.' + nodeClass),
  1112. node;
  1113. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
  1114. if (!priv.options.specialFilterFunctions) {
  1115. return;
  1116. }
  1117. var node = $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>');
  1118. $.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
  1119. var btnHtml, btnSelected, groupHtml = $('<div class="btn-group"></div>');
  1120. // _state.specialFilters[e.data.group] = e.data.value;
  1121. if (groupName in _state.specialFilters) {
  1122. btnSelected = _state.specialFilters[groupName];
  1123. }
  1124. if (groupObj.icon) {
  1125. $('<button class="btn btn-xs btn-default" title="' + groupName + '"><i class="' + groupObj.icon + '"></i></button>').appendTo(groupHtml);
  1126. }
  1127. $.map(groupObj.btns, function(btnObj, btnName) {
  1128. btnHtml = $('<button class="btn btn-xs btn-default' + ((btnSelected && btnSelected == btnObj.value)? ' active' : '') + '">' + btnName + '</button>').appendTo(groupHtml);
  1129. btnHtml.on('click', {group: groupName, value: btnObj.value}, priv.specialFilterChanged);
  1130. });
  1131. btnHtml = $('<button class="btn btn-xs btn-default' + ((!btnSelected)? ' disabled' : '') + '" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  1132. btnHtml.on('click', {group: groupName, value: ''}, priv.specialFilterChanged);
  1133. groupHtml.appendTo(node);
  1134. });
  1135. currentNode.replaceWith(node);
  1136. };
  1137. priv.renderTableTheadFilter = function() {
  1138. var nodeClass = 'tblAjax__' + 'head__filter',
  1139. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  1140. node;
  1141. // currentNode.find('i').tooltip('hide');
  1142. node = $('<tr class="filter ' + nodeClass + '"></tr>');
  1143. //_head.find(".filter").remove();
  1144. //_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
  1145. var headCell;
  1146. var elem;
  1147. var placeHolder = '';
  1148. var tooltip = '';
  1149. //create the functions column
  1150. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1151. var headCell = $('<th class="text-right stickyCol1"></th>').appendTo(node);
  1152. headCell.css({padding: '0'});
  1153. if (priv.options.filtersClean) {
  1154. var elem = $('<button title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button>').appendTo(headCell);
  1155. elem.on('click', priv.filtersClean);
  1156. }
  1157. }
  1158. //create the filter checkbox
  1159. if (_state.uniqueCol && priv.options.checkboxes) {
  1160. tooltip = priv.options.types.bool.filterTooltip || 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked';
  1161. headCell = $('<th></th>').appendTo(node);
  1162. elem = $('<input class="filter indeterminate" checked type="checkbox" />').appendTo(headCell);
  1163. $.map(_state.filters.filterCols, function (colProps, col) {
  1164. if (col == "unique") {
  1165. if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
  1166. else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
  1167. else if (colProps.filter == '') elem.addClass('indeterminate');
  1168. }
  1169. });
  1170. if (tooltip) {
  1171. elem.tooltip({
  1172. title: tooltip.trim(),
  1173. html: true,
  1174. container: 'body',
  1175. trigger: 'hover',
  1176. placement: 'top',
  1177. delay: {
  1178. show: 500,
  1179. hide: 100
  1180. }
  1181. });
  1182. }
  1183. elem.on('click', {column: "unique"}, priv.filterChanged);
  1184. }
  1185. //create the column filters
  1186. for (var i = 0; i < _state.colsSorted.length; i++) {
  1187. var column = _state.colsSorted[i];
  1188. var props = _data.cols[column];
  1189. tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
  1190. placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
  1191. if (!props.hidden) {
  1192. headCell = $('<th></th>').appendTo(node);
  1193. headCell.css({padding: '0'});
  1194. if (i == 1) headCell.addClass('stickyCol2');
  1195. // @mark MarkTableAjaxFilterColType
  1196. switch (props.type || 'string') {
  1197. case "number":
  1198. if (placeHolder == undefined) placeHolder = priv.options.types.number.placeHolder;
  1199. placeHolder = (placeHolder === true || placeHolder == undefined) ? '10..20 =50' : placeHolder === false ? '' : placeHolder;
  1200. if (tooltip == undefined) tooltip = priv.options.types.number.filterTooltip;
  1201. tooltip = (tooltip === true || tooltip == undefined) ? 'Values 10 to 20:<br/>10..20<br/>Values exactly 50:<br/>=50' : tooltip === false ? '' : tooltip;
  1202. elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
  1203. elem.on('keyup', {column: column}, priv.filterChanged);
  1204. break;
  1205. case "date":
  1206. if (placeHolder == undefined) placeHolder = priv.options.types.date.placeHolder;
  1207. placeHolder = (placeHolder === true || placeHolder == undefined) ? '-7..0' : placeHolder === false ? '' : placeHolder;
  1208. if (tooltip == undefined) tooltip = priv.options.types.date.filterTooltip;
  1209. tooltip = (tooltip === true || tooltip == undefined) ? 'Today:<br/>0..1<br/>A week today excluded:<br/>-7..0' : tooltip === false ? '' : tooltip;
  1210. elem = $('<div><input placeholder="{0}" class="filter" type="text" /></div>'.f(placeHolder));
  1211. if (priv.options.types.date.datePicker === true || priv.options.types.date.datePicker == undefined)
  1212. {
  1213. if ($().datepicker)
  1214. {
  1215. elem.addClass('date-wrap');
  1216. var today = 0;//new priv.ext.XDate(false).setHours(0, 0, 0, 0).toString('yyyy-MM-dd');
  1217. var dp = $('<div style="float:right" class="date" data-date="{0}" data-date-format="{1}" />'.f(today, 'yyyy-mm-dd')).appendTo(elem);
  1218. $('<input style="display:none" type="text" />').appendTo(dp);
  1219. $('<span class="add-on"><i class="glyphicon glyphicon-chevron-right"></i></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
  1220. $('<span class="add-on"><i class="glyphicon glyphicon-chevron-left"></i></span>').on('click', {op: "r"}, priv.dpOpChanged).appendTo(dp);
  1221. dp.datepicker({weekStart:1});
  1222. dp.on('changeDate', {column: column, input: $('input.filter', elem)}, priv.dpClicked);
  1223. }
  1224. else
  1225. if (priv.options.debug) console.log('datepicker plugin not found');
  1226. }
  1227. elem.on('keyup', 'input.filter', {column: column}, priv.filterChanged);
  1228. break;
  1229. case "bool":
  1230. if (tooltip == undefined) tooltip = priv.options.types.bool.filterTooltip;
  1231. tooltip = (tooltip === true || tooltip == undefined) ? 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked' : tooltip === false ? '' : tooltip;
  1232. elem = $('<input class="filter indeterminate" checked type="checkbox" />');
  1233. elem.on('click', {column: column}, priv.filterChanged);
  1234. break;
  1235. case "string":
  1236. if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
  1237. placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
  1238. if (tooltip == undefined) tooltip = priv.options.types.string.filterTooltip;
  1239. tooltip = (tooltip === true || tooltip == undefined) ? 'Find str: str<br/>Find all but str: !str<br/>Find str inside: %str%' : tooltip === false ? '' : tooltip;
  1240. elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
  1241. elem.on('keyup', {column: column}, priv.filterChanged);
  1242. break;
  1243. case "special":
  1244. elem = $('<div>&nbsp;</div>');
  1245. break;
  1246. case "simpleLink":
  1247. elem = $('<div>&nbsp;</div>');
  1248. break;
  1249. case "geom":
  1250. if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
  1251. placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
  1252. elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
  1253. elem.on('keyup', {column: column}, priv.filterChanged);
  1254. break;
  1255. case "none":
  1256. elem = $('<div>&nbsp;</div>');
  1257. break;
  1258. }
  1259. if (false) {// tooltip OFF - (tooltip)
  1260. elem.tooltip({
  1261. title: tooltip.trim(),
  1262. html: true,
  1263. container: 'body',
  1264. trigger: 'focus',
  1265. placement: 'top',
  1266. delay: {
  1267. show: 500,
  1268. hide: 100
  1269. }
  1270. });
  1271. }
  1272. if (elem && props.filter) {
  1273. $.map(_state.filters.filterCols, function (colProps, col) {
  1274. if (col == column) {
  1275. var columnSettings = _data.cols[col];
  1276. if (columnSettings.type == 'bool') {
  1277. if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
  1278. else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
  1279. else if (colProps.filter == '') elem.addClass('indeterminate');
  1280. }
  1281. else elem.val(colProps.filter);
  1282. }
  1283. });
  1284. if (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]) {
  1285. elem.prop('disabled', true);
  1286. }
  1287. elem.appendTo(headCell);
  1288. _filterFields[column] = elem;
  1289. }
  1290. }
  1291. }
  1292. currentNode.replaceWith(node);
  1293. };
  1294. priv.renderTableTfoot = function() {
  1295. _uiNode$Table.find('tfoot').remove();
  1296. _foot = $('<tfoot></tfoot>').insertAfter(_bodyNode);
  1297. //$(_uiNodeCont).next('.foot').replaceWith(_foot);
  1298. };
  1299. priv.renderFooter = function() {
  1300. priv.renderFooterInfo();
  1301. priv.renderFooterPagination();
  1302. priv.renderFooterPageSizes();
  1303. priv.renderFooterColumnPicker();
  1304. priv.renderFooterFunctions();
  1305. priv.renderFooterExport();
  1306. };
  1307. priv.renderFooterInfo = function() {
  1308. var nodeClass = 'tblAjax__' + 'footer__toolbar__info',
  1309. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1310. node;
  1311. if (priv.options.debug) console.log('Render: ', nodeClass);
  1312. node = $('<div class="foot-info ' + nodeClass + '"></div>');
  1313. //console.log('renderFooterInfo total', _data.total, 'page', _state.page, 'priv.options.pageSize', priv.options.pageSize);
  1314. var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
  1315. var total = _data.total;
  1316. var toRow = Math.min(fromRow + _state.pageSize, total);
  1317. if (_data.total > 0) {
  1318. $('<p>Wiersze od {0} do {1} z {2}</p>'.f(fromRow + 1, toRow, total)).appendTo(node);
  1319. } else {
  1320. $('<p>Brak wierszy pasujących do kryteriów wyszukiwania</p>').appendTo(node);
  1321. }
  1322. currentNode.replaceWith(node);
  1323. };
  1324. priv.renderFooterPagination = function() {
  1325. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagination',
  1326. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1327. node;
  1328. var currPage = _state.page;
  1329. var totalPages = Math.ceil(_data.total / _state.pageSize);
  1330. if (priv.options.debug) console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage);
  1331. /// console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage, '_state.page', _state.page);
  1332. if (_data.total > 0) {
  1333. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1334. //create the pager.
  1335. var lowerPage = currPage - 2;
  1336. var upperPage = currPage + 2;
  1337. if (upperPage > totalPages) {
  1338. var diff = upperPage - totalPages;
  1339. upperPage = totalPages;
  1340. lowerPage -= diff;
  1341. }
  1342. if (lowerPage < 1) lowerPage = 1;
  1343. if (upperPage < 5) upperPage = 5;
  1344. //$('<li class="{0}"><a href="#">&lt;&lt;</a></li>'.f(currPage == 1 ? 'disabled' : ''))
  1345. $('<button type="button" class="btn btn-default{0}">&lt;&lt;</button>'.f(currPage == 1 ? ' disabled' : ''))
  1346. .on('click', {pageIndex: 1}, priv.pageChanged)
  1347. .appendTo(node);
  1348. //$('<li class="{0}"><a href="#">&lt;</a></li>'.f(currPage == 1 ? 'disabled' : ''))
  1349. $('<button type="button" class="btn btn-default{0}">&lt;</button>'.f(currPage == 1 ? ' disabled' : ''))
  1350. .on('click', {pageIndex: currPage - 1}, priv.pageChanged)
  1351. .appendTo(node);
  1352. for (var i = lowerPage; i <= upperPage; i++) {
  1353. var link;
  1354. //if (i != currPage) link = $('<li class="{1}"><a href="#">{0}</a></li>'.f(i, i > totalPages ? 'disabled' : ''));
  1355. if (i != currPage) link = $('<button type="button" class="btn btn-default{1}">{0}</button>'.f(i, i > totalPages ? 'disabled' : ''));
  1356. //if (i == currPage) link = $('<li class="active"><a href="#">{0}</a></li>'.f(i));
  1357. if (i == currPage) link = $('<button type="button" class="btn btn-default active">{0}</button>'.f(i));
  1358. if (link) {
  1359. link.on('click', {pageIndex: i}, priv.pageChanged);
  1360. link.appendTo(node);
  1361. }
  1362. }
  1363. //$('<li class="{0}"><a href="#">&gt;</a></li>'.f(currPage == totalPages ? 'disabled' : ''))
  1364. $('<button type="button" class="btn btn-default{0}">&gt;</button>'.f(currPage == totalPages ? ' disabled' : ''))
  1365. .on('click', {pageIndex: currPage + 1}, priv.pageChanged)
  1366. .appendTo(node);
  1367. //$('<li class="{0}"><a href="#">&gt;&gt;</a></li>'.f(currPage == totalPages ? 'disabled' : ''))
  1368. $('<button type="button" class="btn btn-default{0}">&gt;&gt;</button>'.f(currPage == totalPages ? ' disabled' : ''))
  1369. .on('click', {pageIndex: totalPages}, priv.pageChanged)
  1370. .appendTo(node);
  1371. } else {
  1372. node = $('<span class="' + nodeClass + '"></span>');
  1373. }
  1374. currentNode.replaceWith(node);
  1375. };
  1376. priv.renderFooterPageSizes = function() {
  1377. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagesizes',
  1378. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1379. node;
  1380. if (priv.options.debug) console.log('Render: ', nodeClass);
  1381. if (_data.total > 0 && priv.options.pageSizes.length > 0) {
  1382. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1383. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy&nbsp;</button>').appendTo(node);
  1384. var span = $('<span class="caret"></span>').appendTo(btn);
  1385. var ul = $('<ul class="dropdown-menu">').appendTo(node);
  1386. $.each(priv.options.pageSizes, function (index, val) {
  1387. var li = $('<li></li>').appendTo(ul);
  1388. if (val == priv.options.pageSize) {
  1389. $('<a style="color:#337AB7;">{0}</a>'.f(val)).appendTo(li);
  1390. } else {
  1391. $('<a href="#">{0}</a>'.f(val)).appendTo(li);
  1392. }
  1393. });
  1394. node.on('click', 'a', priv.pageSizeChanged);
  1395. } else {
  1396. node = $('<span class="' + nodeClass + '"></span>');
  1397. }
  1398. currentNode.replaceWith(node);
  1399. };
  1400. priv.renderFooterColumnPicker = function() {
  1401. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  1402. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1403. node;
  1404. if (priv.options.debug) console.log('Render: ', nodeClass);
  1405. if (priv.options.columnPicker) {
  1406. node = $('<div class="btn-group dropup columnpicker ' + nodeClass + '"></div>');
  1407. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Kolumny&nbsp;</button>').appendTo(node);
  1408. var span = $('<span class="caret"></span>').appendTo(btn);
  1409. var ul = $('<ul class="dropdown-menu">').appendTo(node);
  1410. $.each(_data.cols, function (col, props) {
  1411. if (props.type != "unique" && col != 'ID') {
  1412. var li = $('<li></li>').appendTo(ul),
  1413. label = props.friendly || col;
  1414. label = label.replace(/<br\/?>/g, ' ');
  1415. $('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>'.f((props.hidden) ? '' : 'checked', col, label)).appendTo(li);
  1416. }
  1417. });
  1418. node.on('click', 'input', priv.columnPickerClicked);
  1419. } else {
  1420. node = $('<span class="' + nodeClass + '"></span>');
  1421. }
  1422. currentNode.replaceWith(node);
  1423. };
  1424. priv.renderFooterFunctions = function() {
  1425. var nodeClass = 'tblAjax__' + 'footer__toolbar__functions',
  1426. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1427. node;
  1428. if (priv.options.debug) console.log('Render: ', nodeClass);
  1429. if (priv.options.tblFunctions) {
  1430. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1431. $.map(priv.options.tblFunctions, function(funObj, funName){
  1432. var funHtml = $('<button class="btn btn-sm btn-default"></button>');
  1433. if (funObj.title) funHtml.attr('title', funObj.title);
  1434. if (funObj.method) funHtml.on('click', priv[funObj.method]);
  1435. else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
  1436. var funIconHtml = $('<i></i>');
  1437. if (funObj.icon) funIconHtml.attr('class', 'glyphicon glyphicon-' + funObj.icon);
  1438. funIconHtml.prependTo(funHtml);
  1439. funHtml.addClass('btn');
  1440. funHtml.appendTo(node);
  1441. });
  1442. } else {
  1443. node = $('<span class="' + nodeClass + '"></span>');
  1444. }
  1445. currentNode.replaceWith(node);
  1446. };
  1447. priv.renderFooterExport = function() {
  1448. var nodeClass = 'tblAjax__' + 'footer__toolbar__export',
  1449. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1450. node;
  1451. if (priv.options.debug) console.log('Render: ', nodeClass);
  1452. if (priv.options.exportFields.length) {
  1453. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1454. var btn = $('<button class="btn btn-sm dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;</button>').appendTo(node);
  1455. var span = $('<span class="caret"></span>').appendTo(btn);
  1456. var ul = $('<ul class="dropdown-menu">').appendTo(node);
  1457. $.each(_data.cols, function (col, props) {
  1458. if (-1 !== priv.options.exportFields.indexOf(col)) {
  1459. var li = $('<li></li>').appendTo(ul);
  1460. $('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>'.f((_exportFieldsSelect[col])? 'checked' : '', col, props.friendly || col)).appendTo(li);
  1461. li.on('click', 'input', priv.exportFieldChanged);
  1462. }
  1463. });
  1464. var li = $('<li></li>').appendTo(ul);
  1465. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
  1466. li.on('click', 'a', priv.exportToHTML);
  1467. var li = $('<li></li>').appendTo(ul);
  1468. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
  1469. li.on('click', 'a', priv.exportToCSV);
  1470. } else {
  1471. node = $('<span class="' + nodeClass + '"></span>');
  1472. }
  1473. currentNode.replaceWith(node);
  1474. };
  1475. priv.renderInlineEditBox = function() {
  1476. var nodeClass = 'tblAjax__' + 'inlineEditBox',
  1477. currentNode = $(_uiNodeCont).parent().children('.' + nodeClass),
  1478. node;
  1479. var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
  1480. /// console.log('L.<?php echo __LINE__; ?> Render: priv.renderInlineEditBox, currentNode.html:', currentNode.html(), currentNode);
  1481. var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
  1482. var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
  1483. var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
  1484. var iebHead = $('<div class="modal-header" style="cursor:pointer">').appendTo(frmInlineEdit);
  1485. $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>').appendTo(iebHead);
  1486. $('<h4 id="myModalLabel">Edytuj</h4>').appendTo(iebHead);
  1487. var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
  1488. var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
  1489. $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
  1490. $('<input type="hidden" name="col" value="">').appendTo(iebBody);
  1491. $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
  1492. var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
  1493. $('<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
  1494. var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
  1495. frmInlineEdit.on('submit', function() {
  1496. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  1497. var data = inlineEditBox$Node.find('form').serialize();
  1498. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  1499. function notifyAjaxCallback(data) {
  1500. var notify = {};
  1501. notify.type = (data && data.type)? data.type : '';
  1502. notify.msg = (data && data.msg)? data.msg : '';
  1503. switch (notify.type) {
  1504. case 'success':
  1505. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  1506. break;
  1507. case 'info':
  1508. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  1509. break;
  1510. case 'error':
  1511. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1512. break;
  1513. case 'warning':
  1514. notify.type = 'warn';
  1515. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1516. break;
  1517. default:
  1518. notify.msg = 'Nieznany błąd';
  1519. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1520. notify.type = '';
  1521. }
  1522. jQuery.notify(notify.msg, notify.type);
  1523. }
  1524. $.ajax({
  1525. data: data,
  1526. dataType: 'json',
  1527. type: "POST",
  1528. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE_SAVE'
  1529. })
  1530. .done(function(data, textStatus, jqXHR){
  1531. notifyAjaxCallback(data);
  1532. publ.refresh();
  1533. inlineEditBox$Node.modal('hide');
  1534. })
  1535. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  1536. if (jqXHR.responseJSON) {
  1537. notifyAjaxCallback(jqXHR.responseJSON);
  1538. }
  1539. else {
  1540. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  1541. if (jqXHR.status == 404) {
  1542. jQuery.notify(jqXHR.responseText, 'error');
  1543. } else {
  1544. jQuery.notify(jqXHR.responseText, 'warn');
  1545. }
  1546. }
  1547. inlineEditBox$Node.modal('hide');
  1548. });
  1549. return false;
  1550. });
  1551. currentNode.replaceWith(node);
  1552. };
  1553. priv.exportFieldChanged = function (e) {
  1554. e.stopPropagation();
  1555. var column = $(this).val();
  1556. _exportFieldsSelect[column] = !_exportFieldsSelect[column];
  1557. };
  1558. priv.exportToHTML = function (e) {
  1559. priv.exportData('html', $(this), e);
  1560. };
  1561. priv.exportToCSV = function (e) {
  1562. priv.exportData('csv', $(this), e);
  1563. };
  1564. priv.exportData = function (format, node, e) {
  1565. var exportFields = [];
  1566. $.each(_exportFieldsSelect, function (col, selected) {
  1567. if (selected) {
  1568. exportFields.push(col);
  1569. }
  1570. });
  1571. if (!exportFields.length) {
  1572. alert('Nie wybrano żadnych pól do eksportu.');
  1573. e.preventDefault();
  1574. return false;
  1575. }
  1576. var limit = 10000;
  1577. if (!_data.total || _data.total <= 0) {
  1578. alert('Brak rekordów do eksportu.');
  1579. e.preventDefault();
  1580. return false;
  1581. }
  1582. if (_data.total > limit) {
  1583. if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
  1584. e.preventDefault();
  1585. return false;
  1586. }
  1587. }
  1588. var exportUrl = 'index.php?MENU_INIT=VIEWTABLE_AJAX_EXPORT&ZASOB_ID=<?php echo $this->_zasobID; ?>';
  1589. if ('csv' == format) exportUrl += '&HEADER_NOT_INIT=YES';
  1590. exportUrl += '&format=' + format;
  1591. exportUrl += '&flds=' + exportFields.join(',');
  1592. exportUrl += '&sortCol=' + (_state.filters.currSortCol || '');
  1593. exportUrl += '&sortDir=' + (_state.filters.currSortFlip ? "desc" : "asc");
  1594. if (Object.keys(_state.filters.filterCols).length > 0) {
  1595. $.each(_state.filters.filterCols, function (col, colProps) {
  1596. if (colProps.filter && colProps.filter.length > 0) {
  1597. exportUrl += '&f_' + col + '=' + colProps.filter;
  1598. }
  1599. });
  1600. }
  1601. // specialFilters
  1602. $.each(_state.specialFilters, function(groupName, btnValue) {
  1603. if (btnValue.length > 0) {
  1604. exportUrl += '&sf_' + groupName + '=' + btnValue;
  1605. }
  1606. });
  1607. if (priv.options.forceFilterInit) {
  1608. $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
  1609. exportUrl += '&sf_' + fltr + '=' + fltrProps;
  1610. });
  1611. }
  1612. node.attr('href', exportUrl);
  1613. };
  1614. /*
  1615. calls the webservice(if defined).
  1616. used only inside priv.init
  1617. */
  1618. priv.update = function (callback) {
  1619. var skipCols, resetChecked;// undefined
  1620. if (!priv.options.url) {
  1621. if (priv.options.debug) console.log('no url found L.<?php echo __LINE__; ?>');
  1622. return;
  1623. }
  1624. if (priv.options.debug) console.log('requesting data from url:{0} data:{1} L.<?php echo __LINE__; ?>'.f(priv.options.url, JSON.stringify(priv.options.urlData) || ''));
  1625. var initUrlAdd = '',
  1626. reqData = {},
  1627. filtersInitSet = false;
  1628. initUrlAdd += '&currSortCol=' + _state.filters.currSortCol;
  1629. initUrlAdd += '&currSortFlip=' + ((_state.filters.currSortCol)? "desc" : "asc");
  1630. if (Object.keys(_state.filters.filterCols).length > 0) {
  1631. $.each(_state.filters.filterCols, function (col, colProps) {
  1632. if (colProps.filter && colProps.filter.length > 0) {
  1633. initUrlAdd += '&f_' + col + '=' + colProps.filter;
  1634. filtersInitSet = true;
  1635. }
  1636. });
  1637. }
  1638. $.each(_state.specialFilters, function(groupName, btnValue) {
  1639. if (btnValue.length > 0) {
  1640. initUrlAdd += '&sf_' + groupName + '=' + btnValue;
  1641. filtersInitSet = true;
  1642. }
  1643. });
  1644. if (priv.options.forceFilterInit) {
  1645. $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
  1646. reqData['f_' + fltr] = fltrProps;
  1647. filtersInitSet = true;
  1648. });
  1649. }
  1650. $.ajax({
  1651. url: priv.options.url + initUrlAdd,
  1652. type: priv.options.urlPost ? 'POST' : 'GET',
  1653. dataType: 'json',
  1654. contentType: "application/json; charset=utf-8",
  1655. data: reqData,
  1656. async: true,
  1657. success: function (data) {
  1658. if (priv.options.debug) console.log('request finished L.<?php echo __LINE__; ?>');
  1659. // assign the new data
  1660. if (data && data.cols) {
  1661. priv.setStateCols(data.cols, data.uniqueCol);
  1662. }
  1663. // set initial filters (_state.filters.filterCols)
  1664. if (filtersInitSet && _data && _data.cols) {
  1665. $.map(reqData, function(fltrValue, fltr){
  1666. var colName = null;
  1667. if (fltr.substr(0, 3) == 'sf_') {
  1668. colName = fltr.substr(3);
  1669. }
  1670. else if (fltr.substr(0, 2) == 'f_') {
  1671. colName = fltr.substr(2);
  1672. }
  1673. if (colName && _data.cols[colName]) {
  1674. //add the filter to the filter array
  1675. _state.filters.filterCols[colName] = {
  1676. filter: fltrValue,
  1677. colName: colName
  1678. };
  1679. }
  1680. });
  1681. }
  1682. // assign the new state (data)
  1683. state = {data: {}};
  1684. if (!skipCols) state.data.cols = data.cols || {};
  1685. state.data.rows = data.rows || [];
  1686. state.data.total = data.total || 0;
  1687. state.page = data.page || 0;
  1688. state.pageSize = data.pageSize || priv.options.pageSize;
  1689. state.filters = data.filters || {};
  1690. priv.setState(state);
  1691. if (typeof callback == "function")
  1692. callback.call(this);
  1693. },
  1694. error: function (err) {
  1695. //console.log('request error: {0}'.f(JSON.stringify(err)));
  1696. if (typeof callback == "function")
  1697. callback.call(this);
  1698. }
  1699. });
  1700. };
  1701. /*
  1702. assigns the new data.
  1703. */
  1704. priv.setState = function (state) {
  1705. var oldState = _state,// TODO: use to check what really changed (use extend!)
  1706. renderParts = {};
  1707. if (state.data) {
  1708. if (state.data.cols && state.data.cols.length > 0) {// TODO: never happen, but if happend then rerender all
  1709. priv.setStateCols(state.data.cols, state.data.uniqueCol);
  1710. priv.setStateData(state.data);
  1711. renderParts['head'] = true;
  1712. } else {
  1713. priv.setStateData(state.data, true);
  1714. }
  1715. renderParts['body'] = true;
  1716. renderParts['foot_pagination'] = true;
  1717. }
  1718. if (state.hasOwnProperty('specialFilters')) {
  1719. _state.specialFilters = state.specialFilters;
  1720. renderParts['head__specialFilters'] = true;
  1721. }
  1722. if (state.hasOwnProperty('page')) {
  1723. if (state.page != _state.page) {
  1724. _state.page = state.page;
  1725. renderParts['foot_pagination'] = true;
  1726. }
  1727. }
  1728. if (state.hasOwnProperty('pageSize')) {
  1729. if (state.pageSize != _state.pageSize) {
  1730. _state.pageSize = state.pageSize;
  1731. renderParts['foot_pagination'] = true;
  1732. }
  1733. }
  1734. if (state.hasOwnProperty('filters')) {
  1735. /// console.log('L.<?php echo __LINE__; ?> setState::state.filters: ', state.filters);//TODO:DBG:RMME
  1736. priv.setStateFilters(state.filters);
  1737. // TODO: if state diff's
  1738. renderParts['head__specialFilters'] = true;
  1739. renderParts['foot_pagination'] = true;
  1740. }
  1741. renderParts = Object.keys(renderParts);
  1742. if (priv.options.debug) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
  1743. ///console.log('L.<?php echo __LINE__; ?> setState::renderParts: ', renderParts);//TODO:DBG:RMME
  1744. if (renderParts.length > 0) {
  1745. jQuery(_uiNodeCont).trigger('TableAjax:render', renderParts);
  1746. }
  1747. };
  1748. priv.setStateCols = function (cols, uniqueCol) {
  1749. _state.cols = cols;
  1750. _state.uniqueCol = uniqueCol;
  1751. // fix col name - props.column
  1752. $.each(_state.cols, function (col, props) {
  1753. props.column = col;
  1754. });
  1755. // fix col types - default 'string'
  1756. $.each(_state.cols, function (col, props) {
  1757. if (!props.type) cols[col].type = "string";
  1758. });
  1759. // fix props.filter - set true if not set - TODO: allow filter this col?
  1760. $.each(_state.cols, function (col, props) {
  1761. if (props.filter == undefined) props.filter = true;
  1762. });
  1763. if (_state.uniqueCol) {
  1764. //create a unique column definition
  1765. _state.cols["unique"] = {
  1766. column: "unique",
  1767. type: "unique",
  1768. index: -1,
  1769. hidden: true
  1770. };
  1771. }
  1772. _state.colsSorted = Object.keys(_state.cols).sort(function (a, b) {
  1773. return _state.cols[a].index - _state.cols[b].index;
  1774. });
  1775. };
  1776. priv.setStateFilters = function(stateFilters) {
  1777. var newFilterCols = {},
  1778. newSpecialFilters = {};
  1779. $.map(stateFilters, function (fltrProps, fltr) {
  1780. switch (fltr) {
  1781. case 'currSortCol': _state.filters.currSortCol = fltrProps; break;
  1782. case 'currSortFlip': _state.filters.currSortFlip = (fltrProps == 'desc')? true : false; break;
  1783. default:
  1784. if (fltr.substr(0, 2) == 'f_') {
  1785. newFilterCols[fltr.substr(2)] = {
  1786. filter: fltrProps,
  1787. colName: fltr.substr(2)
  1788. };
  1789. }
  1790. else if (fltr.substr(0, 3) == 'sf_') {
  1791. var groupName = fltr.substr(3);
  1792. if (priv.options.specialFilterFunctions.hasOwnProperty(groupName)) {
  1793. newSpecialFilters[groupName] = fltrProps;
  1794. }
  1795. }
  1796. }
  1797. });
  1798. _state.filters.filterCols = newFilterCols;
  1799. _state.specialFilters = newSpecialFilters;
  1800. };
  1801. priv.setStateData = function (pData, skipCols, resetChecked) {
  1802. var data = $.extend(true, {}, pData);
  1803. data.cols = _state.cols;// always use old cols - change cols mved to priv.setStateCols
  1804. _data = data;
  1805. _data.rowsOrg = _data.rows;
  1806. //we might have more/less data now. Recalculate stuff.
  1807. if (_state.page > 1) {
  1808. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  1809. }
  1810. //keep any previously checked rows around?
  1811. if (resetChecked === true || resetChecked === undefined)
  1812. _uniqueCols = {};
  1813. else {
  1814. for (var key in _uniqueCols)
  1815. _uniqueCols[key] = priv.getRow(key);
  1816. }
  1817. if (_state.uniqueCol) {
  1818. //add rows that needs to be pre-checked
  1819. $.each(_data.rows, function (index, row) {
  1820. if (row["checked"] === true)
  1821. _uniqueCols[row[_state.uniqueCol]] = row;
  1822. });
  1823. }
  1824. };
  1825. /**
  1826. * Filters the data.
  1827. */
  1828. priv.filter = function () {
  1829. if (!priv.options.filter) return;
  1830. if (Object.keys(_state.filters.filterCols).length == 0) return;
  1831. publ.loadPage(0);
  1832. };
  1833. /*
  1834. sorts the data on the current sorting column
  1835. */
  1836. priv.sort = function () {
  1837. if (!_data.cols[_state.filters.currSortCol]) _state.filters.currSortCol = "";
  1838. if (!_state.filters.currSortCol) return;
  1839. publ.loadPage(0);
  1840. };
  1841. /*
  1842. helper that returns the underlying data by the unique value
  1843. */
  1844. priv.getRow = function (uniqueValue) {
  1845. var row;
  1846. $.each(_data.rowsOrg, function (i, r) {
  1847. if (r[_state.uniqueCol] == uniqueValue) {
  1848. row = r;
  1849. return false;
  1850. }
  1851. });
  1852. return row;
  1853. };
  1854. /*
  1855. when: typing a filter
  1856. what: triggers filtering on the value
  1857. */
  1858. priv.filterChanged = function (e) {
  1859. //clear old timer if we're typing fast enough
  1860. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?>');
  1861. if (_filterTimeout) {
  1862. clearTimeout(_filterTimeout);
  1863. if (priv.options.debug) console.log('filtering cancelled');
  1864. }
  1865. var filter = this.value
  1866. , fltr = $(this)
  1867. , col = _data.cols[e.data.column]
  1868. , timeout = 300;
  1869. if (this.value) {
  1870. if (!fltr.hasClass('filter-active')) {
  1871. fltr.addClass('filter-active');
  1872. }
  1873. } else {
  1874. if (fltr.hasClass('filter-active')) {
  1875. fltr.removeClass('filter-active');
  1876. }
  1877. }
  1878. //boolean filters needs some special care
  1879. if (col.type == "bool" || col.type == "unique") {
  1880. timeout = 0;
  1881. var elem = $(this);
  1882. var cssClass = 'indeterminate';
  1883. if (elem.hasClass(cssClass)) {
  1884. e.preventDefault();
  1885. elem.removeClass(cssClass);
  1886. filter = true;
  1887. } else {
  1888. if (!elem.is(':checked')) {
  1889. filter = false;
  1890. } else {
  1891. elem.addClass(cssClass);
  1892. filter = '';
  1893. }
  1894. }
  1895. }
  1896. //add the filter to the filter array
  1897. _state.filters.filterCols[col.column] = {
  1898. filter: filter,
  1899. colName: col.column
  1900. };
  1901. //wait a few deciseconds before filtering
  1902. _filterTimeout = setTimeout(function () {
  1903. _filterTimeout = undefined;
  1904. priv.filter();
  1905. }, timeout);
  1906. };
  1907. priv.filtersClean = function (e) {
  1908. if (_filterTimeout) {
  1909. clearTimeout(_filterTimeout);
  1910. if (priv.options.debug) console.log('filtering cancelled - filtersClean');
  1911. }
  1912. var filtersActive = false;
  1913. $.map(_state.filters.filterCols, function (colProps, col) {
  1914. if (colProps.filter.length > 0) {
  1915. filtersActive = true;
  1916. colProps.filter = '';
  1917. }
  1918. });
  1919. if (filtersActive) {
  1920. // TODO: dont remove value from forceFilterInit fields - no field names in search fields?
  1921. /// TODO: rerender _head (thead.filter)
  1922. var elems = _uiNode$Table.find('thead').find('.filter').find('input');
  1923. elems.val('').prop('disabled', false);
  1924. elems.removeClass('filter-active');
  1925. priv.filter();
  1926. }
  1927. return false;
  1928. },
  1929. /**
  1930. * Filters the data by specialFilter.
  1931. * when: click on special filter
  1932. * what: triggers filtering on the value
  1933. */
  1934. priv.specialFilterChanged = function (e) {
  1935. if (priv.options.debug) console.log('specialFilterChanged e.data:', e.data);
  1936. var state = {};
  1937. state.specialFilters = _state.specialFilters;
  1938. state.specialFilters[e.data.group] = e.data.value;
  1939. priv.setState(state);
  1940. publ.loadPage(0);
  1941. };
  1942. priv.longTextChanged = function(e) {
  1943. priv.options.longDesc = !priv.options.longDesc;
  1944. _bodyNode.find('td').each(function(ind, el){
  1945. var $el = jQuery(el);
  1946. if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
  1947. //console.log(el.attr('class') + ': ' + el.text());
  1948. if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
  1949. if (priv.options.longDesc) {
  1950. $el.addClass('tbl-short-txt');
  1951. var $elSpan = jQuery(el.firstChild);
  1952. $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
  1953. } else {
  1954. $el.removeClass('tbl-short-txt');
  1955. }
  1956. }
  1957. }
  1958. });
  1959. return false;
  1960. };
  1961. priv.mapEditorHide = function() {
  1962. priv.options.mapEditor = false;
  1963. if ('window' == priv.options.mapEditorContainer) {
  1964. //_mapEditorDialog.dialog("close");
  1965. _mapEditorDialog.dialog("destroy");
  1966. }
  1967. _mapEditorWrap.hide();
  1968. _mapEditor.hide();
  1969. };
  1970. priv.mapEditorShow = function() {
  1971. //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
  1972. priv.options.mapEditor = true;
  1973. _mapEditor.show();
  1974. _mapEditorWrap.show();
  1975. _mapEditor.TableAjaxMap({
  1976. //debug: true,
  1977. wpsUrl: 'http://biuro.biall-net.pl/wps',
  1978. wfsUrl: 'http://biuro.biall-net.pl/wps',
  1979. showAddLayerWidget: <?php echo ($this->hasAdditionalLayers())? 'true' : 'false'; ?>,
  1980. zoomStrategyActivate: 14,
  1981. layerName: '<?php echo $this->getLabelHtml(); ?>',
  1982. addBtn: {
  1983. title: 'Przenieś mapę do okna',
  1984. displayClass: 'mapEditor-btnBackToWindow',
  1985. trigger: function() {
  1986. priv.mapEditorHide();
  1987. priv.options.mapEditorContainer = 'window';
  1988. priv.mapEditorShow();
  1989. priv.resizableMapDockNode('destroy');
  1990. }
  1991. },
  1992. onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
  1993. if (priv.options.debug) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
  1994. if (!selectedRecordId) {
  1995. alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
  1996. return;
  1997. }
  1998. function notifyAjaxCallback(data) {
  1999. var notify = {};
  2000. notify.type = (data && data.type)? data.type : '';
  2001. notify.msg = (data && data.msg)? data.msg : '';
  2002. switch (notify.type) {
  2003. case 'success':
  2004. if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
  2005. break;
  2006. case 'info':
  2007. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  2008. break;
  2009. case 'error':
  2010. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2011. break;
  2012. case 'warning':
  2013. notify.type = 'warn';
  2014. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2015. break;
  2016. default:
  2017. notify.msg = 'Nieznany błąd';
  2018. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2019. notify.type = '';
  2020. }
  2021. jQuery.notify(notify.msg, notify.type);
  2022. }
  2023. $.ajax({
  2024. data: {polygon: selectedFeatureExtent},
  2025. dataType: 'json',
  2026. type: "POST",
  2027. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_SAVE&ID=' + selectedRecordId
  2028. })
  2029. .done(function(data, textStatus, jqXHR){
  2030. notifyAjaxCallback(data);
  2031. //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
  2032. publ.loadPage(0);// TODO: reload table data
  2033. })
  2034. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2035. if (jqXHR.responseJSON) {
  2036. notifyAjaxCallback(jqXHR.responseJSON);
  2037. }
  2038. else {
  2039. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2040. if (jqXHR.status == 404) {
  2041. jQuery.notify(jqXHR.responseText, 'error');
  2042. } else {
  2043. jQuery.notify(jqXHR.responseText, 'warn');
  2044. }
  2045. }
  2046. });
  2047. },
  2048. onSelectBox: function(bounds) {
  2049. if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
  2050. var column = 'the_geom';
  2051. if (undefined !== _filterFields['the_geom']) {
  2052. var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
  2053. _filterFields[column].val(filter);
  2054. _state.filters.filterCols[column] = {
  2055. filter: filter,
  2056. colName: column
  2057. };
  2058. priv.filter();
  2059. }
  2060. }
  2061. }
  2062. });
  2063. priv.mapEditorShowElement();
  2064. };
  2065. priv.mapEditorShowElement = function() {
  2066. if ('window' == priv.options.mapEditorContainer) {
  2067. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2068. if (!mapEditor || !mapEditor.length) {
  2069. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2070. var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
  2071. if (!mapEditor || !mapEditor.length) {
  2072. // TODO: create new map
  2073. }
  2074. _mapEditorWrap.append(mapEditor);
  2075. }
  2076. _mapEditorWrap.css({padding:'5px'});
  2077. _mapEditorDialog = _mapEditorWrap.dialog({
  2078. width: 540,
  2079. minWidth: 400,
  2080. minHeight: 400,
  2081. open: function(e, ui) {
  2082. var n = jQuery(this),
  2083. mapWrap = n.children(":first"),
  2084. map = mapWrap.children(":first");
  2085. map.css({width: n.width() - 5, height: n.height() - 5});
  2086. _mapEditor.TableAjaxMapUpdateSize();
  2087. },
  2088. resizeStart: function(e, ui) {
  2089. jQuery(this).children(":first").children(":first").css({display:'none'});
  2090. },
  2091. resizeStop: function(e, ui){
  2092. var n = jQuery(this),
  2093. map = n.children(":first").children(":first");
  2094. n.css({width: n.parent().width()});
  2095. map.css({display: 'block', height: n.height(), width: n.width()});
  2096. _mapEditor.TableAjaxMapUpdateSize();
  2097. },
  2098. dragStop: function(e, ui){
  2099. _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
  2100. }
  2101. });
  2102. _mapEditorWrap.bind('dialogclose', function(e) {
  2103. priv.options.mapEditor = false;
  2104. });
  2105. var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
  2106. var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
  2107. if (dialogTitleBarCloseBtn) {
  2108. var btnToggle = jQuery('<span style="width:18px;height:18px;position:absolute;top:50%;right:25px;margin-top:-9px;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only"><i style="margin-top:3px;" class="glyphicon glyphicon-fullscreen"></i></span>');
  2109. btnToggle.on('click', function(e) {
  2110. priv.options.mapEditorContainer = 'dock';
  2111. _mapEditorWrap.dialog('close');
  2112. priv.mapEditorShowElement();
  2113. });
  2114. btnToggle.insertBefore(dialogTitleBarCloseBtn);
  2115. }
  2116. }
  2117. else if ('dock' == priv.options.mapEditorContainer) {
  2118. priv.resizableMapDockNode('prepare');
  2119. _mapEditor.TableAjaxMapUpdateSize();
  2120. }
  2121. };
  2122. priv.resizableMapDockNode = function(task) {
  2123. if ('prepare' == task) {
  2124. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2125. if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
  2126. var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
  2127. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2128. tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
  2129. var breadcrumb = tblCont.children('.breadcrumb');
  2130. if (!breadcrumb || !breadcrumb.length) {
  2131. tblCont.prepend(mapDockNode);
  2132. } else {
  2133. mapDockNode.insertAfter(breadcrumb);
  2134. }
  2135. mapDockNode.append(mapEditor);
  2136. }
  2137. var mapDockResizable = mapEditor.parent();
  2138. mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
  2139. var resizeLineHeigth = 6;
  2140. mapDockResizable.children(":first").css({height: 'auto'});
  2141. mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
  2142. mapEditor.css({marginBottom: resizeLineHeigth+'px'});
  2143. mapEditor.children(":first").css({width: mapEditor.width()});
  2144. mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
  2145. mapDockResizable.on('resizestart', function(event, ui) {
  2146. ui.element.children(":first").children(":first").css({display:'none'})
  2147. });
  2148. mapDockResizable.on('resizestop', function(event, ui) {
  2149. ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
  2150. });
  2151. } else if ('destroy' == task) {
  2152. var mapDockResizable = jQuery(_uiNodeCont).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
  2153. mapDockResizable.resizable('destroy');
  2154. mapDockResizable.remove();
  2155. }
  2156. };
  2157. priv.mapEditorChanged = function(e) {
  2158. if (priv.options.debug) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
  2159. priv.options.mapEditor = !priv.options.mapEditor;
  2160. if (priv.options.mapEditor) {
  2161. priv.mapEditorShow();
  2162. }
  2163. else {
  2164. priv.mapEditorHide();
  2165. }
  2166. return false;
  2167. };
  2168. /*
  2169. when: changing page in pager
  2170. what: triggers table to be created with new page
  2171. */
  2172. priv.pageChanged = function (e) {
  2173. e.preventDefault();
  2174. var totalPages = Math.ceil(_data.total / _state.pageSize);
  2175. if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
  2176. //set the new page
  2177. _state.page = e.data.pageIndex;
  2178. publ.loadPage(_state.page);
  2179. };
  2180. /*
  2181. when: changing pagesize in pagesize dropdown
  2182. what: triggers table to be created with new pagesize
  2183. */
  2184. priv.pageSizeChanged = function (e) {
  2185. e.preventDefault();
  2186. var val = $(this).text();
  2187. if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));
  2188. if (parseInt(val) == priv.options.pageSize) {
  2189. return false;
  2190. }
  2191. priv.options.pageSize = parseInt(val);
  2192. publ.loadPage(1, priv.options.pageSize);
  2193. jQuery(_uiNodeCont).trigger('TableAjax:render', ['body', 'foot_pagination']);
  2194. priv.saveProfilePageSize(priv.options.pageSize);
  2195. };
  2196. /*
  2197. when: clicking a column
  2198. what: triggers table to be sorted by the column
  2199. */
  2200. priv.columnClicked = function (e) {
  2201. e.preventDefault();
  2202. if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));
  2203. //set the new sorting column
  2204. if (_state.filters.currSortCol == e.data.column) _state.filters.currSortFlip = !_state.filters.currSortFlip;
  2205. _state.filters.currSortCol = e.data.column;
  2206. /// TODO: var state = {}; state.currSortCol = ''; state.currSortFlip = ''; priv.setState(state);
  2207. _headSort = undefined;
  2208. _body = undefined;
  2209. priv.sort();
  2210. };
  2211. priv.saveProfilePageSize = function(pageSize) {
  2212. var reqData = {};
  2213. reqData.pageSize = pageSize;
  2214. $.ajax({
  2215. data: reqData,
  2216. type: "POST",
  2217. dataType: 'json',
  2218. // async: true,
  2219. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PAGE_SIZE_SAVE'
  2220. })
  2221. .done(function(data, textStatus, jqXHR){
  2222. if (data && data.type && data.type == 'info') {
  2223. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2224. } else {
  2225. jQuery.notify('Zapisano ustawienia', 'success');
  2226. }
  2227. })
  2228. .fail(function(){
  2229. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2230. });
  2231. };
  2232. priv.saveHiddenCols = function() {
  2233. var reqData = {};
  2234. $.each(_data.cols, function (col, props) {
  2235. if (props.type != "unique" && col != 'unique' && col != 'ID') {
  2236. reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
  2237. }
  2238. });
  2239. $.ajax({
  2240. data: reqData,
  2241. type: "POST",
  2242. dataType: 'json',
  2243. // async: true,
  2244. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE'
  2245. })
  2246. .done(function(data, textStatus, jqXHR){
  2247. if (data && data.type && data.type == 'info') {
  2248. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2249. } else {
  2250. jQuery.notify('Zapisano ustawienia', 'success');
  2251. }
  2252. })
  2253. .fail(function(){
  2254. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2255. });
  2256. };
  2257. /*
  2258. when: clicking a column in columnpicker
  2259. what: triggers table to show/hide the column
  2260. */
  2261. priv.columnPickerClicked = function (e) {
  2262. e.stopPropagation();
  2263. var column = $(this).val();
  2264. //toggle column visibility
  2265. _data.cols[column].hidden = !_data.cols[column].hidden;
  2266. priv.saveHiddenCols();
  2267. //_data.cols[column].index = new priv.ext.XDate();
  2268. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2269. };
  2270. priv.columnHideClicked = function (e) {
  2271. e.stopPropagation();
  2272. var column;
  2273. if (e.data && e.data.column) {
  2274. column = e.data.column;
  2275. } else {
  2276. return;
  2277. }
  2278. //toggle column visibility
  2279. _data.cols[column].hidden = !_data.cols[column].hidden;
  2280. priv.saveHiddenCols();
  2281. //_data.cols[column].index = new priv.ext.XDate();
  2282. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2283. };
  2284. /*
  2285. when: clicking a row checkbox
  2286. what: toggles checked state on row, and add/removes it from checked array
  2287. */
  2288. priv.rowChecked = function (e) {
  2289. var elem = $(this);
  2290. //get the row's unique value
  2291. var unique = elem.closest('tr').data('unique');
  2292. if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));
  2293. //store the row in checked array
  2294. if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
  2295. else delete _uniqueCols[unique];
  2296. };
  2297. /*
  2298. when: clicking anywhere on a row
  2299. what: row data and other info is returned to caller
  2300. */
  2301. // priv.rowClicked = function (e) {// TODO: not used
  2302. // if (!_state.uniqueCol) {
  2303. // if (priv.options.debug) console.log('no unique column specified');
  2304. // return;
  2305. // }
  2306. // //gather callback data
  2307. // var elem = $(this);
  2308. // var column = _data.cols[elem.data('column')];
  2309. // var unique = elem.closest('tr').data('unique');
  2310. // var row = priv.getRow(unique);
  2311. // var isChecked = elem.closest('tr').find('.unique').is(':checked');
  2312. // //trigger callback
  2313. // if (typeof priv.options.rowClicked == 'function') {
  2314. // priv.options.rowClicked.call(e.target, {
  2315. // event: e,
  2316. // row: row,
  2317. // column: column,
  2318. // checked: isChecked
  2319. // });
  2320. // }
  2321. // };
  2322. /**
  2323. * Inline edit.
  2324. */
  2325. priv.rowDblClicked = function (e) {
  2326. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  2327. // hide popover for typespecial fld on click
  2328. if (_popoverCellCurrent) {
  2329. _popoverCellCurrent.popover('hide');
  2330. }
  2331. // e.clientX: 1002; e.clientY: 245
  2332. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2333. inlineEditBox$Node.modal();
  2334. inlineEditBox$Node.show();
  2335. inlineEditBox$Node.on('shown.bs.modal', function(e) {
  2336. var dialogBox = jQuery(this).find('.modal-dialog'),
  2337. modalBody = dialogBox.find('.modal-body'),
  2338. boudingRect = dialogBox.get(0).getBoundingClientRect();
  2339. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  2340. modalBody.css({overflow: 'scroll'});
  2341. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  2342. dialogBox.draggable({handle: '.modal-header'});
  2343. });
  2344. inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  2345. var dialogBox = jQuery(this).find('.modal-dialog'),
  2346. modalBody = dialogBox.find('.modal-body');
  2347. dialogBox.removeAttr('style');
  2348. modalBody.removeAttr('style');
  2349. modalBody.css({padding: '0'});
  2350. dialogBox.resizable();
  2351. dialogBox.draggable();
  2352. dialogBox.resizable('destroy');
  2353. dialogBox.draggable('destroy');
  2354. });
  2355. inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  2356. inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  2357. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  2358. $.ajax({
  2359. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE&ID=' + e.data.id + '&col=' + e.data.col,
  2360. type: 'GET',
  2361. dataType: 'text',
  2362. data: '',
  2363. async: true,
  2364. success: function (data) {
  2365. inlineEditBox$Node.find('.inlineEditBox-cnt').html(data);
  2366. inlineEditBox$Node.find('.btn-save').show();
  2367. initDateTimePicker(inlineEditBox$Node);
  2368. inlineEditBox$Node.find('textarea').autosize();
  2369. var fld = inlineEditBox$Node.find('input[id^="f"]');
  2370. if (fld && !fld.hasClass('se_type-date')) {
  2371. fld.focus();
  2372. fld.keydown(function(event) {
  2373. if (event.which == 13) {
  2374. event.preventDefault();
  2375. inlineEditBox$Node.find('form').submit();
  2376. }
  2377. });
  2378. }
  2379. },
  2380. error: function (err) {
  2381. if (priv.options.debug) console.log('err');
  2382. }
  2383. });
  2384. } else {
  2385. if (priv.options.debug) console.log('NO data');
  2386. return false;
  2387. }
  2388. };
  2389. priv.ajaxLoadTypeSpeciallCell = function(id, col) {
  2390. if (_popoverCellAjaxXhr) {
  2391. _popoverCellAjaxXhr.abort();
  2392. }
  2393. _popoverCellAjaxXhr = $.ajax({
  2394. type: 'GET',
  2395. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=TYPESPECIALL_CELL&ID=' + id + '&col=' + col,
  2396. dataType: 'json',
  2397. contentType: "application/json; charset=utf-8",
  2398. data: '',
  2399. success: function(req){
  2400. if (req.data && req.data.tbl_id > 0) {
  2401. var addHtml = '';
  2402. for(var i in req.data.items){
  2403. var url = 'index.php?MENU_INIT=VIEWTABLE_AJAX';
  2404. url += '&ZASOB_ID=' + req.data.tbl_id;
  2405. url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
  2406. url += '&_hash=' + Math.random().toString(36).substring(2);
  2407. addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
  2408. addHtml += '<br>';
  2409. }
  2410. //_popoverCell.append(addHtml);// cache
  2411. if (_popoverCellCurrent) {
  2412. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  2413. if (popoverNodeId) {
  2414. jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
  2415. }
  2416. }
  2417. }
  2418. }
  2419. });
  2420. };
  2421. priv.popoverCellTypeSpecial = function (e) {
  2422. e.preventDefault();
  2423. e.stopPropagation();
  2424. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2425. var lastId = _popoverCell.data('rowid'),
  2426. lastCol = _popoverCell.data('col'),
  2427. rowPK = e.data.id,
  2428. colName = e.data.col
  2429. ;
  2430. if (lastId == rowPK && lastCol == colName) {
  2431. //_popoverCellCurrent.popover('toggle');
  2432. }
  2433. else {
  2434. if (_popoverCellCurrent) {
  2435. _popoverCellCurrent.popover('destroy');
  2436. }
  2437. _popoverCell.data('rowid', rowPK);
  2438. _popoverCell.data('col', colName);
  2439. _popoverCell.html(e.data.value + '<div class="popoverCellContent loading" style="white-space:normal"></div>');
  2440. _popoverCellCurrent = jQuery(e.currentTarget);
  2441. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  2442. var opts = {
  2443. placement: 'left'
  2444. , trigger: 'click'
  2445. // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
  2446. , title: '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (e.data.friendly || colName) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>' + '</div>'
  2447. , html: true
  2448. , content: _popoverCell.html()
  2449. }
  2450. _popoverCellCurrent.popover(opts);
  2451. if (_data.cols[colName]) {
  2452. if (_data.cols[colName]._tsRetId > 0) {
  2453. _popoverCellCurrent.on('shown.bs.popover', function() {
  2454. priv.ajaxLoadTypeSpeciallCell(rowPK, colName);
  2455. });
  2456. }
  2457. }
  2458. _popoverCellCurrent.popover('show');
  2459. }
  2460. } else {
  2461. if (priv.options.debug) console.log('NO data');
  2462. return false;
  2463. }
  2464. return;
  2465. };
  2466. priv.routeChanged = function(e) {
  2467. hash = e.data.hash || '';
  2468. if (hash.length == 0) {
  2469. return;
  2470. }
  2471. if (hash.substring(0, 1) != '#') {
  2472. hash = '#' + hash;
  2473. }
  2474. location.hash = hash;
  2475. };
  2476. priv.refresh = function (e) {
  2477. e.preventDefault();
  2478. publ.loadPage(_state.page);
  2479. };
  2480. publ.init = function (options) {
  2481. if (priv.options.debug) console.log('TableAjax initialization...');
  2482. //merge supplied options with defaults
  2483. $.extend(priv.options, defaults, options);
  2484. priv.init();
  2485. return publ;
  2486. };
  2487. publ.refresh = function () {
  2488. publ.loadPage(_state.page);
  2489. };
  2490. publ.loadPage = function(page, pageSize) {
  2491. var skipCols = true, // skipCols = true - prevent columns delete
  2492. resetChecked = false;
  2493. var reqData = {
  2494. page: page,
  2495. pageSize: (pageSize || priv.options.pageSize),
  2496. currSortCol: (_state.filters.currSortCol || ''),
  2497. currSortFlip: _state.filters.currSortFlip ? "desc" : "asc"
  2498. };
  2499. if (Object.keys(_state.filters.filterCols).length > 0) {
  2500. $.each(_state.filters.filterCols, function (col, colProps) {
  2501. if (colProps.filter && colProps.filter.length > 0) {
  2502. reqData['f_' + col] = colProps.filter;
  2503. }
  2504. });
  2505. skipCols = true;
  2506. }
  2507. // specialFilters
  2508. $.each(_state.specialFilters, function(groupName, btnValue) {
  2509. if (btnValue.length > 0) {
  2510. reqData['sf_' + groupName] = btnValue;
  2511. }
  2512. });
  2513. if (priv.options.forceFilterInit) {
  2514. $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
  2515. reqData['f_' + fltr] = fltrProps;
  2516. filtersInitSet = true;
  2517. });
  2518. }
  2519. _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
  2520. $.ajax({
  2521. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2522. type: 'GET',
  2523. dataType: 'json',
  2524. contentType: "application/json; charset=utf-8",
  2525. data: reqData,
  2526. async: true,
  2527. success: function (data) {
  2528. state = {data: {}};
  2529. state.data.rows = data.rows || [];
  2530. state.data.total = data.total || 0;
  2531. state.page = data.page || 0;
  2532. state.pageSize = data.pageSize || priv.options.pageSize;
  2533. state.filters = data.filters || {};
  2534. priv.setState(state);
  2535. _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
  2536. },
  2537. error: function (err) {
  2538. if (priv.options.debug) console.log('request error: {0}'.f(JSON.stringify(err)));
  2539. }
  2540. });
  2541. };
  2542. publ.getCurrentPage = function() {
  2543. return _state.page;
  2544. };
  2545. publ.popoverCellRemove = function () {
  2546. if (_popoverCellCurrent) {
  2547. _popoverCellCurrent.popover('destroy');
  2548. }
  2549. _popoverCell.data('rowid', -1);
  2550. _popoverCell.data('col', -1);
  2551. _popoverCell.html('');
  2552. };
  2553. return publ;
  2554. }
  2555. $.fn.TableAjax = function (options) {
  2556. options = options || {};
  2557. return this.each(function () {
  2558. options.id = this;
  2559. $(this).data('TableAjax', new TableAjax().init(options));
  2560. });
  2561. };
  2562. $.fn.TableAjaxLoadPage = function (page, pageSize) {
  2563. return this.each(function () {
  2564. var tblAjax = jQuery(this).data('TableAjax');
  2565. var curPage = page || tblAjax.getCurrentPage();
  2566. if (tblAjax) tblAjax.loadPage(curPage, pageSize);
  2567. });
  2568. };
  2569. $.fn.TableAjaxRefresh = function (page, pageSize) {
  2570. return this.each(function () {
  2571. var tblAjax = jQuery(this).data('TableAjax');
  2572. if (tblAjax) tblAjax.refresh();
  2573. });
  2574. };
  2575. String.prototype.format = String.prototype.f = function () {
  2576. var s = this;
  2577. i = arguments.length;
  2578. while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
  2579. return s;
  2580. };
  2581. })(jQuery);
  2582. </script>
  2583. <?php
  2584. $filterInit = $this->_filterInit;
  2585. $forceFilterInit = $this->_forceFilterInit;
  2586. $pageSizes = $this->_pageSizes;
  2587. $pageSize = $this->_pageSize;
  2588. $rowFunctions = $this->_showRowFunctionsJson();
  2589. $exportFields = $this->_showExportFieldsJson();
  2590. ?>
  2591. <script>
  2592. jQuery(document).ready(function(){
  2593. jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
  2594. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2595. columnPicker: true,
  2596. filter: true,
  2597. filterInit: <?php echo json_encode($filterInit); ?>,
  2598. forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
  2599. debug: false,
  2600. height: 400,
  2601. sorting: true,
  2602. paging: true,
  2603. pageSize: <?php echo $pageSize; ?>,
  2604. pageSizes: <?php echo json_encode($pageSizes); ?>,
  2605. tblFunctions: {
  2606. shortdesc: {
  2607. icon: 'align-left',
  2608. title: 'Long desc',
  2609. method: 'longTextChanged'
  2610. },
  2611. <?php if ($hasGeomFlds) : ?>
  2612. mapeditor: {
  2613. icon: 'map-marker',
  2614. title: 'Mapa',
  2615. method: 'mapEditorChanged'
  2616. },
  2617. <?php endif; ?>
  2618. create: {
  2619. href: '#CREATE',
  2620. icon: 'plus',
  2621. title: 'Dodaj nowy rekord'
  2622. },
  2623. refresh: {
  2624. icon: 'refresh',
  2625. title: 'Odśwież dane',
  2626. method: 'refresh'
  2627. }
  2628. },
  2629. rowFunctions: <?php echo json_encode($rowFunctions); ?>,
  2630. exportFields: <?php echo json_encode($exportFields); ?>,
  2631. specialFilterFunctions: <?php
  2632. $fltrs = $this->_acl->getSpecialFilters();
  2633. if (!empty($fltrs)) {
  2634. echo json_encode($fltrs);
  2635. } else {
  2636. echo 'false';
  2637. }
  2638. echo ',';
  2639. ?>
  2640. router: function () {
  2641. var routes = {
  2642. EDIT: function (args) {
  2643. var recordID = args;
  2644. if (typeof args == 'object') {
  2645. recordID = args.shift();
  2646. recordID = parseInt(recordID);
  2647. }
  2648. if (typeof recordID !== 'number' || recordID <= 0) {
  2649. // TODO: msg
  2650. return false;
  2651. }
  2652. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2653. cont.hide();
  2654. // remove previous task content
  2655. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2656. taskCnt.parent().remove();
  2657. taskCnt.remove();
  2658. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2659. jQuery('<ul class="breadcrumb">' +
  2660. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2661. '<li class="active">Edytuj rekord</li>' +
  2662. '</ul>').appendTo(taskCont);
  2663. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2664. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2665. jQuery.ajax({
  2666. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT&ID=' + recordID,
  2667. type: 'GET',
  2668. dataType: 'text',
  2669. data: '',
  2670. async: true,
  2671. success: function (data) {
  2672. taskCnt.removeClass('AjaxTable-loading');
  2673. jQuery(data).appendTo(taskCnt);
  2674. initDateTimePicker(taskCnt);
  2675. },
  2676. error: function (err) {
  2677. taskCnt.removeClass('AjaxTable-loading');
  2678. //console.log('request error: {0}'.f(err));
  2679. }
  2680. });
  2681. //return false;
  2682. },
  2683. HIST: function (args) {
  2684. var recordID = args;
  2685. if (typeof args == 'object') {
  2686. recordID = args.shift();
  2687. recordID = parseInt(recordID);
  2688. }
  2689. if (typeof recordID !== 'number' || recordID <= 0) {
  2690. // TODO: msg
  2691. return false;
  2692. }
  2693. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2694. cont.hide();
  2695. // remove previous task content
  2696. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2697. taskCnt.parent().remove();
  2698. taskCnt.remove();
  2699. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2700. jQuery('<ul class="breadcrumb">' +
  2701. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2702. '<li class="active">Historia rekordu</li>' +
  2703. '</ul>').appendTo(taskCont);
  2704. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2705. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2706. jQuery.ajax({
  2707. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
  2708. type: 'GET',
  2709. dataType: 'text',
  2710. data: '',
  2711. async: true,
  2712. success: function (data) {
  2713. taskCnt.removeClass('AjaxTable-loading');
  2714. //console.log('request finished L.<?php echo __LINE__; ?>');
  2715. jQuery(data).appendTo(taskCnt);
  2716. },
  2717. error: function (err) {
  2718. taskCnt.removeClass('AjaxTable-loading');
  2719. //console.log('request error: {0}'.f(err));
  2720. }
  2721. });
  2722. //return false;
  2723. },
  2724. FILES: function tableAjaxFiles(args) {
  2725. var recordID = args;
  2726. if (typeof args == 'object') {
  2727. recordID = args.shift();
  2728. recordID = parseInt(recordID);
  2729. }
  2730. if (typeof recordID !== 'number' || recordID <= 0) {
  2731. // TODO: msg
  2732. return false;
  2733. }
  2734. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2735. cont.hide();
  2736. // remove previous task content
  2737. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2738. taskCnt.parent().remove();
  2739. taskCnt.remove();
  2740. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2741. jQuery('<ul class="breadcrumb">' +
  2742. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2743. '<li class="active">Pliki</li>' +
  2744. '</ul>').appendTo(taskCont);
  2745. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
  2746. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2747. jQuery.ajax({
  2748. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
  2749. type: 'GET',
  2750. dataType: 'text',
  2751. data: '',
  2752. async: true,
  2753. success: function (data) {
  2754. taskCnt.removeClass('AjaxTable-loading');
  2755. //console.log('request finished L.<?php echo __LINE__; ?>', data);
  2756. jQuery(data).appendTo(taskCnt);
  2757. },
  2758. error: function (jqXHR, textStatus, errorThrown) {
  2759. //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
  2760. taskCnt.removeClass('AjaxTable-loading');
  2761. var txt = jqXHR.responseText || 'Error';
  2762. if (jqXHR.status == 404) {
  2763. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  2764. } else {
  2765. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  2766. }
  2767. }
  2768. });
  2769. //return false;
  2770. },
  2771. CREATE: function tableAjaxCreate() {
  2772. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2773. cont.hide();
  2774. // remove previous task content
  2775. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2776. taskCnt.parent().remove();
  2777. taskCnt.remove();
  2778. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2779. jQuery('<ul class="breadcrumb">' +
  2780. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2781. '<li class="active">Dodaj nowy rekord</li>' +
  2782. '</ul>').appendTo(taskCont);
  2783. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2784. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2785. var reqData = {};
  2786. var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
  2787. if (forceFilterInit) {
  2788. $.map(forceFilterInit, function (fltrProps, fltr) {
  2789. reqData['ff_' + fltr] = fltrProps;
  2790. });
  2791. }
  2792. jQuery.ajax({
  2793. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',
  2794. type: 'GET',
  2795. dataType: 'text',
  2796. data: reqData,
  2797. async: true,
  2798. success: function (data) {
  2799. taskCnt.removeClass('AjaxTable-loading');
  2800. //console.log('request finished L.<?php echo __LINE__; ?>');
  2801. jQuery(data).appendTo(taskCnt);
  2802. initDateTimePicker(taskCnt);
  2803. },
  2804. error: function (err) {
  2805. taskCnt.removeClass('AjaxTable-loading');
  2806. //console.log('request error: {0}'.f(err));
  2807. }
  2808. });
  2809. //return false;
  2810. }
  2811. };
  2812. var routePath = location.hash;
  2813. //console.log('location.hash: ' + routePath);
  2814. if (location.hash == '' || location.hash == '#') {
  2815. return false;
  2816. }
  2817. if (routePath.charAt(0) == '#') {
  2818. routePath = routePath.substr(1);
  2819. }
  2820. //console.log('routePath: ' + routePath);
  2821. var parts = routePath.split('/');
  2822. var task = parts.shift();
  2823. //console.log('task(' + task + ') parts:');
  2824. //console.log(parts);
  2825. if (task in routes && typeof routes[task] == 'function') {
  2826. routes[task](parts);
  2827. } else {
  2828. return false;
  2829. }
  2830. },
  2831. filtersClean: true,
  2832. longDesc: true
  2833. });
  2834. });
  2835. function tableAjaxBackToTable() {
  2836. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2837. cont.show();
  2838. var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  2839. taskCont.remove();
  2840. // reload first page
  2841. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2842. con.TableAjaxLoadPage();// TODO: load current page
  2843. }
  2844. function tableAjaxCopy(args) {
  2845. var recordID = args;
  2846. if (typeof args == 'object') {
  2847. recordID = args.shift();
  2848. recordID = parseInt(recordID);
  2849. }
  2850. if (typeof recordID !== 'number' || recordID <= 0) {
  2851. // TODO: msg
  2852. return false;
  2853. }
  2854. if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
  2855. return false;
  2856. }
  2857. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2858. function notifyAjaxCallback(data) {
  2859. var notify = {};
  2860. notify.type = (data && data.type)? data.type : '';
  2861. notify.msg = (data && data.msg)? data.msg : '';
  2862. switch (notify.type) {
  2863. case 'success':
  2864. if (!notify.msg) notify.msg = 'OK';
  2865. break;
  2866. case 'info':
  2867. if (!notify.msg) notify.msg = '';
  2868. break;
  2869. case 'error':
  2870. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2871. break;
  2872. case 'warning':
  2873. notify.type = 'warn';
  2874. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2875. break;
  2876. default:
  2877. notify.msg = 'Nieznany błąd';
  2878. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2879. notify.type = '';
  2880. }
  2881. jQuery.notify(notify.msg, notify.type);
  2882. }
  2883. var reqData = {};
  2884. jQuery.ajax({
  2885. data: reqData,
  2886. dataType: 'json',
  2887. type: "GET",
  2888. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
  2889. })
  2890. .done(function(data, textStatus, jqXHR){
  2891. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2892. con.TableAjaxRefresh();
  2893. notifyAjaxCallback(data);
  2894. })
  2895. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2896. if (jqXHR.responseJSON) {
  2897. notifyAjaxCallback(jqXHR.responseJSON);
  2898. }
  2899. else {
  2900. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2901. if (jqXHR.status == 404) {
  2902. jQuery.notify(jqXHR.responseText, 'error');
  2903. } else {
  2904. jQuery.notify(jqXHR.responseText, 'warn');
  2905. }
  2906. }
  2907. });
  2908. return false;
  2909. }
  2910. function hidePopover() {
  2911. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2912. if (con) {
  2913. var tblAjax = con.data('TableAjax');
  2914. if (tblAjax) {
  2915. tblAjax.popoverCellRemove();
  2916. }
  2917. }
  2918. return false;
  2919. }
  2920. function <?php echo $jsToogleFiltrProcesuFunctionName; ?>(n) {
  2921. var $n = jQuery(n);
  2922. var $ul = $n.next();
  2923. if ($n.data('fetched')) return false;
  2924. function parseProcesInitData(pInitData) {
  2925. var procesInitMapHtml = '';
  2926. if (!pInitData) {
  2927. return '<li><a href="#">' + "Brak danych" + '</a></li>';
  2928. } else {
  2929. function _viewProcesInitListItem(pInitId, gotoIds, pInitList) {
  2930. var label = pInitList[pInitId];
  2931. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + pInitId + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  2932. var out = '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + pInitId + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + pInitId + "} " + label + '">';
  2933. out += ' <i class="glyphicon glyphicon-info-sign"';
  2934. out += ' onclick="' + jsInfo + '"';
  2935. out += ' style="color:#aaa;"';
  2936. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  2937. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  2938. out += " {" + pInitId + "} " + label;
  2939. out += '</a>';
  2940. return out;
  2941. }
  2942. function _viewProcesGotoAndRetListItem(gotoId, pInitList) {
  2943. var label = pInitList[gotoId];
  2944. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + gotoId + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  2945. var out = '';
  2946. out += '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + gotoId + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + gotoId + "} " + label + '">';
  2947. out += ' <span style="padding:10px;"></span>';
  2948. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  2949. out += ' <i class="glyphicon glyphicon-info-sign"';
  2950. out += ' onclick="' + jsInfo + '"';
  2951. out += ' style="color:#aaa;"';
  2952. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  2953. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  2954. out += " {" + gotoId + "} " + label;
  2955. out += '</a>';
  2956. return out;
  2957. }
  2958. function _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitList) {
  2959. var label = pInitList[gotoLvl2Id];
  2960. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + gotoLvl2Id + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  2961. var out = '';
  2962. out += '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + gotoLvl2Id + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + gotoLvl2Id + "} " + label + '">';
  2963. out += ' <span style="padding:20px;"></span>';
  2964. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  2965. out += ' <i class="glyphicon glyphicon-info-sign"';
  2966. out += ' onclick="' + jsInfo + '"';
  2967. out += ' style="color:#aaa;"';
  2968. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  2969. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  2970. out += " {" + gotoLvl2Id + "} " + label;
  2971. out += '</a>';
  2972. return out;
  2973. }
  2974. var sel = '',
  2975. liStyle = "white-space:nowrap; overflow:hidden; max-width:500px; /* text-overflow:ellipsis; */";
  2976. $.map(pInitData.mapTree, function(gotoIds, vInitId) {
  2977. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  2978. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  2979. procesInitMapHtml += _viewProcesInitListItem(vInitId, gotoIds, pInitData.pInitList);
  2980. procesInitMapHtml += '</li>' + "\n";
  2981. $.map(gotoIds, function(gotoLvl2Ids, gotoId) {
  2982. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  2983. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  2984. procesInitMapHtml += _viewProcesGotoAndRetListItem(gotoId, pInitData.pInitList);
  2985. procesInitMapHtml += '</li>' + "\n";
  2986. $.map(gotoLvl2Ids, function(vBool, gotoLvl2Id) {
  2987. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  2988. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  2989. procesInitMapHtml += _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitData.pInitList);
  2990. procesInitMapHtml += '</li>' + "\n";
  2991. });
  2992. });
  2993. });
  2994. }
  2995. return procesInitMapHtml;
  2996. }
  2997. jQuery.ajax({
  2998. data: null,
  2999. dataType: 'json',
  3000. type: "GET",
  3001. async: true,
  3002. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PROCES_INIT_FILTR',
  3003. })
  3004. .always(function(data, textStatus, jqXHR) {
  3005. var type = data.type || null,
  3006. msg = data.msg || "Error",
  3007. pInitData = data.pInitData || null;
  3008. if (type) {
  3009. if ('success' == type) {
  3010. $ul.html(parseProcesInitData(pInitData));
  3011. } else if ('error' == type) {
  3012. $ul.html('<li><a href="#">' + msg + '</a></li>');
  3013. } else {
  3014. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3015. }
  3016. } else {
  3017. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  3018. }
  3019. $n.data('fetched', true);
  3020. });
  3021. return false;
  3022. }
  3023. </script>
  3024. <?php
  3025. $out = ob_get_contents();
  3026. ob_end_clean();
  3027. return $out;
  3028. }
  3029. public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
  3030. $vLabel = $pInitList[$vInitId];
  3031. $kId = $vInitId;
  3032. ?>
  3033. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  3034. <i class="glyphicon glyphicon-info-sign"
  3035. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3036. style="color:#aaa;"
  3037. onmouseover="this.style.color='#337AB7'"
  3038. onmouseout="this.style.color='#aaa'"></i>
  3039. <?php echo "{{$kId}} {$vLabel}"; ?>
  3040. </a>
  3041. <?php
  3042. }
  3043. public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
  3044. $vLabel = $pInitList[$vGotoId];
  3045. $kId = $vGotoId;
  3046. // TODO:?: prevent to execute procedure
  3047. ?>
  3048. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  3049. <span style="padding:10px;"></span>
  3050. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3051. <i class="glyphicon glyphicon-info-sign"
  3052. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3053. style="color:#aaa;"
  3054. onmouseover="this.style.color='#337AB7'"
  3055. onmouseout="this.style.color='#aaa'"></i>
  3056. <?php echo "{{$kId}} {$vLabel}"; ?>
  3057. </a>
  3058. <?php
  3059. }
  3060. public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
  3061. $vLabel = $pInitList[$vGotoLvl2Id];
  3062. $kId = $vGotoLvl2Id;
  3063. // TODO:?: prevent to execute procedure
  3064. ?>
  3065. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  3066. <span style="padding:20px;"></span>
  3067. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  3068. <i class="glyphicon glyphicon-info-sign"
  3069. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  3070. style="color:#aaa;"
  3071. onmouseover="this.style.color='#337AB7'"
  3072. onmouseout="this.style.color='#aaa'"></i>
  3073. <?php echo "{{$kId}} {$vLabel}"; ?>
  3074. </a>
  3075. <?php
  3076. }
  3077. public function hasAdditionalLayers() {
  3078. $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
  3079. return !empty($layers);
  3080. }
  3081. public function ajaxTask($task) {
  3082. switch ($task) {
  3083. case 'EDIT': {
  3084. $id = V::get('ID', 0, $_REQUEST, 'int');
  3085. if ($id > 0) {
  3086. $this->sendAjaxEdit($id, $_REQUEST);
  3087. } else {
  3088. echo '404';
  3089. }
  3090. break;
  3091. }
  3092. case 'EDIT_SAVE': {
  3093. $this->sendAjaxResponseJson('ajaxEditSave', $_REQUEST);
  3094. break;
  3095. }
  3096. case 'EDIT_INLINE': {
  3097. $id = V::get('ID', 0, $_REQUEST, 'int');
  3098. $col = V::get('col', '', $_REQUEST);
  3099. if ($id > 0 && !empty($col)) {
  3100. $this->sendAjaxEditInline($id, $col, $_REQUEST);
  3101. } else {
  3102. echo '404';
  3103. }
  3104. break;
  3105. }
  3106. case 'EDIT_INLINE_SAVE': {
  3107. $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
  3108. break;
  3109. }
  3110. case 'COPY': {
  3111. $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
  3112. break;
  3113. }
  3114. case 'CREATE': {
  3115. $this->sendAjaxCreate($_REQUEST);
  3116. break;
  3117. }
  3118. case 'CREATE_SAVE': {
  3119. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  3120. break;
  3121. }
  3122. case 'HIST': {
  3123. $id = V::get('ID', 0, $_REQUEST, 'int');
  3124. if ($id > 0) {
  3125. $this->sendAjaxHistory($id, $_REQUEST);
  3126. } else {
  3127. echo '404';
  3128. }
  3129. break;
  3130. }
  3131. case 'FILES': {
  3132. $id = V::get('ID', 0, $_REQUEST, 'int');
  3133. if ($id > 0) {
  3134. $this->sendAjaxFiles($id, $_REQUEST);
  3135. } else {
  3136. echo '404';
  3137. }
  3138. break;
  3139. }
  3140. case 'FILES_UPLOAD': {
  3141. $id = V::get('ID', 0, $_REQUEST, 'int');
  3142. if ($id > 0) {
  3143. $this->sendAjaxFilesUpload($id, $_REQUEST);
  3144. } else {
  3145. echo '404';
  3146. }
  3147. break;
  3148. }
  3149. case 'FILES_LIST': {
  3150. $id = V::get('ID', 0, $_REQUEST, 'int');
  3151. if ($id > 0) {
  3152. $this->sendAjaxFilesList($id, $_REQUEST);
  3153. } else {
  3154. echo '404';
  3155. }
  3156. break;
  3157. }
  3158. case 'FILE_REMOVE': {
  3159. $id = V::get('ID', 0, $_REQUEST, 'int');
  3160. if ($id > 0) {
  3161. $this->sendAjaxFileRemove($id, $_REQUEST);
  3162. } else {
  3163. echo '404';
  3164. }
  3165. break;
  3166. }
  3167. case 'filePermsRefresh': {
  3168. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  3169. break;
  3170. }
  3171. case 'FILES_CONN_TBL_LIST': {
  3172. $id = V::get('ID', 0, $_REQUEST, 'int');
  3173. if ($id > 0) {
  3174. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  3175. } else {
  3176. echo '404';
  3177. }
  3178. break;
  3179. }
  3180. case 'TYPESPECIAL': {
  3181. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  3182. if ($fldID > 0) {
  3183. $this->sendTypeSpecial($fldID, $_REQUEST);
  3184. } else {
  3185. echo '404';
  3186. }
  3187. break;
  3188. }
  3189. case 'TYPESPECIALL_CELL': {
  3190. sleep(1);// TODO: RMME
  3191. $id = V::get('ID', 0, $_REQUEST, 'int');
  3192. $col = V::get('col', '', $_REQUEST);
  3193. if ($id > 0 && !empty($col)) {
  3194. $this->sendTypeSpecialCell($id, $col, $_REQUEST);
  3195. } else {
  3196. echo '404';
  3197. }
  3198. break;
  3199. }
  3200. case 'MORE_FUNCTIONS_CELL': {
  3201. sleep(1);// TODO: RMME
  3202. $this->sendAjaxResponseJson('ajaxMoreFunctionsCell', $_REQUEST);
  3203. break;
  3204. }
  3205. case 'HIDDEN_COLS_SAVE': {
  3206. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  3207. break;
  3208. }
  3209. case 'PAGE_SIZE_SAVE': {
  3210. $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
  3211. break;
  3212. }
  3213. case 'THE_GEOM_SAVE': {
  3214. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  3215. break;
  3216. }
  3217. case 'THE_GEOM_REMOVE': {
  3218. $this->sendAjaxResponseJson('ajaxTheGeomRemove', $_REQUEST);
  3219. break;
  3220. }
  3221. case 'PROCES_INIT_FILTR': {
  3222. $this->sendAjaxResponseJson('ajaxProcesInitFiltr', $_REQUEST);
  3223. break;
  3224. }
  3225. default:
  3226. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  3227. }
  3228. }
  3229. /**
  3230. * ajax url: &_task=EDIT_INLINE
  3231. * @param $rowID - $_GET['ID']
  3232. * @param $fieldName - $_GET['col']
  3233. */
  3234. private function sendAjaxEditInline($rowID, $fieldName, $args) {
  3235. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3236. header("Content-type: text/plain");
  3237. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3238. if (!$fieldID) {
  3239. echo "404: No field by name ({$fieldName})";
  3240. exit;
  3241. }
  3242. if ($DBG) echo "fieldID: {$fieldID}\n";
  3243. $row = $this->_acl->getItem($rowID);
  3244. if (!$row) {
  3245. echo "404: No item ID({$rowID})";
  3246. exit;
  3247. }
  3248. if (!$this->_acl->isAllowed($fieldID, 'R', $row)) {
  3249. if ($DBG) echo " R not allowed\n";
  3250. } else {
  3251. if ($DBG) echo " R allowed\n";
  3252. }
  3253. if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
  3254. if ($DBG) echo " W not allowed\n";
  3255. } else {
  3256. if ($DBG) echo " W allowed\n";
  3257. }
  3258. $fieldVal = '';
  3259. if ($this->_acl->isAllowed($fieldID, 'R', $row)) {
  3260. $fieldVal = V::get($fieldName, $fieldVal, $row);
  3261. } else {
  3262. $fieldVal = '*****';
  3263. }
  3264. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  3265. $vCol = $this->_acl->getField($fieldID);
  3266. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3267. $tsValues = array();
  3268. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  3269. if ($typeSpecial) {
  3270. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  3271. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  3272. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  3273. if (!empty($specialValues)) {
  3274. $tsValues[$row->ID] = implode('<br>', $specialValues);
  3275. }
  3276. }
  3277. ?>
  3278. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  3279. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  3280. <?php if (!empty($vCol['opis'])) : ?>
  3281. <em><?php echo $vCol['opis']; ?></em>
  3282. <?php $perms = $this->_acl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
  3283. <?php endif; ?>
  3284. </label>
  3285. <?php
  3286. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  3287. if (!empty($tsValues[$row->ID])) {
  3288. $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  3289. }
  3290. $vDefault = $this->_acl->getColDefault($fieldName);
  3291. if (!empty($vDefault)) {
  3292. $fieldParams['default'] = $vDefault;
  3293. }
  3294. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  3295. if ($typeSpecial
  3296. || $this->_acl->isDateField($fieldName)
  3297. || $this->_acl->isDateTimeField($fieldName)
  3298. ) {
  3299. echo '<p style="padding:120px 0;"></p>';
  3300. }
  3301. exit;
  3302. }
  3303. private function ajaxEditInlineSave($args) {
  3304. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3305. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3306. $fieldName = V::get('col', '', $_REQUEST);
  3307. if (empty($primaryKey) || empty($fieldName)) {
  3308. throw new HttpException("Wrong param id or col!", 400);
  3309. }
  3310. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3311. if (!$fieldID) {
  3312. throw new HttpException("Field not exists!", 404);
  3313. }
  3314. $item = $this->_acl->getItem($primaryKey);
  3315. if (!$item) {
  3316. throw new HttpException("Item not exists!", 404);
  3317. }
  3318. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3319. if (!isset($itemFromUser[$fieldName])) {
  3320. throw new HttpException("Field not set!", 400);
  3321. }
  3322. $itemPatch = array();
  3323. $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
  3324. $itemPatch[$primaryKeyField] = $primaryKey;
  3325. $response = new stdClass();
  3326. try {
  3327. $affected = $this->_acl->updateItem($itemPatch);
  3328. if ($affected > 0) {
  3329. $response->type = 'success';
  3330. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3331. } else if ($affected == 0) {
  3332. $response->type = 'info';
  3333. $response->msg = "Nie wprowadzono żadnych zmian";
  3334. }
  3335. $response->record = $this->_acl->getItem($primaryKey);
  3336. }
  3337. catch (Exception $e) {
  3338. $response->type = 'error';
  3339. $response->msg = $e->getMessage();
  3340. }
  3341. return $response;
  3342. }
  3343. private function sendAjaxEdit($id, $args) {
  3344. header("Content-type: text/plain");
  3345. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3346. $cols = array();
  3347. $record = $this->_acl->getItem($id);
  3348. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  3349. echo '<div class="alert alert-danger">';
  3350. echo "Brak dostępu do rekordu";// TODO: more info - reason
  3351. echo '</div>';
  3352. return;
  3353. }
  3354. $fieldsList = $this->_acl->getFields();
  3355. foreach ($fieldsList as $kID => $vCol) {
  3356. if ($vCol['name'] == 'ID') {
  3357. unset($fieldsList[$kID]);
  3358. continue;
  3359. }
  3360. $cols[$kID] = '';
  3361. if ($this->_acl->isAllowed($kID, 'R', $record)) {
  3362. $cols[$kID] = V::get($vCol['name'], '', $record);
  3363. } else {
  3364. $cols[$kID] = '*****';
  3365. }
  3366. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  3367. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
  3368. }
  3369. $tsValues = array();
  3370. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fieldsList (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fieldsList);echo'</pre>';}
  3371. if (!empty($fieldsList)) {
  3372. foreach ($fieldsList as $vColID => $vCol) {
  3373. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  3374. if ($typeSpecial) {
  3375. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  3376. $colValue = V::get($vCol['name'], '', $record);
  3377. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">V::get('.$vCol['name'].', "", $record) (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($colValue);echo'</pre>';}
  3378. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record->ID, $vCol['name'], $colValue);
  3379. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  3380. if (!empty($specialValues)) {
  3381. $tsValues[$vColID] = implode('<br>', $specialValues);
  3382. }
  3383. }
  3384. }
  3385. }
  3386. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">tsValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($tsValues);echo'</pre>';}
  3387. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('edit', 'cp'), true);
  3388. ?>
  3389. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  3390. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
  3391. <fieldset>
  3392. <legend>Edycja rekordu Nr <?php echo $record->ID; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
  3393. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3394. <?php if ($this->_acl->isAllowed($kID, 'W', $record)) : ?>
  3395. <div class="form-group">
  3396. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3397. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  3398. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3399. </label>
  3400. <div class="col-xs-12 col-sm-9 col-md-10">
  3401. <?php
  3402. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3403. if (!empty($tsValues[$kID])) {
  3404. $fieldParams['typespecialValue'] = $tsValues[$kID];
  3405. }
  3406. echo $this->_acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  3407. ?>
  3408. </div>
  3409. </div>
  3410. <?php elseif ($this->_acl->isAllowed($kID, 'R', $record)) : ?>
  3411. <div class="form-group">
  3412. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3413. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  3414. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3415. </label>
  3416. <div class="col-xs-12 col-sm-9 col-md-10">
  3417. <p style="margin-top:5px;">
  3418. <?php
  3419. //echo $this->_acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  3420. if (!empty($tsValues[$kID])) {
  3421. echo $tsValues[$kID];
  3422. } else if (!empty($record->{$vCol['name']})) {
  3423. echo $record->{$vCol['name']};
  3424. }
  3425. ?>
  3426. </p>
  3427. </div>
  3428. </div>
  3429. <?php endif; ?>
  3430. <?php endforeach; ?>
  3431. <div class="form-group">
  3432. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  3433. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
  3434. </div>
  3435. </div>
  3436. </fieldset>
  3437. </form>
  3438. <p style="padding:100px 0;"></p>
  3439. </div>
  3440. <script>
  3441. jQuery(document).ready(function(){
  3442. jQuery('textarea').autosize();
  3443. jQuery('.frm-help').popover({trigger:'hover'});
  3444. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3445. var data = jQuery(this).serialize();
  3446. // TODO: change Edit btn to return to edit record with fields -> show form
  3447. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  3448. //taskCont.empty();
  3449. taskCont.children().fadeOut('slow');
  3450. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  3451. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  3452. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
  3453. function notifyAjaxCallback(data) {
  3454. var notify = {}, outMsg = '';
  3455. notify.type = (data && data.type)? data.type : '';
  3456. notify.msg = (data && data.msg)? data.msg : '';
  3457. switch (notify.type) {
  3458. case 'success':
  3459. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  3460. break;
  3461. case 'info':
  3462. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  3463. break;
  3464. case 'error':
  3465. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3466. break;
  3467. case 'warning':
  3468. notify.type = 'warn';
  3469. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3470. break;
  3471. default:
  3472. notify.msg = 'Nieznany błąd';
  3473. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3474. notify.type = '';
  3475. }
  3476. jQuery.notify(notify.msg, notify.type);
  3477. var alertType = ('error' == notify.type) ? 'danger' : notify.type;
  3478. outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
  3479. return outMsg;
  3480. }
  3481. $.ajax({
  3482. data: data,
  3483. dataType: 'json',
  3484. type: "POST",
  3485. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_SAVE&ID=<?php echo $record->ID; ?>',
  3486. })
  3487. .done(function(data, textStatus, jqXHR){
  3488. var outMsg = notifyAjaxCallback(data);
  3489. alertCntWrap.removeClass('AjaxTable-loading');
  3490. //console.log('request finished L.<?php echo __LINE__; ?>');
  3491. alertCnt.empty();
  3492. var out = '';
  3493. out += outMsg;
  3494. out += '<div class="breadcrumb">' +
  3495. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  3496. ' <a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord <?php echo $id; ?></a>' +
  3497. '</div>';
  3498. jQuery(out).appendTo(alertCnt);
  3499. })
  3500. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3501. if (jqXHR.responseJSON) {
  3502. notifyAjaxCallback(jqXHR.responseJSON);
  3503. }
  3504. else {
  3505. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3506. if (jqXHR.status == 404) {
  3507. jQuery.notify(jqXHR.responseText, 'error');
  3508. } else {
  3509. jQuery.notify(jqXHR.responseText, 'warn');
  3510. }
  3511. }
  3512. alertCntWrap.removeClass('AjaxTable-loading');
  3513. //console.log('Request Error: {0}: {1}'.f(textStatus, errorThrown));
  3514. alertCnt.empty();
  3515. jQuery(errorTxt).appendTo(alertCnt);
  3516. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  3517. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  3518. var backToEditBtn = jQuery('<a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Popraw dane <?php echo $id; ?></a>').appendTo(errLinks);
  3519. backToEditBtn.on('click', function(){
  3520. alertCnt.remove();
  3521. taskCont.children().fadeIn('slow');
  3522. return false;
  3523. });
  3524. });
  3525. return false;
  3526. });
  3527. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  3528. var input, btn, btnIco;
  3529. input = jQuery(e.target);
  3530. btn = input.next('.button-appendBack');
  3531. btnIco = btn.find('.glyphicon');
  3532. //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
  3533. if (btn.attr('title') != input.val()) {
  3534. btnIco.show();
  3535. } else {
  3536. btnIco.hide();
  3537. }
  3538. });
  3539. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
  3540. var input, btn, btnIco;
  3541. btn = jQuery(this);
  3542. btnIco = btn.find('.glyphicon');
  3543. input = btn.prev();
  3544. //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
  3545. if (input.is('input')) {
  3546. if (btn.attr('title') != input.val()) {
  3547. input.val(btn.attr('title'));
  3548. btnIco.hide();
  3549. }
  3550. }
  3551. });
  3552. });
  3553. </script>
  3554. <?php
  3555. exit;
  3556. }
  3557. private function ajaxEditSave($args) {
  3558. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3559. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3560. if (empty($primaryKey)) {
  3561. throw new HttpException("Wrong param id!", 400);
  3562. }
  3563. $item = $this->_acl->getItem($primaryKey);
  3564. if (!$item) {
  3565. throw new HttpException("Item not exists!", 404);
  3566. }
  3567. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3568. $response = new stdClass();
  3569. try {
  3570. $itemFromUser[$primaryKeyField] = $primaryKey;
  3571. $affected = $this->_acl->updateItem($itemFromUser);
  3572. if ($affected > 0) {
  3573. $response->type = 'success';
  3574. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3575. } else if ($affected == 0) {
  3576. $response->type = 'info';
  3577. $response->msg = "Nie wprowadzono żadnych zmian";
  3578. }
  3579. $response->record = $this->_acl->getItem($primaryKey);
  3580. }
  3581. catch (Exception $e) {
  3582. $response->type = 'error';
  3583. $response->msg = "Wystąpiły błędy!";
  3584. $response->msg .= $e->getMessage();
  3585. }
  3586. return $response;
  3587. }
  3588. private function sendAjaxCreate($args) {
  3589. header("Content-type: text/plain");
  3590. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3591. if (!$this->_acl->hasCreatePerms()) {
  3592. ?>
  3593. <div class="container">
  3594. <div class="alert alert-danger">
  3595. Brak uprawnień do utworzenia nowego rekordu.
  3596. </div>
  3597. </div>
  3598. <?php
  3599. return;
  3600. }
  3601. $cols = array();
  3602. $forceFilterInit = array();
  3603. $defaultAclGroup = User::getDefaultAclGroup();
  3604. if ($defaultAclGroup) {
  3605. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  3606. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  3607. }
  3608. foreach ($_GET as $k => $v) {
  3609. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  3610. $fldName = substr($k, 3);
  3611. $forceFilterInit[$fldName] = $v;
  3612. }
  3613. }
  3614. $fieldsList = $this->_acl->getFields();
  3615. foreach ($fieldsList as $kID => $vCol) {
  3616. $defaultValue = '';
  3617. if ($vCol['name'] == 'ID') {
  3618. unset($fieldsList[$kID]);
  3619. continue;
  3620. }
  3621. if (!empty($forceFilterInit[$vCol['name']])) {
  3622. $defaultValue = $forceFilterInit[$vCol['name']];
  3623. }
  3624. // TODO: read from session cache
  3625. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  3626. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3627. }
  3628. ?>
  3629. <div class="container AjaxFrmHorizontalEdit">
  3630. <form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  3631. <fieldset>
  3632. <legend>Dodaj nowy rekord</legend>
  3633. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3634. <?php if ($this->_acl->isAllowed($kID, 'C')) : ?>
  3635. <div class="form-group">
  3636. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3637. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  3638. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3639. </label>
  3640. <div class="col-xs-12 col-sm-9 col-md-10">
  3641. <?php
  3642. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3643. echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  3644. ?>
  3645. </div>
  3646. </div>
  3647. <?php endif; ?>
  3648. <?php endforeach; ?>
  3649. <div class="form-group">
  3650. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  3651. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  3652. </div>
  3653. </div>
  3654. </fieldset>
  3655. </form>
  3656. </div>
  3657. <script>
  3658. jQuery(document).ready(function(){
  3659. jQuery('textarea').autosize();
  3660. jQuery('.frm-help').popover({trigger:'hover'});
  3661. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3662. var data = jQuery(this).serialize();
  3663. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  3664. taskCont = taskContLast.parent();
  3665. taskContLast.fadeOut('slow');
  3666. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3667. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> save ... </div></div>').appendTo(taskCnt);
  3668. function notifyAjaxCallback(data) {
  3669. var notify = {};
  3670. notify.type = (data && data.type)? data.type : '';
  3671. notify.msg = (data && data.msg)? data.msg : '';
  3672. switch (notify.type) {
  3673. case 'success':
  3674. if (!notify.msg) notify.msg = 'OK';
  3675. break;
  3676. case 'info':
  3677. if (!notify.msg) notify.msg = '';
  3678. break;
  3679. case 'error':
  3680. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3681. break;
  3682. case 'warning':
  3683. notify.type = 'warn';
  3684. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3685. break;
  3686. default:
  3687. notify.msg = 'Nieznany błąd';
  3688. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3689. notify.type = '';
  3690. }
  3691. jQuery.notify(notify.msg, notify.type);
  3692. }
  3693. $.ajax({
  3694. data: data,
  3695. dataType: 'json',
  3696. type: "POST",
  3697. async: true,
  3698. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  3699. })
  3700. .always(function(dataOrJqXHR){
  3701. var data;
  3702. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  3703. if ('responseJSON' in dataOrJqXHR) {
  3704. data = dataOrJqXHR.responseJSON;
  3705. } else {
  3706. data = {};
  3707. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  3708. if (dataOrJqXHR.status == 404) {
  3709. data.type = 'error';
  3710. } else {
  3711. data.type = 'warning';
  3712. }
  3713. }
  3714. }
  3715. else {
  3716. data = dataOrJqXHR;
  3717. }
  3718. notifyAjaxCallback(data);
  3719. taskCnt.removeClass('AjaxTable-loading');
  3720. taskCnt.empty();
  3721. if (data.type == 'error' || data.type == 'warning') {
  3722. var out = '<div class="container">' +
  3723. '<div class="alert alert-danger">' +
  3724. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  3725. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  3726. '</div>';
  3727. out += '<div class="breadcrumb">' +
  3728. ' <a class="create-fix" href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do formularza i popraw dane</a></li>' +
  3729. '</div>' +
  3730. '</div>';
  3731. jQuery(out).appendTo(taskCnt);
  3732. var taskContLastNode = taskContLast
  3733. , taskCntNode = taskCnt;
  3734. taskCnt.find('.create-fix').click(function(){
  3735. taskCntNode.remove();
  3736. taskContLastNode.fadeIn('slow');
  3737. return false;
  3738. });
  3739. }
  3740. else if (data.type == 'success') {
  3741. var msg = '';
  3742. if (data.id && data.id > 0) {
  3743. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  3744. } else if (data.msg) {
  3745. msg = data.msg;
  3746. } else {
  3747. msg = 'OK';
  3748. }
  3749. var out = '<div class="container">';
  3750. out += '<div class="alert alert-success">' + msg + '</div>';
  3751. out += '<div class="breadcrumb">' +
  3752. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  3753. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  3754. ' <a href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-plus"></i> Dodaj nowy rekord</a></li>' +
  3755. '</div>';
  3756. out += '</div>';
  3757. jQuery(out).appendTo(taskCnt);
  3758. }
  3759. });
  3760. return false;
  3761. });
  3762. });
  3763. </script>
  3764. <?php
  3765. exit;
  3766. }
  3767. private function ajaxCreateSave($args) {
  3768. $response = new stdClass();
  3769. $createdId = null;
  3770. try {
  3771. $item = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3772. $createdId = $this->_acl->addItem($item);
  3773. if ($createdId) {
  3774. $response->type = 'success';
  3775. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  3776. $response->id = $createdId;
  3777. $response->record = $this->_acl->getItem($createdId);
  3778. }
  3779. else {
  3780. $response->type = 'error';
  3781. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  3782. }
  3783. }
  3784. catch (Exception $e) {
  3785. $response->type = 'error';
  3786. $response->msg = "Wystąpiły błędy!";
  3787. $response->msg = $e->getMessage();
  3788. }
  3789. return $response;
  3790. }
  3791. private function ajaxCopy($args) {
  3792. $id = V::get('ID', 0, $_REQUEST, 'int');
  3793. if ($id <= 0) {
  3794. throw new HttpException("Wrong param ID!", 404);
  3795. }
  3796. $item = $this->_acl->getItem($id);
  3797. if (!$item) {
  3798. throw new HttpException("Item '{$id}' not exists!", 404);
  3799. }
  3800. $response = new stdClass();
  3801. $itemCopy = $this->_acl->createItemCopy($item);
  3802. $createdId = null;
  3803. try {
  3804. $createdId = $this->_acl->addItem($itemCopy);
  3805. if ($createdId) {
  3806. $response->type = 'success';
  3807. $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
  3808. $response->id = $createdId;
  3809. $response->record = $this->_acl->getItem($createdId);
  3810. }
  3811. else {
  3812. $response->type = 'error';
  3813. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  3814. }
  3815. }
  3816. catch (Exception $e) {
  3817. $response->type = 'error';
  3818. $response->msg = "Wystąpiły błędy!";
  3819. $response->msg = $e->getMessage();
  3820. }
  3821. return $response;
  3822. }
  3823. private function sendAjaxHistory($id, $args) {
  3824. header("Content-type: text/plain");
  3825. $record = $this->_acl->getItem($id);
  3826. if (!$record) {
  3827. header('HTTP/1.0 404 Not Found');
  3828. echo "404: No item ID({$rowID})";
  3829. exit;
  3830. }
  3831. $visibleCols = $this->_acl->getRealFieldList();
  3832. $rowsHist = $this->_acl->getHistItems($id);
  3833. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('hist', 'cp'), true);
  3834. $visibleColsWithIds = array();
  3835. $visibleColsLabels = array();
  3836. foreach ($visibleCols as $vColName) {
  3837. $fldId = $this->_acl->getFieldIdByName($vColName);
  3838. if ($fldId) {
  3839. $visibleColsWithIds[$fldId] = $vColName;
  3840. $label = $this->_acl->getFieldLabel($fldId);
  3841. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  3842. $visibleColsLabels[$fldId] = $label;
  3843. }
  3844. }
  3845. ?>
  3846. <fieldset>
  3847. <legend>Historia rekordu Nr <?php echo $id; ?>
  3848. <span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
  3849. </legend>
  3850. </fieldset>
  3851. <?php if (empty($rowsHist)) : ?>
  3852. <div class="alert alert-info">
  3853. <h4>Brak danych</h4>
  3854. </div>
  3855. <?php else: ?>
  3856. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  3857. <thead>
  3858. <tr>
  3859. <th>Data</th>
  3860. <th>User</th>
  3861. <th>Zmiany</th>
  3862. </tr>
  3863. </thead>
  3864. <tbody>
  3865. <?php foreach ($rowsHist as $row) : ?>
  3866. <tr>
  3867. <td style="white-space:nowrap"><?php echo $row->_created; ?></td>
  3868. <td><?php echo $row->_author; ?></td>
  3869. <td>
  3870. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3871. <?php if (in_array($colName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue; ?>
  3872. <?php if ($row->$colName == 'N/S;') continue; ?>
  3873. <p><em><?php echo $visibleColsLabels[$fldId]; ?></em>:
  3874. <?php if ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  3875. <?php echo $row->$colName; ?>
  3876. <?php else : ?>
  3877. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  3878. <?php endif; ?>
  3879. </p>
  3880. <?php endforeach; ?>
  3881. </td>
  3882. </tr>
  3883. <?php endforeach; ?>
  3884. </tbody>
  3885. </table>
  3886. <div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">
  3887. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  3888. <thead>
  3889. <tr>
  3890. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3891. <th><?php echo str_replace('_', ' ', $visibleColsLabels[$fldId]); ?></th>
  3892. <?php endforeach; ?>
  3893. </tr>
  3894. </thead>
  3895. <tbody>
  3896. <?php foreach ($rowsHist as $row) : ?>
  3897. <tr>
  3898. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3899. <td>
  3900. <?php if ($row->$colName == 'N/S;') : ?>
  3901. <em>N/S;</em>
  3902. <?php elseif ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  3903. <?php echo $row->$colName; ?>
  3904. <?php else : ?>
  3905. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  3906. <?php endif; ?>
  3907. </td>
  3908. <?php endforeach; ?>
  3909. </tr>
  3910. <?php endforeach; ?>
  3911. </tbody>
  3912. </table>
  3913. </div>
  3914. <?php endif; ?>
  3915. <?php
  3916. exit;
  3917. }
  3918. /**
  3919. * Returns text/plain with type at first line: ERROR, WARNING, INFO, SUCCESS
  3920. */
  3921. private function sendAjaxFilesUpload($id, $args) {
  3922. // http://www.sitepoint.com/html5-ajax-file-upload/
  3923. //$ajaxFileName = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
  3924. //header("Content-type: text/plain");
  3925. header("Content-type: application/json");
  3926. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3927. $dbID = $this->_acl->getDB();
  3928. $db = DB::getDB($dbID);
  3929. if (!$db) {
  3930. header('HTTP/1.0 406 Not Acceptable');
  3931. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  3932. exit;
  3933. }
  3934. $record = $this->_acl->getItem($id);
  3935. if (!$record) {
  3936. header('HTTP/1.0 404 Not Found');
  3937. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  3938. exit;
  3939. }
  3940. $tblName = $this->_acl->getName();
  3941. $confTblName = "{$tblName}_COLUMN";
  3942. $folderConfAll = FoldersConfig::getRawData();
  3943. if (!FoldersConfig::hasConfig($confTblName)) {
  3944. header('HTTP/1.0 404 Not Found');
  3945. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych(' . $tblName . ')"}';
  3946. exit;
  3947. }
  3948. $folderConf = FoldersConfig::getAll($confTblName);
  3949. $uploader = new FileUploader($confTblName, $record);
  3950. $errMsg = '';
  3951. if (!$uploader->setConfig($folderConf, $errMsg)) {
  3952. header('HTTP/1.0 404 Not Found');
  3953. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych(' . $tblName . ') <br>' . $errMsg . '"}';
  3954. exit;
  3955. }
  3956. $uploader->findFolder();
  3957. $errorMsg = '';
  3958. if (!empty($_POST['SCANS_COLUMN_ADD'])) {
  3959. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  3960. }
  3961. else {
  3962. $uploaded = $uploader->tryUploadAjax($errorMsg);
  3963. }
  3964. if ($uploaded) {
  3965. $uploadedFileName = '';
  3966. $uploadedFile = $uploader->getLastUploadedFile();
  3967. if ($uploadedFile) {
  3968. $uploadedFileName = explode('/', $uploadedFile);
  3969. $uploadedFileName = end($uploadedFileName);
  3970. }
  3971. echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  3972. if (!empty($uploadedFileName)) {
  3973. $sqlObj = new stdClass();
  3974. $sqlObj->ID = $record->ID;
  3975. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  3976. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  3977. }
  3978. } else {
  3979. echo '{"type":"ERROR", "string": "' . $errorMsg . '"}';
  3980. }
  3981. exit;
  3982. }
  3983. private function sendAjaxFileRemove($id, $args) {
  3984. header("Content-type: application/json");
  3985. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3986. if (empty($_POST['filename'])) {
  3987. echo '{"type":"ERROR", "string": "Nie wybrano pliku do usunięcia"}';
  3988. exit;
  3989. }
  3990. $dbID = $this->_acl->getDB();
  3991. $db = DB::getDB($dbID);
  3992. if (!$db) {
  3993. header('HTTP/1.0 406 Not Acceptable');
  3994. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  3995. exit;
  3996. }
  3997. $record = $this->_acl->getItem($id);
  3998. if (!$record) {
  3999. header('HTTP/1.0 404 Not Found');
  4000. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  4001. exit;
  4002. }
  4003. $tblName = $this->_acl->getName();
  4004. $confTblName = "{$tblName}_COLUMN";
  4005. $folderConfAll = FoldersConfig::getRawData();
  4006. if (!FoldersConfig::hasConfig($confTblName)) {
  4007. header('HTTP/1.0 404 Not Found');
  4008. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4009. exit;
  4010. }
  4011. $folderConf = FoldersConfig::getAll($confTblName);
  4012. $uploader = new FileUploader($confTblName, $record);
  4013. if (!$uploader->setConfig($folderConf)) {
  4014. header('HTTP/1.0 404 Not Found');
  4015. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4016. exit;
  4017. }
  4018. $uploader->findFolder();
  4019. $errorMsg = '';
  4020. $removed = $uploader->tryRemoveFromAjax($_POST['filename'], $errorMsg);
  4021. if (!$removed) {
  4022. echo '{"type":"ERROR", "string": "{' . $errorMsg . '}"}';
  4023. } else {
  4024. echo '{"type":"SUCCESS","string":"Plik został poprawnie usunięty"}';
  4025. }
  4026. exit;
  4027. }
  4028. private function sendAjaxFilesList($id, $args) {
  4029. header("Content-type: application/json");
  4030. $dbID = $this->_acl->getDB();
  4031. $db = DB::getDB($dbID);
  4032. if (!$db) {
  4033. header('HTTP/1.0 406 Not Acceptable');
  4034. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  4035. exit;
  4036. }
  4037. $record = $this->_acl->getItem($id);
  4038. if (!$record) {
  4039. header('HTTP/1.0 404 Not Found');
  4040. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  4041. exit;
  4042. }
  4043. $tblName = $this->_acl->getName();
  4044. $confTblName = "{$tblName}_COLUMN";
  4045. $folderConfAll = FoldersConfig::getRawData();
  4046. if (!FoldersConfig::hasConfig($confTblName)) {
  4047. header('HTTP/1.0 404 Not Found');
  4048. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4049. exit;
  4050. }
  4051. $folderConf = FoldersConfig::getAll($confTblName);
  4052. $uploader = new FileUploader($confTblName, $record);
  4053. if (!$uploader->setConfig($folderConf)) {
  4054. header('HTTP/1.0 404 Not Found');
  4055. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4056. exit;
  4057. }
  4058. $uploader->findFolder();
  4059. $mainFolder = $uploader->getDestFolder();
  4060. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4061. $localPath = $uploader->getLocalPath();
  4062. $folderWeb = $uploader->getFolderWeb();
  4063. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4064. echo json_encode($jsonFiles);
  4065. exit;
  4066. }
  4067. private function ajaxFilePermsRefresh($args) {
  4068. header("Content-type: application/json");
  4069. $id = V::get('ID', 0, $args, 'int');
  4070. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  4071. $dbID = $this->_acl->getDB();
  4072. $db = DB::getDB($dbID);
  4073. if (!$db) throw new HttpException("No DB", 406);
  4074. $record = $this->_acl->getItem($id);
  4075. if (!$record) throw new Exception("No item ID({$rowID})", 404);
  4076. $tblName = $this->_acl->getName();
  4077. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  4078. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  4079. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  4080. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  4081. $mainDB = DB::getDB();
  4082. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  4083. $sql = "insert into `_SYNC_FILE_PERMS` (
  4084. `ID_PROJECT`,
  4085. `A_SYNCHRONIZED`
  4086. )
  4087. values (
  4088. '{$record->ID}'
  4089. , 0
  4090. )
  4091. ON DUPLICATE KEY UPDATE
  4092. `A_SYNCHRONIZED`=0
  4093. ";
  4094. }
  4095. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  4096. $sql = "insert into `_SYNC_FILE_PERMS` (
  4097. `ID_PROJECT`,
  4098. `A_SYNCHRONIZED`
  4099. )
  4100. values (
  4101. '{$record->ID_PROJECT}'
  4102. , 0
  4103. )
  4104. ON DUPLICATE KEY UPDATE
  4105. `A_SYNCHRONIZED`=0
  4106. ";
  4107. }
  4108. else {
  4109. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  4110. `TBL_NAME`,
  4111. `TBL_ID`,
  4112. `L_APPOITMENT_USER`,
  4113. `A_ADM_COMPANY`,
  4114. `A_CLASSIFIED`,
  4115. `A_SYNCHRONIZED`
  4116. )
  4117. values (
  4118. '{$tblName}'
  4119. , '{$id}'
  4120. , '{$sql_L_APPOITMENT_USER}'
  4121. , '{$sql_A_ADM_COMPANY}'
  4122. , '{$sql_A_CLASSIFIED}'
  4123. , 0
  4124. )
  4125. ON DUPLICATE KEY UPDATE
  4126. `A_SYNCHRONIZED`=0
  4127. ";
  4128. }
  4129. $res = $mainDB->query($sql);
  4130. if ($mainDB->has_errors()) {
  4131. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  4132. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainDB->get_errors());echo'</pre>';
  4133. throw new Exception("Nie udało się dodać zadania");
  4134. }
  4135. // TODO: this blocks browser ajax query
  4136. //$limit = 3;
  4137. //while ($limit--) {
  4138. // sleep(10);
  4139. // TODO: check if task is done
  4140. //}
  4141. $confTblName = "{$tblName}_COLUMN";
  4142. $folderConfAll = FoldersConfig::getRawData();
  4143. if (!FoldersConfig::hasConfig($confTblName)) {
  4144. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  4145. }
  4146. $folderConf = FoldersConfig::getAll($confTblName);
  4147. $uploader = new FileUploader($confTblName, $record);
  4148. if (!$uploader->setConfig($folderConf)) {
  4149. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4150. }
  4151. $uploader->findFolder();
  4152. $mainFolder = $uploader->getDestFolder();
  4153. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4154. $localPath = $uploader->getLocalPath();
  4155. $folderWeb = $uploader->getFolderWeb();
  4156. $jsonData = new stdClass();
  4157. $jsonData->msg = 'Zadanie dodane';
  4158. $jsonData->type = 'success';
  4159. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4160. return $jsonData;
  4161. }
  4162. private function sendAjaxFilesConnTblList($id, $args) {
  4163. header("Content-type: application/json");
  4164. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4165. $dbID = $this->_acl->getDB();
  4166. $db = DB::getDB($dbID);
  4167. if (!$db) {
  4168. header('HTTP/1.0 406 Not Acceptable');
  4169. echo 'No DB (' . $dbID . ')';
  4170. exit;
  4171. }
  4172. $record = $this->_acl->getItem($id);
  4173. if (!$record) {
  4174. header('HTTP/1.0 404 Not Found');
  4175. echo 'No item ID(' . $rowID . ')';
  4176. exit;
  4177. }
  4178. $connTblName = '';
  4179. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  4180. if ($connTblID <= 0) {
  4181. header('HTTP/1.0 406 Not Acceptable');
  4182. echo 'No conn Table ID';
  4183. exit;
  4184. }
  4185. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  4186. if (empty($connTblTypespecials)) {
  4187. header('HTTP/1.0 406 Not Acceptable');
  4188. echo "No conn Table (ID={$connTblID})";
  4189. exit;
  4190. }
  4191. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">connTblTypespecials (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($connTblTypespecials);echo'</pre>';}
  4192. if(1) {
  4193. header('HTTP/1.0 404 Not Found');
  4194. echo 'TODO: ...';
  4195. exit;
  4196. }
  4197. $tblName = $this->_acl->getName();
  4198. $confTblName = "{$tblName}_COLUMN";
  4199. $folderConfAll = FoldersConfig::getRawData();
  4200. if (!FoldersConfig::hasConfig($confTblName)) {
  4201. header('HTTP/1.0 404 Not Found');
  4202. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4203. exit;
  4204. }
  4205. $folderConf = FoldersConfig::getAll($confTblName);
  4206. $uploader = new FileUploader($confTblName, $record);
  4207. if (!$uploader->setConfig($folderConf)) {
  4208. header('HTTP/1.0 404 Not Found');
  4209. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4210. exit;
  4211. }
  4212. $uploader->findFolder();
  4213. $mainFolder = $uploader->getDestFolder();
  4214. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4215. $localPath = $uploader->getLocalPath();
  4216. $folderWeb = $uploader->getFolderWeb();
  4217. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4218. echo json_encode($jsonFiles);
  4219. exit;
  4220. }
  4221. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  4222. $jsonFiles = array();
  4223. if (!is_array($files) || empty($files)) {
  4224. return $jsonFiles;
  4225. }
  4226. sort($files);
  4227. foreach ($files as $vFilePath) {
  4228. $file = new stdClass();
  4229. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  4230. //$file->name = explode('/', $vFilePath);
  4231. //$file->name = end($file->name);
  4232. $file->size = filesize($vFilePath);
  4233. $file->sizeStr = round($file->size, 2) . "B";
  4234. if ($file->size > 1024 * 1024) {
  4235. $file->sizeStr = round(($file->size / (1024 * 1024)), 2) . "M";
  4236. } else if ($file->size > 1024) {
  4237. $file->sizeStr = round(($file->size / 1024), 2) . "K";
  4238. }
  4239. $file->type = '';
  4240. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  4241. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  4242. $jsonFiles[] = $file;
  4243. }
  4244. return $jsonFiles;
  4245. }
  4246. private function getConnectedTables() {
  4247. $connTbls = array();
  4248. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  4249. $fields = $this->_acl->getVisibleFieldList();
  4250. if (!empty($fields)) {
  4251. foreach ($fields as $vColID => $vCol) {
  4252. $typeSpecial = Typespecial::getInstance($vColID);
  4253. if ($typeSpecial) {
  4254. $tsConnTbls = $typeSpecial->getTblAliasList();
  4255. if (!empty($tsConnTbls)) {
  4256. foreach ($tsConnTbls as $kID => $vName) {
  4257. $connTbls[$kID] = $vName;
  4258. }
  4259. }
  4260. }
  4261. }
  4262. }
  4263. return $connTbls;
  4264. }
  4265. private function getConnectedTblTypespecials($connTblID) {
  4266. $connTblTypespecials = array();
  4267. $fields = $this->_acl->getVisibleFieldList();
  4268. if (!empty($fields)) {
  4269. foreach ($fields as $vColID => $vCol) {
  4270. $typeSpecial = Typespecial::getInstance($vColID);
  4271. if ($typeSpecial) {
  4272. $tsConnTbls = $typeSpecial->getTblAliasList();
  4273. if (array_key_exists($connTblID, $tsConnTbls)) {
  4274. $connTblTypespecials[] = $typeSpecial;
  4275. }
  4276. }
  4277. }
  4278. }
  4279. return $connTblTypespecials;
  4280. }
  4281. private function sendAjaxFiles($id, $args) {
  4282. header("Content-type: text/plain");
  4283. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4284. $dbID = $this->_acl->getDB();
  4285. $db = DB::getDB($dbID);
  4286. if (!$db) {
  4287. header('HTTP/1.0 406 Not Acceptable');
  4288. exit;
  4289. }
  4290. $record = $this->_acl->getItem($id);
  4291. if (!$record) {
  4292. header('HTTP/1.0 404 Not Found');
  4293. echo "404: No item ID({$rowID})";
  4294. exit;
  4295. }
  4296. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  4297. echo '<div class="alert alert-danger">';
  4298. echo "Brak dostępu do rekordu";// TODO: more info - reason
  4299. echo '</div>';
  4300. return;
  4301. }
  4302. $tblName = $this->_acl->getName();
  4303. $confTblName = "{$tblName}_COLUMN";
  4304. $folderConfAll = FoldersConfig::getRawData();
  4305. if (!FoldersConfig::hasConfig($confTblName)) {
  4306. header('HTTP/1.0 404 Not Found');
  4307. echo "Brak danych konfiguracyjnych";
  4308. exit;
  4309. }
  4310. $folderConf = FoldersConfig::getAll($confTblName);
  4311. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  4312. $uploader = new FileUploader($confTblName, $record);
  4313. $errMsg = '';
  4314. if (!$uploader->setConfig($folderConf, $errMsg)) {
  4315. header('HTTP/1.0 404 Not Found');
  4316. echo "Błąd danych konfiguracyjnych ({$tblName})";
  4317. echo '<br>' . "\n" . $errMsg;
  4318. exit;
  4319. }
  4320. $uploader->findFolder();
  4321. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">uploader (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($uploader);echo'</pre>'; }
  4322. $mainFolder = $uploader->getDestFolder();
  4323. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">mainFolder (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainFolder);echo'</pre>'; }
  4324. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4325. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">files (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($files);echo'</pre>'; }
  4326. $sharePoint = V::get('share_point', null, $folderConf);
  4327. if ($sharePoint) {
  4328. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  4329. }
  4330. $localPath = $uploader->getLocalPath();
  4331. $folderWeb = $uploader->getFolderWeb();
  4332. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4333. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">jsonFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonFiles);echo'</pre>'; }
  4334. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  4335. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  4336. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  4337. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  4338. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  4339. sort($skanyFiles);
  4340. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  4341. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);
  4342. $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
  4343. $fileIndex = V::get($fileIndexField, $record->ID, $record);
  4344. ?>
  4345. <script src="stuff/jquery.form.js"></script>
  4346. <div class="container">
  4347. <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
  4348. <?php if ($sharePoint) : ?>
  4349. <a href="<?php echo $sharePoint; ?>"><span class="glyphicon glyphicon-folder-open"></span><code><?php echo $mainFolder; ?></code></a>
  4350. <?php else : ?>
  4351. <code><?php echo $mainFolder; ?></code>
  4352. <?php endif; ?>
  4353. <span class="pull-right valign-btns-bottom">
  4354. <span id="FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>"></span>
  4355. <?php echo $rowFunctionsOut; ?>
  4356. </span>
  4357. </h4>
  4358. <div style="clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
  4359. <table class="table table-bordered table-hover">
  4360. <colgroup>
  4361. <col style="">
  4362. <col style="width:30px;">
  4363. <?php if ($sharePoint) : ?>
  4364. <col style="width:30px;">
  4365. <?php endif; ?>
  4366. <col style="width:80px;">
  4367. <col style="width:140px;">
  4368. </colgroup>
  4369. <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
  4370. <?php if (empty($mainFolder)) : ?>
  4371. <tr>
  4372. <td colspan="5">
  4373. <div class="alert alert-warning">
  4374. <h4>Brak folderu!</h4>
  4375. Folder dla tego rekordu nie został utworzony.
  4376. </div>
  4377. </td>
  4378. </tr>
  4379. <?php elseif (empty($files)) : ?>
  4380. <tr>
  4381. <td colspan="5">
  4382. <div class="alert alert-info">
  4383. <h4>Brak plików</h4>
  4384. </div>
  4385. </td>
  4386. </tr>
  4387. <?php endif; ?>
  4388. </tbody>
  4389. </table>
  4390. </div>
  4391. <br>
  4392. <br>
  4393. <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
  4394. <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
  4395. <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
  4396. <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
  4397. <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
  4398. <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
  4399. </ul>
  4400. <div id="myTabContent" class="tab-content">
  4401. <div class="tab-pane fade in active" id="local" style="text-align: center;">
  4402. <input name="M_DIST_FILES_NAME" type="file" size="60" class="field-upload btn" style="width:86%;margin:10px auto;padding:10px 4%;background:#eee;text-align:center;" ondragover="this.style.backgroundColor='#D9EDF7'" ondragleave="this.style.backgroundColor='#eee'" ondragend="this.style.backgroundColor='#eee'">
  4403. </div>
  4404. <div class="tab-pane fade" id="scan">
  4405. <?php if (empty($skanyFiles)) : ?>
  4406. <div class="alert alert-info">
  4407. <h4>Brak plików</h4>
  4408. <?php if(!empty($skanyFolderWeb)) echo "skonfiguruj urządzenie biurowe aby wysyłało skany na ftp://skaner:(h*a*s*l*o)@".$_SERVER['SERVER_NAME']." <br> lub <a href=".FoldersConfig::getNfsOsPath().$skanySharePoint.">".FoldersConfig::getNfsOsPath().$skanySharePoint."</a>"; ?>
  4409. </div>
  4410. <?php else : ?>
  4411. <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
  4412. <table class="table table-bordered table-hover">
  4413. <colgroup>
  4414. <col style="width:30px;">
  4415. <col style="">
  4416. <col style="width:30px;">
  4417. <col style="width:80px;">
  4418. <col style="width:140px;">
  4419. </colgroup>
  4420. <tbody>
  4421. <?php foreach ($skanyFiles as $vFilePath) : ?>
  4422. <tr>
  4423. <?php
  4424. $vFileName = explode('/', $vFilePath);
  4425. $vFileName = end($vFileName);
  4426. $vFileSize = filesize($vFilePath);
  4427. $vFileSizeOut = round($vFileSize, 2) . "B";
  4428. if ($vFileSize > 1024 * 1024) {
  4429. $vFileSizeOut = round(($vFileSize / (1024 * 1024)), 2) . "M";
  4430. } else if ($vFileSize > 1024) {
  4431. $vFileSizeOut = round(($vFileSize / 1024), 0) . "K";
  4432. }
  4433. ?>
  4434. <td><input style="margin:0;" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
  4435. <td><div style="overflow:hidden; white-space:nowrap;" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
  4436. <td style="white-space:nowrap; text-align:center;"><a href="<?php echo str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath); ?>" target="_blank" class="glyphicon glyphicon-download-alt"></a></td>
  4437. <td style="white-space:nowrap;"><?php echo $vFileSizeOut; ?></td>
  4438. <td style="white-space:nowrap;"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
  4439. </tr>
  4440. <?php endforeach; ?>
  4441. </tbody>
  4442. </table>
  4443. </div>
  4444. <?php endif; ?>
  4445. </div>
  4446. </div>
  4447. <br>
  4448. <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
  4449. <?php //TODO: link do procesu o obiegu dokumentów <i class="glyphicon glyphicon-question-sign" style="cursor:help" title="działa w nowszych przeglądarkach jak Firefox, Chrome"></i> ?>
  4450. </h4>
  4451. <table style="width:100%" class="table table-bordered">
  4452. <tr>
  4453. <th>Nr</th>
  4454. <th>Typ</th>
  4455. <th style="width:40%;">Opis <i class="glyphicon glyphicon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
  4456. <th style="width:16%">Data wersji</th>
  4457. <th style="width:12%">Numer wersji</th>
  4458. </tr>
  4459. <tr>
  4460. <td>
  4461. <?php echo $fileIndex; ?>
  4462. </td>
  4463. <td>
  4464. <select class="form-control" name="M_DIST_FILES_TYPE">
  4465. <?php foreach ($fileTypes as $kType => $vLabel) : ?>
  4466. <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
  4467. <?php endforeach; ?>
  4468. </select>
  4469. <br>
  4470. <label class="checkbox">
  4471. <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
  4472. Wykrycie automatyczne typu z wysylanego pliku
  4473. </label>
  4474. <label class="checkbox">
  4475. <input type="checkbox" name="M_DIST_FILES_TEMP">
  4476. Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
  4477. </label>
  4478. </td>
  4479. <td>
  4480. <input class="form-control" style="width:100%" type="text" name="M_DIST_FILES_DESCRIPTION" value="" maxlength="50">
  4481. <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
  4482. </td>
  4483. <td>
  4484. <div class="input-group">
  4485. <input name="M_DIST_FILES_DATE" type="text" value="<?php echo date('Y-m-d');?>" class="se_type-date form-control" data-format="yyyy-MM-dd" maxlength="10"><span class="input-group-addon">
  4486. <span class="glyphicon glyphicon-calendar"></span>
  4487. </span>
  4488. </div>
  4489. <!--
  4490. <input class="form-control" type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10">
  4491. -->
  4492. <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
  4493. </td>
  4494. <td>
  4495. <input class="form-control" style="width:100%" type="number" name="M_DIST_FILES_VERSION">
  4496. <br>
  4497. <label class="checkbox">
  4498. <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
  4499. Automatycznie dodaj wersje
  4500. </label>
  4501. </td>
  4502. </tr>
  4503. <tr>
  4504. <td colspan="5">
  4505. <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
  4506. <p>
  4507. <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
  4508. </p>
  4509. <p>
  4510. <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
  4511. <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
  4512. </p>
  4513. </td>
  4514. </tr>
  4515. </table>
  4516. </form>
  4517. </div>
  4518. <script>
  4519. function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
  4520. var postData = {};
  4521. jQuery.ajax({
  4522. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_LIST&ID=<?php echo $record->ID; ?>',
  4523. type: 'POST',
  4524. //dataType: 'json',
  4525. //contentType: "application/json; charset=utf-8",
  4526. data: postData,
  4527. async: true,
  4528. success: function (data) {
  4529. fileListUpdate<?php echo $this->_htmlID; ?>(data);
  4530. },
  4531. error: function (jhr, textStatus, errorThrown) {
  4532. if (priv.options.debug) console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
  4533. }
  4534. });
  4535. }
  4536. function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4537. var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
  4538. fileListNode.empty();
  4539. fileListJson.map(function(file){
  4540. var node = $('<tr></tr>');
  4541. var fFun = $('<i class="glyphicon glyphicon-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
  4542. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4543. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4544. fName.append(fFun);
  4545. fName.append(file.name);
  4546. fName.appendTo(fNameCell);
  4547. node.append(fNameCell);
  4548. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="glyphicon glyphicon-download-alt"></a>' + '</td>');
  4549. <?php if ($sharePoint) : ?>
  4550. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="<?php echo $sharePoint; ?>/' + file.name + '" target="_blank" class="glyphicon glyphicon-folder-open"></a>' + '</td>');
  4551. <?php endif; ?>
  4552. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4553. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4554. node.appendTo(fileListNode);
  4555. $(fFun).click(function(e){
  4556. var n = $(e.target);
  4557. var fname= n.data('filename');
  4558. if (!fname) {
  4559. return false;
  4560. }
  4561. if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
  4562. var postData = {filename: fname};
  4563. jQuery.ajax({
  4564. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILE_REMOVE&ID=<?php echo $record->ID; ?>',
  4565. type: 'POST',
  4566. //dataType: 'json',
  4567. //contentType: "application/json; charset=utf-8",
  4568. data: postData,
  4569. async: true,
  4570. success: function (data) {
  4571. if (data && data.type) {
  4572. if (data.type == 'SUCCESS') {
  4573. n.parents('tr').remove();
  4574. //console.log('TODO: SUCCESS msg: ', data.string);
  4575. }
  4576. else if (data.type == 'ERROR') {
  4577. //console.log('TODO: ERROR msg: ', data.string);
  4578. }
  4579. } else {
  4580. if (priv.options.debug) console.log('TODO: ??? data: ', data);
  4581. }
  4582. },
  4583. error: function (jhr, textStatus, errorThrown) {
  4584. if (priv.options.debug) console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
  4585. }
  4586. });
  4587. }
  4588. });
  4589. });
  4590. }
  4591. function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
  4592. var postData = {};
  4593. // clear current file list
  4594. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
  4595. jQuery.ajax({
  4596. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_CONN_TBL_LIST&ID=<?php echo $record->ID; ?>&connTblID=' + connTblID,
  4597. type: 'POST',
  4598. //dataType: 'json',
  4599. //contentType: "application/json; charset=utf-8",
  4600. data: postData,
  4601. async: true,
  4602. success: function (data) {
  4603. connTblListUpdate<?php echo $this->_htmlID; ?>(data);
  4604. },
  4605. error: function (jqXHR, textStatus, errorThrown) {
  4606. var txt = jqXHR.responseText || 'Error';
  4607. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').html('<tr><td colspan="6"><div class="alert alert-danger">' + txt + '</div></td></tr>');
  4608. if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
  4609. }
  4610. });
  4611. }
  4612. function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4613. var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
  4614. fileListNode.empty();
  4615. fileListJson.map(function(file){
  4616. var node = $('<tr></tr>');
  4617. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4618. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4619. fName.append(file.name);
  4620. fName.appendTo(fNameCell);
  4621. node.append(fNameCell);
  4622. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="glyphicon glyphicon-download-alt"></a>' + '</td>');
  4623. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4624. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4625. node.appendTo(fileListNode);
  4626. });
  4627. }
  4628. function fileListActions<?php echo $this->_htmlID; ?>() {
  4629. var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>');
  4630. var btnReload = jQuery('<button class="btn-link btn-sm" title="odśwież uprawnienia do plików"><span class="glyphicon glyphicon-refresh"></span>Odśwież</button>');
  4631. btnReload.on('click', function(e) {
  4632. console.log('TODO: click reload perms...');
  4633. function notifyAjaxCallback(data) {
  4634. var notify = {};
  4635. notify.type = (data && data.type)? data.type : '';
  4636. notify.msg = (data && data.msg)? data.msg : '';
  4637. switch (notify.type) {
  4638. case 'success':
  4639. if (!notify.msg) notify.msg = 'OK';
  4640. break;
  4641. case 'info':
  4642. if (!notify.msg) notify.msg = '';
  4643. break;
  4644. case 'error':
  4645. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4646. break;
  4647. case 'warning':
  4648. notify.type = 'warn';
  4649. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4650. break;
  4651. default:
  4652. notify.msg = 'Nieznany błąd';
  4653. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4654. notify.type = '';
  4655. }
  4656. jQuery.notify(notify.msg, notify.type);
  4657. }
  4658. var reqData = {};
  4659. jQuery.ajax({
  4660. data: reqData,
  4661. dataType: 'json',
  4662. type: "GET",
  4663. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=filePermsRefresh&ID=<?php echo $record->ID; ?>',
  4664. })
  4665. .done(function(data, textStatus, jqXHR){
  4666. notifyAjaxCallback(data);
  4667. if (data && data.files) {
  4668. fileListUpdate<?php echo $this->_htmlID; ?>(data.files);
  4669. }
  4670. })
  4671. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  4672. if (jqXHR.responseJSON) {
  4673. notifyAjaxCallback(jqXHR.responseJSON);
  4674. }
  4675. else {
  4676. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  4677. if (jqXHR.status == 404) {
  4678. jQuery.notify(jqXHR.responseText, 'error');
  4679. } else {
  4680. jQuery.notify(jqXHR.responseText, 'warn');
  4681. }
  4682. }
  4683. });
  4684. });
  4685. filePermsReload.append(btnReload);
  4686. }
  4687. jQuery(document).ready(function(){
  4688. $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function (e) {
  4689. e.preventDefault();
  4690. $(this).tab('show');
  4691. })
  4692. .on('shown.bs.tab', function (e) {
  4693. var fileSource = $(e.target).data('toggle')
  4694. , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
  4695. if (frm['M_DIST_UPLOAD_SOURCE']) {
  4696. frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
  4697. }
  4698. })
  4699. jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
  4700. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_UPLOAD&ID=<?php echo $record->ID; ?>',
  4701. beforeSubmit: function(args, $form, options) {
  4702. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit()...');
  4703. var argsMap = [];
  4704. args.map(function(v, k) {
  4705. argsMap[v.name] = v.value;
  4706. });
  4707. // validate
  4708. if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
  4709. if (!argsMap['M_DIST_FILES_NAME']) {
  4710. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
  4711. return false;
  4712. }
  4713. }
  4714. else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
  4715. if (!argsMap['SCANS_COLUMN_ADD']) {
  4716. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
  4717. return false;
  4718. }
  4719. }
  4720. else {
  4721. return false;
  4722. }
  4723. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4724. $out.html('Wysyłanie...');
  4725. },
  4726. success: function(data) {
  4727. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->success()...');
  4728. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4729. var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
  4730. if (typeof data == 'object') {
  4731. if (data.type == 'ERROR') {
  4732. $out.html('<div class="alert alert-danger">' + btnClose + data.string + '</div>');
  4733. } else if (data.type == 'SUCCESS') {
  4734. $out.html('<div class="alert alert-success">' + btnClose + data.string + '</div>');
  4735. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4736. }
  4737. } else {
  4738. if (data.substr(0, 7) == 'WARNING') {
  4739. data = data.substr(7);
  4740. $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
  4741. } else if (data.substr(0, 5) == 'ERROR') {
  4742. data = data.substr(5);
  4743. $out.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
  4744. } else if (data.substr(0, 7) == 'SUCCESS') {
  4745. data = data.substr(7);
  4746. $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
  4747. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4748. } else if (data.substr(0, 4) == 'INFO') {
  4749. data = data.substr(4);
  4750. $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
  4751. }
  4752. }
  4753. }
  4754. });
  4755. fileListActions<?php echo $this->_htmlID; ?>();
  4756. var fileList = <?php echo json_encode($jsonFiles); ?>;
  4757. fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
  4758. var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
  4759. if (connTbls) {
  4760. var connTblsOut = '';
  4761. for(var key in connTbls) {
  4762. connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
  4763. };
  4764. if (connTblsOut) {
  4765. connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
  4766. connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
  4767. '<table class="table table-bordered table-hover">' +
  4768. '<colgroup>' +
  4769. '<col style="">' +
  4770. '<col style="width:30px;">' +
  4771. <?php if ($sharePoint) : ?>
  4772. '<col style="width:30px;">' +
  4773. <?php endif; ?>
  4774. '<col style="width:80px;">' +
  4775. '<col style="width:140px;">' +
  4776. '</colgroup>' +
  4777. '<tbody class="files-list">' +
  4778. '</tbody>' +
  4779. '</table>' +
  4780. '</div>';
  4781. var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
  4782. _connTblsWrap.css('marginBottom', '26px');
  4783. _connTblsWrap.html(connTblsOut);
  4784. _connTblsWrap.find('.conn-tbl-load').each(function(){
  4785. jQuery(this).click(function(e){
  4786. var tblID = jQuery(e.target).data('zasobid');
  4787. if (tblID) {
  4788. connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
  4789. }// TODO: else show error
  4790. });
  4791. });
  4792. }
  4793. }
  4794. initDateTimePicker(jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>'));
  4795. });
  4796. </script>
  4797. <?php
  4798. exit;
  4799. }
  4800. private function sendTypeSpecial($fldID, $args) {
  4801. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4802. header("Content-type: application/json");
  4803. $fldName = '';
  4804. $fld = $this->_acl->getField($fldID);
  4805. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fld);echo'</pre>';}
  4806. if (!$fld) {
  4807. // 404
  4808. } else {
  4809. $fldName = $fld['name'];
  4810. }
  4811. $jsonData = array();
  4812. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  4813. if ($typeSpecial) {
  4814. $query = V::get('q', '', $_REQUEST);
  4815. $rawRows = null;
  4816. $rows = $typeSpecial->getValuesWithExports($query);
  4817. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
  4818. foreach ($rows as $kID => $vItem) {
  4819. $itemJson = new stdClass();
  4820. $itemJson->id = $vItem->id;
  4821. $itemJson->name = $vItem->param_out;
  4822. if (!empty($vItem->exports)) {
  4823. $itemJson->exports = $vItem->exports;
  4824. }
  4825. $jsonData[] = $itemJson;
  4826. }
  4827. }
  4828. /*
  4829. MENU_INIT:VIEWTABLE_AJAX
  4830. ZASOB_ID:1188
  4831. _task:TYPESPECIAL
  4832. fldID:3866
  4833. Form Dataview sourceview URL encoded
  4834. q:te
  4835. */
  4836. echo json_encode($jsonData);
  4837. exit;
  4838. }
  4839. private function sendTypeSpecialCell($id, $fldName, $args) {
  4840. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4841. header("Content-type: application/json");
  4842. $jsonData = new stdClass();
  4843. $fldID = $this->_acl->getFieldIdByName($fldName);
  4844. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fldID);echo'</pre>';}
  4845. $item = $this->_acl->getItem($id);
  4846. if (!$this->_acl->isAllowed($fldID, 'R', $item)) {
  4847. $jsonData->msg = 'Brak dostępu';
  4848. echo json_encode($jsonData);
  4849. exit;
  4850. }
  4851. if (!$fldID) {
  4852. $jsonData->msg = 'Wrong field';
  4853. echo json_encode($jsonData);
  4854. exit;
  4855. }
  4856. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  4857. if ($typeSpecial) {
  4858. $jsonData->data = $typeSpecial->getReturnData($this->_zasobID, $id, $fldName, '');
  4859. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">specialValuesByIds('.$id.'/'.$fldName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValuesByIds);echo'</pre>';}
  4860. }
  4861. echo json_encode($jsonData);
  4862. exit;
  4863. }
  4864. private function ajaxData($args) {
  4865. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4866. $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
  4867. $page = V::get('page', 0, $args, 'int');
  4868. $currSortCol = V::get('currSortCol', '', $args);
  4869. $currSortFlip = V::get('currSortFlip', '', $args);
  4870. if ($page > 0) {
  4871. $page -= 1;
  4872. }
  4873. else {
  4874. }
  4875. $params = array();
  4876. $params['limit'] = $pageSize;
  4877. $params['limitstart'] = $page * $params['limit'];
  4878. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  4879. $params['order_dir'] = $currSortFlip;
  4880. $filters = new stdClass();
  4881. $filters->currSortCol = $currSortCol;
  4882. $filters->currSortFlip = $currSortFlip;
  4883. foreach ($args as $k => $v) {
  4884. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  4885. $params[$k] = $v;
  4886. $filters->{$k} = $v;
  4887. }
  4888. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  4889. $params[$k] = $v;
  4890. $filters->{$k} = $v;
  4891. }
  4892. }
  4893. $this->setFilters($filters);
  4894. $vCols = $this->_acl->getVirtualFieldList();
  4895. if (!empty($vCols)) {
  4896. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">vCols (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCols);echo'</pre>';}
  4897. }
  4898. $visibleCols = $this->_acl->getVisibleFieldList();
  4899. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">visibleCols (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($visibleCols);echo'</pre>';}
  4900. $jsonData = new stdClass();
  4901. $jsonData->page = $page + 1;
  4902. $jsonData->pageSize = $pageSize;
  4903. $jsonData->filters = $filters;
  4904. $jsonData->cols = new stdClass();
  4905. $jsonData->uniqueCol = $this->_acl->getPrimaryKeyField();
  4906. $ind = 0;
  4907. foreach ($visibleCols as $fieldID => $col) {
  4908. $ind++;
  4909. $columnConfig = (object)array('index'=>$ind);
  4910. if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  4911. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  4912. }
  4913. else if (in_array($col, array('Status'))) {
  4914. // Ahmes problems Status colors
  4915. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  4916. }
  4917. else if ($this->_acl->isGeomField($col)) {
  4918. $columnConfig->type = 'geom';
  4919. }
  4920. if ('' !== ($label = $this->_acl->getFieldLabel($fieldID))) {
  4921. $columnConfig->friendly = $label;
  4922. }
  4923. $colType = $this->_acl->getFieldType($col);
  4924. if ($colType) {// @see MarkTableAjaxFilterColType
  4925. if ($colType['type'] == 'date') {
  4926. //$columnConfig->type = 'date';// TODO: require datetimepicker
  4927. }
  4928. } else {// typespecial - no type
  4929. $columnConfig->type = 'special';
  4930. }
  4931. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  4932. if ($typeSpecial) {
  4933. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">typeSpecial (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  4934. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  4935. if ($columnConfig->_tsRetId == 0) {
  4936. $tsParamOut = V::get('param_out', null, $typeSpecial);
  4937. if ($tsParamOut) {
  4938. $tsFormat = V::get('format', null, $tsParamOut);
  4939. $tsValues = V::get('values', null, $tsParamOut);
  4940. $tsAliases = V::get('alias', null, $tsParamOut);
  4941. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  4942. $tsAliasMap = array();
  4943. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  4944. $bugTsColsNotVisible = array();
  4945. foreach ($tsValues as $kVarName => $vIdZasob) {
  4946. if (array_key_exists($vIdZasob, $tsAliases)) {
  4947. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  4948. } else {
  4949. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  4950. }
  4951. if (!array_key_exists($vIdZasob, $visibleCols)) {
  4952. $bugTsColsNotVisible[] = $vIdZasob;
  4953. }
  4954. }
  4955. if (empty($bugTsColsNotVisible)) {
  4956. $tsSimpleLink = new stdClass();
  4957. $tsSimpleLink->format = $tsFormat;
  4958. $tsSimpleLink->aliasMap = $tsAliasMap;
  4959. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  4960. $columnConfig->type = 'simpleLink';
  4961. } else {
  4962. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  4963. }
  4964. }
  4965. }
  4966. }
  4967. }
  4968. // @see ajaxHiddenColsSave
  4969. if (UserProfile::isHiddenColumn($this->_zasobID, $fieldID)) {
  4970. $columnConfig->hidden = true;
  4971. }
  4972. $columnConfig->description = $this->_acl->getFieldOpis($fieldID);
  4973. $jsonData->cols->{$col} = $columnConfig;
  4974. }
  4975. $jsonData->rows = array();
  4976. $jsonData->total = $this->_acl->getTotal($params);
  4977. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">get_total (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonData->total);echo'</pre>';}
  4978. $items = $this->_acl->getItems($params);
  4979. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">items (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items);echo'</pre>';}
  4980. // TODO: add virtual data by Typespecial
  4981. if (!empty($vCols) && !empty($items)) {
  4982. foreach ($vCols as $vColID => $vCol) {
  4983. $colType = $this->_acl->getFieldTypeById($vColID);
  4984. if ($colType) {
  4985. continue;// pomin Typespecial dla realnych komorek w bazie danych
  4986. }
  4987. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  4988. if ($typeSpecial) {
  4989. $columnConfig = V::get($vCol, null, $jsonData->cols);
  4990. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  4991. // pomin simple link values - mved to js render
  4992. } else {
  4993. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  4994. $ids = array_keys($items);
  4995. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  4996. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vCol.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  4997. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  4998. $tsValue = implode('<br>', $vValues);
  4999. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Item['.$kItemID.'].'.$vCol.' specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items[$kItemID]);echo'</pre>';}
  5000. if (!empty($items[$kItemID]->{$vCol}) && !empty($tsValue)) {
  5001. $items[$kItemID]->{$vCol} .= ": {$tsValue}";
  5002. } else {
  5003. $items[$kItemID]->{$vCol} = $tsValue;
  5004. }
  5005. }
  5006. }
  5007. }
  5008. }
  5009. }
  5010. foreach ($items as $vItem) {
  5011. // TODO: hide items without 'R'
  5012. foreach ($visibleCols as $kID => $vCol) {
  5013. // TODO: ID default 'R'
  5014. if (!$this->_acl->isAllowed($kID, 'R', $vItem)) {
  5015. $vItem->{$vCol} = '*****';
  5016. }
  5017. // null => empty string
  5018. if (!isset($vItem->{$vCol}) || (!$vItem->{$vCol} && $vItem->{$vCol} !== '0')) {
  5019. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">isEmptyString['.$vCol.'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vItem->{$vCol});echo'</pre>';}
  5020. $vItem->{$vCol} = '';
  5021. }
  5022. }
  5023. $jsonData->rows[] = $vItem;
  5024. }
  5025. return $jsonData;
  5026. }
  5027. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  5028. $value = '';
  5029. $type = $this->_acl->getFieldTypeById($fieldID);
  5030. if ($type) {
  5031. if ($type['type'] == 'date') {
  5032. $value = $type['default'];
  5033. }
  5034. // fix bug when field is unique and is null allowed: change empty string to null
  5035. if ($type['null']) {
  5036. $value = 'NULL';
  5037. }
  5038. // fix bug when field is enum and is set to '0': for php '0' is empty
  5039. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  5040. if (false !== strpos($type['type'], "''")) {
  5041. // enum('', '1','2')
  5042. $value = '';
  5043. } else if (false !== strpos($type['type'], "'0'")) {
  5044. // enum('0', '1','2')
  5045. $value = '0';
  5046. } else {
  5047. $value = $type['default'];
  5048. }
  5049. }
  5050. }
  5051. return $value;
  5052. }
  5053. /**
  5054. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  5055. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  5056. */
  5057. private function ajaxHiddenColsSave($args) {
  5058. $response = new stdClass();
  5059. if (empty($args)) {
  5060. $response->type = 'info';
  5061. return $response;
  5062. }
  5063. UserProfile::load();
  5064. // clean up old, wrong values
  5065. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5066. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5067. }
  5068. $colVis = UserProfile::getHiddenCols($this->_zasobID);
  5069. $fields = $this->_acl->getFields();
  5070. foreach ($fields as $kFldId => $vFld) {
  5071. $vFldName = $vFld['name'];
  5072. if (isset($args[$vFldName])) {
  5073. if ($args[$vFldName] == 'SHOW') {
  5074. $colVis[$kFldId] = 1;
  5075. } else if ($args[$vFldName] == 'HIDE') {
  5076. $colVis[$kFldId] = 0;
  5077. }
  5078. }
  5079. }
  5080. UserProfile::setHiddenCols($this->_zasobID, $colVis);
  5081. UserProfile::save();
  5082. $response->type = 'success';
  5083. return $response;
  5084. }
  5085. private function ajaxPageSizeSave($args) {
  5086. $response = new stdClass();
  5087. if (empty($args)) {
  5088. $response->type = 'info';
  5089. return $response;
  5090. }
  5091. $pageSize = V::get('pageSize', 0, $args, 'int');
  5092. UserProfile::load();
  5093. // clean up old, wrong values
  5094. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  5095. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  5096. }
  5097. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  5098. $tableAjaxSettings['pageSize'] = $pageSize;
  5099. UserProfile::setTableAjaxSettings($tableAjaxSettings);
  5100. UserProfile::save();
  5101. $response->type = 'success';
  5102. return $response;
  5103. }
  5104. private function ajaxTheGeomSave($args) {
  5105. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5106. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5107. $polygon = V::get('polygon', 0, $args);
  5108. $geomFieldName = 'the_geom';
  5109. if ($primaryKey <= 0) {
  5110. throw new HttpException("Wrong param ID", 404);
  5111. }
  5112. // TODO: validate polygon - ex.: POLYGON((2072030.2315435 7234115.910678,2072029.4815435 7234093.660678,2072115.2315435 7234091.160678,2072115.4815435 7234113.660678,2072115.2315435 7234113.660678,2072094.2315435 7234113.910678,2072030.2315435 7234115.910678)))
  5113. $record = $this->_acl->getItem($primaryKey);
  5114. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5115. throw new HttpException("Brak dostępu do rekordu", 403);
  5116. }
  5117. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  5118. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  5119. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5120. }
  5121. $itemPatch = array();
  5122. $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
  5123. $itemPatch[$primaryKeyField] = $primaryKey;
  5124. $response = new stdClass();
  5125. try {
  5126. $affected = $this->_acl->updateItem($itemPatch);
  5127. if ($affected > 0) {
  5128. $response->type = 'success';
  5129. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5130. } else if ($affected == 0) {
  5131. $response->type = 'info';
  5132. $response->msg = "Nie wprowadzono żadnych zmian";
  5133. }
  5134. $response->record = $this->_acl->getItem($primaryKey);
  5135. }
  5136. catch (Exception $e) {
  5137. $response->type = 'error';
  5138. $response->msg = $e->getMessage();
  5139. }
  5140. return $response;
  5141. }
  5142. private function sendAjaxResponseJson($method, $args) {
  5143. try {
  5144. $response = $this->{$method}($args);
  5145. }
  5146. catch (HttpException $e) {
  5147. $response = new stdClass();
  5148. $response->type = 'error';
  5149. $response->msg = $e->getMessage();
  5150. $response->errorCode = $e->getCode();
  5151. Http::sendHeaderByCode($e->getCode());
  5152. }
  5153. catch (Exception $e) {
  5154. $response = new stdClass();
  5155. $response->type = 'error';
  5156. $response->msg = $e->getMessage();
  5157. $response->errorCode = $e->getCode();
  5158. }
  5159. header('Content-type: application/json');
  5160. if (!$response) $response = new stdClass();
  5161. echo json_encode($response);
  5162. exit;
  5163. }
  5164. private function ajaxTheGeomRemove($args) {// ajax task 'THE_GEOM_REMOVE'
  5165. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5166. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5167. $geomFieldName = 'the_geom';
  5168. $response = new stdClass();
  5169. if ($primaryKey <= 0) {
  5170. throw new HttpException("Wrong param ID", 404);
  5171. }
  5172. $record = $this->_acl->getItem($primaryKey);
  5173. if (!$record) {
  5174. throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  5175. }
  5176. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5177. throw new HttpException("Brak dostępu do rekordu nr {$primaryKey}", 403);
  5178. }
  5179. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  5180. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  5181. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5182. }
  5183. if (empty($record->{$geomFieldName})) {
  5184. $response->type = 'info';
  5185. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  5186. $response->record = $record;
  5187. return $response;
  5188. }
  5189. $itemPatch = array();
  5190. $itemPatch[$geomFieldName] = "NULL";
  5191. $itemPatch[$primaryKeyField] = $primaryKey;
  5192. $response = new stdClass();
  5193. try {
  5194. $affected = $this->_acl->updateItem($itemPatch);
  5195. if ($affected > 0) {
  5196. $response->type = 'success';
  5197. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5198. } else if ($affected == 0) {
  5199. $response->type = 'info';
  5200. $response->msg = "Nie wprowadzono żadnych zmian";
  5201. }
  5202. $response->record = $this->_acl->getItem($primaryKey);
  5203. }
  5204. catch (Exception $e) {
  5205. $response->type = 'error';
  5206. $response->msg = $e->getMessage();
  5207. }
  5208. return $response;
  5209. }
  5210. private function ajaxProcesInitFiltr($args) {// ajax task 'PROCES_INIT_FILTR'
  5211. $response = new stdClass();
  5212. $pInitList = array();// [proces_init_id] => label (DESC)
  5213. if (!$this->_showProcesInit) {
  5214. $response->type = 'error';
  5215. return $response;
  5216. }
  5217. $userAcl = User::getAcl();
  5218. $pInitList = $userAcl->getTableProcesInitList($this->_zasobID);
  5219. if (!empty($pInitList)) {
  5220. $procesIds = array_keys($pInitList);
  5221. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  5222. DBG::_('DBG_MAP', '1', "mapTree", $mapTree, __CLASS__, __FUNCTION__, __LINE__);
  5223. DBG::_('DBG_MAP', '1', "pInitList", $pInitList, __CLASS__, __FUNCTION__, __LINE__);
  5224. $pInitListSelected = $this->getProcesInitSelected();
  5225. $response->pInitData = new stdClass();
  5226. $response->pInitData->pInitList = $pInitList;
  5227. $response->pInitData->mapTree = $mapTree;
  5228. $response->pInitData->pInitListSelected = $pInitListSelected;
  5229. }
  5230. $response->type = 'success';
  5231. return $response;
  5232. }
  5233. function ajaxMoreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  5234. $id = V::get('ID', 0, $args, 'int');
  5235. if ($id <= 0) {
  5236. throw new HttpException("404", 404);
  5237. }
  5238. $response = new stdClass();
  5239. $response->type = 'success';
  5240. $response->msg = 'TODO: L.' . __LINE__;
  5241. return $response;
  5242. }
  5243. }