TableAjax.php 193 KB

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