attributedef.class.inc.php 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592
  1. <?php
  2. // Copyright (C) 2010-2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Typology for the attributes
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('MyHelpers.class.inc.php');
  25. require_once('ormdocument.class.inc.php');
  26. require_once('ormstopwatch.class.inc.php');
  27. require_once('ormpassword.class.inc.php');
  28. require_once('ormcaselog.class.inc.php');
  29. /**
  30. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  31. *
  32. * @package iTopORM
  33. */
  34. class MissingColumnException extends Exception
  35. {}
  36. /**
  37. * add some description here...
  38. *
  39. * @package iTopORM
  40. */
  41. define('EXTKEY_RELATIVE', 1);
  42. /**
  43. * add some description here...
  44. *
  45. * @package iTopORM
  46. */
  47. define('EXTKEY_ABSOLUTE', 2);
  48. /**
  49. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  50. *
  51. * @package iTopORM
  52. */
  53. define('DEL_MANUAL', 1);
  54. /**
  55. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  56. *
  57. * @package iTopORM
  58. */
  59. define('DEL_AUTO', 2);
  60. /**
  61. * Fully silent delete... not yet implemented
  62. */
  63. define('DEL_SILENT', 2);
  64. /**
  65. * For HierarchicalKeys only: move all the children up one level automatically
  66. */
  67. define('DEL_MOVEUP', 3);
  68. /**
  69. * For Link sets: tracking_level
  70. *
  71. * @package iTopORM
  72. */
  73. define('ATTRIBUTE_TRACKING_NONE', 0); // Do not track changes of the attribute
  74. define('ATTRIBUTE_TRACKING_ALL', 3); // Do track all changes of the attribute
  75. define('LINKSET_TRACKING_NONE', 0); // Do not track changes in the link set
  76. define('LINKSET_TRACKING_LIST', 1); // Do track added/removed items
  77. define('LINKSET_TRACKING_DETAILS', 2); // Do track modified items
  78. define('LINKSET_TRACKING_ALL', 3); // Do track added/removed/modified items
  79. define('LINKSET_EDITMODE_NONE', 0); // The linkset cannot be edited at all from inside this object
  80. define('LINKSET_EDITMODE_ADDONLY', 1); // The only possible action is to open a new window to create a new object
  81. define('LINKSET_EDITMODE_ACTIONS', 2); // Show the usual 'Actions' popup menu
  82. define('LINKSET_EDITMODE_INPLACE', 3); // The "linked" objects can be created/modified/deleted in place
  83. define('LINKSET_EDITMODE_ADDREMOVE', 4); // The "linked" objects can be added/removed in place
  84. /**
  85. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  86. *
  87. * @package iTopORM
  88. */
  89. abstract class AttributeDefinition
  90. {
  91. public function GetType()
  92. {
  93. return Dict::S('Core:'.get_class($this));
  94. }
  95. public function GetTypeDesc()
  96. {
  97. return Dict::S('Core:'.get_class($this).'+');
  98. }
  99. abstract public function GetEditClass();
  100. protected $m_sCode;
  101. private $m_aParams = array();
  102. protected $m_sHostClass = '!undefined!';
  103. public function Get($sParamName) {return $this->m_aParams[$sParamName];}
  104. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  105. protected function GetOptional($sParamName, $default)
  106. {
  107. if (array_key_exists($sParamName, $this->m_aParams))
  108. {
  109. return $this->m_aParams[$sParamName];
  110. }
  111. else
  112. {
  113. return $default;
  114. }
  115. }
  116. public function __construct($sCode, $aParams)
  117. {
  118. $this->m_sCode = $sCode;
  119. $this->m_aParams = $aParams;
  120. $this->ConsistencyCheck();
  121. }
  122. public function GetParams()
  123. {
  124. return $this->m_aParams;
  125. }
  126. public function SetHostClass($sHostClass)
  127. {
  128. $this->m_sHostClass = $sHostClass;
  129. }
  130. public function GetHostClass()
  131. {
  132. return $this->m_sHostClass;
  133. }
  134. public function ListSubItems()
  135. {
  136. $aSubItems = array();
  137. foreach(MetaModel::ListAttributeDefs($this->m_sHostClass) as $sAttCode => $oAttDef)
  138. {
  139. if ($oAttDef instanceof AttributeSubItem)
  140. {
  141. if ($oAttDef->Get('target_attcode') == $this->m_sCode)
  142. {
  143. $aSubItems[$sAttCode] = $oAttDef;
  144. }
  145. }
  146. }
  147. return $aSubItems;
  148. }
  149. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  150. // to be overloaded
  151. static public function ListExpectedParams()
  152. {
  153. return array();
  154. }
  155. private function ConsistencyCheck()
  156. {
  157. // Check that any mandatory param has been specified
  158. //
  159. $aExpectedParams = $this->ListExpectedParams();
  160. foreach($aExpectedParams as $sParamName)
  161. {
  162. if (!array_key_exists($sParamName, $this->m_aParams))
  163. {
  164. $aBacktrace = debug_backtrace();
  165. $sTargetClass = $aBacktrace[2]["class"];
  166. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  167. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  168. }
  169. }
  170. }
  171. // table, key field, name field
  172. public function ListDBJoins()
  173. {
  174. return "";
  175. // e.g: return array("Site", "infrid", "name");
  176. }
  177. public function GetFinalAttDef()
  178. {
  179. return $this;
  180. }
  181. public function IsDirectField() {return false;}
  182. public function IsScalar() {return false;}
  183. public function IsLinkSet() {return false;}
  184. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  185. public function IsHierarchicalKey() {return false;}
  186. public function IsExternalField() {return false;}
  187. public function IsWritable() {return false;}
  188. public function LoadInObject() {return true;}
  189. public function AlwaysLoadInTables() {return $this->GetOptional('always_load_in_tables', false);}
  190. public function GetValue($oHostObject){return null;} // must return the value if LoadInObject returns false
  191. public function IsNullAllowed() {return true;}
  192. public function GetCode() {return $this->m_sCode;}
  193. public function GetMirrorLinkAttribute() {return null;}
  194. /**
  195. * Helper to browse the hierarchy of classes, searching for a label
  196. */
  197. protected function SearchLabel($sDictEntrySuffix, $sDefault, $bUserLanguageOnly)
  198. {
  199. $sLabel = Dict::S('Class:'.$this->m_sHostClass.$sDictEntrySuffix, '', $bUserLanguageOnly);
  200. if (strlen($sLabel) == 0)
  201. {
  202. // Nothing found: go higher in the hierarchy (if possible)
  203. //
  204. $sLabel = $sDefault;
  205. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  206. if ($sParentClass)
  207. {
  208. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  209. {
  210. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  211. $sLabel = $oAttDef->SearchLabel($sDictEntrySuffix, $sDefault, $bUserLanguageOnly);
  212. }
  213. }
  214. }
  215. return $sLabel;
  216. }
  217. public function GetLabel($sDefault = null)
  218. {
  219. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode, null, true /*user lang*/);
  220. if (is_null($sLabel))
  221. {
  222. // If no default value is specified, let's define the most relevant one for developping purposes
  223. if (is_null($sDefault))
  224. {
  225. $sDefault = str_replace('_', ' ', $this->m_sCode);
  226. }
  227. // Browse the hierarchy again, accepting default (english) translations
  228. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode, $sDefault, false);
  229. }
  230. return $sLabel;
  231. }
  232. /**
  233. * Get the label corresponding to the given value (in plain text)
  234. * To be overloaded for localized enums
  235. */
  236. public function GetValueLabel($sValue)
  237. {
  238. return $sValue;
  239. }
  240. /**
  241. * Get the value from a given string (plain text, CSV import)
  242. * Return null if no match could be found
  243. */
  244. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  245. {
  246. return $this->MakeRealValue($sProposedValue, null);
  247. }
  248. public function GetLabel_Obsolete()
  249. {
  250. // Written for compatibility with a data model written prior to version 0.9.1
  251. if (array_key_exists('label', $this->m_aParams))
  252. {
  253. return $this->m_aParams['label'];
  254. }
  255. else
  256. {
  257. return $this->GetLabel();
  258. }
  259. }
  260. public function GetDescription($sDefault = null)
  261. {
  262. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'+', null, true /*user lang*/);
  263. if (is_null($sLabel))
  264. {
  265. // If no default value is specified, let's define the most relevant one for developping purposes
  266. if (is_null($sDefault))
  267. {
  268. $sDefault = '';
  269. }
  270. // Browse the hierarchy again, accepting default (english) translations
  271. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'+', $sDefault, false);
  272. }
  273. return $sLabel;
  274. }
  275. public function GetHelpOnEdition($sDefault = null)
  276. {
  277. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'?', null, true /*user lang*/);
  278. if (is_null($sLabel))
  279. {
  280. // If no default value is specified, let's define the most relevant one for developping purposes
  281. if (is_null($sDefault))
  282. {
  283. $sDefault = '';
  284. }
  285. // Browse the hierarchy again, accepting default (english) translations
  286. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'?', $sDefault, false);
  287. }
  288. return $sLabel;
  289. }
  290. public function GetHelpOnSmartSearch()
  291. {
  292. $aParents = array_merge(array(get_class($this) => get_class($this)), class_parents($this));
  293. foreach ($aParents as $sClass)
  294. {
  295. $sHelp = Dict::S("Core:$sClass?SmartSearch", '-missing-');
  296. if ($sHelp != '-missing-')
  297. {
  298. return $sHelp;
  299. }
  300. }
  301. return '';
  302. }
  303. public function GetDescription_Obsolete()
  304. {
  305. // Written for compatibility with a data model written prior to version 0.9.1
  306. if (array_key_exists('description', $this->m_aParams))
  307. {
  308. return $this->m_aParams['description'];
  309. }
  310. else
  311. {
  312. return $this->GetDescription();
  313. }
  314. }
  315. public function GetTrackingLevel()
  316. {
  317. return $this->GetOptional('tracking_level', ATTRIBUTE_TRACKING_ALL);
  318. }
  319. public function GetValuesDef() {return null;}
  320. public function GetPrerequisiteAttributes() {return array();}
  321. public function GetNullValue() {return null;}
  322. public function IsNull($proposedValue) {return is_null($proposedValue);}
  323. public function MakeRealValue($proposedValue, $oHostObj) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  324. public function Equals($val1, $val2) {return ($val1 == $val2);}
  325. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  326. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  327. public function GetSQLColumns($bFullSpec = false) {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  328. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  329. public function RequiresIndex() {return false;}
  330. public function GetOrderBySQLExpressions($sClassAlias)
  331. {
  332. // Note: This is the responsibility of this function to place backticks around column aliases
  333. return array('`'.$sClassAlias.$this->GetCode().'`');
  334. }
  335. public function GetOrderByHint()
  336. {
  337. return '';
  338. }
  339. // Import - differs slightly from SQL input, but identical in most cases
  340. //
  341. public function GetImportColumns() {return $this->GetSQLColumns();}
  342. public function FromImportToValue($aCols, $sPrefix = '')
  343. {
  344. $aValues = array();
  345. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  346. {
  347. // This is working, based on the assumption that importable fields
  348. // are not computed fields => the expression is the name of a column
  349. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  350. }
  351. return $this->FromSQLToValue($aValues, $sPrefix);
  352. }
  353. public function GetValidationPattern()
  354. {
  355. return '';
  356. }
  357. public function CheckFormat($value)
  358. {
  359. return true;
  360. }
  361. public function GetMaxSize()
  362. {
  363. return null;
  364. }
  365. public function MakeValue()
  366. {
  367. $sComputeFunc = $this->Get("compute_func");
  368. if (empty($sComputeFunc)) return null;
  369. return call_user_func($sComputeFunc);
  370. }
  371. abstract public function GetDefaultValue();
  372. //
  373. // To be overloaded in subclasses
  374. //
  375. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  376. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  377. //abstract protected GetBasicFilterHTMLInput();
  378. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  379. public function GetFilterDefinitions()
  380. {
  381. return array();
  382. }
  383. public function GetEditValue($sValue, $oHostObj = null)
  384. {
  385. return (string)$sValue;
  386. }
  387. /**
  388. * Helper to get a value that will be JSON encoded
  389. * The operation is the opposite to FromJSONToValue
  390. */
  391. public function GetForJSON($value)
  392. {
  393. // In most of the cases, that will be the expected behavior...
  394. return $this->GetEditValue($value);
  395. }
  396. /**
  397. * Helper to form a value, given JSON decoded data
  398. * The operation is the opposite to GetForJSON
  399. */
  400. public function FromJSONToValue($json)
  401. {
  402. // Passthrough in most of the cases
  403. return $json;
  404. }
  405. /**
  406. * Override to display the value in the GUI
  407. */
  408. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  409. {
  410. return Str::pure2html((string)$sValue);
  411. }
  412. /**
  413. * Override to export the value in XML
  414. */
  415. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  416. {
  417. return Str::pure2xml((string)$sValue);
  418. }
  419. /**
  420. * Override to escape the value when read by DBObject::GetAsCSV()
  421. */
  422. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  423. {
  424. return (string)$sValue;
  425. }
  426. /**
  427. * Override to differentiate a value displayed in the UI or in the history
  428. */
  429. public function GetAsHTMLForHistory($sValue, $oHostObject = null, $bLocalize = true)
  430. {
  431. return $this->GetAsHTML($sValue, $oHostObject, $bLocalize);
  432. }
  433. /**
  434. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  435. * @param $value mixed The current value of the field
  436. * @param $sVerb string The verb specifying the representation of the value
  437. * @param $oHostObject DBObject The object
  438. * @param $bLocalize bool Whether or not to localize the value
  439. */
  440. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  441. {
  442. if ($this->IsScalar())
  443. {
  444. switch ($sVerb)
  445. {
  446. case '':
  447. return $value;
  448. case 'html':
  449. return $this->GetAsHtml($value, $oHostObject, $bLocalize);
  450. case 'label':
  451. return $this->GetEditValue($value);
  452. default:
  453. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  454. }
  455. }
  456. return null;
  457. }
  458. public function GetAllowedValues($aArgs = array(), $sContains = '')
  459. {
  460. $oValSetDef = $this->GetValuesDef();
  461. if (!$oValSetDef) return null;
  462. return $oValSetDef->GetValues($aArgs, $sContains);
  463. }
  464. /**
  465. * Explain the change of the attribute (history)
  466. */
  467. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  468. {
  469. if (is_null($sLabel))
  470. {
  471. $sLabel = $this->GetLabel();
  472. }
  473. $sNewValueHtml = $this->GetAsHTMLForHistory($sNewValue);
  474. $sOldValueHtml = $this->GetAsHTMLForHistory($sOldValue);
  475. if($this->IsExternalKey())
  476. {
  477. $sTargetClass = $this->GetTargetClass();
  478. $sOldValueHtml = (int)$sOldValue ? MetaModel::GetHyperLink($sTargetClass, (int)$sOldValue) : null;
  479. $sNewValueHtml = (int)$sNewValue ? MetaModel::GetHyperLink($sTargetClass, (int)$sNewValue) : null;
  480. }
  481. if ( (($this->GetType() == 'String') || ($this->GetType() == 'Text')) &&
  482. (strlen($sNewValue) > strlen($sOldValue)) )
  483. {
  484. // Check if some text was not appended to the field
  485. if (substr($sNewValue,0, strlen($sOldValue)) == $sOldValue) // Text added at the end
  486. {
  487. $sDelta = $this->GetAsHTML(substr($sNewValue, strlen($sOldValue)));
  488. $sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
  489. }
  490. else if (substr($sNewValue, -strlen($sOldValue)) == $sOldValue) // Text added at the beginning
  491. {
  492. $sDelta = $this->GetAsHTML(substr($sNewValue, 0, strlen($sNewValue) - strlen($sOldValue)));
  493. $sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
  494. }
  495. else
  496. {
  497. if (strlen($sOldValue) == 0)
  498. {
  499. $sResult = Dict::Format('Change:AttName_SetTo', $sLabel, $sNewValueHtml);
  500. }
  501. else
  502. {
  503. if (is_null($sNewValue))
  504. {
  505. $sNewValueHtml = Dict::S('UI:UndefinedObject');
  506. }
  507. $sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValueHtml, $sOldValueHtml);
  508. }
  509. }
  510. }
  511. else
  512. {
  513. if (strlen($sOldValue) == 0)
  514. {
  515. $sResult = Dict::Format('Change:AttName_SetTo', $sLabel, $sNewValueHtml);
  516. }
  517. else
  518. {
  519. if (is_null($sNewValue))
  520. {
  521. $sNewValueHtml = Dict::S('UI:UndefinedObject');
  522. }
  523. $sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValueHtml, $sOldValueHtml);
  524. }
  525. }
  526. return $sResult;
  527. }
  528. /**
  529. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  530. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  531. * does nothing special, and just calls the default (loose) operator
  532. * @param string $sSearchText The search string to analyze for smart patterns
  533. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  534. * @param Hash $aParams Values of the query parameters
  535. * @return Expression The search condition to be added (AND) to the current search
  536. */
  537. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  538. {
  539. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  540. $oRightExpr = new VariableExpression($sParamName);
  541. $sOperator = $this->GetBasicFilterLooseOperator();
  542. switch ($sOperator)
  543. {
  544. case 'Contains':
  545. $aParams[$sParamName] = "%$sSearchText%";
  546. $sSQLOperator = 'LIKE';
  547. break;
  548. default:
  549. $sSQLOperator = $sOperator;
  550. $aParams[$sParamName] = $sSearchText;
  551. }
  552. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  553. return $oNewCondition;
  554. }
  555. }
  556. /**
  557. * Set of objects directly linked to an object, and being part of its definition
  558. *
  559. * @package iTopORM
  560. */
  561. class AttributeLinkedSet extends AttributeDefinition
  562. {
  563. static public function ListExpectedParams()
  564. {
  565. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  566. }
  567. public function GetEditClass() {return "LinkedSet";}
  568. public function IsWritable() {return true;}
  569. public function IsLinkSet() {return true;}
  570. public function IsIndirect() {return false;}
  571. public function GetValuesDef() {return $this->Get("allowed_values");}
  572. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  573. public function GetDefaultValue($aArgs = array())
  574. {
  575. // Note: so far, this feature is a prototype,
  576. // later, the argument 'this' should always be present in the arguments
  577. //
  578. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  579. {
  580. $aValues = $this->Get('default_value')->GetValues($aArgs);
  581. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  582. return $oSet;
  583. }
  584. else
  585. {
  586. return DBObjectSet::FromScratch($this->Get('linked_class'));
  587. }
  588. }
  589. public function GetTrackingLevel()
  590. {
  591. return $this->GetOptional('tracking_level', MetaModel::GetConfig()->Get('tracking_level_linked_set_default'));
  592. }
  593. public function GetEditMode()
  594. {
  595. return $this->GetOptional('edit_mode', LINKSET_EDITMODE_ACTIONS);
  596. }
  597. public function GetLinkedClass() {return $this->Get('linked_class');}
  598. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  599. public function GetBasicFilterOperators() {return array();}
  600. public function GetBasicFilterLooseOperator() {return '';}
  601. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  602. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  603. {
  604. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  605. {
  606. $sValue->Rewind();
  607. $aItems = array();
  608. while ($oObj = $sValue->Fetch())
  609. {
  610. // Show only relevant information (hide the external key to the current object)
  611. $aAttributes = array();
  612. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  613. {
  614. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  615. if ($oAttDef->IsExternalField()) continue;
  616. $sAttValue = $oObj->GetAsHTML($sAttCode);
  617. if (strlen($sAttValue) > 0)
  618. {
  619. $aAttributes[] = $sAttValue;
  620. }
  621. }
  622. $sAttributes = implode(', ', $aAttributes);
  623. $aItems[] = $sAttributes;
  624. }
  625. return implode('<br/>', $aItems);
  626. }
  627. return null;
  628. }
  629. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  630. {
  631. return "Sorry, no yet implemented";
  632. }
  633. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  634. {
  635. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  636. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  637. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  638. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  639. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  640. {
  641. $sValue->Rewind();
  642. $aItems = array();
  643. while ($oObj = $sValue->Fetch())
  644. {
  645. $sObjClass = get_class($oObj);
  646. // Show only relevant information (hide the external key to the current object)
  647. $aAttributes = array();
  648. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  649. {
  650. if ($sAttCode == 'finalclass')
  651. {
  652. if ($sObjClass == $this->GetLinkedClass())
  653. {
  654. // Simplify the output if the exact class could be determined implicitely
  655. continue;
  656. }
  657. }
  658. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  659. if ($oAttDef->IsExternalField()) continue;
  660. if (!$oAttDef->IsDirectField()) continue;
  661. if (!$oAttDef->IsScalar()) continue;
  662. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '');
  663. if (strlen($sAttValue) > 0)
  664. {
  665. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  666. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  667. }
  668. }
  669. $sAttributes = implode($sSepAttribute, $aAttributes);
  670. $aItems[] = $sAttributes;
  671. }
  672. $sRes = implode($sSepItem, $aItems);
  673. }
  674. else
  675. {
  676. $sRes = '';
  677. }
  678. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  679. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  680. return $sRes;
  681. }
  682. /**
  683. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  684. * @param $value mixed The current value of the field
  685. * @param $sVerb string The verb specifying the representation of the value
  686. * @param $oHostObject DBObject The object
  687. * @param $bLocalize bool Whether or not to localize the value
  688. */
  689. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  690. {
  691. $sRemoteName = $this->IsIndirect() ? $this->GetExtKeyToRemote().'_friendlyname' : 'friendlyname';
  692. $oLinkSet = clone $value; // Workaround/Safety net for Trac #887
  693. $iLimit = MetaModel::GetConfig()->Get('max_linkset_output');
  694. if ($iLimit > 0)
  695. {
  696. $oLinkSet->SetLimit($iLimit);
  697. }
  698. $aNames = $oLinkSet->GetColumnAsArray($sRemoteName);
  699. if ($iLimit > 0)
  700. {
  701. $iTotal = $oLinkSet->Count();
  702. if ($iTotal > count($aNames))
  703. {
  704. $aNames[] = '... '.Dict::Format('UI:TruncatedResults', count($aNames), $iTotal);
  705. }
  706. }
  707. switch($sVerb)
  708. {
  709. case '':
  710. return implode("\n", $aNames);
  711. case 'html':
  712. return '<ul><li>'.implode("</li><li>", $aNames).'</li></ul>';
  713. default:
  714. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  715. }
  716. }
  717. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  718. public function GetImportColumns()
  719. {
  720. $aColumns = array();
  721. $aColumns[$this->GetCode()] = 'TEXT';
  722. return $aColumns;
  723. }
  724. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  725. {
  726. if (is_null($sSepItem) || empty($sSepItem))
  727. {
  728. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  729. }
  730. if (is_null($sSepAttribute) || empty($sSepAttribute))
  731. {
  732. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  733. }
  734. if (is_null($sSepValue) || empty($sSepValue))
  735. {
  736. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  737. }
  738. if (is_null($sAttributeQualifier) || empty($sAttributeQualifier))
  739. {
  740. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  741. }
  742. $sTargetClass = $this->Get('linked_class');
  743. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  744. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  745. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  746. $aLinks = array();
  747. foreach($aInput as $aRow)
  748. {
  749. // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
  750. $aExtKeys = array();
  751. $aValues = array();
  752. foreach($aRow as $sCell)
  753. {
  754. $iSepPos = strpos($sCell, $sSepValue);
  755. if ($iSepPos === false)
  756. {
  757. // Houston...
  758. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  759. }
  760. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  761. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  762. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  763. {
  764. $sKeyAttCode = $aMatches[1];
  765. $sRemoteAttCode = $aMatches[2];
  766. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  767. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  768. {
  769. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  770. }
  771. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  772. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  773. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  774. {
  775. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  776. }
  777. }
  778. else
  779. {
  780. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  781. {
  782. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  783. }
  784. $aValues[$sAttCode] = $sValue;
  785. }
  786. }
  787. // 2nd - Instanciate the object and set the value
  788. if (isset($aValues['finalclass']))
  789. {
  790. $sLinkClass = $aValues['finalclass'];
  791. if (!is_subclass_of($sLinkClass, $sTargetClass))
  792. {
  793. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  794. }
  795. }
  796. elseif (MetaModel::IsAbstract($sTargetClass))
  797. {
  798. throw new CoreException('Missing finalclass for link attribute specification');
  799. }
  800. else
  801. {
  802. $sLinkClass = $sTargetClass;
  803. }
  804. $oLink = MetaModel::NewObject($sLinkClass);
  805. foreach ($aValues as $sAttCode => $sValue)
  806. {
  807. $oLink->Set($sAttCode, $sValue);
  808. }
  809. // 3rd - Set external keys from search conditions
  810. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  811. {
  812. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  813. $sKeyClass = $oKeyAttDef->GetTargetClass();
  814. $oExtKeyFilter = new CMDBSearchFilter($sKeyClass);
  815. $aReconciliationDesc = array();
  816. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  817. {
  818. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  819. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  820. }
  821. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  822. switch($oExtKeySet->Count())
  823. {
  824. case 0:
  825. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  826. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  827. break;
  828. case 1:
  829. $oRemoteObj = $oExtKeySet->Fetch();
  830. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  831. break;
  832. default:
  833. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  834. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  835. // Found several matches, ambiguous
  836. }
  837. }
  838. // Check (roughly) if such a link is valid
  839. $aErrors = array();
  840. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  841. {
  842. if ($oAttDef->IsExternalKey())
  843. {
  844. if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())))
  845. {
  846. continue; // Don't check the key to self
  847. }
  848. }
  849. if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed())
  850. {
  851. $aErrors[] = $sAttCode;
  852. }
  853. }
  854. if (count($aErrors) > 0)
  855. {
  856. throw new CoreException("Missing value for mandatory attribute(s): ".implode(', ', $aErrors));
  857. }
  858. $aLinks[] = $oLink;
  859. }
  860. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  861. return $oSet;
  862. }
  863. public function Equals($val1, $val2)
  864. {
  865. if ($val1 === $val2) return true;
  866. if (is_object($val1) != is_object($val2))
  867. {
  868. return false;
  869. }
  870. if (!is_object($val1))
  871. {
  872. // string ?
  873. // todo = implement this case ?
  874. return false;
  875. }
  876. // Both values are Object sets
  877. return $val1->HasSameContents($val2);
  878. }
  879. /**
  880. * Find the corresponding "link" attribute on the target class
  881. *
  882. * @return string The attribute code on the target class, or null if none has been found
  883. */
  884. public function GetMirrorLinkAttribute()
  885. {
  886. $oRemoteAtt = MetaModel::GetAttributeDef($this->GetLinkedClass(), $this->GetExtKeyToMe());
  887. return $oRemoteAtt;
  888. }
  889. }
  890. /**
  891. * Set of objects linked to an object (n-n), and being part of its definition
  892. *
  893. * @package iTopORM
  894. */
  895. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  896. {
  897. static public function ListExpectedParams()
  898. {
  899. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  900. }
  901. public function IsIndirect() {return true;}
  902. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  903. public function GetEditClass() {return "LinkedSet";}
  904. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  905. public function GetTrackingLevel()
  906. {
  907. return $this->GetOptional('tracking_level', MetaModel::GetConfig()->Get('tracking_level_linked_set_indirect_default'));
  908. }
  909. /**
  910. * Find the corresponding "link" attribute on the target class
  911. *
  912. * @return string The attribute code on the target class, or null if none has been found
  913. */
  914. public function GetMirrorLinkAttribute()
  915. {
  916. $oRet = null;
  917. $oExtKeyToRemote = MetaModel::GetAttributeDef($this->GetLinkedClass(), $this->GetExtKeyToRemote());
  918. $sRemoteClass = $oExtKeyToRemote->GetTargetClass();
  919. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  920. {
  921. if (!$oRemoteAttDef instanceof AttributeLinkedSetIndirect) continue;
  922. if ($oRemoteAttDef->GetLinkedClass() != $this->GetLinkedClass()) continue;
  923. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetExtKeyToRemote()) continue;
  924. if ($oRemoteAttDef->GetExtKeyToRemote() != $this->GetExtKeyToMe()) continue;
  925. $oRet = $oRemoteAttDef;
  926. break;
  927. }
  928. return $oRet;
  929. }
  930. }
  931. /**
  932. * Abstract class implementing default filters for a DB column
  933. *
  934. * @package iTopORM
  935. */
  936. class AttributeDBFieldVoid extends AttributeDefinition
  937. {
  938. static public function ListExpectedParams()
  939. {
  940. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  941. }
  942. // To be overriden, used in GetSQLColumns
  943. protected function GetSQLCol($bFullSpec = false)
  944. {
  945. return "VARCHAR(255)".($bFullSpec ? $this->GetSQLColSpec() : '');
  946. }
  947. protected function GetSQLColSpec()
  948. {
  949. $default = $this->ScalarToSQL($this->GetDefaultValue());
  950. if (is_null($default))
  951. {
  952. $sRet = '';
  953. }
  954. else
  955. {
  956. if (is_numeric($default))
  957. {
  958. // Though it is a string in PHP, it will be considered as a numeric value in MySQL
  959. // Then it must not be quoted here, to preserve the compatibility with the value returned by CMDBSource::GetFieldSpec
  960. $sRet = " DEFAULT $default";
  961. }
  962. else
  963. {
  964. $sRet = " DEFAULT ".CMDBSource::Quote($default);
  965. }
  966. }
  967. return $sRet;
  968. }
  969. public function GetEditClass() {return "String";}
  970. public function GetValuesDef() {return $this->Get("allowed_values");}
  971. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  972. public function IsDirectField() {return true;}
  973. public function IsScalar() {return true;}
  974. public function IsWritable() {return true;}
  975. public function GetSQLExpr() {return $this->Get("sql");}
  976. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  977. public function IsNullAllowed() {return false;}
  978. //
  979. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  980. public function GetSQLExpressions($sPrefix = '')
  981. {
  982. $aColumns = array();
  983. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  984. $aColumns[''] = $this->Get("sql");
  985. return $aColumns;
  986. }
  987. public function FromSQLToValue($aCols, $sPrefix = '')
  988. {
  989. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  990. return $value;
  991. }
  992. public function GetSQLValues($value)
  993. {
  994. $aValues = array();
  995. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  996. return $aValues;
  997. }
  998. public function GetSQLColumns($bFullSpec = false)
  999. {
  1000. $aColumns = array();
  1001. $aColumns[$this->Get("sql")] = $this->GetSQLCol($bFullSpec);
  1002. return $aColumns;
  1003. }
  1004. public function GetFilterDefinitions()
  1005. {
  1006. return array($this->GetCode() => new FilterFromAttribute($this));
  1007. }
  1008. public function GetBasicFilterOperators()
  1009. {
  1010. return array("="=>"equals", "!="=>"differs from");
  1011. }
  1012. public function GetBasicFilterLooseOperator()
  1013. {
  1014. return "=";
  1015. }
  1016. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1017. {
  1018. $sQValue = CMDBSource::Quote($value);
  1019. switch ($sOpCode)
  1020. {
  1021. case '!=':
  1022. return $this->GetSQLExpr()." != $sQValue";
  1023. break;
  1024. case '=':
  1025. default:
  1026. return $this->GetSQLExpr()." = $sQValue";
  1027. }
  1028. }
  1029. }
  1030. /**
  1031. * Base class for all kind of DB attributes, with the exception of external keys
  1032. *
  1033. * @package iTopORM
  1034. */
  1035. class AttributeDBField extends AttributeDBFieldVoid
  1036. {
  1037. static public function ListExpectedParams()
  1038. {
  1039. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  1040. }
  1041. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"), null);}
  1042. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1043. }
  1044. /**
  1045. * Map an integer column to an attribute
  1046. *
  1047. * @package iTopORM
  1048. */
  1049. class AttributeInteger extends AttributeDBField
  1050. {
  1051. static public function ListExpectedParams()
  1052. {
  1053. return parent::ListExpectedParams();
  1054. //return array_merge(parent::ListExpectedParams(), array());
  1055. }
  1056. public function GetEditClass() {return "String";}
  1057. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1058. public function GetValidationPattern()
  1059. {
  1060. return "^[0-9]+$";
  1061. }
  1062. public function GetBasicFilterOperators()
  1063. {
  1064. return array(
  1065. "!="=>"differs from",
  1066. "="=>"equals",
  1067. ">"=>"greater (strict) than",
  1068. ">="=>"greater than",
  1069. "<"=>"less (strict) than",
  1070. "<="=>"less than",
  1071. "in"=>"in"
  1072. );
  1073. }
  1074. public function GetBasicFilterLooseOperator()
  1075. {
  1076. // Unless we implement an "equals approximately..." or "same order of magnitude"
  1077. return "=";
  1078. }
  1079. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1080. {
  1081. $sQValue = CMDBSource::Quote($value);
  1082. switch ($sOpCode)
  1083. {
  1084. case '!=':
  1085. return $this->GetSQLExpr()." != $sQValue";
  1086. break;
  1087. case '>':
  1088. return $this->GetSQLExpr()." > $sQValue";
  1089. break;
  1090. case '>=':
  1091. return $this->GetSQLExpr()." >= $sQValue";
  1092. break;
  1093. case '<':
  1094. return $this->GetSQLExpr()." < $sQValue";
  1095. break;
  1096. case '<=':
  1097. return $this->GetSQLExpr()." <= $sQValue";
  1098. break;
  1099. case 'in':
  1100. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  1101. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  1102. break;
  1103. case '=':
  1104. default:
  1105. return $this->GetSQLExpr()." = \"$value\"";
  1106. }
  1107. }
  1108. public function GetNullValue()
  1109. {
  1110. return null;
  1111. }
  1112. public function IsNull($proposedValue)
  1113. {
  1114. return is_null($proposedValue);
  1115. }
  1116. public function MakeRealValue($proposedValue, $oHostObj)
  1117. {
  1118. if (is_null($proposedValue)) return null;
  1119. if ($proposedValue === '') return null; // 0 is transformed into '' !
  1120. return (int)$proposedValue;
  1121. }
  1122. public function ScalarToSQL($value)
  1123. {
  1124. assert(is_numeric($value) || is_null($value));
  1125. return $value; // supposed to be an int
  1126. }
  1127. }
  1128. /**
  1129. * An external key for which the class is defined as the value of another attribute
  1130. *
  1131. * @package iTopORM
  1132. */
  1133. class AttributeObjectKey extends AttributeDBFieldVoid
  1134. {
  1135. static public function ListExpectedParams()
  1136. {
  1137. return array_merge(parent::ListExpectedParams(), array('class_attcode', 'is_null_allowed'));
  1138. }
  1139. public function GetEditClass() {return "String";}
  1140. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  1141. public function GetDefaultValue() {return 0;}
  1142. public function IsNullAllowed()
  1143. {
  1144. return $this->Get("is_null_allowed");
  1145. }
  1146. public function GetBasicFilterOperators()
  1147. {
  1148. return parent::GetBasicFilterOperators();
  1149. }
  1150. public function GetBasicFilterLooseOperator()
  1151. {
  1152. return parent::GetBasicFilterLooseOperator();
  1153. }
  1154. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1155. {
  1156. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1157. }
  1158. public function GetNullValue()
  1159. {
  1160. return 0;
  1161. }
  1162. public function IsNull($proposedValue)
  1163. {
  1164. return ($proposedValue == 0);
  1165. }
  1166. public function MakeRealValue($proposedValue, $oHostObj)
  1167. {
  1168. if (is_null($proposedValue)) return 0;
  1169. if ($proposedValue === '') return 0;
  1170. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  1171. return (int)$proposedValue;
  1172. }
  1173. }
  1174. /**
  1175. * Display an integer between 0 and 100 as a percentage / horizontal bar graph
  1176. *
  1177. * @package iTopORM
  1178. */
  1179. class AttributePercentage extends AttributeInteger
  1180. {
  1181. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1182. {
  1183. $iWidth = 5; // Total width of the percentage bar graph, in em...
  1184. $iValue = (int)$sValue;
  1185. if ($iValue > 100)
  1186. {
  1187. $iValue = 100;
  1188. }
  1189. else if ($iValue < 0)
  1190. {
  1191. $iValue = 0;
  1192. }
  1193. if ($iValue > 90)
  1194. {
  1195. $sColor = "#cc3300";
  1196. }
  1197. else if ($iValue > 50)
  1198. {
  1199. $sColor = "#cccc00";
  1200. }
  1201. else
  1202. {
  1203. $sColor = "#33cc00";
  1204. }
  1205. $iPercentWidth = ($iWidth * $iValue) / 100;
  1206. return "<div style=\"width:{$iWidth}em;-moz-border-radius: 3px;-webkit-border-radius: 3px;border-radius: 3px;display:inline-block;border: 1px #ccc solid;\"><div style=\"width:{$iPercentWidth}em; display:inline-block;background-color:$sColor;\">&nbsp;</div></div>&nbsp;$sValue %";
  1207. }
  1208. }
  1209. /**
  1210. * Map a decimal value column (suitable for financial computations) to an attribute
  1211. * internally in PHP such numbers are represented as string. Should you want to perform
  1212. * a calculation on them, it is recommended to use the BC Math functions in order to
  1213. * retain the precision
  1214. *
  1215. * @package iTopORM
  1216. */
  1217. class AttributeDecimal extends AttributeDBField
  1218. {
  1219. static public function ListExpectedParams()
  1220. {
  1221. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  1222. }
  1223. public function GetEditClass() {return "String";}
  1224. protected function GetSQLCol($bFullSpec = false)
  1225. {
  1226. return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")".($bFullSpec ? $this->GetSQLColSpec() : '');
  1227. }
  1228. public function GetValidationPattern()
  1229. {
  1230. $iNbDigits = $this->Get('digits');
  1231. $iPrecision = $this->Get('decimals');
  1232. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  1233. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  1234. }
  1235. public function GetBasicFilterOperators()
  1236. {
  1237. return array(
  1238. "!="=>"differs from",
  1239. "="=>"equals",
  1240. ">"=>"greater (strict) than",
  1241. ">="=>"greater than",
  1242. "<"=>"less (strict) than",
  1243. "<="=>"less than",
  1244. "in"=>"in"
  1245. );
  1246. }
  1247. public function GetBasicFilterLooseOperator()
  1248. {
  1249. // Unless we implement an "equals approximately..." or "same order of magnitude"
  1250. return "=";
  1251. }
  1252. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1253. {
  1254. $sQValue = CMDBSource::Quote($value);
  1255. switch ($sOpCode)
  1256. {
  1257. case '!=':
  1258. return $this->GetSQLExpr()." != $sQValue";
  1259. break;
  1260. case '>':
  1261. return $this->GetSQLExpr()." > $sQValue";
  1262. break;
  1263. case '>=':
  1264. return $this->GetSQLExpr()." >= $sQValue";
  1265. break;
  1266. case '<':
  1267. return $this->GetSQLExpr()." < $sQValue";
  1268. break;
  1269. case '<=':
  1270. return $this->GetSQLExpr()." <= $sQValue";
  1271. break;
  1272. case 'in':
  1273. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  1274. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  1275. break;
  1276. case '=':
  1277. default:
  1278. return $this->GetSQLExpr()." = \"$value\"";
  1279. }
  1280. }
  1281. public function GetNullValue()
  1282. {
  1283. return null;
  1284. }
  1285. public function IsNull($proposedValue)
  1286. {
  1287. return is_null($proposedValue);
  1288. }
  1289. public function MakeRealValue($proposedValue, $oHostObj)
  1290. {
  1291. if (is_null($proposedValue)) return null;
  1292. if ($proposedValue === '') return null;
  1293. return (string)$proposedValue;
  1294. }
  1295. public function ScalarToSQL($value)
  1296. {
  1297. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  1298. return $value; // null or string
  1299. }
  1300. }
  1301. /**
  1302. * Map a boolean column to an attribute
  1303. *
  1304. * @package iTopORM
  1305. */
  1306. class AttributeBoolean extends AttributeInteger
  1307. {
  1308. static public function ListExpectedParams()
  1309. {
  1310. return parent::ListExpectedParams();
  1311. //return array_merge(parent::ListExpectedParams(), array());
  1312. }
  1313. public function GetEditClass() {return "Integer";}
  1314. protected function GetSQLCol($bFullSpec = false) {return "TINYINT(1)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1315. public function MakeRealValue($proposedValue, $oHostObj)
  1316. {
  1317. if (is_null($proposedValue)) return null;
  1318. if ($proposedValue === '') return null;
  1319. if ((int)$proposedValue) return true;
  1320. return false;
  1321. }
  1322. public function ScalarToSQL($value)
  1323. {
  1324. if ($value) return 1;
  1325. return 0;
  1326. }
  1327. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  1328. {
  1329. return $sValue ? '1' : '0';
  1330. }
  1331. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  1332. {
  1333. return $sValue ? '1' : '0';
  1334. }
  1335. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1336. {
  1337. return $sValue ? '1' : '0';
  1338. }
  1339. /**
  1340. * Helper to get a value that will be JSON encoded
  1341. * The operation is the opposite to FromJSONToValue
  1342. */
  1343. public function GetForJSON($value)
  1344. {
  1345. return $value ? '1' : '0';
  1346. }
  1347. }
  1348. /**
  1349. * Map a varchar column (size < ?) to an attribute
  1350. *
  1351. * @package iTopORM
  1352. */
  1353. class AttributeString extends AttributeDBField
  1354. {
  1355. static public function ListExpectedParams()
  1356. {
  1357. return parent::ListExpectedParams();
  1358. //return array_merge(parent::ListExpectedParams(), array());
  1359. }
  1360. public function GetEditClass() {return "String";}
  1361. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(255)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1362. public function GetValidationPattern()
  1363. {
  1364. $sPattern = $this->GetOptional('validation_pattern', '');
  1365. if (empty($sPattern))
  1366. {
  1367. return parent::GetValidationPattern();
  1368. }
  1369. else
  1370. {
  1371. return $sPattern;
  1372. }
  1373. }
  1374. public function CheckFormat($value)
  1375. {
  1376. $sRegExp = $this->GetValidationPattern();
  1377. if (empty($sRegExp))
  1378. {
  1379. return true;
  1380. }
  1381. else
  1382. {
  1383. $sRegExp = str_replace('/', '\\/', $sRegExp);
  1384. return preg_match("/$sRegExp/", $value);
  1385. }
  1386. }
  1387. public function GetMaxSize()
  1388. {
  1389. return 255;
  1390. }
  1391. public function GetBasicFilterOperators()
  1392. {
  1393. return array(
  1394. "="=>"equals",
  1395. "!="=>"differs from",
  1396. "Like"=>"equals (no case)",
  1397. "NotLike"=>"differs from (no case)",
  1398. "Contains"=>"contains",
  1399. "Begins with"=>"begins with",
  1400. "Finishes with"=>"finishes with"
  1401. );
  1402. }
  1403. public function GetBasicFilterLooseOperator()
  1404. {
  1405. return "Contains";
  1406. }
  1407. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1408. {
  1409. $sQValue = CMDBSource::Quote($value);
  1410. switch ($sOpCode)
  1411. {
  1412. case '=':
  1413. case '!=':
  1414. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1415. case 'Begins with':
  1416. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  1417. case 'Finishes with':
  1418. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  1419. case 'Contains':
  1420. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  1421. case 'NotLike':
  1422. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  1423. case 'Like':
  1424. default:
  1425. return $this->GetSQLExpr()." LIKE $sQValue";
  1426. }
  1427. }
  1428. public function GetNullValue()
  1429. {
  1430. return '';
  1431. }
  1432. public function IsNull($proposedValue)
  1433. {
  1434. return ($proposedValue == '');
  1435. }
  1436. public function MakeRealValue($proposedValue, $oHostObj)
  1437. {
  1438. if (is_null($proposedValue)) return '';
  1439. return (string)$proposedValue;
  1440. }
  1441. public function ScalarToSQL($value)
  1442. {
  1443. if (!is_string($value) && !is_null($value))
  1444. {
  1445. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  1446. }
  1447. return $value;
  1448. }
  1449. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  1450. {
  1451. $sFrom = array("\r\n", $sTextQualifier);
  1452. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1453. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1454. return $sTextQualifier.$sEscaped.$sTextQualifier;
  1455. }
  1456. public function GetDisplayStyle()
  1457. {
  1458. return $this->GetOptional('display_style', 'select');
  1459. }
  1460. }
  1461. /**
  1462. * An attibute that matches an object class
  1463. *
  1464. * @package iTopORM
  1465. */
  1466. class AttributeClass extends AttributeString
  1467. {
  1468. static public function ListExpectedParams()
  1469. {
  1470. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  1471. }
  1472. public function __construct($sCode, $aParams)
  1473. {
  1474. $this->m_sCode = $sCode;
  1475. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  1476. parent::__construct($sCode, $aParams);
  1477. }
  1478. public function GetDefaultValue()
  1479. {
  1480. $sDefault = parent::GetDefaultValue();
  1481. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  1482. {
  1483. // For this kind of attribute specifying null as default value
  1484. // is authorized even if null is not allowed
  1485. // Pick the first one...
  1486. $aClasses = $this->GetAllowedValues();
  1487. $sDefault = key($aClasses);
  1488. }
  1489. return $sDefault;
  1490. }
  1491. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1492. {
  1493. if (empty($sValue)) return '';
  1494. return MetaModel::GetName($sValue);
  1495. }
  1496. public function RequiresIndex()
  1497. {
  1498. return true;
  1499. }
  1500. public function GetBasicFilterLooseOperator()
  1501. {
  1502. return '=';
  1503. }
  1504. }
  1505. /**
  1506. * An attibute that matches one of the language codes availables in the dictionnary
  1507. *
  1508. * @package iTopORM
  1509. */
  1510. class AttributeApplicationLanguage extends AttributeString
  1511. {
  1512. static public function ListExpectedParams()
  1513. {
  1514. return parent::ListExpectedParams();
  1515. }
  1516. public function __construct($sCode, $aParams)
  1517. {
  1518. $this->m_sCode = $sCode;
  1519. $aAvailableLanguages = Dict::GetLanguages();
  1520. $aLanguageCodes = array();
  1521. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  1522. {
  1523. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  1524. }
  1525. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  1526. parent::__construct($sCode, $aParams);
  1527. }
  1528. public function RequiresIndex()
  1529. {
  1530. return true;
  1531. }
  1532. public function GetBasicFilterLooseOperator()
  1533. {
  1534. return '=';
  1535. }
  1536. }
  1537. /**
  1538. * The attribute dedicated to the finalclass automatic attribute
  1539. *
  1540. * @package iTopORM
  1541. */
  1542. class AttributeFinalClass extends AttributeString
  1543. {
  1544. public function __construct($sCode, $aParams)
  1545. {
  1546. $this->m_sCode = $sCode;
  1547. $aParams["allowed_values"] = null;
  1548. parent::__construct($sCode, $aParams);
  1549. $this->m_sValue = $this->Get("default_value");
  1550. }
  1551. public function IsWritable()
  1552. {
  1553. return false;
  1554. }
  1555. public function RequiresIndex()
  1556. {
  1557. return true;
  1558. }
  1559. public function SetFixedValue($sValue)
  1560. {
  1561. $this->m_sValue = $sValue;
  1562. }
  1563. public function GetDefaultValue()
  1564. {
  1565. return $this->m_sValue;
  1566. }
  1567. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1568. {
  1569. if (empty($sValue)) return '';
  1570. return MetaModel::GetName($sValue);
  1571. }
  1572. public function GetBasicFilterLooseOperator()
  1573. {
  1574. return '=';
  1575. }
  1576. public function GetValueLabel($sValue)
  1577. {
  1578. if (empty($sValue)) return '';
  1579. return MetaModel::GetName($sValue);
  1580. }
  1581. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1582. {
  1583. $aRawValues = MetaModel::EnumChildClasses($this->GetHostClass(), ENUM_CHILD_CLASSES_ALL);
  1584. $aLocalizedValues = array();
  1585. foreach ($aRawValues as $sClass)
  1586. {
  1587. $aLocalizedValues[$sClass] = MetaModel::GetName($sClass);
  1588. }
  1589. return $aLocalizedValues;
  1590. }
  1591. }
  1592. /**
  1593. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1594. *
  1595. * @package iTopORM
  1596. */
  1597. class AttributePassword extends AttributeString
  1598. {
  1599. static public function ListExpectedParams()
  1600. {
  1601. return parent::ListExpectedParams();
  1602. //return array_merge(parent::ListExpectedParams(), array());
  1603. }
  1604. public function GetEditClass() {return "Password";}
  1605. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(64)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1606. public function GetMaxSize()
  1607. {
  1608. return 64;
  1609. }
  1610. public function GetFilterDefinitions()
  1611. {
  1612. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1613. // not allowed to search on passwords!
  1614. return array();
  1615. }
  1616. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1617. {
  1618. if (strlen($sValue) == 0)
  1619. {
  1620. return '';
  1621. }
  1622. else
  1623. {
  1624. return '******';
  1625. }
  1626. }
  1627. }
  1628. /**
  1629. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1630. * The encryption is based on a key set per iTop instance. Thus if you export your
  1631. * database (in SQL) to someone else without providing the key at the same time
  1632. * the encrypted fields will remain encrypted
  1633. *
  1634. * @package iTopORM
  1635. */
  1636. class AttributeEncryptedString extends AttributeString
  1637. {
  1638. static $sKey = null; // Encryption key used for all encrypted fields
  1639. public function __construct($sCode, $aParams)
  1640. {
  1641. parent::__construct($sCode, $aParams);
  1642. if (self::$sKey == null)
  1643. {
  1644. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1645. }
  1646. }
  1647. /**
  1648. * When the attribute definitions are stored in APC cache:
  1649. * 1) The static class variable $sKey is NOT serialized
  1650. * 2) The object's constructor is NOT called upon wakeup
  1651. * 3) mcrypt may crash the server if passed an empty key !!
  1652. *
  1653. * So let's restore the key (if needed) when waking up
  1654. **/
  1655. public function __wakeup()
  1656. {
  1657. if (self::$sKey == null)
  1658. {
  1659. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1660. }
  1661. }
  1662. protected function GetSQLCol($bFullSpec = false) {return "TINYBLOB";}
  1663. public function GetMaxSize()
  1664. {
  1665. return 255;
  1666. }
  1667. public function GetFilterDefinitions()
  1668. {
  1669. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1670. // not allowed to search on encrypted fields !
  1671. return array();
  1672. }
  1673. public function MakeRealValue($proposedValue, $oHostObj)
  1674. {
  1675. if (is_null($proposedValue)) return null;
  1676. return (string)$proposedValue;
  1677. }
  1678. /**
  1679. * Decrypt the value when reading from the database
  1680. */
  1681. public function FromSQLToValue($aCols, $sPrefix = '')
  1682. {
  1683. $oSimpleCrypt = new SimpleCrypt();
  1684. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1685. return $sValue;
  1686. }
  1687. /**
  1688. * Encrypt the value before storing it in the database
  1689. */
  1690. public function GetSQLValues($value)
  1691. {
  1692. $oSimpleCrypt = new SimpleCrypt();
  1693. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1694. $aValues = array();
  1695. $aValues[$this->Get("sql")] = $encryptedValue;
  1696. return $aValues;
  1697. }
  1698. }
  1699. // Wiki formatting - experimental
  1700. //
  1701. // [[<objClass>:<objName>]]
  1702. // Example: [[Server:db1.tnut.com]]
  1703. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1704. /**
  1705. * Map a text column (size > ?) to an attribute
  1706. *
  1707. * @package iTopORM
  1708. */
  1709. class AttributeText extends AttributeString
  1710. {
  1711. public function GetEditClass() {return "Text";}
  1712. protected function GetSQLCol($bFullSpec = false) {return "TEXT";}
  1713. public function GetMaxSize()
  1714. {
  1715. // Is there a way to know the current limitation for mysql?
  1716. // See mysql_field_len()
  1717. return 65535;
  1718. }
  1719. static public function RenderWikiHtml($sText)
  1720. {
  1721. $sPattern = '/'.str_replace('/', '\/', utils::GetConfig()->Get('url_validation_pattern')).'/i';
  1722. if (preg_match_all($sPattern, $sText, $aAllMatches, PREG_SET_ORDER /* important !*/ |PREG_OFFSET_CAPTURE /* important ! */))
  1723. {
  1724. $aUrls = array();
  1725. $i = count($aAllMatches);
  1726. // Replace the URLs by an actual hyperlink <a href="...">...</a>
  1727. // Let's do it backwards so that the initial positions are not modified by the replacement
  1728. // This works if the matches are captured: in the order they occur in the string AND
  1729. // with their offset (i.e. position) inside the string
  1730. while($i > 0)
  1731. {
  1732. $i--;
  1733. $sUrl = $aAllMatches[$i][0][0]; // String corresponding to the main pattern
  1734. $iPos = $aAllMatches[$i][0][1]; // Position of the main pattern
  1735. $sText = substr_replace($sText, "<a href=\"$sUrl\">$sUrl</a>", $iPos, strlen($sUrl));
  1736. }
  1737. }
  1738. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  1739. {
  1740. foreach($aAllMatches as $iPos => $aMatches)
  1741. {
  1742. $sClass = $aMatches[1];
  1743. $sName = $aMatches[2];
  1744. if (MetaModel::IsValidClass($sClass))
  1745. {
  1746. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1747. if (is_object($oObj))
  1748. {
  1749. // Propose a std link to the object
  1750. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  1751. }
  1752. else
  1753. {
  1754. // Propose a std link to the object
  1755. $sClassLabel = MetaModel::GetName($sClass);
  1756. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  1757. // Later: propose a link to create a new object
  1758. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1759. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="'.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  1760. }
  1761. }
  1762. }
  1763. }
  1764. return $sText;
  1765. }
  1766. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1767. {
  1768. $sValue = parent::GetAsHTML($sValue, $oHostObject, $bLocalize);
  1769. $sValue = self::RenderWikiHtml($sValue);
  1770. $aStyles = array();
  1771. if ($this->GetWidth() != '')
  1772. {
  1773. $aStyles[] = 'width:'.$this->GetWidth();
  1774. }
  1775. if ($this->GetHeight() != '')
  1776. {
  1777. $aStyles[] = 'height:'.$this->GetHeight();
  1778. }
  1779. $sStyle = '';
  1780. if (count($aStyles) > 0)
  1781. {
  1782. $aStyles[] = 'overflow:auto';
  1783. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1784. }
  1785. return "<div $sStyle>".str_replace("\n", "<br>\n", $sValue).'</div>';
  1786. }
  1787. public function GetEditValue($sValue, $oHostObj = null)
  1788. {
  1789. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1790. {
  1791. foreach($aAllMatches as $iPos => $aMatches)
  1792. {
  1793. $sClass = $aMatches[1];
  1794. $sName = $aMatches[2];
  1795. if (MetaModel::IsValidClass($sClass))
  1796. {
  1797. $sClassLabel = MetaModel::GetName($sClass);
  1798. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  1799. }
  1800. }
  1801. }
  1802. return $sValue;
  1803. }
  1804. public function MakeRealValue($proposedValue, $oHostObj)
  1805. {
  1806. $sValue = $proposedValue;
  1807. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1808. {
  1809. foreach($aAllMatches as $iPos => $aMatches)
  1810. {
  1811. $sClassLabel = $aMatches[1];
  1812. $sName = $aMatches[2];
  1813. if (!MetaModel::IsValidClass($sClassLabel))
  1814. {
  1815. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  1816. if ($sClass)
  1817. {
  1818. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  1819. }
  1820. }
  1821. }
  1822. }
  1823. return $sValue;
  1824. }
  1825. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  1826. {
  1827. return Str::pure2xml($value);
  1828. }
  1829. public function GetWidth()
  1830. {
  1831. return $this->GetOptional('width', '');
  1832. }
  1833. public function GetHeight()
  1834. {
  1835. return $this->GetOptional('height', '');
  1836. }
  1837. }
  1838. /**
  1839. * Map a log to an attribute
  1840. *
  1841. * @package iTopORM
  1842. */
  1843. class AttributeLongText extends AttributeText
  1844. {
  1845. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  1846. public function GetMaxSize()
  1847. {
  1848. // Is there a way to know the current limitation for mysql?
  1849. // See mysql_field_len()
  1850. return 65535*1024; // Limited... still 64 Mb!
  1851. }
  1852. }
  1853. /**
  1854. * An attibute that stores a case log (i.e journal)
  1855. *
  1856. * @package iTopORM
  1857. */
  1858. class AttributeCaseLog extends AttributeLongText
  1859. {
  1860. public function GetNullValue()
  1861. {
  1862. return '';
  1863. }
  1864. public function IsNull($proposedValue)
  1865. {
  1866. if (!($proposedValue instanceof ormCaseLog))
  1867. {
  1868. return ($proposedValue == '');
  1869. }
  1870. return ($proposedValue->GetText() == '');
  1871. }
  1872. public function ScalarToSQL($value)
  1873. {
  1874. if (!is_string($value) && !is_null($value))
  1875. {
  1876. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1877. }
  1878. return $value;
  1879. }
  1880. public function GetEditClass() {return "CaseLog";}
  1881. public function GetEditValue($sValue, $oHostObj = null)
  1882. {
  1883. if (!($sValue instanceOf ormCaseLog))
  1884. {
  1885. return '';
  1886. }
  1887. return $sValue->GetModifiedEntry();
  1888. }
  1889. public function GetDefaultValue() {return new ormCaseLog();}
  1890. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  1891. // Facilitate things: allow the user to Set the value from a string
  1892. public function MakeRealValue($proposedValue, $oHostObj)
  1893. {
  1894. if ($proposedValue instanceof ormCaseLog)
  1895. {
  1896. // Passthrough
  1897. $ret = $proposedValue;
  1898. }
  1899. else
  1900. {
  1901. // Append the new value if an instance of the object is supplied
  1902. //
  1903. $oPreviousLog = null;
  1904. if ($oHostObj != null)
  1905. {
  1906. $oPreviousLog = $oHostObj->Get($this->GetCode());
  1907. if (!is_object($oPreviousLog))
  1908. {
  1909. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  1910. }
  1911. }
  1912. if (is_object($oPreviousLog))
  1913. {
  1914. $oCaseLog = clone($oPreviousLog);
  1915. }
  1916. else
  1917. {
  1918. $oCaseLog = new ormCaseLog();
  1919. }
  1920. if ($proposedValue instanceof stdClass)
  1921. {
  1922. $oCaseLog->AddLogEntryFromJSON($proposedValue);
  1923. }
  1924. else
  1925. {
  1926. if (strlen($proposedValue) > 0)
  1927. {
  1928. $oCaseLog->AddLogEntry(parent::MakeRealValue($proposedValue, $oHostObj));
  1929. }
  1930. }
  1931. $ret = $oCaseLog;
  1932. }
  1933. return $ret;
  1934. }
  1935. public function GetSQLExpressions($sPrefix = '')
  1936. {
  1937. if ($sPrefix == '')
  1938. {
  1939. $sPrefix = $this->GetCode();
  1940. }
  1941. $aColumns = array();
  1942. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1943. $aColumns[''] = $sPrefix;
  1944. $aColumns['_index'] = $sPrefix.'_index';
  1945. return $aColumns;
  1946. }
  1947. public function FromSQLToValue($aCols, $sPrefix = '')
  1948. {
  1949. if (!array_key_exists($sPrefix, $aCols))
  1950. {
  1951. $sAvailable = implode(', ', array_keys($aCols));
  1952. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1953. }
  1954. $sLog = $aCols[$sPrefix];
  1955. if (isset($aCols[$sPrefix.'_index']))
  1956. {
  1957. $sIndex = $aCols[$sPrefix.'_index'];
  1958. }
  1959. else
  1960. {
  1961. // For backward compatibility, allow the current state to be: 1 log, no index
  1962. $sIndex = '';
  1963. }
  1964. if (strlen($sIndex) > 0)
  1965. {
  1966. $aIndex = unserialize($sIndex);
  1967. $value = new ormCaseLog($sLog, $aIndex);
  1968. }
  1969. else
  1970. {
  1971. $value = new ormCaseLog($sLog);
  1972. }
  1973. return $value;
  1974. }
  1975. public function GetSQLValues($value)
  1976. {
  1977. if (!($value instanceOf ormCaseLog))
  1978. {
  1979. $value = new ormCaseLog('');
  1980. }
  1981. $aValues = array();
  1982. $aValues[$this->GetCode()] = $value->GetText();
  1983. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  1984. return $aValues;
  1985. }
  1986. public function GetSQLColumns($bFullSpec = false)
  1987. {
  1988. $aColumns = array();
  1989. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  1990. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  1991. return $aColumns;
  1992. }
  1993. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  1994. {
  1995. if ($value instanceOf ormCaseLog)
  1996. {
  1997. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  1998. }
  1999. else
  2000. {
  2001. $sContent = '';
  2002. }
  2003. $aStyles = array();
  2004. if ($this->GetWidth() != '')
  2005. {
  2006. $aStyles[] = 'width:'.$this->GetWidth();
  2007. }
  2008. if ($this->GetHeight() != '')
  2009. {
  2010. $aStyles[] = 'height:'.$this->GetHeight();
  2011. }
  2012. $sStyle = '';
  2013. if (count($aStyles) > 0)
  2014. {
  2015. $sStyle = 'style="'.implode(';', $aStyles).'"';
  2016. }
  2017. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  2018. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2019. {
  2020. if ($value instanceOf ormCaseLog)
  2021. {
  2022. return parent::GetAsCSV($value->GetText(), $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  2023. }
  2024. else
  2025. {
  2026. return '';
  2027. }
  2028. }
  2029. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2030. {
  2031. if ($value instanceOf ormCaseLog)
  2032. {
  2033. return parent::GetAsXML($value->GetText(), $oHostObject, $bLocalize);
  2034. }
  2035. else
  2036. {
  2037. return '';
  2038. }
  2039. }
  2040. /**
  2041. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  2042. * @param $value mixed The current value of the field
  2043. * @param $sVerb string The verb specifying the representation of the value
  2044. * @param $oHostObject DBObject The object
  2045. * @param $bLocalize bool Whether or not to localize the value
  2046. */
  2047. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  2048. {
  2049. switch($sVerb)
  2050. {
  2051. case '':
  2052. return $value->GetText();
  2053. case 'head':
  2054. return $value->GetLatestEntry();
  2055. case 'head_html':
  2056. return '<div class="caselog_entry">'.str_replace( array( "\r\n", "\n", "\r"), "<br/>", htmlentities($value->GetLatestEntry(), ENT_QUOTES, 'UTF-8')).'</div>';
  2057. case 'html':
  2058. return $value->GetAsEmailHtml();
  2059. default:
  2060. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  2061. }
  2062. }
  2063. /**
  2064. * Helper to get a value that will be JSON encoded
  2065. * The operation is the opposite to FromJSONToValue
  2066. */
  2067. public function GetForJSON($value)
  2068. {
  2069. return $value->GetForJSON();
  2070. }
  2071. /**
  2072. * Helper to form a value, given JSON decoded data
  2073. * The operation is the opposite to GetForJSON
  2074. */
  2075. public function FromJSONToValue($json)
  2076. {
  2077. if (is_string($json))
  2078. {
  2079. // Will be correctly handled in MakeRealValue
  2080. $ret = $json;
  2081. }
  2082. else
  2083. {
  2084. if (isset($json->add_item))
  2085. {
  2086. // Will be correctly handled in MakeRealValue
  2087. $ret = $json->add_item;
  2088. if (!isset($ret->message))
  2089. {
  2090. throw new Exception("Missing mandatory entry: 'message'");
  2091. }
  2092. }
  2093. else
  2094. {
  2095. $ret = ormCaseLog::FromJSON($json);
  2096. }
  2097. }
  2098. return $ret;
  2099. }
  2100. }
  2101. /**
  2102. * Map a text column (size > ?), containing HTML code, to an attribute
  2103. *
  2104. * @package iTopORM
  2105. */
  2106. class AttributeHTML extends AttributeLongText
  2107. {
  2108. public function GetEditClass() {return "HTML";}
  2109. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2110. {
  2111. return $sValue;
  2112. }
  2113. }
  2114. /**
  2115. * Specialization of a string: email
  2116. *
  2117. * @package iTopORM
  2118. */
  2119. class AttributeEmailAddress extends AttributeString
  2120. {
  2121. public function GetValidationPattern()
  2122. {
  2123. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('email_validation_pattern').'$');
  2124. }
  2125. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2126. {
  2127. if (empty($sValue)) return '';
  2128. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  2129. }
  2130. }
  2131. /**
  2132. * Specialization of a string: IP address
  2133. *
  2134. * @package iTopORM
  2135. */
  2136. class AttributeIPAddress extends AttributeString
  2137. {
  2138. public function GetValidationPattern()
  2139. {
  2140. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  2141. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  2142. }
  2143. public function GetOrderBySQLExpressions($sClassAlias)
  2144. {
  2145. // Note: This is the responsibility of this function to place backticks around column aliases
  2146. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  2147. }
  2148. }
  2149. /**
  2150. * Specialization of a string: OQL expression
  2151. *
  2152. * @package iTopORM
  2153. */
  2154. class AttributeOQL extends AttributeText
  2155. {
  2156. public function GetEditClass() {return "OQLExpression";}
  2157. }
  2158. /**
  2159. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2160. *
  2161. * @package iTopORM
  2162. */
  2163. class AttributeTemplateString extends AttributeString
  2164. {
  2165. }
  2166. /**
  2167. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2168. *
  2169. * @package iTopORM
  2170. */
  2171. class AttributeTemplateText extends AttributeText
  2172. {
  2173. }
  2174. /**
  2175. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2176. *
  2177. * @package iTopORM
  2178. */
  2179. class AttributeTemplateHTML extends AttributeText
  2180. {
  2181. public function GetEditClass() {return "HTML";}
  2182. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2183. {
  2184. return $sValue;
  2185. }
  2186. }
  2187. /**
  2188. * Map a enum column to an attribute
  2189. *
  2190. * @package iTopORM
  2191. */
  2192. class AttributeEnum extends AttributeString
  2193. {
  2194. static public function ListExpectedParams()
  2195. {
  2196. return parent::ListExpectedParams();
  2197. //return array_merge(parent::ListExpectedParams(), array());
  2198. }
  2199. public function GetEditClass() {return "String";}
  2200. protected function GetSQLCol($bFullSpec = false)
  2201. {
  2202. $oValDef = $this->GetValuesDef();
  2203. if ($oValDef)
  2204. {
  2205. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  2206. }
  2207. else
  2208. {
  2209. $aValues = array();
  2210. }
  2211. if (count($aValues) > 0)
  2212. {
  2213. // The syntax used here do matters
  2214. // In particular, I had to remove unnecessary spaces to
  2215. // make sure that this string will match the field type returned by the DB
  2216. // (used to perform a comparison between the current DB format and the data model)
  2217. return "ENUM(".implode(",", $aValues).")".($bFullSpec ? $this->GetSQLColSpec() : '');
  2218. }
  2219. else
  2220. {
  2221. return "VARCHAR(255)".($bFullSpec ? " DEFAULT ''" : ""); // ENUM() is not an allowed syntax!
  2222. }
  2223. }
  2224. public function ScalarToSQL($value)
  2225. {
  2226. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  2227. // but that wasn't working for enums, because '' is NOT one of the allowed values
  2228. // that's why a null value must be forced to a real null
  2229. $value = parent::ScalarToSQL($value);
  2230. if ($this->IsNull($value))
  2231. {
  2232. return null;
  2233. }
  2234. else
  2235. {
  2236. return $value;
  2237. }
  2238. }
  2239. public function RequiresIndex()
  2240. {
  2241. return false;
  2242. }
  2243. public function GetBasicFilterOperators()
  2244. {
  2245. return parent::GetBasicFilterOperators();
  2246. }
  2247. public function GetBasicFilterLooseOperator()
  2248. {
  2249. return '=';
  2250. }
  2251. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2252. {
  2253. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2254. }
  2255. public function GetValueLabel($sValue)
  2256. {
  2257. if (is_null($sValue))
  2258. {
  2259. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2260. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  2261. }
  2262. else
  2263. {
  2264. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, null, true /*user lang*/);
  2265. if (is_null($sLabel))
  2266. {
  2267. $sDefault = str_replace('_', ' ', $sValue);
  2268. // Browse the hierarchy again, accepting default (english) translations
  2269. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, $sDefault, false);
  2270. }
  2271. }
  2272. return $sLabel;
  2273. }
  2274. public function GetValueDescription($sValue)
  2275. {
  2276. if (is_null($sValue))
  2277. {
  2278. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2279. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  2280. }
  2281. else
  2282. {
  2283. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '', true /* user language only */);
  2284. if (strlen($sDescription) == 0)
  2285. {
  2286. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  2287. if ($sParentClass)
  2288. {
  2289. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  2290. {
  2291. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  2292. $sDescription = $oAttDef->GetValueDescription($sValue);
  2293. }
  2294. }
  2295. }
  2296. }
  2297. return $sDescription;
  2298. }
  2299. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2300. {
  2301. if ($bLocalize)
  2302. {
  2303. $sLabel = $this->GetValueLabel($sValue);
  2304. $sDescription = $this->GetValueDescription($sValue);
  2305. // later, we could imagine a detailed description in the title
  2306. $sRes = "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  2307. }
  2308. else
  2309. {
  2310. $sRes = parent::GetAsHtml($sValue, $oHostObject, $bLocalize);
  2311. }
  2312. return $sRes;
  2313. }
  2314. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2315. {
  2316. if (is_null($value))
  2317. {
  2318. $sFinalValue = '';
  2319. }
  2320. elseif ($bLocalize)
  2321. {
  2322. $sFinalValue = $this->GetValueLabel($value);
  2323. }
  2324. else
  2325. {
  2326. $sFinalValue = $value;
  2327. }
  2328. $sRes = parent::GetAsXML($sFinalValue, $oHostObject, $bLocalize);
  2329. return $sRes;
  2330. }
  2331. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2332. {
  2333. if (is_null($sValue))
  2334. {
  2335. $sFinalValue = '';
  2336. }
  2337. elseif ($bLocalize)
  2338. {
  2339. $sFinalValue = $this->GetValueLabel($sValue);
  2340. }
  2341. else
  2342. {
  2343. $sFinalValue = $sValue;
  2344. }
  2345. $sRes = parent::GetAsCSV($sFinalValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  2346. return $sRes;
  2347. }
  2348. public function GetEditValue($sValue, $oHostObj = null)
  2349. {
  2350. if (is_null($sValue))
  2351. {
  2352. return '';
  2353. }
  2354. else
  2355. {
  2356. return $this->GetValueLabel($sValue);
  2357. }
  2358. }
  2359. /**
  2360. * Helper to get a value that will be JSON encoded
  2361. * The operation is the opposite to FromJSONToValue
  2362. */
  2363. public function GetForJSON($value)
  2364. {
  2365. return $value;
  2366. }
  2367. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2368. {
  2369. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  2370. if (is_null($aRawValues)) return null;
  2371. $aLocalizedValues = array();
  2372. foreach ($aRawValues as $sKey => $sValue)
  2373. {
  2374. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  2375. }
  2376. return $aLocalizedValues;
  2377. }
  2378. /**
  2379. * An enum can be localized
  2380. */
  2381. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  2382. {
  2383. if ($bLocalizedValue)
  2384. {
  2385. // Lookup for the value matching the input
  2386. //
  2387. $sFoundValue = null;
  2388. $aRawValues = parent::GetAllowedValues();
  2389. if (!is_null($aRawValues))
  2390. {
  2391. foreach ($aRawValues as $sKey => $sValue)
  2392. {
  2393. $sRefValue = $this->GetValueLabel($sKey);
  2394. if ($sProposedValue == $sRefValue)
  2395. {
  2396. $sFoundValue = $sKey;
  2397. break;
  2398. }
  2399. }
  2400. }
  2401. if (is_null($sFoundValue))
  2402. {
  2403. return null;
  2404. }
  2405. return $this->MakeRealValue($sFoundValue, null);
  2406. }
  2407. else
  2408. {
  2409. return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  2410. }
  2411. }
  2412. /**
  2413. * Processes the input value to align it with the values supported
  2414. * by this type of attribute. In this case: turns empty strings into nulls
  2415. * @param mixed $proposedValue The value to be set for the attribute
  2416. * @return mixed The actual value that will be set
  2417. */
  2418. public function MakeRealValue($proposedValue, $oHostObj)
  2419. {
  2420. if ($proposedValue == '') return null;
  2421. return parent::MakeRealValue($proposedValue, $oHostObj);
  2422. }
  2423. public function GetOrderByHint()
  2424. {
  2425. $aValues = $this->GetAllowedValues();
  2426. return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
  2427. }
  2428. }
  2429. /**
  2430. * Map a date+time column to an attribute
  2431. *
  2432. * @package iTopORM
  2433. */
  2434. class AttributeDateTime extends AttributeDBField
  2435. {
  2436. static public function GetDateFormat()
  2437. {
  2438. return "Y-m-d H:i:s";
  2439. }
  2440. static public function ListExpectedParams()
  2441. {
  2442. return parent::ListExpectedParams();
  2443. //return array_merge(parent::ListExpectedParams(), array());
  2444. }
  2445. public function GetEditClass() {return "DateTime";}
  2446. protected function GetSQLCol($bFullSpec = false) {return "DATETIME";}
  2447. public static function GetAsUnixSeconds($value)
  2448. {
  2449. $oDeadlineDateTime = new DateTime($value);
  2450. $iUnixSeconds = $oDeadlineDateTime->format('U');
  2451. return $iUnixSeconds;
  2452. }
  2453. // This has been done at the time when itop was using TIMESTAMP columns,
  2454. // now that iTop is using DATETIME columns, it seems possible to have IsNullAllowed returning false... later when this is needed
  2455. public function IsNullAllowed() {return true;}
  2456. public function GetDefaultValue()
  2457. {
  2458. $default = parent::GetDefaultValue();
  2459. if (!parent::IsNullAllowed())
  2460. {
  2461. if (empty($default))
  2462. {
  2463. $default = date($this->GetDateFormat());
  2464. }
  2465. }
  2466. return $default;
  2467. }
  2468. // END OF THE WORKAROUND
  2469. ///////////////////////////////////////////////////////////////
  2470. public function GetValidationPattern()
  2471. {
  2472. return "^(([0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30))))( (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(:([0-5][0-9])){0,1}){0,1}|0000-00-00 00:00:00|0000-00-00)$";
  2473. }
  2474. public function GetBasicFilterOperators()
  2475. {
  2476. return array(
  2477. "="=>"equals",
  2478. "!="=>"differs from",
  2479. "<"=>"before",
  2480. "<="=>"before",
  2481. ">"=>"after (strictly)",
  2482. ">="=>"after",
  2483. "SameDay"=>"same day (strip time)",
  2484. "SameMonth"=>"same year/month",
  2485. "SameYear"=>"same year",
  2486. "Today"=>"today",
  2487. ">|"=>"after today + N days",
  2488. "<|"=>"before today + N days",
  2489. "=|"=>"equals today + N days",
  2490. );
  2491. }
  2492. public function GetBasicFilterLooseOperator()
  2493. {
  2494. // Unless we implement a "same xxx, depending on given precision" !
  2495. return "=";
  2496. }
  2497. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2498. {
  2499. $sQValue = CMDBSource::Quote($value);
  2500. switch ($sOpCode)
  2501. {
  2502. case '=':
  2503. case '!=':
  2504. case '<':
  2505. case '<=':
  2506. case '>':
  2507. case '>=':
  2508. return $this->GetSQLExpr()." $sOpCode $sQValue";
  2509. case 'SameDay':
  2510. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  2511. case 'SameMonth':
  2512. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  2513. case 'SameYear':
  2514. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  2515. case 'Today':
  2516. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  2517. case '>|':
  2518. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2519. case '<|':
  2520. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2521. case '=|':
  2522. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2523. default:
  2524. return $this->GetSQLExpr()." = $sQValue";
  2525. }
  2526. }
  2527. public function MakeRealValue($proposedValue, $oHostObj)
  2528. {
  2529. if (is_null($proposedValue))
  2530. {
  2531. return null;
  2532. }
  2533. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  2534. {
  2535. return null;
  2536. }
  2537. if (!is_numeric($proposedValue))
  2538. {
  2539. return $proposedValue;
  2540. }
  2541. return date(self::GetDateFormat(), $proposedValue);
  2542. }
  2543. public function ScalarToSQL($value)
  2544. {
  2545. if (is_null($value))
  2546. {
  2547. return null;
  2548. }
  2549. elseif (empty($value))
  2550. {
  2551. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  2552. return '0000-00-00 00:00:00';
  2553. }
  2554. return $value;
  2555. }
  2556. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2557. {
  2558. return Str::pure2html($value);
  2559. }
  2560. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2561. {
  2562. return Str::pure2xml($value);
  2563. }
  2564. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2565. {
  2566. $sFrom = array("\r\n", $sTextQualifier);
  2567. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  2568. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  2569. return $sTextQualifier.$sEscaped.$sTextQualifier;
  2570. }
  2571. /**
  2572. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  2573. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  2574. * does nothing special, and just calls the default (loose) operator
  2575. * @param string $sSearchText The search string to analyze for smart patterns
  2576. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  2577. * @param Hash $aParams Values of the query parameters
  2578. * @return Expression The search condition to be added (AND) to the current search
  2579. */
  2580. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  2581. {
  2582. // Possible smart patterns
  2583. $aPatterns = array(
  2584. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  2585. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  2586. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  2587. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  2588. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  2589. );
  2590. $sPatternFound = '';
  2591. $aMatches = array();
  2592. foreach($aPatterns as $sPatName => $sPattern)
  2593. {
  2594. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  2595. {
  2596. $sPatternFound = $sPatName;
  2597. break;
  2598. }
  2599. }
  2600. switch($sPatternFound)
  2601. {
  2602. case 'between':
  2603. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  2604. $oRightExpr = new VariableExpression($sParamName1);
  2605. $aParams[$sParamName1] = $aMatches[1];
  2606. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  2607. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  2608. $oRightExpr = new VariableExpression($sParamName2);
  2609. $sOperator = $this->GetBasicFilterLooseOperator();
  2610. $aParams[$sParamName2] = $aMatches[2];
  2611. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  2612. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  2613. break;
  2614. case 'greater than':
  2615. case 'greater than or equal':
  2616. case 'less than':
  2617. case 'less than or equal':
  2618. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  2619. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  2620. $oRightExpr = new VariableExpression($sParamName);
  2621. $aParams[$sParamName] = $aMatches[1];
  2622. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  2623. break;
  2624. default:
  2625. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  2626. }
  2627. return $oNewCondition;
  2628. }
  2629. }
  2630. /**
  2631. * Store a duration as a number of seconds
  2632. *
  2633. * @package iTopORM
  2634. */
  2635. class AttributeDuration extends AttributeInteger
  2636. {
  2637. public function GetEditClass() {return "Duration";}
  2638. protected function GetSQLCol($bFullSpec = false) {return "INT(11) UNSIGNED";}
  2639. public function GetNullValue() {return '0';}
  2640. public function MakeRealValue($proposedValue, $oHostObj)
  2641. {
  2642. if (is_null($proposedValue)) return null;
  2643. if (!is_numeric($proposedValue)) return null;
  2644. if ( ((int)$proposedValue) < 0) return null;
  2645. return (int)$proposedValue;
  2646. }
  2647. public function ScalarToSQL($value)
  2648. {
  2649. if (is_null($value))
  2650. {
  2651. return null;
  2652. }
  2653. return $value;
  2654. }
  2655. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2656. {
  2657. return Str::pure2html(self::FormatDuration($value));
  2658. }
  2659. public static function FormatDuration($duration)
  2660. {
  2661. $aDuration = self::SplitDuration($duration);
  2662. $sResult = '';
  2663. if ($duration < 60)
  2664. {
  2665. // Less than 1 min
  2666. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  2667. }
  2668. else if ($duration < 3600)
  2669. {
  2670. // less than 1 hour, display it in minutes/seconds
  2671. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  2672. }
  2673. else if ($duration < 86400)
  2674. {
  2675. // Less than 1 day, display it in hours/minutes/seconds
  2676. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2677. }
  2678. else
  2679. {
  2680. // more than 1 day, display it in days/hours/minutes/seconds
  2681. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2682. }
  2683. return $sResult;
  2684. }
  2685. static function SplitDuration($duration)
  2686. {
  2687. $duration = (int) $duration;
  2688. $days = floor($duration / 86400);
  2689. $hours = floor(($duration - (86400*$days)) / 3600);
  2690. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2691. $seconds = ($duration % 60); // modulo
  2692. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  2693. }
  2694. }
  2695. /**
  2696. * Map a date+time column to an attribute
  2697. *
  2698. * @package iTopORM
  2699. */
  2700. class AttributeDate extends AttributeDateTime
  2701. {
  2702. const MYDATEFORMAT = "Y-m-d";
  2703. static public function GetDateFormat()
  2704. {
  2705. return "Y-m-d";
  2706. }
  2707. static public function ListExpectedParams()
  2708. {
  2709. return parent::ListExpectedParams();
  2710. //return array_merge(parent::ListExpectedParams(), array());
  2711. }
  2712. public function GetEditClass() {return "Date";}
  2713. protected function GetSQLCol($bFullSpec = false) {return "DATE";}
  2714. public function GetValidationPattern()
  2715. {
  2716. return "^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$";
  2717. }
  2718. }
  2719. /**
  2720. * A dead line stored as a date & time
  2721. * The only difference with the DateTime attribute is the display:
  2722. * relative to the current time
  2723. */
  2724. class AttributeDeadline extends AttributeDateTime
  2725. {
  2726. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2727. {
  2728. $sResult = self::FormatDeadline($value);
  2729. return $sResult;
  2730. }
  2731. public static function FormatDeadline($value)
  2732. {
  2733. $sResult = '';
  2734. if ($value !== null)
  2735. {
  2736. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  2737. $sDate = $value;
  2738. $difference = $iValue - time();
  2739. if ($difference >= 0)
  2740. {
  2741. $sDifference = self::FormatDuration($difference);
  2742. }
  2743. else
  2744. {
  2745. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  2746. }
  2747. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  2748. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  2749. }
  2750. return $sResult;
  2751. }
  2752. static function FormatDuration($duration)
  2753. {
  2754. $days = floor($duration / 86400);
  2755. $hours = floor(($duration - (86400*$days)) / 3600);
  2756. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2757. $sResult = '';
  2758. if ($duration < 60)
  2759. {
  2760. // Less than 1 min
  2761. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  2762. }
  2763. else if ($duration < 3600)
  2764. {
  2765. // less than 1 hour, display it in minutes
  2766. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  2767. }
  2768. else if ($duration < 86400)
  2769. {
  2770. // Less that 1 day, display it in hours/minutes
  2771. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  2772. }
  2773. else
  2774. {
  2775. // Less that 1 day, display it in hours/minutes
  2776. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  2777. }
  2778. return $sResult;
  2779. }
  2780. }
  2781. /**
  2782. * Map a foreign key to an attribute
  2783. * AttributeExternalKey and AttributeExternalField may be an external key
  2784. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  2785. * where an AttributeExternalField corresponds to a column into another table (class)
  2786. *
  2787. * @package iTopORM
  2788. */
  2789. class AttributeExternalKey extends AttributeDBFieldVoid
  2790. {
  2791. static public function ListExpectedParams()
  2792. {
  2793. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  2794. }
  2795. public function GetEditClass() {return "ExtKey";}
  2796. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  2797. public function RequiresIndex()
  2798. {
  2799. return true;
  2800. }
  2801. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  2802. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  2803. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2804. public function GetKeyAttCode() {return $this->GetCode();}
  2805. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  2806. public function GetDefaultValue() {return 0;}
  2807. public function IsNullAllowed()
  2808. {
  2809. if (MetaModel::GetConfig()->Get('disable_mandatory_ext_keys'))
  2810. {
  2811. return true;
  2812. }
  2813. return $this->Get("is_null_allowed");
  2814. }
  2815. public function GetBasicFilterOperators()
  2816. {
  2817. return parent::GetBasicFilterOperators();
  2818. }
  2819. public function GetBasicFilterLooseOperator()
  2820. {
  2821. return parent::GetBasicFilterLooseOperator();
  2822. }
  2823. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2824. {
  2825. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2826. }
  2827. // overloaded here so that an ext key always have the answer to
  2828. // "what are your possible values?"
  2829. public function GetValuesDef()
  2830. {
  2831. $oValSetDef = $this->Get("allowed_values");
  2832. if (!$oValSetDef)
  2833. {
  2834. // Let's propose every existing value
  2835. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2836. }
  2837. return $oValSetDef;
  2838. }
  2839. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2840. {
  2841. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  2842. try
  2843. {
  2844. return parent::GetAllowedValues($aArgs, $sContains);
  2845. }
  2846. catch (MissingQueryArgument $e)
  2847. {
  2848. // Some required arguments could not be found, enlarge to any existing value
  2849. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2850. return $oValSetDef->GetValues($aArgs, $sContains);
  2851. }
  2852. }
  2853. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2854. {
  2855. $oValSetDef = $this->GetValuesDef();
  2856. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2857. return $oSet;
  2858. }
  2859. public function GetDeletionPropagationOption()
  2860. {
  2861. return $this->Get("on_target_delete");
  2862. }
  2863. public function GetNullValue()
  2864. {
  2865. return 0;
  2866. }
  2867. public function IsNull($proposedValue)
  2868. {
  2869. return ($proposedValue == 0);
  2870. }
  2871. public function MakeRealValue($proposedValue, $oHostObj)
  2872. {
  2873. if (is_null($proposedValue)) return 0;
  2874. if ($proposedValue === '') return 0;
  2875. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  2876. return (int)$proposedValue;
  2877. }
  2878. public function GetMaximumComboLength()
  2879. {
  2880. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  2881. }
  2882. public function GetMinAutoCompleteChars()
  2883. {
  2884. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  2885. }
  2886. public function AllowTargetCreation()
  2887. {
  2888. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  2889. }
  2890. /**
  2891. * Find the corresponding "link" attribute on the target class
  2892. *
  2893. * @return string The attribute code on the target class, or null if none has been found
  2894. */
  2895. public function GetMirrorLinkAttribute()
  2896. {
  2897. $oRet = null;
  2898. $sRemoteClass = $this->GetTargetClass();
  2899. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  2900. {
  2901. if (!$oRemoteAttDef->IsLinkSet()) continue;
  2902. if (!is_subclass_of($this->GetHostClass(), $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $this->GetHostClass()) continue;
  2903. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetCode()) continue;
  2904. $oRet = $oRemoteAttDef;
  2905. break;
  2906. }
  2907. return $oRet;
  2908. }
  2909. }
  2910. /**
  2911. * Special kind of External Key to manage a hierarchy of objects
  2912. */
  2913. class AttributeHierarchicalKey extends AttributeExternalKey
  2914. {
  2915. protected $m_sTargetClass;
  2916. static public function ListExpectedParams()
  2917. {
  2918. $aParams = parent::ListExpectedParams();
  2919. $idx = array_search('targetclass', $aParams);
  2920. unset($aParams[$idx]);
  2921. $idx = array_search('jointype', $aParams);
  2922. unset($aParams[$idx]);
  2923. return $aParams; // TODO: mettre les bons parametres ici !!
  2924. }
  2925. public function GetEditClass() {return "ExtKey";}
  2926. public function RequiresIndex()
  2927. {
  2928. return true;
  2929. }
  2930. /*
  2931. * The target class is the class for which the attribute has been defined first
  2932. */
  2933. public function SetHostClass($sHostClass)
  2934. {
  2935. if (!isset($this->m_sTargetClass))
  2936. {
  2937. $this->m_sTargetClass = $sHostClass;
  2938. }
  2939. parent::SetHostClass($sHostClass);
  2940. }
  2941. public function IsHierarchicalKey() {return true;}
  2942. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  2943. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2944. public function GetKeyAttCode() {return $this->GetCode();}
  2945. public function GetBasicFilterOperators()
  2946. {
  2947. return parent::GetBasicFilterOperators();
  2948. }
  2949. public function GetBasicFilterLooseOperator()
  2950. {
  2951. return parent::GetBasicFilterLooseOperator();
  2952. }
  2953. public function GetSQLColumns($bFullSpec = false)
  2954. {
  2955. $aColumns = array();
  2956. $aColumns[$this->GetCode()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  2957. $aColumns[$this->GetSQLLeft()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  2958. $aColumns[$this->GetSQLRight()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  2959. return $aColumns;
  2960. }
  2961. public function GetSQLRight()
  2962. {
  2963. return $this->GetCode().'_right';
  2964. }
  2965. public function GetSQLLeft()
  2966. {
  2967. return $this->GetCode().'_left';
  2968. }
  2969. public function GetSQLValues($value)
  2970. {
  2971. if (!is_array($value))
  2972. {
  2973. $aValues[$this->GetCode()] = $value;
  2974. }
  2975. else
  2976. {
  2977. $aValues = array();
  2978. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  2979. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  2980. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  2981. }
  2982. return $aValues;
  2983. }
  2984. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2985. {
  2986. if (array_key_exists('this', $aArgs))
  2987. {
  2988. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2989. // "under" themselves
  2990. $iRootId = $aArgs['this']->GetKey();
  2991. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2992. {
  2993. $oValSetDef = $this->GetValuesDef();
  2994. $sClass = $this->m_sTargetClass;
  2995. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2996. $oValSetDef->AddCondition($oFilter);
  2997. }
  2998. }
  2999. else
  3000. {
  3001. return parent::GetAllowedValues($aArgs, $sContains);
  3002. }
  3003. }
  3004. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3005. {
  3006. $oValSetDef = $this->GetValuesDef();
  3007. if (array_key_exists('this', $aArgs))
  3008. {
  3009. // Hierarchical keys have one more constraint: the "parent value" cannot be
  3010. // "under" themselves
  3011. $iRootId = $aArgs['this']->GetKey();
  3012. if ($iRootId > 0) // ignore objects that do no exist in the database...
  3013. {
  3014. $aValuesSetDef = $this->GetValuesDef();
  3015. $sClass = $this->m_sTargetClass;
  3016. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  3017. $oValSetDef->AddCondition($oFilter);
  3018. }
  3019. }
  3020. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3021. return $oSet;
  3022. }
  3023. /**
  3024. * Find the corresponding "link" attribute on the target class
  3025. *
  3026. * @return string The attribute code on the target class, or null if none has been found
  3027. */
  3028. public function GetMirrorLinkAttribute()
  3029. {
  3030. return null;
  3031. }
  3032. }
  3033. /**
  3034. * An attribute which corresponds to an external key (direct or indirect)
  3035. *
  3036. * @package iTopORM
  3037. */
  3038. class AttributeExternalField extends AttributeDefinition
  3039. {
  3040. static public function ListExpectedParams()
  3041. {
  3042. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  3043. }
  3044. public function GetEditClass() {return "ExtField";}
  3045. public function GetFinalAttDef()
  3046. {
  3047. $oExtAttDef = $this->GetExtAttDef();
  3048. return $oExtAttDef->GetFinalAttDef();
  3049. }
  3050. protected function GetSQLCol($bFullSpec = false)
  3051. {
  3052. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  3053. $oExtAttDef = $this->GetExtAttDef();
  3054. return $oExtAttDef->GetSQLCol($bFullSpec);
  3055. }
  3056. public function GetSQLExpressions($sPrefix = '')
  3057. {
  3058. if ($sPrefix == '')
  3059. {
  3060. return array('' => $this->GetCode());
  3061. }
  3062. else
  3063. {
  3064. return $sPrefix;
  3065. }
  3066. }
  3067. public function GetLabel($sDefault = null)
  3068. {
  3069. $sLabel = parent::GetLabel('');
  3070. if (strlen($sLabel) == 0)
  3071. {
  3072. $oRemoteAtt = $this->GetExtAttDef();
  3073. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  3074. }
  3075. return $sLabel;
  3076. }
  3077. public function GetDescription($sDefault = null)
  3078. {
  3079. $sLabel = parent::GetDescription('');
  3080. if (strlen($sLabel) == 0)
  3081. {
  3082. $oRemoteAtt = $this->GetExtAttDef();
  3083. $sLabel = $oRemoteAtt->GetDescription('');
  3084. }
  3085. return $sLabel;
  3086. }
  3087. public function GetHelpOnEdition($sDefault = null)
  3088. {
  3089. $sLabel = parent::GetHelpOnEdition('');
  3090. if (strlen($sLabel) == 0)
  3091. {
  3092. $oRemoteAtt = $this->GetExtAttDef();
  3093. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  3094. }
  3095. return $sLabel;
  3096. }
  3097. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  3098. {
  3099. switch($iType)
  3100. {
  3101. case EXTKEY_ABSOLUTE:
  3102. // see further
  3103. $oRemoteAtt = $this->GetExtAttDef();
  3104. return $oRemoteAtt->IsExternalKey($iType);
  3105. case EXTKEY_RELATIVE:
  3106. return false;
  3107. default:
  3108. throw new CoreException("Unexpected value for argument iType: '$iType'");
  3109. }
  3110. }
  3111. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  3112. {
  3113. return $this->GetKeyAttDef($iType)->GetTargetClass();
  3114. }
  3115. public function IsExternalField() {return true;}
  3116. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  3117. public function GetExtAttCode() {return $this->Get("target_attcode");}
  3118. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  3119. {
  3120. switch($iType)
  3121. {
  3122. case EXTKEY_ABSOLUTE:
  3123. // see further
  3124. $oRemoteAtt = $this->GetExtAttDef();
  3125. if ($oRemoteAtt->IsExternalField())
  3126. {
  3127. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  3128. }
  3129. else if ($oRemoteAtt->IsExternalKey())
  3130. {
  3131. return $oRemoteAtt;
  3132. }
  3133. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  3134. case EXTKEY_RELATIVE:
  3135. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  3136. default:
  3137. throw new CoreException("Unexpected value for argument iType: '$iType'");
  3138. }
  3139. }
  3140. public function GetPrerequisiteAttributes()
  3141. {
  3142. return array($this->Get("extkey_attcode"));
  3143. }
  3144. public function GetExtAttDef()
  3145. {
  3146. $oKeyAttDef = $this->GetKeyAttDef();
  3147. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  3148. if (!is_object($oExtAttDef)) throw new CoreException("Invalid external field ".$this->GetCode()." in class ".$this->GetHostClass().". The class ".$oKeyAttDef->GetTargetClass()." has no attribute ".$this->Get("target_attcode"));
  3149. return $oExtAttDef;
  3150. }
  3151. public function GetSQLExpr()
  3152. {
  3153. $oExtAttDef = $this->GetExtAttDef();
  3154. return $oExtAttDef->GetSQLExpr();
  3155. }
  3156. public function GetDefaultValue()
  3157. {
  3158. $oExtAttDef = $this->GetExtAttDef();
  3159. return $oExtAttDef->GetDefaultValue();
  3160. }
  3161. public function IsNullAllowed()
  3162. {
  3163. $oExtAttDef = $this->GetExtAttDef();
  3164. return $oExtAttDef->IsNullAllowed();
  3165. }
  3166. public function IsScalar()
  3167. {
  3168. $oExtAttDef = $this->GetExtAttDef();
  3169. return $oExtAttDef->IsScalar();
  3170. }
  3171. public function GetFilterDefinitions()
  3172. {
  3173. return array($this->GetCode() => new FilterFromAttribute($this));
  3174. }
  3175. public function GetBasicFilterOperators()
  3176. {
  3177. $oExtAttDef = $this->GetExtAttDef();
  3178. return $oExtAttDef->GetBasicFilterOperators();
  3179. }
  3180. public function GetBasicFilterLooseOperator()
  3181. {
  3182. $oExtAttDef = $this->GetExtAttDef();
  3183. return $oExtAttDef->GetBasicFilterLooseOperator();
  3184. }
  3185. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3186. {
  3187. $oExtAttDef = $this->GetExtAttDef();
  3188. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  3189. }
  3190. public function GetNullValue()
  3191. {
  3192. $oExtAttDef = $this->GetExtAttDef();
  3193. return $oExtAttDef->GetNullValue();
  3194. }
  3195. public function IsNull($proposedValue)
  3196. {
  3197. $oExtAttDef = $this->GetExtAttDef();
  3198. return $oExtAttDef->IsNull($proposedValue);
  3199. }
  3200. public function MakeRealValue($proposedValue, $oHostObj)
  3201. {
  3202. $oExtAttDef = $this->GetExtAttDef();
  3203. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  3204. }
  3205. public function ScalarToSQL($value)
  3206. {
  3207. // This one could be used in case of filtering only
  3208. $oExtAttDef = $this->GetExtAttDef();
  3209. return $oExtAttDef->ScalarToSQL($value);
  3210. }
  3211. // Do not overload GetSQLExpression here because this is handled in the joins
  3212. //public function GetSQLExpressions($sPrefix = '') {return array();}
  3213. // Here, we get the data...
  3214. public function FromSQLToValue($aCols, $sPrefix = '')
  3215. {
  3216. $oExtAttDef = $this->GetExtAttDef();
  3217. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  3218. }
  3219. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3220. {
  3221. $oExtAttDef = $this->GetExtAttDef();
  3222. return $oExtAttDef->GetAsHTML($value, null, $bLocalize);
  3223. }
  3224. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3225. {
  3226. $oExtAttDef = $this->GetExtAttDef();
  3227. return $oExtAttDef->GetAsXML($value, null, $bLocalize);
  3228. }
  3229. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null, $bLocalize = true)
  3230. {
  3231. $oExtAttDef = $this->GetExtAttDef();
  3232. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier, null, $bLocalize);
  3233. }
  3234. }
  3235. /**
  3236. * Map a varchar column to an URL (formats the ouput in HMTL)
  3237. *
  3238. * @package iTopORM
  3239. */
  3240. class AttributeURL extends AttributeString
  3241. {
  3242. static public function ListExpectedParams()
  3243. {
  3244. //return parent::ListExpectedParams();
  3245. return array_merge(parent::ListExpectedParams(), array("target"));
  3246. }
  3247. public function GetEditClass() {return "String";}
  3248. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  3249. {
  3250. $sTarget = $this->Get("target");
  3251. if (empty($sTarget)) $sTarget = "_blank";
  3252. $sLabel = Str::pure2html($sValue);
  3253. if (strlen($sLabel) > 255)
  3254. {
  3255. // Truncate the length to 128 characters, by removing the middle
  3256. $sLabel = substr($sLabel, 0, 100).'.....'.substr($sLabel, -20);
  3257. }
  3258. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  3259. }
  3260. public function GetValidationPattern()
  3261. {
  3262. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('url_validation_pattern').'$');
  3263. }
  3264. }
  3265. /**
  3266. * A blob is an ormDocument, it is stored as several columns in the database
  3267. *
  3268. * @package iTopORM
  3269. */
  3270. class AttributeBlob extends AttributeDefinition
  3271. {
  3272. static public function ListExpectedParams()
  3273. {
  3274. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  3275. }
  3276. public function GetEditClass() {return "Document";}
  3277. public function IsDirectField() {return true;}
  3278. public function IsScalar() {return true;}
  3279. public function IsWritable() {return true;}
  3280. public function GetDefaultValue() {return "";}
  3281. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  3282. public function GetEditValue($sValue, $oHostObj = null)
  3283. {
  3284. return '';
  3285. }
  3286. // Facilitate things: allow administrators to upload a document
  3287. // from a CSV by specifying its path/URL
  3288. public function MakeRealValue($proposedValue, $oHostObj)
  3289. {
  3290. if (!is_object($proposedValue))
  3291. {
  3292. if (file_exists($proposedValue) && UserRights::IsAdministrator())
  3293. {
  3294. $sContent = file_get_contents($proposedValue);
  3295. $sExtension = strtolower(pathinfo($proposedValue, PATHINFO_EXTENSION));
  3296. $sMimeType = "application/x-octet-stream";
  3297. $aKnownExtensions = array(
  3298. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  3299. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3300. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3301. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3302. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3303. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3304. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3305. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3306. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3307. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12.xlsx',
  3308. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3309. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3310. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3311. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3312. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3313. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3314. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3315. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3316. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  3317. 'jpg' => 'image/jpeg',
  3318. 'jpeg' => 'image/jpeg',
  3319. 'gif' => 'image/gif',
  3320. 'png' => 'image/png',
  3321. 'pdf' => 'application/pdf',
  3322. 'doc' => 'application/msword',
  3323. 'dot' => 'application/msword',
  3324. 'xls' => 'application/vnd.ms-excel',
  3325. 'ppt' => 'application/vnd.ms-powerpoint',
  3326. 'vsd' => 'application/x-visio',
  3327. 'vdx' => 'application/visio.drawing',
  3328. 'odt' => 'application/vnd.oasis.opendocument.text',
  3329. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  3330. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  3331. 'zip' => 'application/zip',
  3332. 'txt' => 'text/plain',
  3333. 'htm' => 'text/html',
  3334. 'html' => 'text/html',
  3335. 'exe' => 'application/octet-stream'
  3336. );
  3337. if (!array_key_exists($sExtension, $aKnownExtensions) && extension_loaded('fileinfo'))
  3338. {
  3339. $finfo = new finfo(FILEINFO_MIME);
  3340. $sMimeType = $finfo->file($proposedValue);
  3341. }
  3342. return new ormDocument($sContent, $sMimeType);
  3343. }
  3344. else
  3345. {
  3346. return new ormDocument($proposedValue, 'text/plain');
  3347. }
  3348. }
  3349. return $proposedValue;
  3350. }
  3351. public function GetSQLExpressions($sPrefix = '')
  3352. {
  3353. if ($sPrefix == '')
  3354. {
  3355. $sPrefix = $this->GetCode();
  3356. }
  3357. $aColumns = array();
  3358. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3359. $aColumns[''] = $sPrefix.'_mimetype';
  3360. $aColumns['_data'] = $sPrefix.'_data';
  3361. $aColumns['_filename'] = $sPrefix.'_filename';
  3362. return $aColumns;
  3363. }
  3364. public function FromSQLToValue($aCols, $sPrefix = '')
  3365. {
  3366. if (!array_key_exists($sPrefix, $aCols))
  3367. {
  3368. $sAvailable = implode(', ', array_keys($aCols));
  3369. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  3370. }
  3371. $sMimeType = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  3372. if (!array_key_exists($sPrefix.'_data', $aCols))
  3373. {
  3374. $sAvailable = implode(', ', array_keys($aCols));
  3375. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  3376. }
  3377. $data = isset($aCols[$sPrefix.'_data']) ? $aCols[$sPrefix.'_data'] : null;
  3378. if (!array_key_exists($sPrefix.'_filename', $aCols))
  3379. {
  3380. $sAvailable = implode(', ', array_keys($aCols));
  3381. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  3382. }
  3383. $sFileName = isset($aCols[$sPrefix.'_filename']) ? $aCols[$sPrefix.'_filename'] : '';
  3384. $value = new ormDocument($data, $sMimeType, $sFileName);
  3385. return $value;
  3386. }
  3387. public function GetSQLValues($value)
  3388. {
  3389. // #@# Optimization: do not load blobs anytime
  3390. // As per mySQL doc, selecting blob columns will prevent mySQL from
  3391. // using memory in case a temporary table has to be created
  3392. // (temporary tables created on disk)
  3393. // We will have to remove the blobs from the list of attributes when doing the select
  3394. // then the use of Get() should finalize the load
  3395. if ($value instanceOf ormDocument)
  3396. {
  3397. $aValues = array();
  3398. $aValues[$this->GetCode().'_data'] = $value->GetData();
  3399. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  3400. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  3401. }
  3402. else
  3403. {
  3404. $aValues = array();
  3405. $aValues[$this->GetCode().'_data'] = '';
  3406. $aValues[$this->GetCode().'_mimetype'] = '';
  3407. $aValues[$this->GetCode().'_filename'] = '';
  3408. }
  3409. return $aValues;
  3410. }
  3411. public function GetSQLColumns($bFullSpec = false)
  3412. {
  3413. $aColumns = array();
  3414. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  3415. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  3416. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  3417. return $aColumns;
  3418. }
  3419. public function GetFilterDefinitions()
  3420. {
  3421. return array();
  3422. // still not working... see later...
  3423. return array(
  3424. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  3425. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  3426. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  3427. );
  3428. }
  3429. public function GetBasicFilterOperators()
  3430. {
  3431. return array();
  3432. }
  3433. public function GetBasicFilterLooseOperator()
  3434. {
  3435. return '=';
  3436. }
  3437. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3438. {
  3439. return 'true';
  3440. }
  3441. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3442. {
  3443. if (is_object($value))
  3444. {
  3445. return $value->GetAsHTML();
  3446. }
  3447. }
  3448. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  3449. {
  3450. return ''; // Not exportable in CSV !
  3451. }
  3452. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3453. {
  3454. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  3455. }
  3456. /**
  3457. * Helper to get a value that will be JSON encoded
  3458. * The operation is the opposite to FromJSONToValue
  3459. */
  3460. public function GetForJSON($value)
  3461. {
  3462. if ($value instanceOf ormDocument)
  3463. {
  3464. $aValues = array();
  3465. $aValues['data'] = base64_encode($value->GetData());
  3466. $aValues['mimetype'] = $value->GetMimeType();
  3467. $aValues['filename'] = $value->GetFileName();
  3468. }
  3469. else
  3470. {
  3471. $aValues = null;
  3472. }
  3473. return $aValues;
  3474. }
  3475. /**
  3476. * Helper to form a value, given JSON decoded data
  3477. * The operation is the opposite to GetForJSON
  3478. */
  3479. public function FromJSONToValue($json)
  3480. {
  3481. if (isset($json->data))
  3482. {
  3483. $data = base64_decode($json->data);
  3484. $value = new ormDocument($data, $json->mimetype, $json->filename);
  3485. }
  3486. else
  3487. {
  3488. $value = null;
  3489. }
  3490. return $value;
  3491. }
  3492. }
  3493. /**
  3494. * A stop watch is an ormStopWatch object, it is stored as several columns in the database
  3495. *
  3496. * @package iTopORM
  3497. */
  3498. class AttributeStopWatch extends AttributeDefinition
  3499. {
  3500. static public function ListExpectedParams()
  3501. {
  3502. // The list of thresholds must be an array of iPercent => array of 'option' => value
  3503. return array_merge(parent::ListExpectedParams(), array("states", "goal_computing", "working_time_computing", "thresholds"));
  3504. }
  3505. public function GetEditClass() {return "StopWatch";}
  3506. public function IsDirectField() {return true;}
  3507. public function IsScalar() {return true;}
  3508. public function IsWritable() {return false;}
  3509. public function GetDefaultValue() {return $this->NewStopWatch();}
  3510. public function GetEditValue($value, $oHostObj = null)
  3511. {
  3512. return $value->GetTimeSpent();
  3513. }
  3514. public function GetStates()
  3515. {
  3516. return $this->Get('states');
  3517. }
  3518. /**
  3519. * Construct a brand new (but configured) stop watch
  3520. */
  3521. public function NewStopWatch()
  3522. {
  3523. $oSW = new ormStopWatch();
  3524. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3525. {
  3526. $oSW->DefineThreshold($iThreshold);
  3527. }
  3528. return $oSW;
  3529. }
  3530. // Facilitate things: allow the user to Set the value from a string
  3531. public function MakeRealValue($proposedValue, $oHostObj)
  3532. {
  3533. if (!$proposedValue instanceof ormStopWatch)
  3534. {
  3535. return $this->NewStopWatch();
  3536. }
  3537. return $proposedValue;
  3538. }
  3539. public function GetSQLExpressions($sPrefix = '')
  3540. {
  3541. if ($sPrefix == '')
  3542. {
  3543. $sPrefix = $this->GetCode();
  3544. }
  3545. $aColumns = array();
  3546. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3547. $aColumns[''] = $sPrefix.'_timespent';
  3548. $aColumns['_started'] = $sPrefix.'_started';
  3549. $aColumns['_laststart'] = $sPrefix.'_laststart';
  3550. $aColumns['_stopped'] = $sPrefix.'_stopped';
  3551. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3552. {
  3553. $sThPrefix = '_'.$iThreshold;
  3554. $aColumns[$sThPrefix.'_deadline'] = $sPrefix.$sThPrefix.'_deadline';
  3555. $aColumns[$sThPrefix.'_passed'] = $sPrefix.$sThPrefix.'_passed';
  3556. $aColumns[$sThPrefix.'_triggered'] = $sPrefix.$sThPrefix.'_triggered';
  3557. $aColumns[$sThPrefix.'_overrun'] = $sPrefix.$sThPrefix.'_overrun';
  3558. }
  3559. return $aColumns;
  3560. }
  3561. public static function DateToSeconds($sDate)
  3562. {
  3563. if (is_null($sDate))
  3564. {
  3565. return null;
  3566. }
  3567. $oDateTime = new DateTime($sDate);
  3568. $iSeconds = $oDateTime->format('U');
  3569. return $iSeconds;
  3570. }
  3571. public static function SecondsToDate($iSeconds)
  3572. {
  3573. if (is_null($iSeconds))
  3574. {
  3575. return null;
  3576. }
  3577. return date("Y-m-d H:i:s", $iSeconds);
  3578. }
  3579. public function FromSQLToValue($aCols, $sPrefix = '')
  3580. {
  3581. $aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
  3582. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3583. {
  3584. $sThPrefix = '_'.$iThreshold;
  3585. $aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
  3586. $aExpectedCols[] = $sPrefix.$sThPrefix.'_passed';
  3587. $aExpectedCols[] = $sPrefix.$sThPrefix.'_triggered';
  3588. $aExpectedCols[] = $sPrefix.$sThPrefix.'_overrun';
  3589. }
  3590. foreach ($aExpectedCols as $sExpectedCol)
  3591. {
  3592. if (!array_key_exists($sExpectedCol, $aCols))
  3593. {
  3594. $sAvailable = implode(', ', array_keys($aCols));
  3595. throw new MissingColumnException("Missing column '$sExpectedCol' from {$sAvailable}");
  3596. }
  3597. }
  3598. $value = new ormStopWatch(
  3599. $aCols[$sPrefix],
  3600. self::DateToSeconds($aCols[$sPrefix.'_started']),
  3601. self::DateToSeconds($aCols[$sPrefix.'_laststart']),
  3602. self::DateToSeconds($aCols[$sPrefix.'_stopped'])
  3603. );
  3604. $aThresholds = array();
  3605. foreach ($this->ListThresholds() as $iThreshold => $aDefinition)
  3606. {
  3607. $sThPrefix = '_'.$iThreshold;
  3608. $value->DefineThreshold(
  3609. $iThreshold,
  3610. self::DateToSeconds($aCols[$sPrefix.$sThPrefix.'_deadline']),
  3611. (bool)($aCols[$sPrefix.$sThPrefix.'_passed'] == 1),
  3612. (bool)($aCols[$sPrefix.$sThPrefix.'_triggered'] == 1),
  3613. $aCols[$sPrefix.$sThPrefix.'_overrun'],
  3614. array_key_exists('highlight', $aDefinition) ? $aDefinition['highlight'] : null
  3615. );
  3616. }
  3617. return $value;
  3618. }
  3619. public function GetSQLValues($value)
  3620. {
  3621. if ($value instanceOf ormStopWatch)
  3622. {
  3623. $aValues = array();
  3624. $aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
  3625. $aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
  3626. $aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
  3627. $aValues[$this->GetCode().'_stopped'] = self::SecondsToDate($value->GetStopDate());
  3628. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3629. {
  3630. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3631. $aValues[$sPrefix.'_deadline'] = self::SecondsToDate($value->GetThresholdDate($iThreshold));
  3632. $aValues[$sPrefix.'_passed'] = $value->IsThresholdPassed($iThreshold) ? '1' : '0';
  3633. $aValues[$sPrefix.'_triggered'] = $value->IsThresholdTriggered($iThreshold) ? '1' : '0';
  3634. $aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
  3635. }
  3636. }
  3637. else
  3638. {
  3639. $aValues = array();
  3640. $aValues[$this->GetCode().'_timespent'] = '';
  3641. $aValues[$this->GetCode().'_started'] = '';
  3642. $aValues[$this->GetCode().'_laststart'] = '';
  3643. $aValues[$this->GetCode().'_stopped'] = '';
  3644. }
  3645. return $aValues;
  3646. }
  3647. public function GetSQLColumns($bFullSpec = false)
  3648. {
  3649. $aColumns = array();
  3650. $aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED';
  3651. $aColumns[$this->GetCode().'_started'] = 'DATETIME';
  3652. $aColumns[$this->GetCode().'_laststart'] = 'DATETIME';
  3653. $aColumns[$this->GetCode().'_stopped'] = 'DATETIME';
  3654. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3655. {
  3656. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3657. $aColumns[$sPrefix.'_deadline'] = 'DATETIME';
  3658. $aColumns[$sPrefix.'_passed'] = 'TINYINT(1) UNSIGNED';
  3659. $aColumns[$sPrefix.'_triggered'] = 'TINYINT(1)';
  3660. $aColumns[$sPrefix.'_overrun'] = 'INT(11) UNSIGNED';
  3661. }
  3662. return $aColumns;
  3663. }
  3664. public function GetFilterDefinitions()
  3665. {
  3666. $aRes = array(
  3667. $this->GetCode() => new FilterFromAttribute($this),
  3668. $this->GetCode().'_started' => new FilterFromAttribute($this, '_started'),
  3669. $this->GetCode().'_laststart' => new FilterFromAttribute($this, '_laststart'),
  3670. $this->GetCode().'_stopped' => new FilterFromAttribute($this, '_stopped')
  3671. );
  3672. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3673. {
  3674. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3675. $aRes[$sPrefix.'_deadline'] = new FilterFromAttribute($this, '_deadline');
  3676. $aRes[$sPrefix.'_passed'] = new FilterFromAttribute($this, '_passed');
  3677. $aRes[$sPrefix.'_triggered'] = new FilterFromAttribute($this, '_triggered');
  3678. $aRes[$sPrefix.'_overrun'] = new FilterFromAttribute($this, '_overrun');
  3679. }
  3680. return $aRes;
  3681. }
  3682. public function GetBasicFilterOperators()
  3683. {
  3684. return array();
  3685. }
  3686. public function GetBasicFilterLooseOperator()
  3687. {
  3688. return '=';
  3689. }
  3690. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3691. {
  3692. return 'true';
  3693. }
  3694. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3695. {
  3696. if (is_object($value))
  3697. {
  3698. return $value->GetAsHTML($this, $oHostObject);
  3699. }
  3700. }
  3701. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  3702. {
  3703. return $value->GetTimeSpent();
  3704. }
  3705. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3706. {
  3707. return $value->GetTimeSpent();
  3708. }
  3709. public function ListThresholds()
  3710. {
  3711. return $this->Get('thresholds');
  3712. }
  3713. /**
  3714. * To expose internal values: Declare an attribute AttributeSubItem
  3715. * and implement the GetSubItemXXXX verbs
  3716. */
  3717. public function GetSubItemSQLExpression($sItemCode)
  3718. {
  3719. $sPrefix = $this->GetCode();
  3720. switch($sItemCode)
  3721. {
  3722. case 'timespent':
  3723. return array('' => $sPrefix.'_timespent');
  3724. case 'started':
  3725. return array('' => $sPrefix.'_started');
  3726. case 'laststart':
  3727. return array('' => $sPrefix.'_laststart');
  3728. case 'stopped':
  3729. return array('' => $sPrefix.'_stopped');
  3730. }
  3731. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3732. {
  3733. $sThPrefix = $iThreshold.'_';
  3734. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3735. {
  3736. // The current threshold is concerned
  3737. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3738. switch($sThresholdCode)
  3739. {
  3740. case 'deadline':
  3741. return array('' => $sPrefix.'_'.$iThreshold.'_deadline');
  3742. case 'passed':
  3743. return array('' => $sPrefix.'_'.$iThreshold.'_passed');
  3744. case 'triggered':
  3745. return array('' => $sPrefix.'_'.$iThreshold.'_triggered');
  3746. case 'overrun':
  3747. return array('' => $sPrefix.'_'.$iThreshold.'_overrun');
  3748. }
  3749. }
  3750. }
  3751. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  3752. }
  3753. public function GetSubItemValue($sItemCode, $value, $oHostObject = null)
  3754. {
  3755. $oStopWatch = $value;
  3756. switch($sItemCode)
  3757. {
  3758. case 'timespent':
  3759. return $oStopWatch->GetTimeSpent();
  3760. case 'started':
  3761. return $oStopWatch->GetStartDate();
  3762. case 'laststart':
  3763. return $oStopWatch->GetLastStartDate();
  3764. case 'stopped':
  3765. return $oStopWatch->GetStopDate();
  3766. }
  3767. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3768. {
  3769. $sThPrefix = $iThreshold.'_';
  3770. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3771. {
  3772. // The current threshold is concerned
  3773. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3774. switch($sThresholdCode)
  3775. {
  3776. case 'deadline':
  3777. return $oStopWatch->GetThresholdDate($iThreshold);
  3778. case 'passed':
  3779. return $oStopWatch->IsThresholdPassed($iThreshold);
  3780. case 'triggered':
  3781. return $oStopWatch->IsThresholdTriggered($iThreshold);
  3782. case 'overrun':
  3783. return $oStopWatch->GetOverrun($iThreshold);
  3784. }
  3785. }
  3786. }
  3787. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  3788. }
  3789. protected function GetBooleanLabel($bValue)
  3790. {
  3791. $sDictKey = $bValue ? 'yes' : 'no';
  3792. return Dict::S('BooleanLabel:'.$sDictKey, 'def:'.$sDictKey);
  3793. }
  3794. public function GetSubItemAsHTMLForHistory($sItemCode, $sValue)
  3795. {
  3796. switch($sItemCode)
  3797. {
  3798. case 'timespent':
  3799. $sHtml = (int)$sValue ? Str::pure2html(AttributeDuration::FormatDuration($sValue)) : null;
  3800. break;
  3801. case 'started':
  3802. case 'laststart':
  3803. case 'stopped':
  3804. $sHtml = (int)$sValue ? date(self::GetDateFormat(), (int)$sValue) : null;
  3805. break;
  3806. default:
  3807. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3808. {
  3809. $sThPrefix = $iThreshold.'_';
  3810. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3811. {
  3812. // The current threshold is concerned
  3813. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3814. switch($sThresholdCode)
  3815. {
  3816. case 'deadline':
  3817. $sHtml = (int)$sValue ? date(self::GetDateFormat(true /*full*/), (int)$sValue) : null;
  3818. break;
  3819. case 'passed':
  3820. $sHtml = $this->GetBooleanLabel((int)$sValue);
  3821. break;
  3822. case 'triggered':
  3823. $sHtml = $this->GetBooleanLabel((int)$sValue);
  3824. break;
  3825. case 'overrun':
  3826. $sHtml = (int)$sValue > 0 ? Str::pure2html(AttributeDuration::FormatDuration((int)$sValue)) : '';
  3827. }
  3828. }
  3829. }
  3830. }
  3831. return $sHtml;
  3832. }
  3833. static protected function GetDateFormat($bFull = false)
  3834. {
  3835. if ($bFull)
  3836. {
  3837. return "Y-m-d H:i:s";
  3838. }
  3839. else
  3840. {
  3841. return "Y-m-d H:i";
  3842. }
  3843. }
  3844. public function GetSubItemAsHTML($sItemCode, $value)
  3845. {
  3846. $sHtml = $value;
  3847. switch($sItemCode)
  3848. {
  3849. case 'timespent':
  3850. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  3851. break;
  3852. case 'started':
  3853. case 'laststart':
  3854. case 'stopped':
  3855. if (is_null($value))
  3856. {
  3857. $sHtml = ''; // Undefined
  3858. }
  3859. else
  3860. {
  3861. $sHtml = date(self::GetDateFormat(), $value);
  3862. }
  3863. break;
  3864. default:
  3865. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3866. {
  3867. $sThPrefix = $iThreshold.'_';
  3868. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3869. {
  3870. // The current threshold is concerned
  3871. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3872. switch($sThresholdCode)
  3873. {
  3874. case 'deadline':
  3875. if ($value)
  3876. {
  3877. $sDate = date(self::GetDateFormat(true /*full*/), $value);
  3878. $sHtml = Str::pure2html(AttributeDeadline::FormatDeadline($sDate));
  3879. }
  3880. else
  3881. {
  3882. $sHtml = '';
  3883. }
  3884. break;
  3885. case 'passed':
  3886. case 'triggered':
  3887. $sHtml = $this->GetBooleanLabel($value);
  3888. break;
  3889. case 'overrun':
  3890. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  3891. break;
  3892. }
  3893. }
  3894. }
  3895. }
  3896. return $sHtml;
  3897. }
  3898. public function GetSubItemAsCSV($sItemCode, $value, $sSeparator = ',', $sTextQualifier = '"')
  3899. {
  3900. $sFrom = array("\r\n", $sTextQualifier);
  3901. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  3902. $sEscaped = str_replace($sFrom, $sTo, (string)$value);
  3903. $sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
  3904. switch($sItemCode)
  3905. {
  3906. case 'timespent':
  3907. case 'started':
  3908. case 'laststart':
  3909. case 'stopped':
  3910. break;
  3911. default:
  3912. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3913. {
  3914. $sThPrefix = $iThreshold.'_';
  3915. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3916. {
  3917. // The current threshold is concerned
  3918. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3919. switch($sThresholdCode)
  3920. {
  3921. case 'deadline':
  3922. break;
  3923. case 'passed':
  3924. case 'triggered':
  3925. $sRet = $sTextQualifier.$this->GetBooleanLabel($value).$sTextQualifier;
  3926. break;
  3927. case 'overrun':
  3928. break;
  3929. }
  3930. }
  3931. }
  3932. }
  3933. return $sRet;
  3934. }
  3935. public function GetSubItemAsXML($sItemCode, $value)
  3936. {
  3937. $sRet = Str::pure2xml((string)$value);
  3938. switch($sItemCode)
  3939. {
  3940. case 'timespent':
  3941. case 'started':
  3942. case 'laststart':
  3943. case 'stopped':
  3944. break;
  3945. default:
  3946. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3947. {
  3948. $sThPrefix = $iThreshold.'_';
  3949. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3950. {
  3951. // The current threshold is concerned
  3952. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3953. switch($sThresholdCode)
  3954. {
  3955. case 'deadline':
  3956. break;
  3957. case 'passed':
  3958. case 'triggered':
  3959. $sRet = $this->GetBooleanLabel($value);
  3960. break;
  3961. case 'overrun':
  3962. break;
  3963. }
  3964. }
  3965. }
  3966. }
  3967. return $sRet;
  3968. }
  3969. /**
  3970. * Implemented for the HTML spreadsheet format!
  3971. */
  3972. public function GetSubItemAsEditValue($sItemCode, $value)
  3973. {
  3974. $sRet = $value;
  3975. switch($sItemCode)
  3976. {
  3977. case 'timespent':
  3978. break;
  3979. case 'started':
  3980. case 'laststart':
  3981. case 'stopped':
  3982. if (is_null($value))
  3983. {
  3984. $sRet = ''; // Undefined
  3985. }
  3986. else
  3987. {
  3988. $sRet = date(self::GetDateFormat(), $value);
  3989. }
  3990. break;
  3991. default:
  3992. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3993. {
  3994. $sThPrefix = $iThreshold.'_';
  3995. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3996. {
  3997. // The current threshold is concerned
  3998. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3999. switch($sThresholdCode)
  4000. {
  4001. case 'deadline':
  4002. if ($value)
  4003. {
  4004. $sRet = date(self::GetDateFormat(true /*full*/), $value);
  4005. }
  4006. else
  4007. {
  4008. $sRet = '';
  4009. }
  4010. break;
  4011. case 'passed':
  4012. case 'triggered':
  4013. $sRet = $this->GetBooleanLabel($value);
  4014. break;
  4015. case 'overrun':
  4016. break;
  4017. }
  4018. }
  4019. }
  4020. }
  4021. return $sRet;
  4022. }
  4023. }
  4024. /**
  4025. * View of a subvalue of another attribute
  4026. * If an attribute implements the verbs GetSubItem.... then it can expose
  4027. * internal values, each of them being an attribute and therefore they
  4028. * can be displayed at different times in the object lifecycle, and used for
  4029. * reporting (as a condition in OQL, or as an additional column in an export)
  4030. * Known usages: Stop Watches can expose threshold statuses
  4031. */
  4032. class AttributeSubItem extends AttributeDefinition
  4033. {
  4034. static public function ListExpectedParams()
  4035. {
  4036. return array_merge(parent::ListExpectedParams(), array('target_attcode', 'item_code'));
  4037. }
  4038. public function GetParentAttCode() {return $this->Get("target_attcode");}
  4039. /**
  4040. * Helper : get the attribute definition to which the execution will be forwarded
  4041. */
  4042. public function GetTargetAttDef()
  4043. {
  4044. $sClass = $this->GetHostClass();
  4045. $oParentAttDef = MetaModel::GetAttributeDef($sClass, $this->Get('target_attcode'));
  4046. return $oParentAttDef;
  4047. }
  4048. public function GetEditClass() {return "";}
  4049. public function GetValuesDef() {return null;}
  4050. //public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  4051. public function IsDirectField() {return true;}
  4052. public function IsScalar() {return true;}
  4053. public function IsWritable() {return false;}
  4054. public function GetDefaultValue() {return null;}
  4055. // public function IsNullAllowed() {return false;}
  4056. public function LoadInObject() {return false;} // if this verb returns true, then GetValue must be implemented
  4057. //
  4058. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  4059. public function FromSQLToValue($aCols, $sPrefix = '')
  4060. {
  4061. }
  4062. public function GetSQLColumns($bFullSpec = false)
  4063. {
  4064. return array();
  4065. }
  4066. public function GetFilterDefinitions()
  4067. {
  4068. return array($this->GetCode() => new FilterFromAttribute($this));
  4069. }
  4070. public function GetBasicFilterOperators()
  4071. {
  4072. return array();
  4073. }
  4074. public function GetBasicFilterLooseOperator()
  4075. {
  4076. return "=";
  4077. }
  4078. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4079. {
  4080. $sQValue = CMDBSource::Quote($value);
  4081. switch ($sOpCode)
  4082. {
  4083. case '!=':
  4084. return $this->GetSQLExpr()." != $sQValue";
  4085. break;
  4086. case '=':
  4087. default:
  4088. return $this->GetSQLExpr()." = $sQValue";
  4089. }
  4090. }
  4091. public function GetSQLExpressions($sPrefix = '')
  4092. {
  4093. $oParent = $this->GetTargetAttDef();
  4094. $res = $oParent->GetSubItemSQLExpression($this->Get('item_code'));
  4095. return $res;
  4096. }
  4097. /**
  4098. * Used by DBOBject::Get()
  4099. */
  4100. public function GetValue($parentValue, $oHostObject = null)
  4101. {
  4102. $oParent = $this->GetTargetAttDef();
  4103. $res = $oParent->GetSubItemValue($this->Get('item_code'), $parentValue, $oHostObject);
  4104. return $res;
  4105. }
  4106. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4107. {
  4108. $oParent = $this->GetTargetAttDef();
  4109. $res = $oParent->GetSubItemAsHTML($this->Get('item_code'), $value);
  4110. return $res;
  4111. }
  4112. public function GetAsHTMLForHistory($value, $oHostObject = null, $bLocalize = true)
  4113. {
  4114. $oParent = $this->GetTargetAttDef();
  4115. $res = $oParent->GetSubItemAsHTMLForHistory($this->Get('item_code'), $value);
  4116. return $res;
  4117. }
  4118. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4119. {
  4120. $oParent = $this->GetTargetAttDef();
  4121. $res = $oParent->GetSubItemAsCSV($this->Get('item_code'), $value, $sSeparator, $sTextQualifier);
  4122. return $res;
  4123. }
  4124. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4125. {
  4126. $oParent = $this->GetTargetAttDef();
  4127. $res = $oParent->GetSubItemAsXML($this->Get('item_code'), $value);
  4128. return $res;
  4129. }
  4130. /**
  4131. * As of now, this function must be implemented to have the value in spreadsheet format
  4132. */
  4133. public function GetEditValue($value, $oHostObj = null)
  4134. {
  4135. $oParent = $this->GetTargetAttDef();
  4136. $res = $oParent->GetSubItemAsEditValue($this->Get('item_code'), $value);
  4137. return $res;
  4138. }
  4139. }
  4140. /**
  4141. * One way encrypted (hashed) password
  4142. */
  4143. class AttributeOneWayPassword extends AttributeDefinition
  4144. {
  4145. static public function ListExpectedParams()
  4146. {
  4147. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  4148. }
  4149. public function GetEditClass() {return "One Way Password";}
  4150. public function IsDirectField() {return true;}
  4151. public function IsScalar() {return true;}
  4152. public function IsWritable() {return true;}
  4153. public function GetDefaultValue() {return "";}
  4154. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  4155. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  4156. public function MakeRealValue($proposedValue, $oHostObj)
  4157. {
  4158. $oPassword = $proposedValue;
  4159. if (!is_object($oPassword))
  4160. {
  4161. $oPassword = new ormPassword('', '');
  4162. $oPassword->SetPassword($proposedValue);
  4163. }
  4164. return $oPassword;
  4165. }
  4166. public function GetSQLExpressions($sPrefix = '')
  4167. {
  4168. if ($sPrefix == '')
  4169. {
  4170. $sPrefix = $this->GetCode();
  4171. }
  4172. $aColumns = array();
  4173. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4174. $aColumns[''] = $sPrefix.'_hash';
  4175. $aColumns['_salt'] = $sPrefix.'_salt';
  4176. return $aColumns;
  4177. }
  4178. public function FromSQLToValue($aCols, $sPrefix = '')
  4179. {
  4180. if (!array_key_exists($sPrefix, $aCols))
  4181. {
  4182. $sAvailable = implode(', ', array_keys($aCols));
  4183. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4184. }
  4185. $hashed = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  4186. if (!array_key_exists($sPrefix.'_salt', $aCols))
  4187. {
  4188. $sAvailable = implode(', ', array_keys($aCols));
  4189. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  4190. }
  4191. $sSalt = isset($aCols[$sPrefix.'_salt']) ? $aCols[$sPrefix.'_salt'] : '';
  4192. $value = new ormPassword($hashed, $sSalt);
  4193. return $value;
  4194. }
  4195. public function GetSQLValues($value)
  4196. {
  4197. // #@# Optimization: do not load blobs anytime
  4198. // As per mySQL doc, selecting blob columns will prevent mySQL from
  4199. // using memory in case a temporary table has to be created
  4200. // (temporary tables created on disk)
  4201. // We will have to remove the blobs from the list of attributes when doing the select
  4202. // then the use of Get() should finalize the load
  4203. if ($value instanceOf ormPassword)
  4204. {
  4205. $aValues = array();
  4206. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  4207. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  4208. }
  4209. else
  4210. {
  4211. $aValues = array();
  4212. $aValues[$this->GetCode().'_hash'] = '';
  4213. $aValues[$this->GetCode().'_salt'] = '';
  4214. }
  4215. return $aValues;
  4216. }
  4217. public function GetSQLColumns($bFullSpec = false)
  4218. {
  4219. $aColumns = array();
  4220. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  4221. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  4222. return $aColumns;
  4223. }
  4224. public function GetImportColumns()
  4225. {
  4226. $aColumns = array();
  4227. $aColumns[$this->GetCode()] = 'TINYTEXT';
  4228. return $aColumns;
  4229. }
  4230. public function FromImportToValue($aCols, $sPrefix = '')
  4231. {
  4232. if (!isset($aCols[$sPrefix]))
  4233. {
  4234. $sAvailable = implode(', ', array_keys($aCols));
  4235. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4236. }
  4237. $sClearPwd = $aCols[$sPrefix];
  4238. $oPassword = new ormPassword('', '');
  4239. $oPassword->SetPassword($sClearPwd);
  4240. return $oPassword;
  4241. }
  4242. public function GetFilterDefinitions()
  4243. {
  4244. return array();
  4245. // still not working... see later...
  4246. }
  4247. public function GetBasicFilterOperators()
  4248. {
  4249. return array();
  4250. }
  4251. public function GetBasicFilterLooseOperator()
  4252. {
  4253. return '=';
  4254. }
  4255. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4256. {
  4257. return 'true';
  4258. }
  4259. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4260. {
  4261. if (is_object($value))
  4262. {
  4263. return $value->GetAsHTML();
  4264. }
  4265. }
  4266. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4267. {
  4268. return ''; // Not exportable in CSV
  4269. }
  4270. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4271. {
  4272. return ''; // Not exportable in XML
  4273. }
  4274. }
  4275. // Indexed array having two dimensions
  4276. class AttributeTable extends AttributeDBField
  4277. {
  4278. public function GetEditClass() {return "Table";}
  4279. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  4280. public function GetMaxSize()
  4281. {
  4282. return null;
  4283. }
  4284. public function GetNullValue()
  4285. {
  4286. return array();
  4287. }
  4288. public function IsNull($proposedValue)
  4289. {
  4290. return (count($proposedValue) == 0);
  4291. }
  4292. public function GetEditValue($sValue, $oHostObj = null)
  4293. {
  4294. return '';
  4295. }
  4296. // Facilitate things: allow the user to Set the value from a string
  4297. public function MakeRealValue($proposedValue, $oHostObj)
  4298. {
  4299. if (is_null($proposedValue))
  4300. {
  4301. return array();
  4302. }
  4303. else if (!is_array($proposedValue))
  4304. {
  4305. return array(0 => array(0 => $proposedValue));
  4306. }
  4307. return $proposedValue;
  4308. }
  4309. public function FromSQLToValue($aCols, $sPrefix = '')
  4310. {
  4311. try
  4312. {
  4313. $value = @unserialize($aCols[$sPrefix.'']);
  4314. if ($value === false)
  4315. {
  4316. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  4317. }
  4318. }
  4319. catch(Exception $e)
  4320. {
  4321. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  4322. }
  4323. return $value;
  4324. }
  4325. public function GetSQLValues($value)
  4326. {
  4327. $aValues = array();
  4328. $aValues[$this->Get("sql")] = serialize($value);
  4329. return $aValues;
  4330. }
  4331. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4332. {
  4333. if (!is_array($value))
  4334. {
  4335. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  4336. }
  4337. if (count($value) == 0)
  4338. {
  4339. return "";
  4340. }
  4341. $sRes = "<TABLE class=\"listResults\">";
  4342. $sRes .= "<TBODY>";
  4343. foreach($value as $iRow => $aRawData)
  4344. {
  4345. $sRes .= "<TR>";
  4346. foreach ($aRawData as $iCol => $cell)
  4347. {
  4348. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  4349. $sRes .= "<TD>$sCell</TD>";
  4350. }
  4351. $sRes .= "</TR>";
  4352. }
  4353. $sRes .= "</TBODY>";
  4354. $sRes .= "</TABLE>";
  4355. return $sRes;
  4356. }
  4357. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4358. {
  4359. // Not implemented
  4360. return '';
  4361. }
  4362. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4363. {
  4364. if (count($value) == 0)
  4365. {
  4366. return "";
  4367. }
  4368. $sRes = "";
  4369. foreach($value as $iRow => $aRawData)
  4370. {
  4371. $sRes .= "<row>";
  4372. foreach ($aRawData as $iCol => $cell)
  4373. {
  4374. $sCell = Str::pure2xml((string)$cell);
  4375. $sRes .= "<cell icol=\"$iCol\">$sCell</cell>";
  4376. }
  4377. $sRes .= "</row>";
  4378. }
  4379. return $sRes;
  4380. }
  4381. }
  4382. // The PHP value is a hash array, it is stored as a TEXT column
  4383. class AttributePropertySet extends AttributeTable
  4384. {
  4385. public function GetEditClass() {return "PropertySet";}
  4386. // Facilitate things: allow the user to Set the value from a string
  4387. public function MakeRealValue($proposedValue, $oHostObj)
  4388. {
  4389. if (!is_array($proposedValue))
  4390. {
  4391. return array('?' => (string)$proposedValue);
  4392. }
  4393. return $proposedValue;
  4394. }
  4395. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4396. {
  4397. if (!is_array($value))
  4398. {
  4399. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  4400. }
  4401. if (count($value) == 0)
  4402. {
  4403. return "";
  4404. }
  4405. $sRes = "<TABLE class=\"listResults\">";
  4406. $sRes .= "<TBODY>";
  4407. foreach($value as $sProperty => $sValue)
  4408. {
  4409. if ($sProperty == 'auth_pwd')
  4410. {
  4411. $sValue = '*****';
  4412. }
  4413. $sRes .= "<TR>";
  4414. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  4415. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  4416. $sRes .= "</TR>";
  4417. }
  4418. $sRes .= "</TBODY>";
  4419. $sRes .= "</TABLE>";
  4420. return $sRes;
  4421. }
  4422. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4423. {
  4424. if (count($value) == 0)
  4425. {
  4426. return "";
  4427. }
  4428. $aRes = array();
  4429. foreach($value as $sProperty => $sValue)
  4430. {
  4431. if ($sProperty == 'auth_pwd')
  4432. {
  4433. $sValue = '*****';
  4434. }
  4435. $sFrom = array(',', '=');
  4436. $sTo = array('\,', '\=');
  4437. $aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
  4438. }
  4439. $sRaw = implode(',', $aRes);
  4440. $sFrom = array("\r\n", $sTextQualifier);
  4441. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4442. $sEscaped = str_replace($sFrom, $sTo, $sRaw);
  4443. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4444. }
  4445. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4446. {
  4447. if (count($value) == 0)
  4448. {
  4449. return "";
  4450. }
  4451. $sRes = "";
  4452. foreach($value as $sProperty => $sValue)
  4453. {
  4454. if ($sProperty == 'auth_pwd')
  4455. {
  4456. $sValue = '*****';
  4457. }
  4458. $sRes .= "<property id=\"$sProperty\">";
  4459. $sRes .= Str::pure2xml((string)$sValue);
  4460. $sRes .= "</property>";
  4461. }
  4462. return $sRes;
  4463. }
  4464. }
  4465. /**
  4466. * The attribute dedicated to the friendly name automatic attribute (not written)
  4467. *
  4468. * @package iTopORM
  4469. */
  4470. class AttributeComputedFieldVoid extends AttributeDefinition
  4471. {
  4472. static public function ListExpectedParams()
  4473. {
  4474. return array_merge(parent::ListExpectedParams(), array());
  4475. }
  4476. public function GetEditClass() {return "";}
  4477. public function GetValuesDef() {return null;}
  4478. public function GetPrerequisiteAttributes() {return $this->GetOptional("depends_on", array());}
  4479. public function IsDirectField() {return true;}
  4480. public function IsScalar() {return true;}
  4481. public function IsWritable() {return false;}
  4482. public function GetSQLExpr() {return null;}
  4483. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  4484. public function IsNullAllowed() {return false;}
  4485. //
  4486. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  4487. public function GetSQLExpressions($sPrefix = '')
  4488. {
  4489. if ($sPrefix == '')
  4490. {
  4491. $sPrefix = $this->GetCode();
  4492. }
  4493. return array('' => $sPrefix);
  4494. }
  4495. public function FromSQLToValue($aCols, $sPrefix = '')
  4496. {
  4497. return null;
  4498. }
  4499. public function GetSQLValues($value)
  4500. {
  4501. return array();
  4502. }
  4503. public function GetSQLColumns($bFullSpec = false)
  4504. {
  4505. return array();
  4506. }
  4507. public function GetFilterDefinitions()
  4508. {
  4509. return array($this->GetCode() => new FilterFromAttribute($this));
  4510. }
  4511. public function GetBasicFilterOperators()
  4512. {
  4513. return array("="=>"equals", "!="=>"differs from");
  4514. }
  4515. public function GetBasicFilterLooseOperator()
  4516. {
  4517. return "=";
  4518. }
  4519. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4520. {
  4521. $sQValue = CMDBSource::Quote($value);
  4522. switch ($sOpCode)
  4523. {
  4524. case '!=':
  4525. return $this->GetSQLExpr()." != $sQValue";
  4526. break;
  4527. case '=':
  4528. default:
  4529. return $this->GetSQLExpr()." = $sQValue";
  4530. }
  4531. }
  4532. }
  4533. /**
  4534. * The attribute dedicated to the friendly name automatic attribute (not written)
  4535. *
  4536. * @package iTopORM
  4537. */
  4538. class AttributeFriendlyName extends AttributeComputedFieldVoid
  4539. {
  4540. public function __construct($sCode, $sExtKeyAttCode)
  4541. {
  4542. $this->m_sCode = $sCode;
  4543. $aParams = array();
  4544. // $aParams["is_null_allowed"] = false,
  4545. $aParams["default_value"] = '';
  4546. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  4547. parent::__construct($sCode, $aParams);
  4548. $this->m_sValue = $this->Get("default_value");
  4549. }
  4550. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  4551. public function GetExtAttCode() {return 'friendlyname';}
  4552. public function GetLabel($sDefault = null)
  4553. {
  4554. $sLabel = parent::GetLabel('');
  4555. if (strlen($sLabel) == 0)
  4556. {
  4557. $sKeyAttCode = $this->Get("extkey_attcode");
  4558. if ($sKeyAttCode == 'id')
  4559. {
  4560. return Dict::S('Core:FriendlyName-Label');
  4561. }
  4562. else
  4563. {
  4564. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  4565. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  4566. }
  4567. }
  4568. return $sLabel;
  4569. }
  4570. public function GetDescription($sDefault = null)
  4571. {
  4572. $sLabel = parent::GetDescription('');
  4573. if (strlen($sLabel) == 0)
  4574. {
  4575. $sKeyAttCode = $this->Get("extkey_attcode");
  4576. if ($sKeyAttCode == 'id')
  4577. {
  4578. return Dict::S('Core:FriendlyName-Description');
  4579. }
  4580. else
  4581. {
  4582. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  4583. $sLabel = $oExtKeyAttDef->GetDescription('');
  4584. }
  4585. }
  4586. return $sLabel;
  4587. }
  4588. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  4589. protected function GetSQLCol($bFullSpec = false) {return "";}
  4590. public function FromSQLToValue($aCols, $sPrefix = '')
  4591. {
  4592. $sValue = $aCols[$sPrefix];
  4593. return $sValue;
  4594. }
  4595. /**
  4596. * Encrypt the value before storing it in the database
  4597. */
  4598. public function GetSQLValues($value)
  4599. {
  4600. return array();
  4601. }
  4602. public function IsWritable()
  4603. {
  4604. return false;
  4605. }
  4606. public function IsDirectField()
  4607. {
  4608. return false;
  4609. }
  4610. public function SetFixedValue($sValue)
  4611. {
  4612. $this->m_sValue = $sValue;
  4613. }
  4614. public function GetDefaultValue()
  4615. {
  4616. return $this->m_sValue;
  4617. }
  4618. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  4619. {
  4620. return Str::pure2html((string)$sValue);
  4621. }
  4622. // Do not display friendly names in the history of change
  4623. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  4624. {
  4625. return '';
  4626. }
  4627. public function GetBasicFilterLooseOperator()
  4628. {
  4629. return "Contains";
  4630. }
  4631. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4632. {
  4633. $sQValue = CMDBSource::Quote($value);
  4634. switch ($sOpCode)
  4635. {
  4636. case '=':
  4637. case '!=':
  4638. return $this->GetSQLExpr()." $sOpCode $sQValue";
  4639. case 'Contains':
  4640. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  4641. case 'NotLike':
  4642. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  4643. case 'Like':
  4644. default:
  4645. return $this->GetSQLExpr()." LIKE $sQValue";
  4646. }
  4647. }
  4648. }
  4649. /**
  4650. * Holds the setting for the redundancy on a specific relation
  4651. * Its value is a string, containing either:
  4652. * - 'disabled'
  4653. * - 'n', where n is a positive integer value giving the minimum count of items upstream
  4654. * - 'n%', where n is a positive integer value, giving the minimum as a percentage of the total count of items upstream
  4655. *
  4656. * @package iTopORM
  4657. */
  4658. class AttributeRedundancySettings extends AttributeDBField
  4659. {
  4660. static public function ListExpectedParams()
  4661. {
  4662. return array('sql', 'relation_code', 'from_class', 'neighbour_id', 'enabled', 'enabled_mode', 'min_up', 'min_up_type', 'min_up_mode');
  4663. }
  4664. public function GetValuesDef() {return null;}
  4665. public function GetPrerequisiteAttributes() {return array();}
  4666. public function GetEditClass() {return "RedundancySetting";}
  4667. protected function GetSQLCol($bFullSpec = false)
  4668. {
  4669. return "VARCHAR(20)".($bFullSpec ? $this->GetSQLColSpec() : '');
  4670. }
  4671. public function GetValidationPattern()
  4672. {
  4673. return "^[0-9]{1,3}|[0-9]{1,2}%|disabled$";
  4674. }
  4675. public function GetMaxSize()
  4676. {
  4677. return 20;
  4678. }
  4679. public function GetDefaultValue($aArgs = array())
  4680. {
  4681. $sRet = 'disabled';
  4682. if ($this->Get('enabled'))
  4683. {
  4684. if ($this->Get('min_up_type') == 'count')
  4685. {
  4686. $sRet = (string) $this->Get('min_up');
  4687. }
  4688. else // percent
  4689. {
  4690. $sRet = $this->Get('min_up').'%';
  4691. }
  4692. }
  4693. return $sRet;
  4694. }
  4695. public function IsNullAllowed()
  4696. {
  4697. return false;
  4698. }
  4699. public function GetNullValue()
  4700. {
  4701. return '';
  4702. }
  4703. public function IsNull($proposedValue)
  4704. {
  4705. return ($proposedValue == '');
  4706. }
  4707. public function MakeRealValue($proposedValue, $oHostObj)
  4708. {
  4709. if (is_null($proposedValue)) return '';
  4710. return (string)$proposedValue;
  4711. }
  4712. public function ScalarToSQL($value)
  4713. {
  4714. if (!is_string($value))
  4715. {
  4716. throw new CoreException('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  4717. }
  4718. return $value;
  4719. }
  4720. public function GetRelationQueryData()
  4721. {
  4722. foreach (MetaModel::EnumRelationQueries($this->GetHostClass(), $this->Get('relation_code'), false) as $sDummy => $aQueryInfo)
  4723. {
  4724. if ($aQueryInfo['sFromClass'] == $this->Get('from_class'))
  4725. {
  4726. if ($aQueryInfo['sNeighbour'] == $this->Get('neighbour_id'))
  4727. {
  4728. return $aQueryInfo;
  4729. }
  4730. }
  4731. }
  4732. }
  4733. /**
  4734. * Find the user option label
  4735. * @param user option : disabled|cout|percent
  4736. */
  4737. public function GetUserOptionFormat($sUserOption, $sDefault = null)
  4738. {
  4739. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, null, true /*user lang*/);
  4740. if (is_null($sLabel))
  4741. {
  4742. // If no default value is specified, let's define the most relevant one for developping purposes
  4743. if (is_null($sDefault))
  4744. {
  4745. $sDefault = str_replace('_', ' ', $this->m_sCode.':'.$sUserOption.'(%1$s)');
  4746. }
  4747. // Browse the hierarchy again, accepting default (english) translations
  4748. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, $sDefault, false);
  4749. }
  4750. return $sLabel;
  4751. }
  4752. /**
  4753. * Override to display the value in the GUI
  4754. */
  4755. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  4756. {
  4757. $sCurrentOption = $this->GetCurrentOption($sValue);
  4758. $sClass = $oHostObject ? get_class($oHostObject) : $this->m_sHostClass;
  4759. return sprintf($this->GetUserOptionFormat($sCurrentOption), $this->GetMinUpValue($sValue), MetaModel::GetName($sClass));
  4760. }
  4761. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4762. {
  4763. $sFrom = array("\r\n", $sTextQualifier);
  4764. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4765. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  4766. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4767. }
  4768. /**
  4769. * Helper to interpret the value, given the current settings and string representation of the attribute
  4770. */
  4771. public function IsEnabled($sValue)
  4772. {
  4773. if ($this->get('enabled_mode') == 'fixed')
  4774. {
  4775. $bRet = $this->get('enabled');
  4776. }
  4777. else
  4778. {
  4779. $bRet = ($sValue != 'disabled');
  4780. }
  4781. return $bRet;
  4782. }
  4783. /**
  4784. * Helper to interpret the value, given the current settings and string representation of the attribute
  4785. */
  4786. public function GetMinUpType($sValue)
  4787. {
  4788. if ($this->get('min_up_mode') == 'fixed')
  4789. {
  4790. $sRet = $this->get('min_up_type');
  4791. }
  4792. else
  4793. {
  4794. $sRet = 'count';
  4795. if (substr(trim($sValue), -1, 1) == '%')
  4796. {
  4797. $sRet = 'percent';
  4798. }
  4799. }
  4800. return $sRet;
  4801. }
  4802. /**
  4803. * Helper to interpret the value, given the current settings and string representation of the attribute
  4804. */
  4805. public function GetMinUpValue($sValue)
  4806. {
  4807. if ($this->get('min_up_mode') == 'fixed')
  4808. {
  4809. $iRet = (int) $this->Get('min_up');
  4810. }
  4811. else
  4812. {
  4813. $sRefValue = $sValue;
  4814. if (substr(trim($sValue), -1, 1) == '%')
  4815. {
  4816. $sRefValue = substr(trim($sValue), 0, -1);
  4817. }
  4818. $iRet = (int) trim($sRefValue);
  4819. }
  4820. return $iRet;
  4821. }
  4822. /**
  4823. * Helper to determine if the redundancy can be viewed/edited by the end-user
  4824. */
  4825. public function IsVisible()
  4826. {
  4827. $bRet = false;
  4828. if ($this->Get('enabled_mode') == 'fixed')
  4829. {
  4830. $bRet = $this->Get('enabled');
  4831. }
  4832. elseif ($this->Get('enabled_mode') == 'user')
  4833. {
  4834. $bRet = true;
  4835. }
  4836. return $bRet;
  4837. }
  4838. public function IsWritable()
  4839. {
  4840. if (($this->Get('enabled_mode') == 'fixed') && ($this->Get('min_up_mode') == 'fixed'))
  4841. {
  4842. return false;
  4843. }
  4844. return true;
  4845. }
  4846. /**
  4847. * Returns an HTML form that can be read by ReadValueFromPostedForm
  4848. */
  4849. public function GetDisplayForm($sCurrentValue, $oPage, $bEditMode = false, $sFormPrefix = '')
  4850. {
  4851. $sRet = '';
  4852. $aUserOptions = $this->GetUserOptions($sCurrentValue);
  4853. if (count($aUserOptions) < 2)
  4854. {
  4855. $bEditOption = false;
  4856. }
  4857. else
  4858. {
  4859. $bEditOption = $bEditMode;
  4860. }
  4861. $sCurrentOption = $this->GetCurrentOption($sCurrentValue);
  4862. foreach($aUserOptions as $sUserOption)
  4863. {
  4864. $bSelected = ($sUserOption == $sCurrentOption);
  4865. $sRet .= '<div>';
  4866. $sRet .= $this->GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditOption, $sUserOption, $bSelected);
  4867. $sRet .= '</div>';
  4868. }
  4869. return $sRet;
  4870. }
  4871. const USER_OPTION_DISABLED = 'disabled';
  4872. const USER_OPTION_ENABLED_COUNT = 'count';
  4873. const USER_OPTION_ENABLED_PERCENT = 'percent';
  4874. /**
  4875. * Depending on the xxx_mode parameters, build the list of options that are allowed to the end-user
  4876. */
  4877. protected function GetUserOptions($sValue)
  4878. {
  4879. $aRet = array();
  4880. if ($this->Get('enabled_mode') == 'user')
  4881. {
  4882. $aRet[] = self::USER_OPTION_DISABLED;
  4883. }
  4884. if ($this->Get('min_up_mode') == 'user')
  4885. {
  4886. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  4887. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  4888. }
  4889. else
  4890. {
  4891. if ($this->GetMinUpType($sValue) == 'count')
  4892. {
  4893. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  4894. }
  4895. else
  4896. {
  4897. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  4898. }
  4899. }
  4900. return $aRet;
  4901. }
  4902. /**
  4903. * Convert the string representation into one of the existing options
  4904. */
  4905. protected function GetCurrentOption($sValue)
  4906. {
  4907. $sRet = self::USER_OPTION_DISABLED;
  4908. if ($this->IsEnabled($sValue))
  4909. {
  4910. if ($this->GetMinUpType($sValue) == 'count')
  4911. {
  4912. $sRet = self::USER_OPTION_ENABLED_COUNT;
  4913. }
  4914. else
  4915. {
  4916. $sRet = self::USER_OPTION_ENABLED_PERCENT;
  4917. }
  4918. }
  4919. return $sRet;
  4920. }
  4921. /**
  4922. * Display an option (form, or current value)
  4923. */
  4924. protected function GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditMode, $sUserOption, $bSelected = true)
  4925. {
  4926. $sRet = '';
  4927. $iCurrentValue = $this->GetMinUpValue($sCurrentValue);
  4928. if ($bEditMode)
  4929. {
  4930. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  4931. switch ($sUserOption)
  4932. {
  4933. case self::USER_OPTION_DISABLED:
  4934. $sValue = ''; // Empty placeholder
  4935. break;
  4936. case self::USER_OPTION_ENABLED_COUNT:
  4937. if ($bEditMode)
  4938. {
  4939. $sName = $sHtmlNamesPrefix.'_min_up_count';
  4940. $sEditValue = $bSelected ? $iCurrentValue : '';
  4941. $sValue = '<input class="redundancy-min-up-count" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  4942. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  4943. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  4944. }
  4945. else
  4946. {
  4947. $sValue = $iCurrentValue;
  4948. }
  4949. break;
  4950. case self::USER_OPTION_ENABLED_PERCENT:
  4951. if ($bEditMode)
  4952. {
  4953. $sName = $sHtmlNamesPrefix.'_min_up_percent';
  4954. $sEditValue = $bSelected ? $iCurrentValue : '';
  4955. $sValue = '<input class="redundancy-min-up-percent" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  4956. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  4957. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  4958. }
  4959. else
  4960. {
  4961. $sValue = $iCurrentValue;
  4962. }
  4963. break;
  4964. }
  4965. $sLabel = sprintf($this->GetUserOptionFormat($sUserOption), $sValue, MetaModel::GetName($this->GetHostClass()));
  4966. $sOptionName = $sHtmlNamesPrefix.'_user_option';
  4967. $sOptionId = $sOptionName.'_'.$sUserOption;
  4968. $sChecked = $bSelected ? 'checked' : '';
  4969. $sRet = '<input type="radio" name="'.$sOptionName.'" id="'.$sOptionId.'" value="'.$sUserOption.'"'.$sChecked.'> <label for="'.$sOptionId.'">'.$sLabel.'</label>';
  4970. }
  4971. else
  4972. {
  4973. // Read-only: display only the currently selected option
  4974. if ($bSelected)
  4975. {
  4976. $sRet = sprintf($this->GetUserOptionFormat($sUserOption), $iCurrentValue, MetaModel::GetName($this->GetHostClass()));
  4977. }
  4978. }
  4979. return $sRet;
  4980. }
  4981. /**
  4982. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  4983. */
  4984. public function ReadValueFromPostedForm($sFormPrefix)
  4985. {
  4986. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  4987. $iMinUpCount = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_count', null, 'raw_data');
  4988. $iMinUpPercent = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_percent', null, 'raw_data');
  4989. $sSelectedOption = utils::ReadPostedParam($sHtmlNamesPrefix.'_user_option', null, 'raw_data');
  4990. switch ($sSelectedOption)
  4991. {
  4992. case self::USER_OPTION_ENABLED_COUNT:
  4993. $sRet = $iMinUpCount;
  4994. break;
  4995. case self::USER_OPTION_ENABLED_PERCENT:
  4996. $sRet = $iMinUpPercent.'%';
  4997. break;
  4998. case self::USER_OPTION_DISABLED:
  4999. default:
  5000. $sRet = 'disabled';
  5001. break;
  5002. }
  5003. return $sRet;
  5004. }
  5005. }