TableAjax.php 242 KB

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