TableAjax.php 231 KB

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