TableAjax.php 170 KB

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