TableAjax.php 171 KB

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