TableAjax.php 168 KB

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