TableAjax.php 181 KB

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