TableAjax.php 229 KB

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