TableAjax.php 169 KB

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