TableAjax.php 242 KB

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