TableAjax.php 183 KB

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