TableAjax.php 225 KB

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