TableAjax.php 195 KB

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