TableAjax.php 223 KB

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