TableAjax.php 180 KB

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