TableAjax.php 183 KB

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