TableAjax.php 159 KB

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