TableAjax.php 230 KB

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