TableAjax.php 190 KB

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