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