TableAjax.php 181 KB

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