TableAjax.php 182 KB

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