TableAjax.php 216 KB

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