metamodel.class.php 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156
  1. <?php
  2. // Copyright (C) 2010-2017 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. require_once(APPROOT.'core/modulehandler.class.inc.php');
  19. require_once(APPROOT.'core/querybuildercontext.class.inc.php');
  20. require_once(APPROOT.'core/querymodifier.class.inc.php');
  21. require_once(APPROOT.'core/metamodelmodifier.inc.php');
  22. require_once(APPROOT.'core/computing.inc.php');
  23. require_once(APPROOT.'core/relationgraph.class.inc.php');
  24. require_once(APPROOT.'core/apc-compat.php');
  25. /**
  26. * Metamodel
  27. *
  28. * @copyright Copyright (C) 2010-2017 Combodo SARL
  29. * @license http://opensource.org/licenses/AGPL-3.0
  30. */
  31. /**
  32. * @package iTopORM
  33. */
  34. define('ENUM_PARENT_CLASSES_EXCLUDELEAF', 1);
  35. /**
  36. * @package iTopORM
  37. */
  38. define('ENUM_PARENT_CLASSES_ALL', 2);
  39. /**
  40. * Specifies that this attribute is visible/editable.... normal (default config)
  41. *
  42. * @package iTopORM
  43. */
  44. define('OPT_ATT_NORMAL', 0);
  45. /**
  46. * Specifies that this attribute is hidden in that state
  47. *
  48. * @package iTopORM
  49. */
  50. define('OPT_ATT_HIDDEN', 1);
  51. /**
  52. * Specifies that this attribute is not editable in that state
  53. *
  54. * @package iTopORM
  55. */
  56. define('OPT_ATT_READONLY', 2);
  57. /**
  58. * Specifieds that the attribute must be set (different than default value?) when arriving into that state
  59. *
  60. * @package iTopORM
  61. */
  62. define('OPT_ATT_MANDATORY', 4);
  63. /**
  64. * Specifies that the attribute must change when arriving into that state
  65. *
  66. * @package iTopORM
  67. */
  68. define('OPT_ATT_MUSTCHANGE', 8);
  69. /**
  70. * Specifies that the attribute must be proposed when arriving into that state
  71. *
  72. * @package iTopORM
  73. */
  74. define('OPT_ATT_MUSTPROMPT', 16);
  75. /**
  76. * Specifies that the attribute is in 'slave' mode compared to one data exchange task:
  77. * it should not be edited inside iTop anymore
  78. *
  79. * @package iTopORM
  80. */
  81. define('OPT_ATT_SLAVE', 32);
  82. /**
  83. * DB Engine -should be moved into CMDBSource
  84. *
  85. * @package iTopORM
  86. */
  87. define('MYSQL_ENGINE', 'innodb');
  88. //define('MYSQL_ENGINE', 'myisam');
  89. /**
  90. * (API) The objects definitions as well as their mapping to the database
  91. *
  92. * @package iTopORM
  93. */
  94. abstract class MetaModel
  95. {
  96. ///////////////////////////////////////////////////////////////////////////
  97. //
  98. // STATIC Members
  99. //
  100. ///////////////////////////////////////////////////////////////////////////
  101. private static $m_bTraceSourceFiles = false;
  102. private static $m_aClassToFile = array();
  103. protected static $m_sEnvironment = 'production';
  104. public static function GetClassFiles()
  105. {
  106. return self::$m_aClassToFile;
  107. }
  108. // Purpose: workaround the following limitation = PHP5 does not allow to know the class (derived from the current one)
  109. // from which a static function is called (__CLASS__ and self are interpreted during parsing)
  110. private static function GetCallersPHPClass($sExpectedFunctionName = null, $bRecordSourceFile = false)
  111. {
  112. //var_dump(debug_backtrace());
  113. $aBacktrace = debug_backtrace();
  114. // $aBacktrace[0] is where we are
  115. // $aBacktrace[1] is the caller of GetCallersPHPClass
  116. // $aBacktrace[1] is the info we want
  117. if (!empty($sExpectedFunctionName))
  118. {
  119. assert('$aBacktrace[2]["function"] == $sExpectedFunctionName');
  120. }
  121. if ($bRecordSourceFile)
  122. {
  123. self::$m_aClassToFile[$aBacktrace[2]["class"]] = $aBacktrace[1]["file"];
  124. }
  125. return $aBacktrace[2]["class"];
  126. }
  127. // Static init -why and how it works
  128. //
  129. // We found the following limitations:
  130. //- it is not possible to define non scalar constants
  131. //- it is not possible to declare a static variable as '= new myclass()'
  132. // Then we had do propose this model, in which a derived (non abstract)
  133. // class should implement Init(), to call InheritAttributes or AddAttribute.
  134. private static function _check_subclass($sClass)
  135. {
  136. // See also IsValidClass()... ???? #@#
  137. // class is mandatory
  138. // (it is not possible to guess it when called as myderived::...)
  139. if (!array_key_exists($sClass, self::$m_aClassParams))
  140. {
  141. throw new CoreException("Unknown class '$sClass'");
  142. }
  143. }
  144. public static function static_var_dump()
  145. {
  146. var_dump(get_class_vars(__CLASS__));
  147. }
  148. private static $m_oConfig = null;
  149. protected static $m_aModulesParameters = array();
  150. private static $m_bSkipCheckToWrite = false;
  151. private static $m_bSkipCheckExtKeys = false;
  152. private static $m_bUseAPCCache = false;
  153. private static $m_bLogIssue = false;
  154. private static $m_bLogNotification = false;
  155. private static $m_bLogWebService = false;
  156. public static function SkipCheckToWrite()
  157. {
  158. return self::$m_bSkipCheckToWrite;
  159. }
  160. public static function SkipCheckExtKeys()
  161. {
  162. return self::$m_bSkipCheckExtKeys;
  163. }
  164. public static function IsLogEnabledIssue()
  165. {
  166. return self::$m_bLogIssue;
  167. }
  168. public static function IsLogEnabledNotification()
  169. {
  170. return self::$m_bLogNotification;
  171. }
  172. public static function IsLogEnabledWebService()
  173. {
  174. return self::$m_bLogWebService;
  175. }
  176. private static $m_sDBName = "";
  177. private static $m_sTablePrefix = ""; // table prefix for the current application instance (allow several applications on the same DB)
  178. private static $m_Category2Class = array();
  179. private static $m_aRootClasses = array(); // array of "classname" => "rootclass"
  180. private static $m_aParentClasses = array(); // array of ("classname" => array of "parentclass")
  181. private static $m_aChildClasses = array(); // array of ("classname" => array of "childclass")
  182. private static $m_aClassParams = array(); // array of ("classname" => array of class information)
  183. private static $m_aHighlightScales = array(); // array of ("classname" => array of highlightscale information)
  184. static public function GetParentPersistentClass($sRefClass)
  185. {
  186. $sClass = get_parent_class($sRefClass);
  187. if (!$sClass) return '';
  188. if ($sClass == 'DBObject') return ''; // Warning: __CLASS__ is lower case in my version of PHP
  189. // Note: the UI/business model may implement pure PHP classes (intermediate layers)
  190. if (array_key_exists($sClass, self::$m_aClassParams))
  191. {
  192. return $sClass;
  193. }
  194. return self::GetParentPersistentClass($sClass);
  195. }
  196. final static public function GetName($sClass)
  197. {
  198. self::_check_subclass($sClass);
  199. $sStringCode = 'Class:'.$sClass;
  200. return Dict::S($sStringCode, str_replace('_', ' ', $sClass));
  201. }
  202. final static public function GetName_Obsolete($sClass)
  203. {
  204. // Written for compatibility with a data model written prior to version 0.9.1
  205. self::_check_subclass($sClass);
  206. if (array_key_exists('name', self::$m_aClassParams[$sClass]))
  207. {
  208. return self::$m_aClassParams[$sClass]['name'];
  209. }
  210. else
  211. {
  212. return self::GetName($sClass);
  213. }
  214. }
  215. final static public function GetClassFromLabel($sClassLabel, $bCaseSensitive = true)
  216. {
  217. foreach(self::GetClasses() as $sClass)
  218. {
  219. if ($bCaseSensitive)
  220. {
  221. if (self::GetName($sClass) == $sClassLabel)
  222. {
  223. return $sClass;
  224. }
  225. }
  226. else
  227. {
  228. if (strcasecmp(self::GetName($sClass), $sClassLabel) == 0)
  229. {
  230. return $sClass;
  231. }
  232. }
  233. }
  234. return null;
  235. }
  236. final static public function GetCategory($sClass)
  237. {
  238. self::_check_subclass($sClass);
  239. return self::$m_aClassParams[$sClass]["category"];
  240. }
  241. final static public function HasCategory($sClass, $sCategory)
  242. {
  243. self::_check_subclass($sClass);
  244. return (strpos(self::$m_aClassParams[$sClass]["category"], $sCategory) !== false);
  245. }
  246. final static public function GetClassDescription($sClass)
  247. {
  248. self::_check_subclass($sClass);
  249. $sStringCode = 'Class:'.$sClass.'+';
  250. return Dict::S($sStringCode, '');
  251. }
  252. final static public function GetClassDescription_Obsolete($sClass)
  253. {
  254. // Written for compatibility with a data model written prior to version 0.9.1
  255. self::_check_subclass($sClass);
  256. if (array_key_exists('description', self::$m_aClassParams[$sClass]))
  257. {
  258. return self::$m_aClassParams[$sClass]['description'];
  259. }
  260. else
  261. {
  262. return self::GetClassDescription($sClass);
  263. }
  264. }
  265. final static public function GetClassIcon($sClass, $bImgTag = true, $sMoreStyles = '')
  266. {
  267. self::_check_subclass($sClass);
  268. $sIcon = '';
  269. if (array_key_exists('icon', self::$m_aClassParams[$sClass]))
  270. {
  271. $sIcon = self::$m_aClassParams[$sClass]['icon'];
  272. }
  273. if (strlen($sIcon) == 0)
  274. {
  275. $sParentClass = self::GetParentPersistentClass($sClass);
  276. if (strlen($sParentClass) > 0)
  277. {
  278. return self::GetClassIcon($sParentClass, $bImgTag, $sMoreStyles);
  279. }
  280. }
  281. $sIcon = str_replace('/modules/', '/env-'.self::$m_sEnvironment.'/', $sIcon); // Support of pre-2.0 modules
  282. if ($bImgTag && ($sIcon != ''))
  283. {
  284. $sIcon = "<img src=\"$sIcon\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  285. }
  286. return $sIcon;
  287. }
  288. final static public function IsAutoIncrementKey($sClass)
  289. {
  290. self::_check_subclass($sClass);
  291. return (self::$m_aClassParams[$sClass]["key_type"] == "autoincrement");
  292. }
  293. final static public function GetNameSpec($sClass)
  294. {
  295. self::_check_subclass($sClass);
  296. $nameRawSpec = self::$m_aClassParams[$sClass]["name_attcode"];
  297. if (is_array($nameRawSpec))
  298. {
  299. $sFormat = Dict::S("Class:$sClass/Name", '');
  300. if (strlen($sFormat) == 0)
  301. {
  302. // Default to "%1$s %2$s..."
  303. for($i = 1 ; $i <= count($nameRawSpec) ; $i++)
  304. {
  305. if (empty($sFormat))
  306. {
  307. $sFormat .= '%'.$i.'$s';
  308. }
  309. else
  310. {
  311. $sFormat .= ' %'.$i.'$s';
  312. }
  313. }
  314. }
  315. return array($sFormat, $nameRawSpec);
  316. }
  317. elseif (empty($nameRawSpec))
  318. {
  319. //return array($sClass.' %s', array('id'));
  320. return array($sClass, array());
  321. }
  322. else
  323. {
  324. // string -> attcode
  325. return array('%1$s', array($nameRawSpec));
  326. }
  327. }
  328. /**
  329. * Get the friendly name expression for a given class
  330. */
  331. final static public function GetNameExpression($sClass)
  332. {
  333. $aNameSpec = self::GetNameSpec($sClass);
  334. $sFormat = $aNameSpec[0];
  335. $aAttributes = $aNameSpec[1];
  336. $aPieces = preg_split('/%([0-9])\\$s/', $sFormat, -1, PREG_SPLIT_DELIM_CAPTURE);
  337. $aExpressions = array();
  338. foreach($aPieces as $i => $sPiece)
  339. {
  340. if ($i & 1)
  341. {
  342. // $i is ODD - sPiece is a delimiter
  343. //
  344. $iReplacement = (int)$sPiece - 1;
  345. if (isset($aAttributes[$iReplacement]))
  346. {
  347. $sAttCode = $aAttributes[$iReplacement];
  348. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  349. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  350. {
  351. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  352. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sKeyAttCode);
  353. }
  354. else
  355. {
  356. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sAttCode);
  357. }
  358. $aExpressions[] = new FieldExpression($sAttCode, $sClassOfAttribute);
  359. }
  360. }
  361. else
  362. {
  363. // $i is EVEN - sPiece is a literal
  364. //
  365. if (strlen($sPiece) > 0)
  366. {
  367. $aExpressions[] = new ScalarExpression($sPiece);
  368. }
  369. }
  370. }
  371. $oNameExpr = new CharConcatExpression($aExpressions);
  372. return $oNameExpr;
  373. }
  374. /**
  375. * Returns the friendly name IIF it is equivalent to a single attribute
  376. */
  377. final static public function GetFriendlyNameAttributeCode($sClass)
  378. {
  379. $aNameSpec = self::GetNameSpec($sClass);
  380. $sFormat = trim($aNameSpec[0]);
  381. $aAttributes = $aNameSpec[1];
  382. if (($sFormat != '') && ($sFormat != '%1$s'))
  383. {
  384. return null;
  385. }
  386. if (count($aAttributes) > 1)
  387. {
  388. return null;
  389. }
  390. return reset($aAttributes);
  391. }
  392. final static public function GetStateAttributeCode($sClass)
  393. {
  394. self::_check_subclass($sClass);
  395. return self::$m_aClassParams[$sClass]["state_attcode"];
  396. }
  397. final static public function GetDefaultState($sClass)
  398. {
  399. $sDefaultState = '';
  400. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  401. if (!empty($sStateAttrCode))
  402. {
  403. $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  404. $sDefaultState = $oStateAttrDef->GetDefaultValue();
  405. }
  406. return $sDefaultState;
  407. }
  408. final static public function GetReconcKeys($sClass)
  409. {
  410. self::_check_subclass($sClass);
  411. return self::$m_aClassParams[$sClass]["reconc_keys"];
  412. }
  413. final static public function GetDisplayTemplate($sClass)
  414. {
  415. self::_check_subclass($sClass);
  416. return array_key_exists("display_template", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["display_template"]: '';
  417. }
  418. final static public function GetOrderByDefault($sClass, $bOnlyDeclared = false)
  419. {
  420. self::_check_subclass($sClass);
  421. $aOrderBy = array_key_exists("order_by_default", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["order_by_default"]: array();
  422. if ($bOnlyDeclared)
  423. {
  424. // Used to reverse engineer the declaration of the data model
  425. return $aOrderBy;
  426. }
  427. else
  428. {
  429. if (count($aOrderBy) == 0)
  430. {
  431. $aOrderBy['friendlyname'] = true;
  432. }
  433. return $aOrderBy;
  434. }
  435. }
  436. final static public function GetAttributeOrigin($sClass, $sAttCode)
  437. {
  438. self::_check_subclass($sClass);
  439. return self::$m_aAttribOrigins[$sClass][$sAttCode];
  440. }
  441. final static public function GetPrerequisiteAttributes($sClass, $sAttCode)
  442. {
  443. self::_check_subclass($sClass);
  444. $oAtt = self::GetAttributeDef($sClass, $sAttCode);
  445. // Temporary implementation: later, we might be able to compute
  446. // the dependencies, based on the attributes definition
  447. // (allowed values and default values)
  448. // Even non-writable attributes (like ExternalFields) can now have Prerequisites
  449. return $oAtt->GetPrerequisiteAttributes();
  450. }
  451. /**
  452. * Find all attributes that depend on the specified one (reverse of GetPrerequisiteAttributes)
  453. * @param string $sClass Name of the class
  454. * @param string $sAttCode Code of the attributes
  455. * @return Array List of attribute codes that depend on the given attribute, empty array if none.
  456. */
  457. final static public function GetDependentAttributes($sClass, $sAttCode)
  458. {
  459. $aResults = array();
  460. self::_check_subclass($sClass);
  461. foreach (self::ListAttributeDefs($sClass) as $sDependentAttCode=>$void)
  462. {
  463. $aPrerequisites = self::GetPrerequisiteAttributes($sClass, $sDependentAttCode);
  464. if (in_array($sAttCode, $aPrerequisites))
  465. {
  466. $aResults[] = $sDependentAttCode;
  467. }
  468. }
  469. return $aResults;
  470. }
  471. // #@# restore to private ?
  472. final static public function DBGetTable($sClass, $sAttCode = null)
  473. {
  474. self::_check_subclass($sClass);
  475. if (empty($sAttCode) || ($sAttCode == "id"))
  476. {
  477. $sTableRaw = self::$m_aClassParams[$sClass]["db_table"];
  478. if (empty($sTableRaw))
  479. {
  480. // return an empty string whenever the table is undefined, meaning that there is no table associated to this 'abstract' class
  481. return '';
  482. }
  483. else
  484. {
  485. // If the format changes here, do not forget to update the setup index page (detection of installed modules)
  486. return self::$m_sTablePrefix.$sTableRaw;
  487. }
  488. }
  489. // This attribute has been inherited (compound objects)
  490. return self::DBGetTable(self::$m_aAttribOrigins[$sClass][$sAttCode]);
  491. }
  492. final static public function DBGetView($sClass)
  493. {
  494. return self::$m_sTablePrefix."view_".$sClass;
  495. }
  496. final static public function DBEnumTables()
  497. {
  498. // This API does not rely on our capability to query the DB and retrieve
  499. // the list of existing tables
  500. // Rather, it uses the list of expected tables, corresponding to the data model
  501. $aTables = array();
  502. foreach (self::GetClasses() as $sClass)
  503. {
  504. if (!self::HasTable($sClass)) continue;
  505. $sTable = self::DBGetTable($sClass);
  506. // Could be completed later with all the classes that are using a given table
  507. if (!array_key_exists($sTable, $aTables))
  508. {
  509. $aTables[$sTable] = array();
  510. }
  511. $aTables[$sTable][] = $sClass;
  512. }
  513. return $aTables;
  514. }
  515. final static public function DBGetIndexes($sClass)
  516. {
  517. self::_check_subclass($sClass);
  518. if (isset(self::$m_aClassParams[$sClass]['indexes']))
  519. {
  520. return self::$m_aClassParams[$sClass]['indexes'];
  521. }
  522. else
  523. {
  524. return array();
  525. }
  526. }
  527. final static public function DBGetKey($sClass)
  528. {
  529. self::_check_subclass($sClass);
  530. return self::$m_aClassParams[$sClass]["db_key_field"];
  531. }
  532. final static public function DBGetClassField($sClass)
  533. {
  534. self::_check_subclass($sClass);
  535. return self::$m_aClassParams[$sClass]["db_finalclass_field"];
  536. }
  537. final static public function IsStandaloneClass($sClass)
  538. {
  539. self::_check_subclass($sClass);
  540. if (count(self::$m_aChildClasses[$sClass]) == 0)
  541. {
  542. if (count(self::$m_aParentClasses[$sClass]) == 0)
  543. {
  544. return true;
  545. }
  546. }
  547. return false;
  548. }
  549. final static public function IsParentClass($sParentClass, $sChildClass)
  550. {
  551. self::_check_subclass($sChildClass);
  552. self::_check_subclass($sParentClass);
  553. if (in_array($sParentClass, self::$m_aParentClasses[$sChildClass])) return true;
  554. if ($sChildClass == $sParentClass) return true;
  555. return false;
  556. }
  557. final static public function IsSameFamilyBranch($sClassA, $sClassB)
  558. {
  559. self::_check_subclass($sClassA);
  560. self::_check_subclass($sClassB);
  561. if (in_array($sClassA, self::$m_aParentClasses[$sClassB])) return true;
  562. if (in_array($sClassB, self::$m_aParentClasses[$sClassA])) return true;
  563. if ($sClassA == $sClassB) return true;
  564. return false;
  565. }
  566. final static public function IsSameFamily($sClassA, $sClassB)
  567. {
  568. self::_check_subclass($sClassA);
  569. self::_check_subclass($sClassB);
  570. return (self::GetRootClass($sClassA) == self::GetRootClass($sClassB));
  571. }
  572. // Attributes of a given class may contain attributes defined in a parent class
  573. // - Some attributes are a copy of the definition
  574. // - Some attributes correspond to the upper class table definition (compound objects)
  575. // (see also filters definition)
  576. private static $m_aAttribDefs = array(); // array of ("classname" => array of attributes)
  577. private static $m_aAttribOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  578. private static $m_aExtKeyFriends = array(); // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  579. private static $m_aIgnoredAttributes = array(); //array of ("classname" => array of ("attcode"))
  580. private static $m_aEnumToMeta = array(); // array of ("classname" => array of ("attcode" => array of ("metaattcode" => oMetaAttDef))
  581. final static public function ListAttributeDefs($sClass)
  582. {
  583. self::_check_subclass($sClass);
  584. return self::$m_aAttribDefs[$sClass];
  585. }
  586. final public static function GetAttributesList($sClass)
  587. {
  588. self::_check_subclass($sClass);
  589. return array_keys(self::$m_aAttribDefs[$sClass]);
  590. }
  591. final public static function GetFiltersList($sClass)
  592. {
  593. self::_check_subclass($sClass);
  594. return array_keys(self::$m_aFilterDefs[$sClass]);
  595. }
  596. final public static function GetKeysList($sClass)
  597. {
  598. self::_check_subclass($sClass);
  599. $aExtKeys = array();
  600. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  601. {
  602. if ($oAttDef->IsExternalKey())
  603. {
  604. $aExtKeys[] = $sAttCode;
  605. }
  606. }
  607. return $aExtKeys;
  608. }
  609. final static public function IsValidKeyAttCode($sClass, $sAttCode)
  610. {
  611. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  612. if (!array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass])) return false;
  613. return (self::$m_aAttribDefs[$sClass][$sAttCode]->IsExternalKey());
  614. }
  615. final static public function IsValidAttCode($sClass, $sAttCode, $bExtended = false)
  616. {
  617. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  618. if ($bExtended)
  619. {
  620. if (($iPos = strpos($sAttCode, '->')) === false)
  621. {
  622. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  623. }
  624. else
  625. {
  626. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  627. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  628. if (MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  629. {
  630. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  631. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  632. $bRes = MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode, true);
  633. }
  634. else
  635. {
  636. $bRes = false;
  637. }
  638. }
  639. }
  640. else
  641. {
  642. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  643. }
  644. return $bRes;
  645. }
  646. final static public function IsAttributeOrigin($sClass, $sAttCode)
  647. {
  648. return (self::$m_aAttribOrigins[$sClass][$sAttCode] == $sClass);
  649. }
  650. final static public function IsValidFilterCode($sClass, $sFilterCode)
  651. {
  652. if (!array_key_exists($sClass, self::$m_aFilterDefs)) return false;
  653. return (array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]));
  654. }
  655. public static function IsValidClass($sClass)
  656. {
  657. return (array_key_exists($sClass, self::$m_aAttribDefs));
  658. }
  659. public static function IsValidObject($oObject)
  660. {
  661. if (!is_object($oObject)) return false;
  662. return (self::IsValidClass(get_class($oObject)));
  663. }
  664. public static function IsReconcKey($sClass, $sAttCode)
  665. {
  666. return (in_array($sAttCode, self::GetReconcKeys($sClass)));
  667. }
  668. final static public function GetAttributeDef($sClass, $sAttCode)
  669. {
  670. self::_check_subclass($sClass);
  671. if (isset(self::$m_aAttribDefs[$sClass][$sAttCode]))
  672. {
  673. return self::$m_aAttribDefs[$sClass][$sAttCode];
  674. }
  675. elseif (($iPos = strpos($sAttCode, '->')) !== false)
  676. {
  677. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  678. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  679. $oKeyAttDef = self::GetAttributeDef($sClass, $sExtKeyAttCode);
  680. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  681. return self::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  682. }
  683. else
  684. {
  685. throw new Exception("Unknown attribute $sAttCode from class $sClass");
  686. }
  687. }
  688. final static public function GetExternalKeys($sClass)
  689. {
  690. $aExtKeys = array();
  691. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  692. {
  693. if ($oAtt->IsExternalKey())
  694. {
  695. $aExtKeys[$sAttCode] = $oAtt;
  696. }
  697. }
  698. return $aExtKeys;
  699. }
  700. final static public function GetLinkedSets($sClass)
  701. {
  702. $aLinkedSets = array();
  703. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  704. {
  705. if (is_subclass_of($oAtt, 'AttributeLinkedSet'))
  706. {
  707. $aLinkedSets[$sAttCode] = $oAtt;
  708. }
  709. }
  710. return $aLinkedSets;
  711. }
  712. final static public function GetExternalFields($sClass, $sKeyAttCode)
  713. {
  714. static $aExtFields = array();
  715. if (!isset($aExtFields[$sClass][$sKeyAttCode]))
  716. {
  717. $aExtFields[$sClass][$sKeyAttCode] = array();
  718. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  719. {
  720. if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode))
  721. {
  722. $aExtFields[$sClass][$sKeyAttCode][$oAtt->GetExtAttCode()] = $oAtt;
  723. }
  724. }
  725. }
  726. return $aExtFields[$sClass][$sKeyAttCode];
  727. }
  728. final static public function FindExternalField($sClass, $sKeyAttCode, $sRemoteAttCode)
  729. {
  730. $aExtFields = self::GetExternalFields($sClass, $sKeyAttCode);
  731. if (isset($aExtFields[$sRemoteAttCode]))
  732. {
  733. return $aExtFields[$sRemoteAttCode];
  734. }
  735. else
  736. {
  737. return null;
  738. }
  739. }
  740. final static public function GetExtKeyFriends($sClass, $sExtKeyAttCode)
  741. {
  742. if (array_key_exists($sExtKeyAttCode, self::$m_aExtKeyFriends[$sClass]))
  743. {
  744. return self::$m_aExtKeyFriends[$sClass][$sExtKeyAttCode];
  745. }
  746. else
  747. {
  748. return array();
  749. }
  750. }
  751. protected static $m_aTrackForwardCache = array();
  752. /**
  753. * List external keys for which there is a LinkSet (direct or indirect) on the other end
  754. * For those external keys, a change will have a special meaning on the other end
  755. * in term of change tracking
  756. */
  757. final static public function GetTrackForwardExternalKeys($sClass)
  758. {
  759. if (!isset(self::$m_aTrackForwardCache[$sClass]))
  760. {
  761. $aRes = array();
  762. foreach (MetaModel::GetExternalKeys($sClass) as $sAttCode => $oAttDef)
  763. {
  764. $sRemoteClass = $oAttDef->GetTargetClass();
  765. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  766. {
  767. if (!$oRemoteAttDef->IsLinkSet()) continue;
  768. if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass) continue;
  769. if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode) continue;
  770. $aRes[$sAttCode] = $oRemoteAttDef;
  771. }
  772. }
  773. self::$m_aTrackForwardCache[$sClass] = $aRes;
  774. }
  775. return self::$m_aTrackForwardCache[$sClass];
  776. }
  777. final static public function ListMetaAttributes($sClass, $sAttCode)
  778. {
  779. if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode]))
  780. {
  781. $aRet = self::$m_aEnumToMeta[$sClass][$sAttCode];
  782. }
  783. else
  784. {
  785. $aRet = array();
  786. }
  787. return $aRet;
  788. }
  789. /**
  790. * Get the attribute label
  791. * @param string sClass Persistent class
  792. * @param string sAttCodeEx Extended attribute code: attcode[->attcode]
  793. * @param bool $bShowMandatory If true, add a star character (at the end or before the ->) to show that the field is mandatory
  794. * @return string A user friendly format of the string: AttributeName or AttributeName->ExtAttributeName
  795. */
  796. public static function GetLabel($sClass, $sAttCodeEx, $bShowMandatory = false)
  797. {
  798. $sLabel = '';
  799. if (($iPos = strpos($sAttCodeEx, '->')) === false)
  800. {
  801. if ($sAttCodeEx == 'id')
  802. {
  803. $sLabel = Dict::S('UI:CSVImport:idField');
  804. }
  805. else
  806. {
  807. $oAttDef = self::GetAttributeDef($sClass, $sAttCodeEx);
  808. $sMandatory = ($bShowMandatory && !$oAttDef->IsNullAllowed()) ? '*' : '';
  809. $sLabel = $oAttDef->GetLabel().$sMandatory;
  810. }
  811. }
  812. else
  813. {
  814. $sExtKeyAttCode = substr($sAttCodeEx, 0, $iPos);
  815. $sRemoteAttCode = substr($sAttCodeEx, $iPos + 2);
  816. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  817. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  818. // Recurse
  819. $sLabel = self::GetLabel($sClass, $sExtKeyAttCode).'->'.self::GetLabel($sRemoteClass, $sRemoteAttCode);
  820. }
  821. return $sLabel;
  822. }
  823. public static function GetDescription($sClass, $sAttCode)
  824. {
  825. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  826. if ($oAttDef) return $oAttDef->GetDescription();
  827. return "";
  828. }
  829. // Filters of a given class may contain filters defined in a parent class
  830. // - Some filters are a copy of the definition
  831. // - Some filters correspond to the upper class table definition (compound objects)
  832. // (see also attributes definition)
  833. private static $m_aFilterDefs = array(); // array of ("classname" => array filterdef)
  834. private static $m_aFilterOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  835. public static function GetClassFilterDefs($sClass)
  836. {
  837. self::_check_subclass($sClass);
  838. return self::$m_aFilterDefs[$sClass];
  839. }
  840. final static public function GetClassFilterDef($sClass, $sFilterCode)
  841. {
  842. self::_check_subclass($sClass);
  843. if (!array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]))
  844. {
  845. throw new CoreException("Unknown filter code '$sFilterCode' for class '$sClass'");
  846. }
  847. return self::$m_aFilterDefs[$sClass][$sFilterCode];
  848. }
  849. public static function GetFilterLabel($sClass, $sFilterCode)
  850. {
  851. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  852. if ($oFilter) return $oFilter->GetLabel();
  853. return "";
  854. }
  855. public static function GetFilterDescription($sClass, $sFilterCode)
  856. {
  857. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  858. if ($oFilter) return $oFilter->GetDescription();
  859. return "";
  860. }
  861. // returns an array of opcode=>oplabel (e.g. "differs from")
  862. public static function GetFilterOperators($sClass, $sFilterCode)
  863. {
  864. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  865. if ($oFilter) return $oFilter->GetOperators();
  866. return array();
  867. }
  868. // returns an opcode
  869. public static function GetFilterLooseOperator($sClass, $sFilterCode)
  870. {
  871. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  872. if ($oFilter) return $oFilter->GetLooseOperator();
  873. return array();
  874. }
  875. public static function GetFilterOpDescription($sClass, $sFilterCode, $sOpCode)
  876. {
  877. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  878. if ($oFilter) return $oFilter->GetOpDescription($sOpCode);
  879. return "";
  880. }
  881. public static function GetFilterHTMLInput($sFilterCode)
  882. {
  883. return "<INPUT name=\"$sFilterCode\">";
  884. }
  885. // Lists of attributes/search filters
  886. //
  887. private static $m_aListInfos = array(); // array of ("listcode" => various info on the list, common to every classes)
  888. private static $m_aListData = array(); // array of ("classname" => array of "listcode" => list)
  889. // list may be an array of attcode / fltcode
  890. // list may be an array of "groupname" => (array of attcode / fltcode)
  891. public static function EnumZLists()
  892. {
  893. return array_keys(self::$m_aListInfos);
  894. }
  895. final static public function GetZListInfo($sListCode)
  896. {
  897. return self::$m_aListInfos[$sListCode];
  898. }
  899. public static function GetZListItems($sClass, $sListCode)
  900. {
  901. if (array_key_exists($sClass, self::$m_aListData))
  902. {
  903. if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
  904. {
  905. return self::$m_aListData[$sClass][$sListCode];
  906. }
  907. }
  908. $sParentClass = self::GetParentPersistentClass($sClass);
  909. if (empty($sParentClass)) return array(); // nothing for the mother of all classes
  910. // Dig recursively
  911. return self::GetZListItems($sParentClass, $sListCode);
  912. }
  913. public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
  914. {
  915. $aZList = self::FlattenZlist(self::GetZListItems($sClass, $sListCode));
  916. if (!$sGroup)
  917. {
  918. return (in_array($sAttCodeOrFltCode, $aZList));
  919. }
  920. return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
  921. }
  922. //
  923. // Relations
  924. //
  925. private static $m_aRelationInfos = array(); // array of ("relcode" => various info on the list, common to every classes)
  926. /**
  927. * TO BE DEPRECATED: use EnumRelationsEx instead
  928. * @param string $sClass
  929. * @return multitype:string unknown |Ambigous <string, multitype:>
  930. */
  931. public static function EnumRelations($sClass = '')
  932. {
  933. $aResult = array_keys(self::$m_aRelationInfos);
  934. if (!empty($sClass))
  935. {
  936. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  937. // for the specified class
  938. $aClassRelations = array();
  939. foreach($aResult as $sRelCode)
  940. {
  941. $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode);
  942. if (count($aQueriesDown) > 0)
  943. {
  944. $aClassRelations[] = $sRelCode;
  945. }
  946. // Temporary patch: until the impact analysis GUI gets rewritten,
  947. // let's consider that "depends on" is equivalent to "impacts/up"
  948. // The current patch has been implemented in DBObject and MetaModel
  949. if ($sRelCode == 'impacts')
  950. {
  951. $aQueriesUp = self::EnumRelationQueries($sClass, 'impacts', false);
  952. if (count($aQueriesUp) > 0)
  953. {
  954. $aClassRelations[] = 'depends on';
  955. }
  956. }
  957. }
  958. return $aClassRelations;
  959. }
  960. // Temporary patch: until the impact analysis GUI gets rewritten,
  961. // let's consider that "depends on" is equivalent to "impacts/up"
  962. // The current patch has been implemented in DBObject and MetaModel
  963. if (in_array('impacts', $aResult))
  964. {
  965. $aResult[] = 'depends on';
  966. }
  967. return $aResult;
  968. }
  969. public static function EnumRelationsEx($sClass)
  970. {
  971. $aRelationInfo = array_keys(self::$m_aRelationInfos);
  972. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  973. // for the specified class
  974. $aClassRelations = array();
  975. foreach($aRelationInfo as $sRelCode)
  976. {
  977. $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode, true /* Down */);
  978. if (count($aQueriesDown) > 0)
  979. {
  980. $aClassRelations[$sRelCode]['down'] = self::GetRelationLabel($sRelCode, true);
  981. }
  982. $aQueriesUp = self::EnumRelationQueries($sClass, $sRelCode, false /* Up */);
  983. if (count($aQueriesUp) > 0)
  984. {
  985. $aClassRelations[$sRelCode]['up'] = self::GetRelationLabel($sRelCode, false);
  986. }
  987. }
  988. return $aClassRelations;
  989. }
  990. final static public function GetRelationDescription($sRelCode)
  991. {
  992. return Dict::S("Relation:$sRelCode/Description");
  993. }
  994. final static public function GetRelationLabel($sRelCode, $bDown = true)
  995. {
  996. if ($bDown)
  997. {
  998. // The legacy convention is confusing with regard to the way we have conceptualized the relations:
  999. // In the former representation, the main stream was named after "up"
  1000. // Now, the relation from A to B says that something is transmitted from A to B, thus going DOWNstream as described in a petri net.
  1001. $sKey = "Relation:$sRelCode/DownStream";
  1002. $sLegacy = Dict::S("Relation:$sRelCode/VerbUp", $sKey);
  1003. }
  1004. else
  1005. {
  1006. $sKey = "Relation:$sRelCode/UpStream";
  1007. $sLegacy = Dict::S("Relation:$sRelCode/VerbDown", $sKey);
  1008. }
  1009. $sRet = Dict::S($sKey, $sLegacy);
  1010. return $sRet;
  1011. }
  1012. protected static function ComputeRelationQueries($sRelCode)
  1013. {
  1014. $bHasLegacy = false;
  1015. $aQueries = array();
  1016. foreach (self::GetClasses() as $sClass)
  1017. {
  1018. $aQueries[$sClass]['down'] = array();
  1019. if (!array_key_exists('up', $aQueries[$sClass]))
  1020. {
  1021. $aQueries[$sClass]['up'] = array();
  1022. }
  1023. $aNeighboursDown = call_user_func_array(array($sClass, 'GetRelationQueriesEx'), array($sRelCode));
  1024. // Translate attributes into queries (new style of spec only)
  1025. foreach($aNeighboursDown as $sNeighbourId => $aNeighbourData)
  1026. {
  1027. $aNeighbourData['sFromClass'] = $aNeighbourData['sDefinedInClass'];
  1028. try
  1029. {
  1030. if (strlen($aNeighbourData['sQueryDown']) == 0)
  1031. {
  1032. $oAttDef = self::GetAttributeDef($sClass, $aNeighbourData['sAttribute']);
  1033. if ($oAttDef instanceof AttributeExternalKey)
  1034. {
  1035. $sTargetClass = $oAttDef->GetTargetClass();
  1036. $aNeighbourData['sToClass'] = $sTargetClass;
  1037. $aNeighbourData['sQueryDown'] = 'SELECT '.$sTargetClass.' AS o WHERE o.id = :this->'.$aNeighbourData['sAttribute'];
  1038. $aNeighbourData['sQueryUp'] = 'SELECT '.$aNeighbourData['sFromClass'].' AS o WHERE o.'.$aNeighbourData['sAttribute'].' = :this->id';
  1039. }
  1040. elseif ($oAttDef instanceof AttributeLinkedSet)
  1041. {
  1042. $sLinkedClass = $oAttDef->GetLinkedClass();
  1043. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1044. if ($oAttDef->IsIndirect())
  1045. {
  1046. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  1047. $oRemoteAttDef = self::GetAttributeDef($sLinkedClass, $sExtKeyToRemote);
  1048. $sRemoteClass = $oRemoteAttDef->GetTargetClass();
  1049. $aNeighbourData['sToClass'] = $sRemoteClass;
  1050. $aNeighbourData['sQueryDown'] = "SELECT $sRemoteClass AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToRemote = o.id WHERE lnk.$sExtKeyToMe = :this->id";
  1051. $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToMe = o.id WHERE lnk.$sExtKeyToRemote = :this->id";
  1052. }
  1053. else
  1054. {
  1055. $aNeighbourData['sToClass'] = $sLinkedClass;
  1056. $aNeighbourData['sQueryDown'] = "SELECT $sLinkedClass AS o WHERE o.$sExtKeyToMe = :this->id";
  1057. $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o WHERE o.id = :this->$sExtKeyToMe";
  1058. }
  1059. }
  1060. else
  1061. {
  1062. throw new Exception("Unexpected attribute type for '{$aNeighbourData['sAttribute']}'. Expecting a link set or external key.");
  1063. }
  1064. }
  1065. else
  1066. {
  1067. $oSearch = DBObjectSearch::FromOQL($aNeighbourData['sQueryDown']);
  1068. $aNeighbourData['sToClass'] = $oSearch->GetClass();
  1069. }
  1070. }
  1071. catch (Exception $e)
  1072. {
  1073. throw new Exception("Wrong definition for the relation $sRelCode/{$aNeighbourData['sDefinedInClass']}/{$aNeighbourData['sNeighbour']}: ".$e->getMessage());
  1074. }
  1075. if ($aNeighbourData['sDirection'] == 'down')
  1076. {
  1077. $aNeighbourData['sQueryUp'] = null;
  1078. }
  1079. $sArrowId = $aNeighbourData['sDefinedInClass'].'_'.$sNeighbourId;
  1080. $aQueries[$sClass]['down'][$sArrowId] = $aNeighbourData;
  1081. // Compute the reverse index
  1082. if ($aNeighbourData['sDefinedInClass'] == $sClass)
  1083. {
  1084. if ($aNeighbourData['sDirection'] == 'both')
  1085. {
  1086. $sFromClass = $aNeighbourData['sFromClass'];
  1087. $sToClass = $aNeighbourData['sToClass'];
  1088. foreach (self::EnumChildClasses($sToClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  1089. {
  1090. $aQueries[$sSubClass]['up'][$sArrowId] = $aNeighbourData;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. // Read legacy definitions
  1096. // The up/down queries have to be reconcilied, which can only be done later when all the classes have been browsed
  1097. //
  1098. // The keys used to store a query (up or down) into the array are built differently between the modern and legacy made data:
  1099. // Modern way: aQueries[sClass]['up'|'down'][sArrowId], where sArrowId is made of the source class + neighbour id (XML def)
  1100. // Legacy way: aQueries[sClass]['up'|'down'][sRemoteClass]
  1101. // The modern way does allow for several arrows between two classes
  1102. // The legacy way aims at simplifying the transformation (reconciliation between up and down)
  1103. if ($sRelCode == 'impacts')
  1104. {
  1105. $sRevertCode = 'depends on';
  1106. $aLegacy = call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRelCode));
  1107. foreach($aLegacy as $sId => $aLegacyEntry)
  1108. {
  1109. $bHasLegacy = true;
  1110. $oFilter = DBObjectSearch::FromOQL($aLegacyEntry['sQuery']);
  1111. $sRemoteClass = $oFilter->GetClass();
  1112. // Determine wether the query is inherited from a parent or not
  1113. $bInherited = false;
  1114. foreach (self::EnumParentClasses($sClass) as $sParent)
  1115. {
  1116. if (!isset($aQueries[$sParent]['down'][$sRemoteClass])) continue;
  1117. if ($aLegacyEntry['sQuery'] == $aQueries[$sParent]['down'][$sRemoteClass]['sQueryDown'])
  1118. {
  1119. $bInherited = true;
  1120. $aQueries[$sClass]['down'][$sRemoteClass] = $aQueries[$sParent]['down'][$sRemoteClass];
  1121. break;
  1122. }
  1123. }
  1124. if (!$bInherited)
  1125. {
  1126. $aQueries[$sClass]['down'][$sRemoteClass] = array(
  1127. '_legacy_' => true,
  1128. 'sDefinedInClass' => $sClass,
  1129. 'sFromClass' => $sClass,
  1130. 'sToClass' => $sRemoteClass,
  1131. 'sDirection' => 'down',
  1132. 'sQueryDown' => $aLegacyEntry['sQuery'],
  1133. 'sQueryUp' => null,
  1134. 'sNeighbour' => $sRemoteClass // Normalize the neighbour id
  1135. );
  1136. }
  1137. }
  1138. $aLegacy = call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRevertCode));
  1139. foreach($aLegacy as $sId => $aLegacyEntry)
  1140. {
  1141. $bHasLegacy = true;
  1142. $oFilter = DBObjectSearch::FromOQL($aLegacyEntry['sQuery']);
  1143. $sRemoteClass = $oFilter->GetClass();
  1144. // Determine wether the query is inherited from a parent or not
  1145. $bInherited = false;
  1146. foreach (self::EnumParentClasses($sClass) as $sParent)
  1147. {
  1148. if (!isset($aQueries[$sParent]['up'][$sRemoteClass])) continue;
  1149. if ($aLegacyEntry['sQuery'] == $aQueries[$sParent]['up'][$sRemoteClass]['sQueryUp'])
  1150. {
  1151. $bInherited = true;
  1152. $aQueries[$sClass]['up'][$sRemoteClass] = $aQueries[$sParent]['up'][$sRemoteClass];
  1153. break;
  1154. }
  1155. }
  1156. if (!$bInherited)
  1157. {
  1158. $aQueries[$sClass]['up'][$sRemoteClass] = array(
  1159. '_legacy_' => true,
  1160. 'sDefinedInClass' => $sRemoteClass,
  1161. 'sFromClass' => $sRemoteClass,
  1162. 'sToClass' => $sClass,
  1163. 'sDirection' => 'both',
  1164. 'sQueryDown' => null,
  1165. 'sQueryUp' => $aLegacyEntry['sQuery'],
  1166. 'sNeighbour' => $sClass// Normalize the neighbour id
  1167. );
  1168. }
  1169. }
  1170. }
  1171. else
  1172. {
  1173. // Cannot take the legacy system into account... simply ignore it
  1174. }
  1175. } // foreach class
  1176. // Perform the up/down reconciliation for the legacy definitions
  1177. if ($bHasLegacy)
  1178. {
  1179. foreach (self::GetClasses() as $sClass)
  1180. {
  1181. // Foreach "up" legacy query, update its "down" counterpart
  1182. if (isset($aQueries[$sClass]['up']))
  1183. {
  1184. foreach ($aQueries[$sClass]['up'] as $sNeighbourId => $aNeighbourData)
  1185. {
  1186. if (!array_key_exists('_legacy_', $aNeighbourData))
  1187. {
  1188. continue;
  1189. }
  1190. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1191. $sLocalClass = $aNeighbourData['sToClass'];
  1192. foreach (self::EnumChildClasses($aNeighbourData['sFromClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1193. {
  1194. if (isset($aQueries[$sRemoteClass]['down'][$sLocalClass]))
  1195. {
  1196. $aQueries[$sRemoteClass]['down'][$sLocalClass]['sQueryUp'] = $aNeighbourData['sQueryUp'];
  1197. $aQueries[$sRemoteClass]['down'][$sLocalClass]['sDirection'] = 'both';
  1198. }
  1199. // Be silent in order to transparently support legacy data models where the counterpart query does not always exist
  1200. //else
  1201. //{
  1202. // throw new Exception("Legacy definition of the relation '$sRelCode/$sRevertCode', defined on $sLocalClass (relation: $sRevertCode, inherited to $sClass), missing the counterpart query on class $sRemoteClass ($sRelCode)");
  1203. //}
  1204. }
  1205. }
  1206. }
  1207. // Foreach "down" legacy query, update its "up" counterpart (if any)
  1208. foreach ($aQueries[$sClass]['down'] as $sNeighbourId => $aNeighbourData)
  1209. {
  1210. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1211. $sLocalClass = $aNeighbourData['sFromClass'];
  1212. foreach (self::EnumChildClasses($aNeighbourData['sToClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1213. {
  1214. if (isset($aQueries[$sRemoteClass]['up'][$sLocalClass]))
  1215. {
  1216. $aQueries[$sRemoteClass]['up'][$sLocalClass]['sQueryDown'] = $aNeighbourData['sQueryDown'];
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. return $aQueries;
  1223. }
  1224. public static function EnumRelationQueries($sClass, $sRelCode, $bDown = true)
  1225. {
  1226. static $aQueries = array();
  1227. if (!isset($aQueries[$sRelCode]))
  1228. {
  1229. $aQueries[$sRelCode] = self::ComputeRelationQueries($sRelCode);
  1230. }
  1231. $sDirection = $bDown ? 'down' : 'up';
  1232. if (isset($aQueries[$sRelCode][$sClass][$sDirection]))
  1233. {
  1234. return $aQueries[$sRelCode][$sClass][$sDirection];
  1235. }
  1236. else
  1237. {
  1238. return array();
  1239. }
  1240. }
  1241. /**
  1242. * Compute the "RelatedObjects" for a whole set of DBObjects
  1243. *
  1244. * @param string $sRelCode The code of the relation to use for the computation
  1245. * @param array $asourceObjects The objects to start with
  1246. * @param int $iMaxDepth
  1247. * @param boolean $bEnableReduncancy
  1248. * @param array $aUnreachable Array of objects to be considered as 'unreachable'
  1249. *
  1250. * @return RelationGraph The graph of all the related objects
  1251. */
  1252. static public function GetRelatedObjectsDown($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aUnreachable = array(), $aContexts = array())
  1253. {
  1254. $oGraph = new RelationGraph();
  1255. foreach ($aSourceObjects as $oObject)
  1256. {
  1257. $oGraph->AddSourceObject($oObject);
  1258. }
  1259. foreach($aContexts as $key => $sOQL)
  1260. {
  1261. $oGraph->AddContextQuery($key, $sOQL);
  1262. }
  1263. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy, $aUnreachable);
  1264. return $oGraph;
  1265. }
  1266. /**
  1267. * Compute the "RelatedObjects" in the reverse way
  1268. *
  1269. * @param string $sRelCode The code of the relation to use for the computation
  1270. * @param array $asourceObjects The objects to start with
  1271. * @param int $iMaxDepth
  1272. * @param boolean $bEnableReduncancy
  1273. *
  1274. * @return RelationGraph The graph of all the related objects
  1275. */
  1276. static public function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aContexts = array())
  1277. {
  1278. $oGraph = new RelationGraph();
  1279. foreach ($aSourceObjects as $oObject)
  1280. {
  1281. $oGraph->AddSinkObject($oObject);
  1282. }
  1283. foreach($aContexts as $key => $sOQL)
  1284. {
  1285. $oGraph->AddContextQuery($key, $sOQL);
  1286. }
  1287. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  1288. return $oGraph;
  1289. }
  1290. //
  1291. // Object lifecycle model
  1292. //
  1293. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  1294. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  1295. private static $m_aTransitions = array(); // array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
  1296. public static function EnumStates($sClass)
  1297. {
  1298. if (array_key_exists($sClass, self::$m_aStates))
  1299. {
  1300. return self::$m_aStates[$sClass];
  1301. }
  1302. else
  1303. {
  1304. return array();
  1305. }
  1306. }
  1307. /*
  1308. * Enumerate all possible initial states, including the default one
  1309. */
  1310. public static function EnumInitialStates($sClass)
  1311. {
  1312. if (array_key_exists($sClass, self::$m_aStates))
  1313. {
  1314. $aRet = array();
  1315. // Add the states for which the flag 'is_initial_state' is set to <true>
  1316. foreach(self::$m_aStates[$sClass] as $aStateCode => $aProps)
  1317. {
  1318. if (isset($aProps['initial_state_path']))
  1319. {
  1320. $aRet[$aStateCode] = $aProps['initial_state_path'];
  1321. }
  1322. }
  1323. // Add the default initial state
  1324. $sMainInitialState = self::GetDefaultState($sClass);
  1325. if (!isset($aRet[$sMainInitialState]))
  1326. {
  1327. $aRet[$sMainInitialState] = array();
  1328. }
  1329. return $aRet;
  1330. }
  1331. else
  1332. {
  1333. return array();
  1334. }
  1335. }
  1336. public static function EnumStimuli($sClass)
  1337. {
  1338. if (array_key_exists($sClass, self::$m_aStimuli))
  1339. {
  1340. return self::$m_aStimuli[$sClass];
  1341. }
  1342. else
  1343. {
  1344. return array();
  1345. }
  1346. }
  1347. public static function GetStateLabel($sClass, $sStateValue)
  1348. {
  1349. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1350. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1351. return $oAttDef->GetValueLabel($sStateValue);
  1352. }
  1353. public static function GetStateDescription($sClass, $sStateValue)
  1354. {
  1355. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1356. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1357. return $oAttDef->GetValueDescription($sStateValue);
  1358. }
  1359. public static function EnumTransitions($sClass, $sStateCode)
  1360. {
  1361. if (array_key_exists($sClass, self::$m_aTransitions))
  1362. {
  1363. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  1364. {
  1365. return self::$m_aTransitions[$sClass][$sStateCode];
  1366. }
  1367. }
  1368. return array();
  1369. }
  1370. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  1371. {
  1372. $iFlags = 0; // By default (if no life cycle) no flag at all
  1373. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1374. if (!empty($sStateAttCode))
  1375. {
  1376. $aStates = MetaModel::EnumStates($sClass);
  1377. if (!array_key_exists($sState, $aStates))
  1378. {
  1379. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  1380. }
  1381. $aCurrentState = $aStates[$sState];
  1382. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  1383. {
  1384. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  1385. }
  1386. }
  1387. return $iFlags;
  1388. }
  1389. /**
  1390. * Returns the $sAttCode flags when $sStimulus is applied on an object of $sClass in the $sState state.
  1391. * Note: This does NOT combine flags from the target state.
  1392. *
  1393. * @param $sClass string
  1394. * @param $sState string
  1395. * @param $sStimulus string
  1396. * @param $sAttCode string
  1397. * @return int
  1398. * @throws CoreException
  1399. */
  1400. public static function GetTransitionFlags($sClass, $sState, $sStimulus, $sAttCode)
  1401. {
  1402. $iFlags = 0; // By default (if no lifecycle) no flag at all
  1403. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1404. if (!empty($sStateAttCode))
  1405. {
  1406. $aTransitions = MetaModel::EnumTransitions($sClass, $sState);
  1407. if(!array_key_exists($sStimulus, $aTransitions))
  1408. {
  1409. throw new CoreException("Invalid transition '$sStimulus' for class '$sClass', expecting a value in {".implode(', ', array_keys($aTransitions))."}");
  1410. }
  1411. $aCurrentTransition = $aTransitions[$sStimulus];
  1412. if( (array_key_exists('attribute_list', $aCurrentTransition)) && (array_key_exists($sAttCode, $aCurrentTransition['attribute_list'])) )
  1413. {
  1414. $iFlags = $aCurrentTransition['attribute_list'][$sAttCode];
  1415. }
  1416. }
  1417. return $iFlags;
  1418. }
  1419. /**
  1420. * Returns an array of attribute codes (with their flags) when $sStimulus is applied on an object of $sClass in the $sOriginState state.
  1421. * Note: Attributes (and flags) from the target state and the transition are combined.
  1422. *
  1423. * @param $sClass string Object class
  1424. * @param $sStimulus string Stimulus code applied
  1425. * @param $sOriginState string State the stimulus comes from
  1426. * @return array
  1427. */
  1428. public static function GetTransitionAttributes($sClass, $sStimulus, $sOriginState)
  1429. {
  1430. $aAttributes = array();
  1431. // Retrieving target state
  1432. $aTransitions = MetaModel::EnumTransitions($sClass, $sOriginState);
  1433. $aTransition = $aTransitions[$sStimulus];
  1434. $sTargetState = $aTransition['target_state'];
  1435. // Retrieving attributes from state
  1436. $aStates = MetaModel::EnumStates($sClass);
  1437. $aTargetState = $aStates[$sTargetState];
  1438. $aTargetStateAttributes = $aTargetState['attribute_list'];
  1439. // - Merging with results
  1440. $aAttributes = $aTargetStateAttributes;
  1441. // Retrieving attributes from transition
  1442. $aTransitionAttributes = $aTransition['attribute_list'];
  1443. // - Merging with results
  1444. foreach($aTransitionAttributes as $sAttCode => $iAttributeFlags)
  1445. {
  1446. if(array_key_exists($sAttCode, $aAttributes))
  1447. {
  1448. $aAttributes[$sAttCode] = $aAttributes[$sAttCode] | $iAttributeFlags;
  1449. }
  1450. else
  1451. {
  1452. $aAttributes[$sAttCode] = $iAttributeFlags;
  1453. }
  1454. }
  1455. return $aAttributes;
  1456. }
  1457. /**
  1458. * Combines the flags from the all states that compose the initial_state_path
  1459. */
  1460. public static function GetInitialStateAttributeFlags($sClass, $sState, $sAttCode)
  1461. {
  1462. $iFlags = self::GetAttributeFlags($sClass, $sState, $sAttCode); // Be default set the same flags as the 'target' state
  1463. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1464. if (!empty($sStateAttCode))
  1465. {
  1466. $aStates = MetaModel::EnumInitialStates($sClass);
  1467. if (array_key_exists($sState, $aStates))
  1468. {
  1469. $bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY);
  1470. $bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN);
  1471. foreach($aStates[$sState] as $sPrevState)
  1472. {
  1473. $iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode);
  1474. if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN)
  1475. {
  1476. $bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not
  1477. }
  1478. $bHidden = $bHidden && (($iPrevFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN); // if it is/was not hidden => then it's not
  1479. }
  1480. if ($bReadOnly)
  1481. {
  1482. $iFlags = $iFlags | OPT_ATT_READONLY;
  1483. }
  1484. else
  1485. {
  1486. $iFlags = $iFlags & ~OPT_ATT_READONLY;
  1487. }
  1488. if ($bHidden)
  1489. {
  1490. $iFlags = $iFlags | OPT_ATT_HIDDEN;
  1491. }
  1492. else
  1493. {
  1494. $iFlags = $iFlags & ~OPT_ATT_HIDDEN;
  1495. }
  1496. }
  1497. }
  1498. return $iFlags;
  1499. }
  1500. //
  1501. // Allowed values
  1502. //
  1503. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1504. {
  1505. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1506. return $oAttDef->GetAllowedValues($aArgs, $sContains);
  1507. }
  1508. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sContains = '')
  1509. {
  1510. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  1511. return $oFltDef->GetAllowedValues($aArgs, $sContains);
  1512. }
  1513. public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1514. {
  1515. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1516. return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains);
  1517. }
  1518. //
  1519. // Businezz model declaration verbs (should be static)
  1520. //
  1521. public static function RegisterZList($sListCode, $aListInfo)
  1522. {
  1523. // Check mandatory params
  1524. $aMandatParams = array(
  1525. "description" => "detailed (though one line) description of the list",
  1526. "type" => "attributes | filters",
  1527. );
  1528. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1529. {
  1530. if (!array_key_exists($sParamName, $aListInfo))
  1531. {
  1532. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  1533. }
  1534. }
  1535. self::$m_aListInfos[$sListCode] = $aListInfo;
  1536. }
  1537. public static function RegisterRelation($sRelCode)
  1538. {
  1539. // Each item used to be an array of properties...
  1540. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  1541. }
  1542. // Must be called once and only once...
  1543. public static function InitClasses($sTablePrefix)
  1544. {
  1545. if (count(self::GetClasses()) > 0)
  1546. {
  1547. throw new CoreException("InitClasses should not be called more than once -skipped");
  1548. return;
  1549. }
  1550. self::$m_sTablePrefix = $sTablePrefix;
  1551. // Build the list of available extensions
  1552. //
  1553. $aInterfaces = array('iApplicationUIExtension', 'iApplicationObjectExtension', 'iQueryModifier', 'iOnClassInitialization', 'iPopupMenuExtension', 'iPageUIExtension');
  1554. foreach($aInterfaces as $sInterface)
  1555. {
  1556. self::$m_aExtensionClasses[$sInterface] = array();
  1557. }
  1558. foreach(get_declared_classes() as $sPHPClass)
  1559. {
  1560. $oRefClass = new ReflectionClass($sPHPClass);
  1561. $oExtensionInstance = null;
  1562. foreach($aInterfaces as $sInterface)
  1563. {
  1564. if ($oRefClass->implementsInterface($sInterface) && $oRefClass->isInstantiable())
  1565. {
  1566. if (is_null($oExtensionInstance))
  1567. {
  1568. $oExtensionInstance = new $sPHPClass;
  1569. }
  1570. self::$m_aExtensionClasses[$sInterface][$sPHPClass] = $oExtensionInstance;
  1571. }
  1572. }
  1573. }
  1574. // Initialize the classes (declared attributes, etc.)
  1575. //
  1576. foreach(get_declared_classes() as $sPHPClass)
  1577. {
  1578. if (is_subclass_of($sPHPClass, 'DBObject'))
  1579. {
  1580. $sParent = get_parent_class($sPHPClass);
  1581. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  1582. {
  1583. // Inherit info about attributes to ignore
  1584. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  1585. }
  1586. try
  1587. {
  1588. $oMethod = new ReflectionMethod($sPHPClass, 'Init');
  1589. if ($oMethod->getDeclaringClass()->name == $sPHPClass)
  1590. {
  1591. call_user_func(array($sPHPClass, 'Init'));
  1592. foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit)
  1593. {
  1594. $oClassInit->OnAfterClassInitialization($sPHPClass);
  1595. }
  1596. }
  1597. }
  1598. catch (ReflectionException $e)
  1599. {
  1600. // This class is only implementing methods, ignore it from the MetaModel perspective
  1601. }
  1602. }
  1603. }
  1604. // Add a 'class' attribute/filter to the root classes and their children
  1605. //
  1606. foreach(self::EnumRootClasses() as $sRootClass)
  1607. {
  1608. if (self::IsStandaloneClass($sRootClass)) continue;
  1609. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  1610. if (strlen($sDbFinalClassField) == 0)
  1611. {
  1612. $sDbFinalClassField = 'finalclass';
  1613. self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
  1614. }
  1615. $oClassAtt = new AttributeFinalClass('finalclass', array(
  1616. "sql"=>$sDbFinalClassField,
  1617. "default_value"=>$sRootClass,
  1618. "is_null_allowed"=>false,
  1619. "depends_on"=>array()
  1620. ));
  1621. $oClassAtt->SetHostClass($sRootClass);
  1622. self::$m_aAttribDefs[$sRootClass]['finalclass'] = $oClassAtt;
  1623. self::$m_aAttribOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1624. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1625. self::$m_aFilterDefs[$sRootClass]['finalclass'] = $oClassFlt;
  1626. self::$m_aFilterOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1627. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  1628. {
  1629. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  1630. {
  1631. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  1632. }
  1633. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  1634. {
  1635. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  1636. }
  1637. $oCloned = clone $oClassAtt;
  1638. $oCloned->SetHostClass($sChildClass);
  1639. $oCloned->SetFixedValue($sChildClass);
  1640. self::$m_aAttribDefs[$sChildClass]['finalclass'] = $oCloned;
  1641. self::$m_aAttribOrigins[$sChildClass]['finalclass'] = $sRootClass;
  1642. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1643. self::$m_aFilterDefs[$sChildClass]['finalclass'] = $oClassFlt;
  1644. self::$m_aFilterOrigins[$sChildClass]['finalclass'] = self::GetRootClass($sChildClass);
  1645. }
  1646. }
  1647. // Prepare external fields and filters
  1648. // Add final class to external keys
  1649. //
  1650. foreach (self::GetClasses() as $sClass)
  1651. {
  1652. // Create the friendly name attribute
  1653. $sFriendlyNameAttCode = 'friendlyname';
  1654. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, 'id');
  1655. $oFriendlyName->SetHostClass($sClass);
  1656. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1657. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1658. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1659. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1660. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1661. self::$m_aExtKeyFriends[$sClass] = array();
  1662. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  1663. {
  1664. // Compute the filter codes
  1665. //
  1666. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  1667. {
  1668. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  1669. if ($oAttDef->IsExternalField())
  1670. {
  1671. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1672. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1673. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  1674. }
  1675. else
  1676. {
  1677. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1678. }
  1679. }
  1680. // Compute the fields that will be used to display a pointer to another object
  1681. //
  1682. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  1683. {
  1684. // oAttDef is either
  1685. // - an external KEY / FIELD (direct),
  1686. // - an external field pointing to an external KEY / FIELD
  1687. // - an external field pointing to an external field pointing to....
  1688. $sRemoteClass = $oAttDef->GetTargetClass();
  1689. if ($oAttDef->IsExternalField())
  1690. {
  1691. // This is a key, but the value comes from elsewhere
  1692. // Create an external field pointing to the remote friendly name attribute
  1693. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1694. $sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname";
  1695. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1696. // propagate "is_null_allowed" ?
  1697. $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values"=>null, "extkey_attcode"=>$sKeyAttCode, "target_attcode"=>$sRemoteAttCode, "depends_on"=>array()));
  1698. $oFriendlyName->SetHostClass($sClass);
  1699. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1700. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1701. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1702. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1703. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = self::$m_aFilterOrigins[$sClass][$sKeyAttCode];
  1704. }
  1705. else
  1706. {
  1707. // Create the friendly name attribute
  1708. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1709. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, $sAttCode);
  1710. $oFriendlyName->SetHostClass($sClass);
  1711. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1712. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1713. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1714. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1715. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = self::$m_aFilterOrigins[$sClass][$sAttCode];
  1716. if (self::HasChildrenClasses($sRemoteClass))
  1717. {
  1718. // First, create an external field attribute, that gets the final class
  1719. $sClassRecallAttCode = $sAttCode.'_finalclass_recall';
  1720. $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
  1721. "allowed_values"=>null,
  1722. "extkey_attcode"=>$sAttCode,
  1723. "target_attcode"=>"finalclass",
  1724. "is_null_allowed"=>true,
  1725. "depends_on"=>array()
  1726. ));
  1727. $oClassRecall->SetHostClass($sClass);
  1728. self::$m_aAttribDefs[$sClass][$sClassRecallAttCode] = $oClassRecall;
  1729. self::$m_aAttribOrigins[$sClass][$sClassRecallAttCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1730. $oClassFlt = new FilterFromAttribute($oClassRecall);
  1731. self::$m_aFilterDefs[$sClass][$sClassRecallAttCode] = $oClassFlt;
  1732. self::$m_aFilterOrigins[$sClass][$sClassRecallAttCode] = self::$m_aFilterOrigins[$sClass][$sAttCode];
  1733. // Add it to the ZLists where the external key is present
  1734. //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
  1735. $sListCode = 'list';
  1736. if (isset(self::$m_aListData[$sClass][$sListCode]))
  1737. {
  1738. $aAttributes = self::$m_aListData[$sClass][$sListCode];
  1739. // temporary.... no loop
  1740. {
  1741. if (in_array($sAttCode, $aAttributes))
  1742. {
  1743. $aNewList = array();
  1744. foreach($aAttributes as $iPos => $sAttToDisplay)
  1745. {
  1746. if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
  1747. {
  1748. // Insert the final class right before
  1749. $aNewList[] = $sClassRecallAttCode;
  1750. }
  1751. $aNewList[] = $sAttToDisplay;
  1752. }
  1753. self::$m_aListData[$sClass][$sListCode] = $aNewList;
  1754. }
  1755. }
  1756. }
  1757. }
  1758. }
  1759. // Get the real external key attribute
  1760. // It will be our reference to determine the other ext fields related to the same ext key
  1761. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1762. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  1763. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  1764. {
  1765. // skip : those extfields will be processed as external keys
  1766. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1767. // Note: I could not compare the objects by the mean of '==='
  1768. // because they are copied for the inheritance, and the internal references are NOT updated
  1769. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  1770. {
  1771. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  1772. }
  1773. }
  1774. }
  1775. if ($oAttDef instanceof AttributeMetaEnum)
  1776. {
  1777. $aMappingData = $oAttDef->GetMapRule($sClass);
  1778. if ($aMappingData != null)
  1779. {
  1780. $sEnumAttCode = $aMappingData['attcode'];
  1781. self::$m_aEnumToMeta[$sClass][$sEnumAttCode][$sAttCode] = $oAttDef;
  1782. }
  1783. }
  1784. }
  1785. // Add a 'id' filter
  1786. //
  1787. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  1788. {
  1789. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  1790. }
  1791. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  1792. {
  1793. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  1794. }
  1795. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  1796. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  1797. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  1798. // Define defaults values for the standard ZLists
  1799. //
  1800. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  1801. //{
  1802. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  1803. // {
  1804. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  1805. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  1806. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  1807. // }
  1808. //}
  1809. }
  1810. }
  1811. // To be overriden, must be called for any object class (optimization)
  1812. public static function Init()
  1813. {
  1814. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1815. }
  1816. // To be overloaded by biz model declarations
  1817. public static function GetRelationQueries($sRelCode)
  1818. {
  1819. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1820. return array();
  1821. }
  1822. public static function Init_Params($aParams)
  1823. {
  1824. // Check mandatory params
  1825. $aMandatParams = array(
  1826. "category" => "group classes by modules defining their visibility in the UI",
  1827. "key_type" => "autoincrement | string",
  1828. "name_attcode" => "define wich attribute is the class name, may be an array of attributes (format specified in the dictionary as 'Class:myclass/Name' => '%1\$s %2\$s...'",
  1829. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1830. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1831. "db_table" => "database table",
  1832. "db_key_field" => "database field which is the key",
  1833. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1834. );
  1835. $sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles);
  1836. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1837. {
  1838. if (!array_key_exists($sParamName, $aParams))
  1839. {
  1840. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1841. }
  1842. }
  1843. $aCategories = explode(',', $aParams['category']);
  1844. foreach ($aCategories as $sCategory)
  1845. {
  1846. self::$m_Category2Class[$sCategory][] = $sClass;
  1847. }
  1848. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1849. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1850. self::$m_aParentClasses[$sClass] = array();
  1851. self::$m_aChildClasses[$sClass] = array();
  1852. self::$m_aClassParams[$sClass]= $aParams;
  1853. self::$m_aAttribDefs[$sClass] = array();
  1854. self::$m_aAttribOrigins[$sClass] = array();
  1855. self::$m_aExtKeyFriends[$sClass] = array();
  1856. self::$m_aFilterDefs[$sClass] = array();
  1857. self::$m_aFilterOrigins[$sClass] = array();
  1858. }
  1859. protected static function object_array_mergeclone($aSource1, $aSource2)
  1860. {
  1861. $aRes = array();
  1862. foreach ($aSource1 as $key=>$object)
  1863. {
  1864. $aRes[$key] = clone $object;
  1865. }
  1866. foreach ($aSource2 as $key=>$object)
  1867. {
  1868. $aRes[$key] = clone $object;
  1869. }
  1870. return $aRes;
  1871. }
  1872. public static function Init_InheritAttributes($sSourceClass = null)
  1873. {
  1874. $sTargetClass = self::GetCallersPHPClass("Init");
  1875. if (empty($sSourceClass))
  1876. {
  1877. // Default: inherit from parent class
  1878. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1879. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1880. }
  1881. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1882. {
  1883. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1884. {
  1885. self::$m_aAttribDefs[$sTargetClass] = array();
  1886. self::$m_aAttribOrigins[$sTargetClass] = array();
  1887. }
  1888. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1889. foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1890. {
  1891. $oAttDef->SetHostClass($sTargetClass);
  1892. }
  1893. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1894. }
  1895. // Build root class information
  1896. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1897. {
  1898. // Inherit...
  1899. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1900. }
  1901. else
  1902. {
  1903. // This class will be the root class
  1904. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1905. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1906. }
  1907. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1908. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1909. // I am the child of each and every parent...
  1910. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1911. {
  1912. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1913. }
  1914. }
  1915. protected static function Init_IsKnownClass($sClass)
  1916. {
  1917. // Differs from self::IsValidClass()
  1918. // because it is being called before all the classes have been initialized
  1919. if (!class_exists($sClass)) return false;
  1920. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1921. return true;
  1922. }
  1923. public static function Init_AddAttribute(AttributeDefinition $oAtt, $sTargetClass = null)
  1924. {
  1925. if (!$sTargetClass)
  1926. {
  1927. $sTargetClass = self::GetCallersPHPClass("Init");
  1928. }
  1929. $sAttCode = $oAtt->GetCode();
  1930. if ($sAttCode == 'finalclass')
  1931. {
  1932. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1933. }
  1934. if ($sAttCode == 'friendlyname')
  1935. {
  1936. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1937. }
  1938. if (array_key_exists($sAttCode, self::$m_aAttribDefs[$sTargetClass]))
  1939. {
  1940. throw new Exception("Declaration of $sTargetClass: attempting to redeclare the inherited attribute '$sAttCode', originaly declared in ".self::$m_aAttribOrigins[$sTargetClass][$sAttCode]);
  1941. }
  1942. // Set the "host class" as soon as possible, since HierarchicalKeys use it for their 'target class' as well
  1943. // and this needs to be know early (for Init_IsKnowClass 19 lines below)
  1944. $oAtt->SetHostClass($sTargetClass);
  1945. // Some attributes could refer to a class
  1946. // declared in a module which is currently not installed/active
  1947. // We simply discard those attributes
  1948. //
  1949. if ($oAtt->IsLinkSet())
  1950. {
  1951. $sRemoteClass = $oAtt->GetLinkedClass();
  1952. if (!self::Init_IsKnownClass($sRemoteClass))
  1953. {
  1954. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1955. return;
  1956. }
  1957. }
  1958. elseif($oAtt->IsExternalKey())
  1959. {
  1960. $sRemoteClass = $oAtt->GetTargetClass();
  1961. if (!self::Init_IsKnownClass($sRemoteClass))
  1962. {
  1963. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1964. return;
  1965. }
  1966. }
  1967. elseif($oAtt->IsExternalField())
  1968. {
  1969. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  1970. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  1971. {
  1972. // The corresponding external key has already been ignored
  1973. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  1974. return;
  1975. }
  1976. // #@# todo - Check if the target attribute is still there
  1977. // this is not simple to implement because is involves
  1978. // several passes (the load order has a significant influence on that)
  1979. }
  1980. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  1981. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  1982. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1983. }
  1984. public static function Init_SetZListItems($sListCode, $aItems, $sTargetClass = null)
  1985. {
  1986. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  1987. if (!$sTargetClass)
  1988. {
  1989. $sTargetClass = self::GetCallersPHPClass("Init");
  1990. }
  1991. // Discard attributes that do not make sense
  1992. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  1993. //
  1994. self::Init_CheckZListItems($aItems, $sTargetClass);
  1995. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  1996. }
  1997. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  1998. {
  1999. foreach($aItems as $iFoo => $attCode)
  2000. {
  2001. if (is_array($attCode))
  2002. {
  2003. // Note: to make sure that the values will be updated recursively,
  2004. // do not pass $attCode, but $aItems[$iFoo] instead
  2005. self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass);
  2006. if (count($aItems[$iFoo]) == 0)
  2007. {
  2008. unset($aItems[$iFoo]);
  2009. }
  2010. }
  2011. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  2012. {
  2013. unset($aItems[$iFoo]);
  2014. }
  2015. }
  2016. }
  2017. public static function FlattenZList($aList)
  2018. {
  2019. $aResult = array();
  2020. foreach($aList as $value)
  2021. {
  2022. if (!is_array($value))
  2023. {
  2024. $aResult[] = $value;
  2025. }
  2026. else
  2027. {
  2028. $aResult = array_merge($aResult, self::FlattenZList($value));
  2029. }
  2030. }
  2031. return $aResult;
  2032. }
  2033. public static function Init_DefineState($sStateCode, $aStateDef)
  2034. {
  2035. $sTargetClass = self::GetCallersPHPClass("Init");
  2036. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  2037. $sParentState = $aStateDef['attribute_inherit'];
  2038. if (!empty($sParentState))
  2039. {
  2040. // Inherit from the given state (must be defined !)
  2041. //
  2042. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  2043. // Reset the constraint when it was mandatory to set the value at the previous state
  2044. //
  2045. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  2046. {
  2047. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  2048. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  2049. $aToInherit['attribute_list'][$sState] = $iFlags;
  2050. }
  2051. // The inherited configuration could be overriden
  2052. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  2053. }
  2054. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  2055. {
  2056. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  2057. {
  2058. unset($aStateDef['attribute_list'][$sAttCode]);
  2059. }
  2060. }
  2061. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  2062. // by default, create an empty set of transitions associated to that state
  2063. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  2064. }
  2065. public static function Init_DefineHighlightScale($aHighlightScale)
  2066. {
  2067. $sTargetClass = self::GetCallersPHPClass("Init");
  2068. self::$m_aHighlightScales[$sTargetClass] = $aHighlightScale;
  2069. }
  2070. public static function GetHighlightScale($sTargetClass)
  2071. {
  2072. $aScale = array();
  2073. $aParentScale = array();
  2074. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2075. if (!empty($sParentClass))
  2076. {
  2077. // inherit the scale from the parent class
  2078. $aParentScale = self::GetHighlightScale($sParentClass);
  2079. }
  2080. if (array_key_exists($sTargetClass, self::$m_aHighlightScales))
  2081. {
  2082. $aScale = self::$m_aHighlightScales[$sTargetClass];
  2083. }
  2084. return array_merge($aParentScale, $aScale); // Merge both arrays, the values from the last one have precedence
  2085. }
  2086. public static function GetHighlightCode($sTargetClass, $sStateCode)
  2087. {
  2088. $sCode = '';
  2089. if ( array_key_exists($sTargetClass, self::$m_aStates)
  2090. && array_key_exists($sStateCode, self::$m_aStates[$sTargetClass])
  2091. && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode]) )
  2092. {
  2093. $sCode = self::$m_aStates[$sTargetClass][$sStateCode]['highlight']['code'];
  2094. }
  2095. else
  2096. {
  2097. // Check the parent's definition
  2098. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2099. if (!empty($sParentClass))
  2100. {
  2101. $sCode = self::GetHighlightCode($sParentClass, $sStateCode);
  2102. }
  2103. }
  2104. return $sCode;
  2105. }
  2106. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  2107. {
  2108. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  2109. $sTargetClass = self::GetCallersPHPClass("Init");
  2110. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  2111. }
  2112. public static function Init_DefineStimulus($oStimulus)
  2113. {
  2114. $sTargetClass = self::GetCallersPHPClass("Init");
  2115. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  2116. // I wanted to simplify the syntax of the declaration of objects in the biz model
  2117. // Therefore, the reference to the host class is set there
  2118. $oStimulus->SetHostClass($sTargetClass);
  2119. }
  2120. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  2121. {
  2122. $sTargetClass = self::GetCallersPHPClass("Init");
  2123. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  2124. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  2125. }
  2126. public static function Init_InheritLifecycle($sSourceClass = '')
  2127. {
  2128. $sTargetClass = self::GetCallersPHPClass("Init");
  2129. if (empty($sSourceClass))
  2130. {
  2131. // Default: inherit from parent class
  2132. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  2133. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  2134. }
  2135. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  2136. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  2137. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  2138. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  2139. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  2140. }
  2141. //
  2142. // Static API
  2143. //
  2144. public static function GetRootClass($sClass = null)
  2145. {
  2146. self::_check_subclass($sClass);
  2147. return self::$m_aRootClasses[$sClass];
  2148. }
  2149. public static function IsRootClass($sClass)
  2150. {
  2151. self::_check_subclass($sClass);
  2152. return (self::GetRootClass($sClass) == $sClass);
  2153. }
  2154. public static function GetParentClass($sClass)
  2155. {
  2156. if (count(self::$m_aParentClasses[$sClass]) == 0)
  2157. {
  2158. return null;
  2159. }
  2160. else
  2161. {
  2162. return end(self::$m_aParentClasses[$sClass]);
  2163. }
  2164. }
  2165. public static function GetLowestCommonAncestor($aClasses)
  2166. {
  2167. $sAncestor = null;
  2168. foreach($aClasses as $sClass)
  2169. {
  2170. if (is_null($sAncestor))
  2171. {
  2172. // first loop
  2173. $sAncestor = $sClass;
  2174. }
  2175. elseif ($sClass == $sAncestor)
  2176. {
  2177. // remains the same
  2178. }
  2179. elseif (self::GetRootClass($sClass) != self::GetRootClass($sAncestor))
  2180. {
  2181. $sAncestor = null;
  2182. break;
  2183. }
  2184. else
  2185. {
  2186. $sAncestor = self::LowestCommonAncestor($sAncestor, $sClass);
  2187. }
  2188. }
  2189. return $sAncestor;
  2190. }
  2191. /**
  2192. * Note: assumes that class A and B have a common ancestor
  2193. */
  2194. protected static function LowestCommonAncestor($sClassA, $sClassB)
  2195. {
  2196. if ($sClassA == $sClassB)
  2197. {
  2198. $sRet = $sClassA;
  2199. }
  2200. elseif (is_subclass_of($sClassA, $sClassB))
  2201. {
  2202. $sRet = $sClassB;
  2203. }
  2204. elseif (is_subclass_of($sClassB, $sClassA))
  2205. {
  2206. $sRet = $sClassA;
  2207. }
  2208. else
  2209. {
  2210. // Recurse
  2211. $sRet = self::LowestCommonAncestor($sClassA, self::GetParentClass($sClassB));
  2212. }
  2213. return $sRet;
  2214. }
  2215. /**
  2216. * Tells if a class contains a hierarchical key, and if so what is its AttCode
  2217. * @return mixed String = sAttCode or false if the class is not part of a hierarchy
  2218. */
  2219. public static function IsHierarchicalClass($sClass)
  2220. {
  2221. $sHierarchicalKeyCode = false;
  2222. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  2223. {
  2224. if ($oAtt->IsHierarchicalKey())
  2225. {
  2226. $sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue
  2227. break;
  2228. }
  2229. }
  2230. return $sHierarchicalKeyCode;
  2231. }
  2232. public static function EnumRootClasses()
  2233. {
  2234. return array_unique(self::$m_aRootClasses);
  2235. }
  2236. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF, $bRootFirst = true)
  2237. {
  2238. self::_check_subclass($sClass);
  2239. if ($bRootFirst)
  2240. {
  2241. $aRes = self::$m_aParentClasses[$sClass];
  2242. }
  2243. else
  2244. {
  2245. $aRes = array_reverse(self::$m_aParentClasses[$sClass], true);
  2246. }
  2247. if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF)
  2248. {
  2249. if ($bRootFirst)
  2250. {
  2251. // Leaf class at the end
  2252. $aRes[] = $sClass;
  2253. }
  2254. else
  2255. {
  2256. // Leaf class on top
  2257. array_unshift($aRes, $sClass);
  2258. }
  2259. }
  2260. return $aRes;
  2261. }
  2262. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  2263. {
  2264. self::_check_subclass($sClass);
  2265. $aRes = self::$m_aChildClasses[$sClass];
  2266. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  2267. {
  2268. // Add it to the list
  2269. $aRes[] = $sClass;
  2270. }
  2271. return $aRes;
  2272. }
  2273. public static function HasChildrenClasses($sClass)
  2274. {
  2275. return (count(self::$m_aChildClasses[$sClass]) > 0);
  2276. }
  2277. public static function EnumCategories()
  2278. {
  2279. return array_keys(self::$m_Category2Class);
  2280. }
  2281. // Note: use EnumChildClasses to take the compound objects into account
  2282. public static function GetSubclasses($sClass)
  2283. {
  2284. self::_check_subclass($sClass);
  2285. $aSubClasses = array();
  2286. foreach(self::$m_aClassParams as $sSubClass => $foo)
  2287. {
  2288. if (is_subclass_of($sSubClass, $sClass))
  2289. {
  2290. $aSubClasses[] = $sSubClass;
  2291. }
  2292. }
  2293. return $aSubClasses;
  2294. }
  2295. public static function GetClasses($sCategories = '', $bStrict = false)
  2296. {
  2297. $aCategories = explode(',', $sCategories);
  2298. $aClasses = array();
  2299. foreach($aCategories as $sCategory)
  2300. {
  2301. $sCategory = trim($sCategory);
  2302. if (strlen($sCategory) == 0)
  2303. {
  2304. return array_keys(self::$m_aClassParams);
  2305. }
  2306. if (array_key_exists($sCategory, self::$m_Category2Class))
  2307. {
  2308. $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
  2309. }
  2310. elseif ($bStrict)
  2311. {
  2312. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  2313. }
  2314. }
  2315. return array_unique($aClasses);
  2316. }
  2317. public static function HasTable($sClass)
  2318. {
  2319. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  2320. return true;
  2321. }
  2322. public static function IsAbstract($sClass)
  2323. {
  2324. $oReflection = new ReflectionClass($sClass);
  2325. return $oReflection->isAbstract();
  2326. }
  2327. /**
  2328. * Normalizes query arguments and adds magic parameters:
  2329. * - current_contact_id
  2330. * - current_contact (DBObject)
  2331. * - current_user (DBObject)
  2332. *
  2333. * @param array $aArgs Context arguments (some can be persistent objects)
  2334. * @param array $aMoreArgs Other query parameters
  2335. * @return array
  2336. */
  2337. public static function PrepareQueryArguments($aArgs, $aMoreArgs = array())
  2338. {
  2339. $aScalarArgs = array();
  2340. foreach(array_merge($aArgs, $aMoreArgs) as $sArgName => $value)
  2341. {
  2342. if (self::IsValidObject($value))
  2343. {
  2344. if (strpos($sArgName, '->object()') === false)
  2345. {
  2346. // Normalize object arguments
  2347. $aScalarArgs[$sArgName.'->object()'] = $value;
  2348. }
  2349. else
  2350. {
  2351. // Leave as is
  2352. $aScalarArgs[$sArgName] = $value;
  2353. }
  2354. }
  2355. else
  2356. {
  2357. if (is_scalar($value))
  2358. {
  2359. $aScalarArgs[$sArgName] = (string) $value;
  2360. }
  2361. elseif (is_null($value))
  2362. {
  2363. $aScalarArgs[$sArgName] = null;
  2364. }
  2365. elseif (is_array($value))
  2366. {
  2367. $aScalarArgs[$sArgName] = $value;
  2368. }
  2369. }
  2370. }
  2371. // Add standard magic arguments
  2372. //
  2373. $aScalarArgs['current_contact_id'] = UserRights::GetContactId(); // legacy
  2374. $oUser = UserRights::GetUserObject();
  2375. if (!is_null($oUser))
  2376. {
  2377. $aScalarArgs['current_user->object()'] = $oUser;
  2378. $oContact = UserRights::GetContactObject();
  2379. if (!is_null($oContact))
  2380. {
  2381. $aScalarArgs['current_contact->object()'] = $oContact;
  2382. }
  2383. }
  2384. return $aScalarArgs;
  2385. }
  2386. public static function MakeModifierProperties($oFilter)
  2387. {
  2388. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2389. //
  2390. $aModifierProperties = array();
  2391. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2392. {
  2393. // Lowest precedence: the application context
  2394. $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
  2395. // Highest precedence: programmatically specified (or OQL)
  2396. foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
  2397. {
  2398. $aPluginProps[$sProp] = $value;
  2399. }
  2400. if (count($aPluginProps) > 0)
  2401. {
  2402. $aModifierProperties[$sPluginClass] = $aPluginProps;
  2403. }
  2404. }
  2405. return $aModifierProperties;
  2406. }
  2407. /**
  2408. * Special processing for the hierarchical keys stored as nested sets
  2409. * @param $iId integer The identifier of the parent
  2410. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2411. * @param $stable string The name of the database table containing the hierarchical key
  2412. */
  2413. public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
  2414. {
  2415. // Get the parent id.right value
  2416. if ($iId == 0)
  2417. {
  2418. // No parent, insert completely at the right of the tree
  2419. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  2420. $aRes = CMDBSource::QueryToArray($sSQL);
  2421. if (count($aRes) == 0)
  2422. {
  2423. $iMyRight = 1;
  2424. }
  2425. else
  2426. {
  2427. $iMyRight = $aRes[0]['max']+1;
  2428. }
  2429. }
  2430. else
  2431. {
  2432. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
  2433. $iMyRight = CMDBSource::QueryToScalar($sSQL);
  2434. $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
  2435. CMDBSource::Query($sSQLUpdateRight);
  2436. $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2437. CMDBSource::Query($sSQLUpdateLeft);
  2438. }
  2439. return array($oAttDef->GetSQLRight() => $iMyRight+1, $oAttDef->GetSQLLeft() => $iMyRight);
  2440. }
  2441. /**
  2442. * Special processing for the hierarchical keys stored as nested sets: temporary remove the branch
  2443. * @param $iId integer The identifier of the parent
  2444. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2445. * @param $sTable string The name of the database table containing the hierarchical key
  2446. */
  2447. public static function HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable)
  2448. {
  2449. $iDelta = $iMyRight - $iMyLeft + 1;
  2450. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iMyLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iMyLeft - `".$oAttDef->GetSQLLeft();
  2451. $sSQL .= "` WHERE `".$oAttDef->GetSQLLeft()."`> $iMyLeft AND `".$oAttDef->GetSQLRight()."`< $iMyRight";
  2452. CMDBSource::Query($sSQL);
  2453. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` - $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2454. CMDBSource::Query($sSQL);
  2455. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` - $iDelta WHERE `".$oAttDef->GetSQLRight()."` > $iMyRight";
  2456. CMDBSource::Query($sSQL);
  2457. }
  2458. /**
  2459. * Special processing for the hierarchical keys stored as nested sets: replug the temporary removed branch
  2460. * @param $iId integer The identifier of the parent
  2461. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2462. * @param $sTable string The name of the database table containing the hierarchical key
  2463. */
  2464. public static function HKReplugBranch($iNewLeft, $iNewRight, $oAttDef, $sTable)
  2465. {
  2466. $iDelta = $iNewRight - $iNewLeft + 1;
  2467. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iNewLeft";
  2468. CMDBSource::Query($sSQL);
  2469. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + $iDelta WHERE `".$oAttDef->GetSQLRight()."` >= $iNewLeft";
  2470. CMDBSource::Query($sSQL);
  2471. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iNewLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iNewLeft - `".$oAttDef->GetSQLLeft()."` WHERE `".$oAttDef->GetSQLRight()."`< 0";
  2472. CMDBSource::Query($sSQL);
  2473. }
  2474. /**
  2475. * Check (and updates if needed) the hierarchical keys
  2476. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2477. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2478. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2479. */
  2480. public static function CheckHKeys($bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2481. {
  2482. $bChangeNeeded = false;
  2483. foreach (self::GetClasses() as $sClass)
  2484. {
  2485. if (!self::HasTable($sClass)) continue;
  2486. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2487. {
  2488. // Check (once) all the attributes that are hierarchical keys
  2489. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
  2490. {
  2491. if ($bVerbose)
  2492. {
  2493. echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
  2494. }
  2495. $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
  2496. $bChangeNeeded |= $bResult;
  2497. if ($bVerbose && !$bResult)
  2498. {
  2499. echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
  2500. }
  2501. }
  2502. }
  2503. }
  2504. return $bChangeNeeded;
  2505. }
  2506. /**
  2507. * Initializes (i.e converts) a hierarchy stored using a 'parent_id' external key
  2508. * into a hierarchy stored with a HierarchicalKey, by initializing the _left and _right values
  2509. * to correspond to the existing hierarchy in the database
  2510. * @param $sClass string Name of the class to process
  2511. * @param $sAttCode string Code of the attribute to process
  2512. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2513. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2514. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2515. * @return true if an update is needed (diagnostics only) / was performed
  2516. */
  2517. public static function HKInit($sClass, $sAttCode, $bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2518. {
  2519. $idx = 1;
  2520. $bUpdateNeeded = $bForceComputation;
  2521. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  2522. $sTable = self::DBGetTable($sClass, $sAttCode);
  2523. if ($oAttDef->IsHierarchicalKey())
  2524. {
  2525. // Check if some values already exist in the table for the _right value, if so, do nothing
  2526. $sRight = $oAttDef->GetSQLRight();
  2527. $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
  2528. $iMaxRight = CMDBSource::QueryToScalar($sSQL);
  2529. $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
  2530. $iCount = CMDBSource::QueryToScalar($sSQL);
  2531. if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
  2532. {
  2533. $bUpdateNeeded = true;
  2534. if ($bVerbose)
  2535. {
  2536. echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
  2537. }
  2538. }
  2539. if ($bForceComputation && !$bDiagnosticsOnly)
  2540. {
  2541. echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
  2542. }
  2543. if ($bUpdateNeeded && !$bDiagnosticsOnly)
  2544. {
  2545. try
  2546. {
  2547. CMDBSource::Query('START TRANSACTION');
  2548. self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
  2549. CMDBSource::Query('COMMIT');
  2550. if ($bVerbose)
  2551. {
  2552. echo "Ok, table '$sTable' successfully updated.\n";
  2553. }
  2554. }
  2555. catch(Exception $e)
  2556. {
  2557. CMDBSource::Query('ROLLBACK');
  2558. throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
  2559. }
  2560. }
  2561. }
  2562. return $bUpdateNeeded;
  2563. }
  2564. /**
  2565. * Recursive helper function called by HKInit
  2566. */
  2567. protected static function HKInitChildren($sTable, $sAttCode, $oAttDef, $iId, &$iCurrIndex)
  2568. {
  2569. $sSQL = "SELECT id FROM `$sTable` WHERE `$sAttCode` = $iId";
  2570. $aRes = CMDBSource::QueryToArray($sSQL);
  2571. $aTree = array();
  2572. $sLeft = $oAttDef->GetSQLLeft();
  2573. $sRight = $oAttDef->GetSQLRight();
  2574. foreach($aRes as $aValues)
  2575. {
  2576. $iChildId = $aValues['id'];
  2577. $iLeft = $iCurrIndex++;
  2578. $aChildren = self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
  2579. $iRight = $iCurrIndex++;
  2580. $sSQL = "UPDATE `$sTable` SET `$sLeft` = $iLeft, `$sRight` = $iRight WHERE id= $iChildId";
  2581. CMDBSource::Query($sSQL);
  2582. }
  2583. }
  2584. /**
  2585. * Update the meta enums
  2586. * See Also AttributeMetaEnum::MapValue that must be aligned with the above implementation
  2587. *
  2588. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2589. */
  2590. public static function RebuildMetaEnums($bVerbose = false)
  2591. {
  2592. foreach (self::GetClasses() as $sClass)
  2593. {
  2594. if (!self::HasTable($sClass)) continue;
  2595. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2596. {
  2597. // Check (once) all the attributes that are hierarchical keys
  2598. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef instanceof AttributeEnum)
  2599. {
  2600. if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode]))
  2601. {
  2602. foreach (self::$m_aEnumToMeta[$sClass][$sAttCode] as $sMetaAttCode => $oMetaAttDef)
  2603. {
  2604. $aMetaValues = array(); // array of (metavalue => array of values)
  2605. foreach ($oAttDef->GetAllowedValues() as $sCode => $sLabel)
  2606. {
  2607. $aMappingData = $oMetaAttDef->GetMapRule($sClass);
  2608. if ($aMappingData == null)
  2609. {
  2610. $sMetaValue = $oMetaAttDef->GetDefaultValue();
  2611. }
  2612. else
  2613. {
  2614. if (array_key_exists($sCode, $aMappingData['values']))
  2615. {
  2616. $sMetaValue = $aMappingData['values'][$sCode];
  2617. }
  2618. elseif ($oMetaAttDef->GetDefaultValue() != '')
  2619. {
  2620. $sMetaValue = $oMetaAttDef->GetDefaultValue();
  2621. }
  2622. else
  2623. {
  2624. throw new Exception('MetaModel::RebuildMetaEnums(): mapping not found for value "'.$sCode.'"" in '.$sClass.', on attribute '.self::GetAttributeOrigin($sClass, $oMetaAttDef->GetCode()).'::'.$oMetaAttDef->GetCode());
  2625. }
  2626. }
  2627. $aMetaValues[$sMetaValue][] = $sCode;
  2628. }
  2629. foreach ($aMetaValues as $sMetaValue => $aEnumValues)
  2630. {
  2631. $sMetaTable = self::DBGetTable($sClass, $sMetaAttCode);
  2632. $sEnumTable = self::DBGetTable($sClass);
  2633. $aColumns = array_keys($oMetaAttDef->GetSQLColumns());
  2634. $sMetaColumn = reset($aColumns);
  2635. $aColumns = array_keys($oAttDef->GetSQLColumns());
  2636. $sEnumColumn = reset($aColumns);
  2637. $sValueList = implode(', ', CMDBSource::Quote($aEnumValues));
  2638. $sSql = "UPDATE `$sMetaTable` JOIN `$sEnumTable` ON `$sEnumTable`.id = `$sMetaTable`.id SET `$sMetaTable`.`$sMetaColumn` = '$sMetaValue' WHERE `$sEnumTable`.`$sEnumColumn` IN ($sValueList) AND `$sMetaTable`.`$sMetaColumn` != '$sMetaValue'";
  2639. if ($bVerbose)
  2640. {
  2641. echo "Executing query: $sSql\n";
  2642. }
  2643. CMDBSource::Query($sSql);
  2644. }
  2645. }
  2646. }
  2647. }
  2648. }
  2649. }
  2650. }
  2651. public static function CheckDataSources($bDiagnostics, $bVerbose)
  2652. {
  2653. $sOQL = 'SELECT SynchroDataSource';
  2654. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2655. $bFixNeeded = false;
  2656. if ($bVerbose && $oSet->Count() == 0)
  2657. {
  2658. echo "There are no Data Sources in the database.\n";
  2659. }
  2660. while($oSource = $oSet->Fetch())
  2661. {
  2662. if ($bVerbose)
  2663. {
  2664. echo "Checking Data Source '".$oSource->GetName()."'...\n";
  2665. $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
  2666. }
  2667. }
  2668. if (!$bFixNeeded && $bVerbose)
  2669. {
  2670. echo "Ok.\n";
  2671. }
  2672. return $bFixNeeded;
  2673. }
  2674. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  2675. {
  2676. if (!array_key_exists($sNewName, $aAliases))
  2677. {
  2678. $aAliases[$sNewName] = $sRealName;
  2679. return $sNewName;
  2680. }
  2681. for ($i = 1 ; $i < 100 ; $i++)
  2682. {
  2683. $sAnAlias = $sNewName.$i;
  2684. if (!array_key_exists($sAnAlias, $aAliases))
  2685. {
  2686. // Create that new alias
  2687. $aAliases[$sAnAlias] = $sRealName;
  2688. return $sAnAlias;
  2689. }
  2690. }
  2691. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  2692. }
  2693. public static function CheckDefinitions($bExitOnError = true)
  2694. {
  2695. if (count(self::GetClasses()) == 0)
  2696. {
  2697. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  2698. }
  2699. $aErrors = array();
  2700. $aSugFix = array();
  2701. foreach (self::GetClasses() as $sClass)
  2702. {
  2703. $sTable = self::DBGetTable($sClass);
  2704. $sTableLowercase = strtolower($sTable);
  2705. if ($sTableLowercase != $sTable)
  2706. {
  2707. $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
  2708. $aSugFix[$sClass][] = "Use '$sTableLowercase' instead. Step 1: If already installed, then rename manually in the DB: RENAME TABLE `$sTable` TO `{$sTableLowercase}_tempname`, `{$sTableLowercase}_tempname` TO `$sTableLowercase`; Step 2: Rename the table in the datamodel and compile the application. Note: the MySQL statement provided in step 1 has been designed to be compatible with Windows or Linux.";
  2709. }
  2710. $aNameSpec = self::GetNameSpec($sClass);
  2711. foreach($aNameSpec[1] as $i => $sAttCode)
  2712. {
  2713. if(!self::IsValidAttCode($sClass, $sAttCode))
  2714. {
  2715. $aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition";
  2716. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2717. }
  2718. }
  2719. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  2720. {
  2721. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  2722. {
  2723. $aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  2724. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2725. }
  2726. }
  2727. $bHasWritableAttribute = false;
  2728. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2729. {
  2730. // It makes no sense to check the attributes again and again in the subclasses
  2731. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2732. if ($oAttDef->IsExternalKey())
  2733. {
  2734. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  2735. {
  2736. $aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  2737. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  2738. }
  2739. }
  2740. elseif ($oAttDef->IsExternalField())
  2741. {
  2742. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2743. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  2744. {
  2745. $aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  2746. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  2747. }
  2748. else
  2749. {
  2750. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  2751. $sTargetClass = $oKeyAttDef->GetTargetClass();
  2752. $sExtAttCode = $oAttDef->GetExtAttCode();
  2753. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  2754. {
  2755. $aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  2756. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  2757. }
  2758. }
  2759. }
  2760. else if ($oAttDef->IsLinkSet())
  2761. {
  2762. // Do nothing...
  2763. }
  2764. else if ($oAttDef instanceof AttributeStopWatch)
  2765. {
  2766. $aThresholds = $oAttDef->ListThresholds();
  2767. if (is_array($aThresholds))
  2768. {
  2769. foreach($aThresholds as $iPercent => $aDef)
  2770. {
  2771. if (array_key_exists('highlight', $aDef))
  2772. {
  2773. if(!array_key_exists('code', $aDef['highlight']))
  2774. {
  2775. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'.";
  2776. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold.";
  2777. }
  2778. else
  2779. {
  2780. $aScale = self::GetHighlightScale($sClass);
  2781. if (!array_key_exists($aDef['highlight']['code'], $aScale))
  2782. {
  2783. $aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'.";
  2784. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  2785. }
  2786. }
  2787. }
  2788. }
  2789. }
  2790. }
  2791. else // standard attributes
  2792. {
  2793. // Check that the default values definition is a valid object!
  2794. $oValSetDef = $oAttDef->GetValuesDef();
  2795. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  2796. {
  2797. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  2798. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  2799. }
  2800. else
  2801. {
  2802. // Default value must be listed in the allowed values (if defined)
  2803. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2804. if (!is_null($aAllowedValues))
  2805. {
  2806. $sDefaultValue = $oAttDef->GetDefaultValue();
  2807. if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
  2808. {
  2809. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  2810. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  2811. }
  2812. }
  2813. }
  2814. }
  2815. // Check dependencies
  2816. if ($oAttDef->IsWritable())
  2817. {
  2818. $bHasWritableAttribute = true;
  2819. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  2820. {
  2821. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  2822. {
  2823. $aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  2824. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2825. }
  2826. }
  2827. }
  2828. }
  2829. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  2830. {
  2831. if (method_exists($oFilterDef, '__GetRefAttribute'))
  2832. {
  2833. $oAttDef = $oFilterDef->__GetRefAttribute();
  2834. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  2835. {
  2836. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  2837. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2838. }
  2839. }
  2840. }
  2841. // Lifecycle
  2842. //
  2843. $sStateAttCode = self::GetStateAttributeCode($sClass);
  2844. if (strlen($sStateAttCode) > 0)
  2845. {
  2846. // Lifecycle - check that the state attribute does exist as an attribute
  2847. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  2848. {
  2849. $aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition";
  2850. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2851. }
  2852. else
  2853. {
  2854. // Lifecycle - check that there is a value set constraint on the state attribute
  2855. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  2856. $aStates = array_keys(self::EnumStates($sClass));
  2857. if (is_null($aAllowedValuesRaw))
  2858. {
  2859. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  2860. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  2861. }
  2862. else
  2863. {
  2864. $aAllowedValues = array_keys($aAllowedValuesRaw);
  2865. // Lifecycle - check the the state attribute allowed values are defined states
  2866. foreach($aAllowedValues as $sValue)
  2867. {
  2868. if (!in_array($sValue, $aStates))
  2869. {
  2870. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  2871. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2872. }
  2873. }
  2874. // Lifecycle - check that defined states are allowed values
  2875. foreach($aStates as $sStateValue)
  2876. {
  2877. if (!in_array($sStateValue, $aAllowedValues))
  2878. {
  2879. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  2880. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2881. }
  2882. }
  2883. }
  2884. // Lifecycle - check that the action handlers are defined
  2885. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  2886. {
  2887. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  2888. {
  2889. foreach ($aTransitionDef['actions'] as $actionHandler)
  2890. {
  2891. if (is_string($actionHandler))
  2892. {
  2893. if (!method_exists($sClass, $actionHandler))
  2894. {
  2895. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2896. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  2897. }
  2898. }
  2899. else // if(is_array($actionHandler))
  2900. {
  2901. $sActionHandler = $actionHandler['verb'];
  2902. if (!method_exists($sClass, $sActionHandler))
  2903. {
  2904. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2905. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(...){return true;}]";
  2906. }
  2907. }
  2908. }
  2909. }
  2910. if (array_key_exists('highlight', $aStateDef))
  2911. {
  2912. if(!array_key_exists('code', $aStateDef['highlight']))
  2913. {
  2914. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'.";
  2915. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state.";
  2916. }
  2917. else
  2918. {
  2919. $aScale = self::GetHighlightScale($sClass);
  2920. if (!array_key_exists($aStateDef['highlight']['code'], $aScale))
  2921. {
  2922. $aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'.";
  2923. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  2924. }
  2925. }
  2926. }
  2927. }
  2928. }
  2929. }
  2930. if ($bHasWritableAttribute)
  2931. {
  2932. if (!self::HasTable($sClass))
  2933. {
  2934. $aErrors[$sClass][] = "No table has been defined for this class";
  2935. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  2936. }
  2937. }
  2938. // ZList
  2939. //
  2940. foreach(self::EnumZLists() as $sListCode)
  2941. {
  2942. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  2943. {
  2944. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  2945. {
  2946. $aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  2947. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2948. }
  2949. }
  2950. }
  2951. // Check unicity of the SQL columns
  2952. //
  2953. if (self::HasTable($sClass))
  2954. {
  2955. $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
  2956. $aTableColumns[self::DBGetKey($sClass)] = 'id';
  2957. // Check that SQL columns are declared only once
  2958. //
  2959. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2960. {
  2961. // Skip this attribute if not originaly defined in this class
  2962. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2963. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  2964. {
  2965. if (array_key_exists($sField, $aTableColumns))
  2966. {
  2967. $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
  2968. $aSugFix[$sClass][] = "Please find another name for the SQL column";
  2969. }
  2970. else
  2971. {
  2972. $aTableColumns[$sField] = $sAttCode;
  2973. }
  2974. }
  2975. }
  2976. }
  2977. } // foreach class
  2978. if (count($aErrors) > 0)
  2979. {
  2980. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2981. echo "<h3>Business model inconsistencies have been found</h3>\n";
  2982. // #@# later -> this is the responsibility of the caller to format the output
  2983. foreach ($aErrors as $sClass => $aMessages)
  2984. {
  2985. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  2986. echo "<ul class=\"treeview\">\n";
  2987. $i = 0;
  2988. foreach ($aMessages as $sMsg)
  2989. {
  2990. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  2991. $i++;
  2992. }
  2993. echo "</ul>\n";
  2994. }
  2995. if ($bExitOnError) echo "<p>Aborting...</p>\n";
  2996. echo "</div>\n";
  2997. if ($bExitOnError) exit;
  2998. }
  2999. }
  3000. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  3001. {
  3002. if (empty($sRepairUrl)) return;
  3003. // By design, some queries might be blank, we have to ignore them
  3004. $aCleanFixes = array();
  3005. foreach($aSQLFixes as $sSQLFix)
  3006. {
  3007. if (!empty($sSQLFix))
  3008. {
  3009. $aCleanFixes[] = $sSQLFix;
  3010. }
  3011. }
  3012. if (count($aCleanFixes) == 0) return;
  3013. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  3014. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  3015. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  3016. echo "</form>\n";
  3017. }
  3018. public static function DBExists($bMustBeComplete = true)
  3019. {
  3020. // returns true if at least one table exists
  3021. //
  3022. if (!CMDBSource::IsDB(self::$m_sDBName))
  3023. {
  3024. return false;
  3025. }
  3026. CMDBSource::SelectDB(self::$m_sDBName);
  3027. $aFound = array();
  3028. $aMissing = array();
  3029. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3030. {
  3031. if (CMDBSource::IsTable($sTable))
  3032. {
  3033. $aFound[] = $sTable;
  3034. }
  3035. else
  3036. {
  3037. $aMissing[] = $sTable;
  3038. }
  3039. }
  3040. if (count($aFound) == 0)
  3041. {
  3042. // no expected table has been found
  3043. return false;
  3044. }
  3045. else
  3046. {
  3047. if (count($aMissing) == 0)
  3048. {
  3049. // the database is complete (still, could be some fields missing!)
  3050. return true;
  3051. }
  3052. else
  3053. {
  3054. // not all the tables, could be an older version
  3055. if ($bMustBeComplete)
  3056. {
  3057. return false;
  3058. }
  3059. else
  3060. {
  3061. return true;
  3062. }
  3063. }
  3064. }
  3065. }
  3066. public static function DBDrop()
  3067. {
  3068. $bDropEntireDB = true;
  3069. if (!empty(self::$m_sTablePrefix))
  3070. {
  3071. // Do drop only tables corresponding to the sub-database (table prefix)
  3072. // then possibly drop the DB itself (if no table remain)
  3073. foreach (CMDBSource::EnumTables() as $sTable)
  3074. {
  3075. // perform a case insensitive test because on Windows the table names become lowercase :-(
  3076. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  3077. {
  3078. CMDBSource::DropTable($sTable);
  3079. }
  3080. else
  3081. {
  3082. // There is at least one table which is out of the scope of the current application
  3083. $bDropEntireDB = false;
  3084. }
  3085. }
  3086. }
  3087. if ($bDropEntireDB)
  3088. {
  3089. CMDBSource::DropDB(self::$m_sDBName);
  3090. }
  3091. }
  3092. public static function DBCreate($aCallback = null)
  3093. {
  3094. // Note: we have to check if the DB does exist, because we may share the DB
  3095. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  3096. if (!CMDBSource::IsDB(self::$m_sDBName))
  3097. {
  3098. CMDBSource::CreateDB(self::$m_sDBName);
  3099. }
  3100. self::DBCreateTables($aCallback);
  3101. self::DBCreateViews();
  3102. }
  3103. protected static function DBCreateTables($aCallback = null)
  3104. {
  3105. list($aErrors, $aSugFix, $aCondensedQueries) = self::DBCheckFormat();
  3106. //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
  3107. foreach($aCondensedQueries as $sQuery)
  3108. {
  3109. $fStart = microtime(true);
  3110. CMDBSource::CreateTable($sQuery);
  3111. $fDuration = microtime(true) - $fStart;
  3112. if ($aCallback != null)
  3113. {
  3114. call_user_func($aCallback, $sQuery, $fDuration);
  3115. }
  3116. }
  3117. }
  3118. protected static function DBCreateViews()
  3119. {
  3120. list($aErrors, $aSugFix) = self::DBCheckViews();
  3121. $aSQL = array();
  3122. foreach ($aSugFix as $sClass => $aTarget)
  3123. {
  3124. foreach ($aTarget as $aQueries)
  3125. {
  3126. foreach ($aQueries as $sQuery)
  3127. {
  3128. if (!empty($sQuery))
  3129. {
  3130. //$aSQL[] = $sQuery;
  3131. // forces a refresh of cached information
  3132. CMDBSource::CreateTable($sQuery);
  3133. }
  3134. }
  3135. }
  3136. }
  3137. }
  3138. public static function DBDump()
  3139. {
  3140. $aDataDump = array();
  3141. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3142. {
  3143. $aRows = CMDBSource::DumpTable($sTable);
  3144. $aDataDump[$sTable] = $aRows;
  3145. }
  3146. return $aDataDump;
  3147. }
  3148. /*
  3149. * Determines wether the target DB is frozen or not
  3150. */
  3151. public static function DBIsReadOnly()
  3152. {
  3153. // Improvement: check the mySQL variable -> Read-only
  3154. if (UserRights::IsAdministrator())
  3155. {
  3156. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  3157. }
  3158. else
  3159. {
  3160. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  3161. }
  3162. }
  3163. public static function DBHasAccess($iRequested = ACCESS_FULL)
  3164. {
  3165. $iMode = self::$m_oConfig->Get('access_mode');
  3166. if (($iMode & $iRequested) == 0) return false;
  3167. return true;
  3168. }
  3169. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  3170. {
  3171. $sValue = Dict::S($sKey, 'x-no-nothing');
  3172. if ($sValue == 'x-no-nothing')
  3173. {
  3174. $bNotInDico = true;
  3175. $sValue = $sValueFromOldSystem;
  3176. if (strlen($sValue) == 0)
  3177. {
  3178. $sValue = $sDefaultValue;
  3179. }
  3180. }
  3181. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  3182. }
  3183. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  3184. {
  3185. $sRes = '';
  3186. $sRes .= "// Dictionnay conventions\n";
  3187. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  3188. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  3189. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  3190. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  3191. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  3192. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  3193. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  3194. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  3195. $sRes .= "\n";
  3196. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  3197. // Need to invent the "module", to characterize the origins of a class
  3198. if (strlen($sModules) == 0)
  3199. {
  3200. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  3201. }
  3202. else
  3203. {
  3204. $aModules = explode(', ', $sModules);
  3205. }
  3206. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3207. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  3208. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3209. foreach ($aModules as $sCategory)
  3210. {
  3211. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3212. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  3213. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3214. $sRes .= "//\n";
  3215. $sRes .= "\n";
  3216. foreach (self::GetClasses($sCategory) as $sClass)
  3217. {
  3218. if (!self::HasTable($sClass)) continue;
  3219. $bNotInDico = false;
  3220. $sClassRes = "//\n";
  3221. $sClassRes .= "// Class: $sClass\n";
  3222. $sClassRes .= "//\n";
  3223. $sClassRes .= "\n";
  3224. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  3225. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  3226. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  3227. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  3228. {
  3229. // Skip this attribute if not originaly defined in this class
  3230. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3231. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  3232. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  3233. if ($oAttDef instanceof AttributeEnum)
  3234. {
  3235. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  3236. {
  3237. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  3238. {
  3239. if (array_key_exists('label', $aStateData))
  3240. {
  3241. $sValue = $aStateData['label'];
  3242. }
  3243. else
  3244. {
  3245. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  3246. }
  3247. if (array_key_exists('description', $aStateData))
  3248. {
  3249. $sValuePlus = $aStateData['description'];
  3250. }
  3251. else
  3252. {
  3253. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  3254. }
  3255. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  3256. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  3257. }
  3258. }
  3259. else
  3260. {
  3261. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  3262. {
  3263. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  3264. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  3265. }
  3266. }
  3267. }
  3268. }
  3269. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  3270. {
  3271. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  3272. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  3273. }
  3274. $sClassRes .= "));\n";
  3275. $sClassRes .= "\n";
  3276. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  3277. {
  3278. $sRes .= $sClassRes;
  3279. }
  3280. }
  3281. }
  3282. return $sRes;
  3283. }
  3284. public static function DBCheckFormat()
  3285. {
  3286. $aErrors = array();
  3287. $aSugFix = array();
  3288. // A new way of representing things to be done - quicker to execute !
  3289. $aCreateTable = array(); // array of <table> => <table options>
  3290. $aCreateTableItems = array(); // array of <table> => array of <create definition>
  3291. $aAlterTableItems = array(); // array of <table> => <alter specification>
  3292. foreach (self::GetClasses() as $sClass)
  3293. {
  3294. if (!self::HasTable($sClass)) continue;
  3295. // Check that the table exists
  3296. //
  3297. $sTable = self::DBGetTable($sClass);
  3298. $sKeyField = self::DBGetKey($sClass);
  3299. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  3300. $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  3301. if (!CMDBSource::IsTable($sTable))
  3302. {
  3303. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  3304. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3305. $aCreateTable[$sTable] = "ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3306. $aCreateTableItems[$sTable][$sKeyField] = $sKeyFieldDefinition;
  3307. }
  3308. // Check that the key field exists
  3309. //
  3310. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  3311. {
  3312. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  3313. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
  3314. if (!array_key_exists($sTable, $aCreateTable))
  3315. {
  3316. $aAlterTableItems[$sTable][$sKeyField] = "ADD $sKeyFieldDefinition";
  3317. }
  3318. }
  3319. else
  3320. {
  3321. // Check the key field properties
  3322. //
  3323. if (!CMDBSource::IsKey($sTable, $sKeyField))
  3324. {
  3325. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  3326. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  3327. if (!array_key_exists($sTable, $aCreateTable))
  3328. {
  3329. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3330. }
  3331. }
  3332. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  3333. {
  3334. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  3335. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
  3336. if (!array_key_exists($sTable, $aCreateTable))
  3337. {
  3338. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3339. }
  3340. }
  3341. }
  3342. // Check that any defined field exists
  3343. //
  3344. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  3345. $aTableInfo['Fields'][$sKeyField]['used'] = true;
  3346. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3347. {
  3348. // Skip this attribute if not originaly defined in this class
  3349. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3350. foreach($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec)
  3351. {
  3352. // Keep track of columns used by iTop
  3353. $aTableInfo['Fields'][$sField]['used'] = true;
  3354. $bIndexNeeded = $oAttDef->RequiresIndex();
  3355. $sFieldDefinition = "`$sField` $sDBFieldSpec";
  3356. if (!CMDBSource::IsField($sTable, $sField))
  3357. {
  3358. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  3359. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
  3360. if ($bIndexNeeded)
  3361. {
  3362. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3363. }
  3364. if (array_key_exists($sTable, $aCreateTable))
  3365. {
  3366. $aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
  3367. if ($bIndexNeeded)
  3368. {
  3369. $aCreateTableItems[$sTable][] = "INDEX (`$sField`)";
  3370. }
  3371. }
  3372. else
  3373. {
  3374. $aAlterTableItems[$sTable][$sField] = "ADD $sFieldDefinition";
  3375. if ($bIndexNeeded)
  3376. {
  3377. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3378. }
  3379. }
  3380. }
  3381. else
  3382. {
  3383. // The field already exists, does it have the relevant properties?
  3384. //
  3385. $bToBeChanged = false;
  3386. $sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField);
  3387. if (strcasecmp($sDBFieldSpec, $sActualFieldSpec) != 0)
  3388. {
  3389. $bToBeChanged = true;
  3390. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldSpec' while expecting '$sDBFieldSpec'";
  3391. }
  3392. if ($bToBeChanged)
  3393. {
  3394. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3395. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3396. }
  3397. // Create indexes (external keys only... so far)
  3398. //
  3399. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField, array($sField)))
  3400. {
  3401. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  3402. if (CMDBSource::HasIndex($sTable, $sField))
  3403. {
  3404. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sField`, ADD INDEX (`$sField`)";
  3405. $aAlterTableItems[$sTable][] = "DROP INDEX `$sField`";
  3406. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3407. }
  3408. else
  3409. {
  3410. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3411. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3412. }
  3413. }
  3414. }
  3415. }
  3416. }
  3417. // Check indexes
  3418. foreach (self::DBGetIndexes($sClass) as $aColumns)
  3419. {
  3420. $sIndexId = implode('_', $aColumns);
  3421. if(!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns))
  3422. {
  3423. $sColumns = "`".implode("`, `", $aColumns)."`";
  3424. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3425. {
  3426. $aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'";
  3427. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`, ADD INDEX `$sIndexId` ($sColumns)";
  3428. }
  3429. else
  3430. {
  3431. $aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'";
  3432. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
  3433. }
  3434. if (array_key_exists($sTable, $aCreateTable))
  3435. {
  3436. $aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)";
  3437. }
  3438. else
  3439. {
  3440. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3441. {
  3442. $aAlterTableItems[$sTable][] = "DROP INDEX `$sIndexId`";
  3443. }
  3444. $aAlterTableItems[$sTable][] = "ADD INDEX `$sIndexId` ($sColumns)";
  3445. }
  3446. }
  3447. }
  3448. // Find out unused columns
  3449. //
  3450. foreach($aTableInfo['Fields'] as $sField => $aFieldData)
  3451. {
  3452. if (!isset($aFieldData['used']) || !$aFieldData['used'])
  3453. {
  3454. $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
  3455. if (!CMDBSource::IsNullAllowed($sTable, $sField))
  3456. {
  3457. // Allow null values so that new record can be inserted
  3458. // without specifying the value of this unknown column
  3459. $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
  3460. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3461. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3462. }
  3463. }
  3464. }
  3465. }
  3466. $aCondensedQueries = array();
  3467. foreach($aCreateTable as $sTable => $sTableOptions)
  3468. {
  3469. $sTableItems = implode(', ', $aCreateTableItems[$sTable]);
  3470. $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
  3471. }
  3472. foreach($aAlterTableItems as $sTable => $aChangeList)
  3473. {
  3474. $sChangeList = implode(', ', $aChangeList);
  3475. $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
  3476. }
  3477. return array($aErrors, $aSugFix, $aCondensedQueries);
  3478. }
  3479. public static function DBCheckViews()
  3480. {
  3481. $aErrors = array();
  3482. $aSugFix = array();
  3483. // Reporting views (must be created after any other table)
  3484. //
  3485. foreach (self::GetClasses('bizmodel') as $sClass)
  3486. {
  3487. $sView = self::DBGetView($sClass);
  3488. if (CMDBSource::IsTable($sView))
  3489. {
  3490. // Check that the view is complete
  3491. //
  3492. // Note: checking the list of attributes is not enough because the columns can be stable while the SELECT is not stable
  3493. // Example: new way to compute the friendly name
  3494. // The correct comparison algorithm is to compare the queries,
  3495. // by using "SHOW CREATE VIEW" (MySQL 5.0.1 required) or to look into INFORMATION_SCHEMA/views
  3496. // both requiring some privileges
  3497. // Decision: to simplify, let's consider the views as being wrong anytime
  3498. if (true)
  3499. {
  3500. // Rework the view
  3501. //
  3502. $oFilter = new DBObjectSearch($sClass, '');
  3503. $oFilter->AllowAllData();
  3504. $sSQL = $oFilter->MakeSelectQuery();
  3505. $aErrors[$sClass]['*'][] = "Redeclare view '$sView' (systematic - to support an eventual change in the friendly name computation)";
  3506. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  3507. }
  3508. }
  3509. else
  3510. {
  3511. // Create the view
  3512. //
  3513. $oFilter = new DBObjectSearch($sClass, '');
  3514. $oFilter->AllowAllData();
  3515. $sSQL = $oFilter->MakeSelectQuery();
  3516. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  3517. $aSugFix[$sClass]['*'][] = "DROP VIEW IF EXISTS `$sView`";
  3518. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  3519. }
  3520. }
  3521. return array($aErrors, $aSugFix);
  3522. }
  3523. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  3524. {
  3525. $sRootClass = self::GetRootClass($sClass);
  3526. $sTable = self::DBGetTable($sClass);
  3527. $sKeyField = self::DBGetKey($sClass);
  3528. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3529. {
  3530. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3531. }
  3532. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3533. if (count($aWrongRecords) == 0) return;
  3534. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3535. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3536. foreach ($aWrongRecords as $iRecordId)
  3537. {
  3538. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3539. {
  3540. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3541. {
  3542. case 'Delete':
  3543. // Already planned for a deletion
  3544. // Let's concatenate the errors description together
  3545. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3546. break;
  3547. case 'Update':
  3548. // Let's plan a deletion
  3549. break;
  3550. }
  3551. }
  3552. else
  3553. {
  3554. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3555. }
  3556. if (!$bProcessingFriends)
  3557. {
  3558. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  3559. {
  3560. // Something new to be deleted...
  3561. $iNewDelCount++;
  3562. }
  3563. }
  3564. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  3565. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  3566. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3567. $aPlannedDel[$sTable][] = $iRecordId;
  3568. }
  3569. // Now make sure that we would delete the records of the other tables for that class
  3570. //
  3571. if (!$bProcessingFriends)
  3572. {
  3573. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  3574. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  3575. {
  3576. $sFriendTable = self::DBGetTable($sFriendClass);
  3577. $sFriendKey = self::DBGetKey($sFriendClass);
  3578. // skip the current table
  3579. if ($sFriendTable == $sTable) continue;
  3580. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  3581. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  3582. }
  3583. }
  3584. }
  3585. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3586. {
  3587. $sRootClass = self::GetRootClass($sClass);
  3588. $sTable = self::DBGetTable($sClass);
  3589. $sKeyField = self::DBGetKey($sClass);
  3590. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3591. {
  3592. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3593. }
  3594. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3595. if (count($aWrongRecords) == 0) return;
  3596. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3597. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3598. foreach ($aWrongRecords as $iRecordId)
  3599. {
  3600. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3601. {
  3602. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3603. {
  3604. case 'Delete':
  3605. // No need to update, the record will be deleted!
  3606. break;
  3607. case 'Update':
  3608. // Already planned for an update
  3609. // Add this new update spec to the list
  3610. $bFoundSameSpec = false;
  3611. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  3612. {
  3613. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  3614. {
  3615. $bFoundSameSpec = true;
  3616. }
  3617. }
  3618. if (!$bFoundSameSpec)
  3619. {
  3620. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3621. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3622. }
  3623. break;
  3624. }
  3625. }
  3626. else
  3627. {
  3628. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3629. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  3630. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3631. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3632. }
  3633. }
  3634. }
  3635. // returns the count of records found for deletion
  3636. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3637. {
  3638. foreach (self::GetClasses() as $sClass)
  3639. {
  3640. if (!self::HasTable($sClass)) continue;
  3641. $sRootClass = self::GetRootClass($sClass);
  3642. $sTable = self::DBGetTable($sClass);
  3643. $sKeyField = self::DBGetKey($sClass);
  3644. if (!self::IsStandaloneClass($sClass))
  3645. {
  3646. if (self::IsRootClass($sClass))
  3647. {
  3648. // Check that the final class field contains the name of a class which inherited from the current class
  3649. //
  3650. $sFinalClassField = self::DBGetClassField($sClass);
  3651. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3652. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  3653. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  3654. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3655. }
  3656. else
  3657. {
  3658. $sRootTable = self::DBGetTable($sRootClass);
  3659. $sRootKey = self::DBGetKey($sRootClass);
  3660. $sFinalClassField = self::DBGetClassField($sRootClass);
  3661. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3662. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  3663. // Check that any record found here has its counterpart in the root table
  3664. // and which refers to a child class
  3665. //
  3666. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` as maintable LEFT JOIN `$sRootTable` ON maintable.`$sKeyField` = `$sRootTable`.`$sRootKey` AND `$sRootTable`.`$sFinalClassField` IN ($sExpectedClasses) WHERE `$sRootTable`.`$sRootKey` IS NULL";
  3667. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Found a record in `<em>$sTable</em>`, but no counterpart in root table `<em>$sRootTable</em>` (inc. records pointing to a class in {".$sExpectedClasses."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3668. // Check that any record found in the root table and referring to a child class
  3669. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  3670. //
  3671. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sRootKey` AS id FROM `$sRootTable` AS maintable LEFT JOIN `$sTable` ON maintable.`$sRootKey` = `$sTable`.`$sKeyField` WHERE `$sTable`.`$sKeyField` IS NULL AND maintable.`$sFinalClassField` IN ($sExpectedClasses)";
  3672. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Found a record in root table `<em>$sRootTable</em>`, but no counterpart in table `<em>$sTable</em>` (root records pointing to a class in {".$sExpectedClasses."})", $sRootClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3673. }
  3674. }
  3675. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3676. {
  3677. // Skip this attribute if not defined in this table
  3678. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3679. if ($oAttDef->IsExternalKey())
  3680. {
  3681. // Check that any external field is pointing to an existing object
  3682. //
  3683. $sRemoteClass = $oAttDef->GetTargetClass();
  3684. $sRemoteTable = self::DBGetTable($sRemoteClass);
  3685. $sRemoteKey = self::DBGetKey($sRemoteClass);
  3686. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3687. $sExtKeyField = current($aCols); // get the first column for an external key
  3688. // Note: a class/table may have an external key on itself
  3689. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  3690. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  3691. if ($oAttDef->IsNullAllowed())
  3692. {
  3693. // Exclude the records pointing to 0/null from the errors
  3694. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3695. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3696. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3697. }
  3698. else
  3699. {
  3700. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3701. }
  3702. // Do almost the same, taking into account the records planned for deletion
  3703. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  3704. {
  3705. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  3706. // but in that case you won't be able to track the root cause (cascading)
  3707. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  3708. if ($oAttDef->IsNullAllowed())
  3709. {
  3710. // Exclude the records pointing to 0/null from the errors
  3711. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3712. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3713. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3714. }
  3715. else
  3716. {
  3717. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3718. }
  3719. }
  3720. }
  3721. else if ($oAttDef->IsDirectField())
  3722. {
  3723. // Check that the values fit the allowed values
  3724. //
  3725. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3726. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  3727. {
  3728. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  3729. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3730. $sMyAttributeField = current($aCols); // get the first column for the moment
  3731. $sDefaultValue = $oAttDef->GetDefaultValue();
  3732. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  3733. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3734. }
  3735. }
  3736. }
  3737. }
  3738. }
  3739. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  3740. {
  3741. // Records in error, and action to be taken: delete or update
  3742. // by RootClass/Table/Record
  3743. $aErrorsAndFixes = array();
  3744. // Records to be ignored in the current/next pass
  3745. // by Table = array of RecordId
  3746. $aPlannedDel = array();
  3747. // Count of errors in the next pass: no error means that we can leave...
  3748. $iErrorCount = 0;
  3749. // Limit in case of a bug in the algorythm
  3750. $iLoopCount = 0;
  3751. $iNewDelCount = 1; // startup...
  3752. while ($iNewDelCount > 0)
  3753. {
  3754. $iNewDelCount = 0;
  3755. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3756. $iErrorCount += $iNewDelCount;
  3757. // Safety net #1 - limit the planned deletions
  3758. //
  3759. $iMaxDel = 1000;
  3760. $iPlannedDel = 0;
  3761. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  3762. {
  3763. $iPlannedDel += count($aPlannedDelOnTable);
  3764. }
  3765. if ($iPlannedDel > $iMaxDel)
  3766. {
  3767. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  3768. break;
  3769. }
  3770. // Safety net #2 - limit the iterations
  3771. //
  3772. $iLoopCount++;
  3773. $iMaxLoops = 10;
  3774. if ($iLoopCount > $iMaxLoops)
  3775. {
  3776. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  3777. break;
  3778. }
  3779. }
  3780. // Display the results
  3781. //
  3782. $iIssueCount = 0;
  3783. $aFixesDelete = array();
  3784. $aFixesUpdate = array();
  3785. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  3786. {
  3787. foreach ($aTables as $sTable => $aRecords)
  3788. {
  3789. foreach ($aRecords as $iRecord => $aError)
  3790. {
  3791. $sAction = $aError['Action'];
  3792. $sReason = $aError['Reason'];
  3793. $iPass = $aError['Pass'];
  3794. switch ($sAction)
  3795. {
  3796. case 'Delete':
  3797. $sActionDetails = "";
  3798. $aFixesDelete[$sTable][] = $iRecord;
  3799. break;
  3800. case 'Update':
  3801. $aUpdateDesc = array();
  3802. foreach($aError['Action_Details'] as $aUpdateSpec)
  3803. {
  3804. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  3805. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  3806. }
  3807. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  3808. break;
  3809. default:
  3810. $sActionDetails = "bug: unknown action '$sAction'";
  3811. }
  3812. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  3813. $iIssueCount++;
  3814. }
  3815. }
  3816. }
  3817. if ($iIssueCount > 0)
  3818. {
  3819. // Build the queries to fix in the database
  3820. //
  3821. // First step, be able to get class data out of the table name
  3822. // Could be optimized, because we've made the job earlier... but few benefits, so...
  3823. $aTable2ClassProp = array();
  3824. foreach (self::GetClasses() as $sClass)
  3825. {
  3826. if (!self::HasTable($sClass)) continue;
  3827. $sRootClass = self::GetRootClass($sClass);
  3828. $sTable = self::DBGetTable($sClass);
  3829. $sKeyField = self::DBGetKey($sClass);
  3830. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3831. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  3832. }
  3833. // Second step, build a flat list of SQL queries
  3834. $aSQLFixes = array();
  3835. $iPlannedUpdate = 0;
  3836. foreach ($aFixesUpdate as $sTable => $aColumns)
  3837. {
  3838. foreach ($aColumns as $sColumn => $aNewValues)
  3839. {
  3840. foreach ($aNewValues as $sNewValue => $aRecords)
  3841. {
  3842. $iPlannedUpdate += count($aRecords);
  3843. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3844. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3845. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  3846. }
  3847. }
  3848. }
  3849. $iPlannedDel = 0;
  3850. foreach ($aFixesDelete as $sTable => $aRecords)
  3851. {
  3852. $iPlannedDel += count($aRecords);
  3853. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3854. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3855. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  3856. }
  3857. // Report the results
  3858. //
  3859. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3860. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  3861. // #@# later -> this is the responsibility of the caller to format the output
  3862. echo "<ul class=\"treeview\">\n";
  3863. foreach ($aIssues as $sIssueDesc)
  3864. {
  3865. echo "<li>$sIssueDesc</li>\n";
  3866. }
  3867. echo "</ul>\n";
  3868. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  3869. echo "<p>Aborting...</p>\n";
  3870. echo "</div>\n";
  3871. exit;
  3872. }
  3873. }
  3874. public static function Startup($config, $bModelOnly = false, $bAllowCache = true, $bTraceSourceFiles = false, $sEnvironment = 'production')
  3875. {
  3876. self::$m_sEnvironment = $sEnvironment;
  3877. if (!defined('MODULESROOT'))
  3878. {
  3879. define('MODULESROOT', APPROOT.'env-'.self::$m_sEnvironment.'/');
  3880. self::$m_bTraceSourceFiles = $bTraceSourceFiles;
  3881. // $config can be either a filename, or a Configuration object (volatile!)
  3882. if ($config instanceof Config)
  3883. {
  3884. self::LoadConfig($config, $bAllowCache);
  3885. }
  3886. else
  3887. {
  3888. self::LoadConfig(new Config($config), $bAllowCache);
  3889. }
  3890. if ($bModelOnly) return;
  3891. }
  3892. CMDBSource::SelectDB(self::$m_sDBName);
  3893. foreach(get_declared_classes() as $sPHPClass)
  3894. {
  3895. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  3896. {
  3897. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  3898. call_user_func_array($aCallSpec, array());
  3899. }
  3900. }
  3901. if (false)
  3902. {
  3903. echo "Debug<br/>\n";
  3904. self::static_var_dump();
  3905. }
  3906. }
  3907. public static function LoadConfig($oConfiguration, $bAllowCache = false)
  3908. {
  3909. self::$m_oConfig = $oConfiguration;
  3910. // Set log ASAP
  3911. if (self::$m_oConfig->GetLogGlobal())
  3912. {
  3913. if (self::$m_oConfig->GetLogIssue())
  3914. {
  3915. self::$m_bLogIssue = true;
  3916. IssueLog::Enable(APPROOT.'log/error.log');
  3917. }
  3918. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  3919. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  3920. ToolsLog::Enable(APPROOT.'log/tools.log');
  3921. }
  3922. else
  3923. {
  3924. self::$m_bLogIssue = false;
  3925. self::$m_bLogNotification = false;
  3926. self::$m_bLogWebService = false;
  3927. }
  3928. ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration'));
  3929. ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory'));
  3930. ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
  3931. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  3932. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  3933. self::$m_bUseAPCCache = $bAllowCache
  3934. && self::$m_oConfig->Get('apc_cache.enabled')
  3935. && function_exists('apc_fetch')
  3936. && function_exists('apc_store');
  3937. DBSearch::EnableQueryCache(self::$m_oConfig->GetQueryCacheEnabled(), self::$m_bUseAPCCache, self::$m_oConfig->Get('apc_cache.query_ttl'));
  3938. DBSearch::EnableQueryTrace(self::$m_oConfig->GetLogQueries());
  3939. DBSearch::EnableQueryIndentation(self::$m_oConfig->Get('query_indentation_enabled'));
  3940. DBSearch::EnableOptimizeQuery(self::$m_oConfig->Get('query_optimization_enabled'));
  3941. // PHP timezone first...
  3942. //
  3943. $sPHPTimezone = self::$m_oConfig->Get('timezone');
  3944. if ($sPHPTimezone == '')
  3945. {
  3946. // Leave as is... up to the admin to set a value somewhere...
  3947. //$sPHPTimezone = date_default_timezone_get();
  3948. }
  3949. else
  3950. {
  3951. date_default_timezone_set($sPHPTimezone);
  3952. }
  3953. // Note: load the dictionary as soon as possible, because it might be
  3954. // needed when some error occur
  3955. $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
  3956. $bDictInitializedFromData = false;
  3957. if (self::$m_bUseAPCCache)
  3958. {
  3959. Dict::EnableCache($sAppIdentity);
  3960. }
  3961. require_once(APPROOT.'env-'.self::$m_sEnvironment.'/dictionaries/languages.php');
  3962. // Set the default language...
  3963. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  3964. // Romain: this is the only way I've found to cope with the fact that
  3965. // classes have to be derived from cmdbabstract (to be editable in the UI)
  3966. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  3967. require_once(APPROOT.'core/autoload.php');
  3968. require_once(APPROOT.'env-'.self::$m_sEnvironment.'/autoload.php');
  3969. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  3970. {
  3971. self::IncludeModule($sToInclude, 'addons');
  3972. }
  3973. $sServer = self::$m_oConfig->GetDBHost();
  3974. $sUser = self::$m_oConfig->GetDBUser();
  3975. $sPwd = self::$m_oConfig->GetDBPwd();
  3976. $sSource = self::$m_oConfig->GetDBName();
  3977. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  3978. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  3979. $sCollation = self::$m_oConfig->GetDBCollation();
  3980. if (self::$m_bUseAPCCache)
  3981. {
  3982. $oKPI = new ExecutionKPI();
  3983. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  3984. //
  3985. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-metamodel';
  3986. $result = apc_fetch($sOqlAPCCacheId);
  3987. if (is_array($result))
  3988. {
  3989. // todo - verifier que toutes les classes mentionnees ici sont chargees dans InitClasses()
  3990. self::$m_aExtensionClasses = $result['m_aExtensionClasses'];
  3991. self::$m_Category2Class = $result['m_Category2Class'];
  3992. self::$m_aRootClasses = $result['m_aRootClasses'];
  3993. self::$m_aParentClasses = $result['m_aParentClasses'];
  3994. self::$m_aChildClasses = $result['m_aChildClasses'];
  3995. self::$m_aClassParams = $result['m_aClassParams'];
  3996. self::$m_aAttribDefs = $result['m_aAttribDefs'];
  3997. self::$m_aAttribOrigins = $result['m_aAttribOrigins'];
  3998. self::$m_aExtKeyFriends = $result['m_aExtKeyFriends'];
  3999. self::$m_aIgnoredAttributes = $result['m_aIgnoredAttributes'];
  4000. self::$m_aFilterDefs = $result['m_aFilterDefs'];
  4001. self::$m_aFilterOrigins = $result['m_aFilterOrigins'];
  4002. self::$m_aListInfos = $result['m_aListInfos'];
  4003. self::$m_aListData = $result['m_aListData'];
  4004. self::$m_aRelationInfos = $result['m_aRelationInfos'];
  4005. self::$m_aStates = $result['m_aStates'];
  4006. self::$m_aStimuli = $result['m_aStimuli'];
  4007. self::$m_aTransitions = $result['m_aTransitions'];
  4008. self::$m_aHighlightScales = $result['m_aHighlightScales'];
  4009. self::$m_aEnumToMeta = $result['m_aEnumToMeta'];
  4010. }
  4011. $oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
  4012. }
  4013. if (count(self::$m_aAttribDefs) == 0)
  4014. {
  4015. // The includes have been included, let's browse the existing classes and
  4016. // develop some data based on the proposed model
  4017. $oKPI = new ExecutionKPI();
  4018. self::InitClasses($sTablePrefix);
  4019. $oKPI->ComputeAndReport('Initialization of Data model structures');
  4020. if (self::$m_bUseAPCCache)
  4021. {
  4022. $oKPI = new ExecutionKPI();
  4023. $aCache = array();
  4024. $aCache['m_aExtensionClasses'] = self::$m_aExtensionClasses;
  4025. $aCache['m_Category2Class'] = self::$m_Category2Class;
  4026. $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
  4027. $aCache['m_aParentClasses'] = self::$m_aParentClasses; // array of ("classname" => array of "parentclass")
  4028. $aCache['m_aChildClasses'] = self::$m_aChildClasses; // array of ("classname" => array of "childclass")
  4029. $aCache['m_aClassParams'] = self::$m_aClassParams; // array of ("classname" => array of class information)
  4030. $aCache['m_aAttribDefs'] = self::$m_aAttribDefs; // array of ("classname" => array of attributes)
  4031. $aCache['m_aAttribOrigins'] = self::$m_aAttribOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4032. $aCache['m_aExtKeyFriends'] = self::$m_aExtKeyFriends; // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  4033. $aCache['m_aIgnoredAttributes'] = self::$m_aIgnoredAttributes; //array of ("classname" => array of ("attcode")
  4034. $aCache['m_aFilterDefs'] = self::$m_aFilterDefs; // array of ("classname" => array filterdef)
  4035. $aCache['m_aFilterOrigins'] = self::$m_aFilterOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4036. $aCache['m_aListInfos'] = self::$m_aListInfos; // array of ("listcode" => various info on the list, common to every classes)
  4037. $aCache['m_aListData'] = self::$m_aListData; // array of ("classname" => array of "listcode" => list)
  4038. $aCache['m_aRelationInfos'] = self::$m_aRelationInfos; // array of ("relcode" => various info on the list, common to every classes)
  4039. $aCache['m_aStates'] = self::$m_aStates; // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  4040. $aCache['m_aStimuli'] = self::$m_aStimuli; // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  4041. $aCache['m_aTransitions'] = self::$m_aTransitions; // array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
  4042. $aCache['m_aHighlightScales'] = self::$m_aHighlightScales; // array of ("classname" => array of higlightcodes)))
  4043. $aCache['m_aEnumToMeta'] = self::$m_aEnumToMeta;
  4044. apc_store($sOqlAPCCacheId, $aCache);
  4045. $oKPI->ComputeAndReport('Metamodel APC (store)');
  4046. }
  4047. }
  4048. self::$m_sDBName = $sSource;
  4049. self::$m_sTablePrefix = $sTablePrefix;
  4050. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  4051. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  4052. // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
  4053. }
  4054. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  4055. {
  4056. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  4057. }
  4058. public static function GetModuleParameter($sModule, $sProperty, $defaultvalue = null)
  4059. {
  4060. $value = $defaultvalue;
  4061. if (!array_key_exists($sModule, self::$m_aModulesParameters))
  4062. {
  4063. }
  4064. if (!self::$m_aModulesParameters[$sModule] == null)
  4065. {
  4066. $value = self::$m_aModulesParameters[$sModule]->Get($sProperty, $defaultvalue);
  4067. }
  4068. return $value;
  4069. }
  4070. public static function GetConfig()
  4071. {
  4072. return self::$m_oConfig;
  4073. }
  4074. public static function GetEnvironmentId()
  4075. {
  4076. return md5(APPROOT).'-'.self::$m_sEnvironment;
  4077. }
  4078. protected static $m_aExtensionClasses = array();
  4079. protected static function IncludeModule($sToInclude, $sModuleType = null)
  4080. {
  4081. $sFirstChar = substr($sToInclude, 0, 1);
  4082. $sSecondChar = substr($sToInclude, 1, 1);
  4083. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  4084. {
  4085. // It is a relative path, prepend APPROOT
  4086. if (substr($sToInclude, 0, 3) == '../')
  4087. {
  4088. // Preserve compatibility with config files written before 1.0.1
  4089. // Replace '../' by '<root>/'
  4090. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  4091. }
  4092. else
  4093. {
  4094. $sFile = APPROOT.'/'.$sToInclude;
  4095. }
  4096. }
  4097. else
  4098. {
  4099. // Leave as is - should be an absolute path
  4100. $sFile = $sToInclude;
  4101. }
  4102. if (!file_exists($sFile))
  4103. {
  4104. $sConfigFile = self::$m_oConfig->GetLoadedFile();
  4105. if ($sModuleType == null)
  4106. {
  4107. throw new CoreException("Include: unable to load the file '$sFile'");
  4108. }
  4109. else
  4110. {
  4111. if (strlen($sConfigFile) > 0)
  4112. {
  4113. throw new CoreException('Include: wrong file name in configuration file', array('config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile));
  4114. }
  4115. else
  4116. {
  4117. // The configuration is in memory only
  4118. throw new CoreException('Include: wrong file name in configuration file (in memory)', array('section' => $sModuleType, 'filename' => $sFile));
  4119. }
  4120. }
  4121. }
  4122. // Note: We do not expect the modules to output characters while loading them.
  4123. // Therefore, and because unexpected characters can corrupt the output,
  4124. // they must be trashed here.
  4125. // Additionnaly, pages aiming at delivering data in their output can call WebPage::TrashUnexpectedOutput()
  4126. // to get rid of chars that could be generated during the execution of the code
  4127. ob_start();
  4128. require_once($sFile);
  4129. $sPreviousContent = ob_get_clean();
  4130. if (self::$m_oConfig->Get('debug_report_spurious_chars'))
  4131. {
  4132. if ($sPreviousContent != '')
  4133. {
  4134. IssueLog::Error("Spurious characters injected by '$sFile'");
  4135. }
  4136. }
  4137. }
  4138. // Building an object
  4139. //
  4140. //
  4141. private static $aQueryCacheGetObject = array();
  4142. private static $aQueryCacheGetObjectHits = array();
  4143. public static function GetQueryCacheStatus()
  4144. {
  4145. $aRes = array();
  4146. $iTotalHits = 0;
  4147. foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
  4148. {
  4149. $aRes[] = "$sClassSign: $iHits";
  4150. $iTotalHits += $iHits;
  4151. }
  4152. return $iTotalHits.' ('.implode(', ', $aRes).')';
  4153. }
  4154. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4155. {
  4156. // Build the query cache signature
  4157. //
  4158. $sQuerySign = $sClass;
  4159. if($bAllowAllData)
  4160. {
  4161. $sQuerySign .= '_all_';
  4162. }
  4163. if (count($aModifierProperties))
  4164. {
  4165. array_multisort($aModifierProperties);
  4166. $sModifierProperties = json_encode($aModifierProperties);
  4167. $sQuerySign .= '_all_'.md5($sModifierProperties);
  4168. }
  4169. if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
  4170. {
  4171. // NOTE: Quick and VERY dirty caching mechanism which relies on
  4172. // the fact that the string '987654321' will never appear in the
  4173. // standard query
  4174. // This could be simplified a little, relying solely on the query cache,
  4175. // but this would slow down -by how much time?- the application
  4176. $oFilter = new DBObjectSearch($sClass);
  4177. $oFilter->AddCondition('id', 987654321, '=');
  4178. if ($aModifierProperties)
  4179. {
  4180. foreach ($aModifierProperties as $sPluginClass => $aProperties)
  4181. {
  4182. foreach ($aProperties as $sProperty => $value)
  4183. {
  4184. $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
  4185. }
  4186. }
  4187. }
  4188. if ($bAllowAllData)
  4189. {
  4190. $oFilter->AllowAllData();
  4191. }
  4192. $oFilter->NoContextParameters();
  4193. $sSQL = $oFilter->MakeSelectQuery();
  4194. self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
  4195. self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
  4196. }
  4197. else
  4198. {
  4199. $sSQL = self::$aQueryCacheGetObject[$sQuerySign];
  4200. self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
  4201. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sQuerySign]."<br/>\n";
  4202. }
  4203. $sSQL = str_replace(CMDBSource::Quote(987654321), CMDBSource::Quote($iKey), $sSQL);
  4204. $res = CMDBSource::Query($sSQL);
  4205. $aRow = CMDBSource::FetchArray($res);
  4206. CMDBSource::FreeResult($res);
  4207. if ($bMustBeFound && empty($aRow))
  4208. {
  4209. throw new CoreException("No result for the single row query: '$sSQL'");
  4210. }
  4211. return $aRow;
  4212. }
  4213. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  4214. {
  4215. self::_check_subclass($sClass);
  4216. if (strlen($sClassAlias) == 0)
  4217. {
  4218. $sClassAlias = $sClass;
  4219. }
  4220. // Compound objects: if available, get the final object class
  4221. //
  4222. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  4223. {
  4224. // Either this is a bug (forgot to specify a root class with a finalclass field
  4225. // Or this is the expected behavior, because the object is not made of several tables
  4226. }
  4227. elseif (empty($aRow[$sClassAlias."finalclass"]))
  4228. {
  4229. // The data is missing in the DB
  4230. // @#@ possible improvement: check that the class is valid !
  4231. $sRootClass = self::GetRootClass($sClass);
  4232. $sFinalClassField = self::DBGetClassField($sRootClass);
  4233. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  4234. }
  4235. else
  4236. {
  4237. // do the job for the real target class
  4238. $sClass = $aRow[$sClassAlias."finalclass"];
  4239. }
  4240. return new $sClass($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  4241. }
  4242. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4243. {
  4244. self::_check_subclass($sClass);
  4245. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4246. if (empty($aRow))
  4247. {
  4248. return null;
  4249. }
  4250. return self::GetObjectByRow($sClass, $aRow);
  4251. }
  4252. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  4253. {
  4254. self::_check_subclass($sClass);
  4255. $oObjSearch = new DBObjectSearch($sClass);
  4256. $oObjSearch->AddNameCondition($sName);
  4257. $oSet = new DBObjectSet($oObjSearch);
  4258. if ($oSet->Count() != 1)
  4259. {
  4260. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  4261. return null;
  4262. }
  4263. $oObj = $oSet->fetch();
  4264. return $oObj;
  4265. }
  4266. static protected $m_aCacheObjectByColumn = array();
  4267. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  4268. {
  4269. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  4270. {
  4271. self::_check_subclass($sClass);
  4272. $oObjSearch = new DBObjectSearch($sClass);
  4273. $oObjSearch->AddCondition($sAttCode, $value, '=');
  4274. $oSet = new DBObjectSet($oObjSearch);
  4275. if ($oSet->Count() == 1)
  4276. {
  4277. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  4278. }
  4279. else
  4280. {
  4281. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  4282. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  4283. }
  4284. }
  4285. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  4286. }
  4287. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  4288. {
  4289. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  4290. if ($bAllowAllData)
  4291. {
  4292. $oFilter->AllowAllData();
  4293. }
  4294. $oSet = new DBObjectSet($oFilter);
  4295. $oObject = $oSet->Fetch();
  4296. return $oObject;
  4297. }
  4298. public static function GetHyperLink($sTargetClass, $iKey)
  4299. {
  4300. if ($iKey < 0)
  4301. {
  4302. return "$sTargetClass: $iKey (invalid value)";
  4303. }
  4304. $oObj = self::GetObject($sTargetClass, $iKey, false);
  4305. if (is_null($oObj))
  4306. {
  4307. // Whatever we are looking for, the root class is the key to search for
  4308. $sRootClass = self::GetRootClass($sTargetClass);
  4309. $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
  4310. $oSet = new DBObjectSet($oSearch);
  4311. $oRecord = $oSet->Fetch();
  4312. // An empty fname is obtained with iTop < 2.0
  4313. if (is_null($oRecord) || (strlen(trim($oRecord->Get('fname'))) == 0))
  4314. {
  4315. $sName = Dict::Format('Core:UnknownObjectLabel', $sTargetClass, $iKey);
  4316. $sTitle = Dict::S('Core:UnknownObjectTip');
  4317. }
  4318. else
  4319. {
  4320. $sName = $oRecord->Get('fname');
  4321. $sTitle = Dict::Format('Core:DeletedObjectTip', $oRecord->Get('date'), $oRecord->Get('userinfo'));
  4322. }
  4323. return '<span class="itop-deleted-object" title="'.htmlentities($sTitle, ENT_QUOTES, 'UTF-8').'">'.htmlentities($sName, ENT_QUOTES, 'UTF-8').'</span>';
  4324. }
  4325. return $oObj->GetHyperLink();
  4326. }
  4327. public static function NewObject($sClass)
  4328. {
  4329. self::_check_subclass($sClass);
  4330. return new $sClass();
  4331. }
  4332. public static function GetNextKey($sClass)
  4333. {
  4334. $sRootClass = MetaModel::GetRootClass($sClass);
  4335. $sRootTable = MetaModel::DBGetTable($sRootClass);
  4336. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  4337. return $iNextKey;
  4338. }
  4339. /**
  4340. * Deletion of records, bypassing DBObject::DBDelete !!!
  4341. * It is NOT recommended to use this shortcut
  4342. * In particular, it will not work
  4343. * - if the class is not a final class
  4344. * - if the class has a hierarchical key (need to rebuild the indexes)
  4345. * - if the class overload DBDelete !
  4346. * Todo: protect it against forbidden usages (in such a case, delete objects one by one)
  4347. */
  4348. public static function BulkDelete(DBObjectSearch $oFilter)
  4349. {
  4350. $sSQL = $oFilter->MakeDeleteQuery();
  4351. if (!self::DBIsReadOnly())
  4352. {
  4353. CMDBSource::Query($sSQL);
  4354. }
  4355. }
  4356. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  4357. {
  4358. // $aValues is an array of $sAttCode => $value
  4359. $sSQL = $oFilter->MakeUpdateQuery($aValues);
  4360. if (!self::DBIsReadOnly())
  4361. {
  4362. CMDBSource::Query($sSQL);
  4363. }
  4364. }
  4365. /**
  4366. * Helper to remove selected objects without calling any handler
  4367. * Surpasses BulkDelete as it can handle abstract classes, but has the other limitation as it bypasses standard objects handlers
  4368. *
  4369. * @param string $oFilter Scope of objects to wipe out
  4370. * @return The count of deleted objects
  4371. */
  4372. public static function PurgeData($oFilter)
  4373. {
  4374. $sTargetClass = $oFilter->GetClass();
  4375. $oSet = new DBObjectSet($oFilter);
  4376. $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass')));
  4377. $aIdToClass = $oSet->GetColumnAsArray('finalclass', true);
  4378. $aIds = array_keys($aIdToClass);
  4379. if (count($aIds) > 0)
  4380. {
  4381. $aQuotedIds = CMDBSource::Quote($aIds);
  4382. $sIdList = implode(',', $aQuotedIds);
  4383. $aTargetClasses = array_merge(
  4384. self::EnumChildClasses($sTargetClass, ENUM_CHILD_CLASSES_ALL),
  4385. self::EnumParentClasses($sTargetClass, ENUM_PARENT_CLASSES_EXCLUDELEAF)
  4386. );
  4387. foreach ($aTargetClasses as $sSomeClass)
  4388. {
  4389. $sTable = MetaModel::DBGetTable($sSomeClass);
  4390. $sPKField = MetaModel::DBGetKey($sSomeClass);
  4391. $sDeleteSQL = "DELETE FROM `$sTable` WHERE `$sPKField` IN ($sIdList)";
  4392. CMDBSource::DeleteFrom($sDeleteSQL);
  4393. }
  4394. }
  4395. return count($aIds);
  4396. }
  4397. // Links
  4398. //
  4399. //
  4400. public static function EnumReferencedClasses($sClass)
  4401. {
  4402. self::_check_subclass($sClass);
  4403. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  4404. $aResult = array();
  4405. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  4406. {
  4407. if ($oAttDef->IsExternalKey())
  4408. {
  4409. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  4410. }
  4411. }
  4412. return $aResult;
  4413. }
  4414. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  4415. {
  4416. self::_check_subclass($sClass);
  4417. if ($bSkipLinkingClasses)
  4418. {
  4419. $aLinksClasses = self::EnumLinksClasses();
  4420. }
  4421. // 1-N links (referencing my class), array of sClass => array of sAttcode
  4422. $aResult = array();
  4423. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4424. {
  4425. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  4426. $aExtKeys = array();
  4427. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4428. {
  4429. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4430. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  4431. {
  4432. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  4433. // Ok, I want this one
  4434. $aExtKeys[$sAttCode] = $oAttDef;
  4435. }
  4436. }
  4437. if (count($aExtKeys) != 0)
  4438. {
  4439. $aResult[$sSomeClass] = $aExtKeys;
  4440. }
  4441. }
  4442. return $aResult;
  4443. }
  4444. /**
  4445. * It is not recommended to use this function: call GetLinkClasses instead
  4446. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4447. * The only difference with EnumLinkingClasses is the output format
  4448. */
  4449. public static function EnumLinksClasses()
  4450. {
  4451. // Returns a flat array of classes having at least two external keys
  4452. $aResult = array();
  4453. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4454. {
  4455. $iExtKeyCount = 0;
  4456. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4457. {
  4458. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4459. if ($oAttDef->IsExternalKey())
  4460. {
  4461. $iExtKeyCount++;
  4462. }
  4463. }
  4464. if ($iExtKeyCount >= 2)
  4465. {
  4466. $aResult[] = $sSomeClass;
  4467. }
  4468. }
  4469. return $aResult;
  4470. }
  4471. /**
  4472. * It is not recommended to use this function: call GetLinkClasses instead
  4473. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4474. * The only difference with EnumLinksClasses is the output format
  4475. */
  4476. public static function EnumLinkingClasses($sClass = "")
  4477. {
  4478. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  4479. $aResult = array();
  4480. foreach (self::EnumLinksClasses() as $sSomeClass)
  4481. {
  4482. $aTargets = array();
  4483. $bFoundClass = false;
  4484. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  4485. {
  4486. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4487. if ($oAttDef->IsExternalKey())
  4488. {
  4489. $sRemoteClass = $oAttDef->GetTargetClass();
  4490. if (empty($sClass))
  4491. {
  4492. $aTargets[$sAttCode] = $sRemoteClass;
  4493. }
  4494. elseif ($sClass == $sRemoteClass)
  4495. {
  4496. $bFoundClass = true;
  4497. }
  4498. else
  4499. {
  4500. $aTargets[$sAttCode] = $sRemoteClass;
  4501. }
  4502. }
  4503. }
  4504. if (empty($sClass) || $bFoundClass)
  4505. {
  4506. $aResult[$sSomeClass] = $aTargets;
  4507. }
  4508. }
  4509. return $aResult;
  4510. }
  4511. /**
  4512. * This function has two siblings that will be soon deprecated:
  4513. * EnumLinkingClasses and EnumLinkClasses
  4514. *
  4515. * Using GetLinkClasses is the recommended way to determine if a class is
  4516. * actually an N-N relation because it is based on the decision made by the
  4517. * designer the data model
  4518. */
  4519. public static function GetLinkClasses()
  4520. {
  4521. $aRet = array();
  4522. foreach(self::GetClasses() as $sClass)
  4523. {
  4524. if (isset(self::$m_aClassParams[$sClass]["is_link"]))
  4525. {
  4526. if (self::$m_aClassParams[$sClass]["is_link"])
  4527. {
  4528. $aExtKeys = array();
  4529. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  4530. {
  4531. if ($oAttDef->IsExternalKey())
  4532. {
  4533. $aExtKeys[$sAttCode] = $oAttDef->GetTargetClass();
  4534. }
  4535. }
  4536. $aRet[$sClass] = $aExtKeys;
  4537. }
  4538. }
  4539. }
  4540. return $aRet;
  4541. }
  4542. public static function GetLinkLabel($sLinkClass, $sAttCode)
  4543. {
  4544. self::_check_subclass($sLinkClass);
  4545. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  4546. return self::GetLabel($sLinkClass, $sAttCode);
  4547. }
  4548. /**
  4549. * Replaces all the parameters by the values passed in the hash array
  4550. */
  4551. static public function ApplyParams($sInput, $aParams)
  4552. {
  4553. // Declare magic parameters
  4554. $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
  4555. $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
  4556. $aSearches = array();
  4557. $aReplacements = array();
  4558. foreach($aParams as $sSearch => $replace)
  4559. {
  4560. // Some environment parameters are objects, we just need scalars
  4561. if (is_object($replace))
  4562. {
  4563. $iPos = strpos($sSearch, '->object()');
  4564. if ($iPos !== false)
  4565. {
  4566. // Expand the parameters for the object
  4567. $sName = substr($sSearch, 0, $iPos);
  4568. if (preg_match_all('/\\$'.$sName.'-(>|&gt;)([^\\$]+)\\$/', $sInput, $aMatches)) // Support both syntaxes: $this->xxx$ or $this-&gt;xxx$ for HTML compatibility
  4569. {
  4570. foreach($aMatches[2] as $idx => $sPlaceholderAttCode)
  4571. {
  4572. try
  4573. {
  4574. $sReplacement = $replace->GetForTemplate($sPlaceholderAttCode);
  4575. if ($sReplacement !== null)
  4576. {
  4577. $aReplacements[] = $sReplacement;
  4578. $aSearches[] = '$'.$sName.'-'.$aMatches[1][$idx].$sPlaceholderAttCode.'$';
  4579. }
  4580. }
  4581. catch(Exception $e)
  4582. {
  4583. // No replacement will occur
  4584. }
  4585. }
  4586. }
  4587. }
  4588. else
  4589. {
  4590. continue; // Ignore this non-scalar value
  4591. }
  4592. }
  4593. else
  4594. {
  4595. $aSearches[] = '$'.$sSearch.'$';
  4596. $aReplacements[] = (string) $replace;
  4597. }
  4598. }
  4599. return str_replace($aSearches, $aReplacements, $sInput);
  4600. }
  4601. /**
  4602. * Returns an array of classes=>instance implementing the given interface
  4603. */
  4604. public static function EnumPlugins($sInterface)
  4605. {
  4606. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4607. {
  4608. return self::$m_aExtensionClasses[$sInterface];
  4609. }
  4610. else
  4611. {
  4612. return array();
  4613. }
  4614. }
  4615. /**
  4616. * Returns the instance of the specified plug-ins for the given interface
  4617. */
  4618. public static function GetPlugins($sInterface, $sClassName)
  4619. {
  4620. $oInstance = null;
  4621. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4622. {
  4623. if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
  4624. {
  4625. return self::$m_aExtensionClasses[$sInterface][$sClassName];
  4626. }
  4627. }
  4628. return $oInstance;
  4629. }
  4630. public static function GetCacheEntries($sEnvironment = null)
  4631. {
  4632. if (!function_exists('apc_cache_info')) return array();
  4633. if (is_null($sEnvironment))
  4634. {
  4635. $sEnvironment = MetaModel::GetEnvironmentId();
  4636. }
  4637. $aEntries = array();
  4638. if (extension_loaded('apcu'))
  4639. {
  4640. // Beware: APCu behaves slightly differently from APC !!
  4641. $aCacheUserData = @apc_cache_info();
  4642. }
  4643. else
  4644. {
  4645. $aCacheUserData = @apc_cache_info('user');
  4646. }
  4647. if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
  4648. {
  4649. $sPrefix = 'itop-'.$sEnvironment.'-';
  4650. foreach($aCacheUserData['cache_list'] as $i => $aEntry)
  4651. {
  4652. $sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
  4653. if (strpos($sEntryKey, $sPrefix) === 0)
  4654. {
  4655. $sCleanKey = substr($sEntryKey, strlen($sPrefix));
  4656. $aEntries[$sCleanKey] = $aEntry;
  4657. $aEntries[$sCleanKey]['info'] = $sEntryKey;
  4658. }
  4659. }
  4660. }
  4661. return $aEntries;
  4662. }
  4663. public static function ResetCache($sEnvironmentId = null)
  4664. {
  4665. if (!function_exists('apc_delete')) return;
  4666. if (is_null($sEnvironmentId))
  4667. {
  4668. $sEnvironmentId = MetaModel::GetEnvironmentId();
  4669. }
  4670. $sAppIdentity = 'itop-'.$sEnvironmentId;
  4671. Dict::ResetCache($sAppIdentity);
  4672. foreach(self::GetCacheEntries($sEnvironmentId) as $sKey => $aAPCInfo)
  4673. {
  4674. $sAPCKey = $aAPCInfo['info'];
  4675. apc_delete($sAPCKey);
  4676. }
  4677. }
  4678. /**
  4679. * Given a field spec, get the most relevant (unique) representation
  4680. * Examples for a user request:
  4681. * - friendlyname => ref
  4682. * - org_name => org_id->name
  4683. * - org_id_friendlyname => org_id=>name
  4684. * - caller_name => caller_id->name
  4685. * - caller_id_friendlyname => caller_id->friendlyname
  4686. * @param string $sClass
  4687. * @param string $sField
  4688. * @return string
  4689. */
  4690. public static function NormalizeFieldSpec($sClass, $sField)
  4691. {
  4692. $sRet = $sField;
  4693. if ($sField == 'id')
  4694. {
  4695. $sRet = 'id';
  4696. }
  4697. elseif ($sField == 'friendlyname')
  4698. {
  4699. $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sClass);
  4700. if (!is_null($sFriendlyNameAttCode))
  4701. {
  4702. // The friendly name is made of a single attribute
  4703. $sRet = $sFriendlyNameAttCode;
  4704. }
  4705. }
  4706. else
  4707. {
  4708. $oAttDef = static::GetAttributeDef($sClass, $sField);
  4709. if ($oAttDef instanceof AttributeFriendlyName)
  4710. {
  4711. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $oAttDef->GetKeyAttCode());
  4712. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  4713. $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sRemoteClass);
  4714. if (is_null($sFriendlyNameAttCode))
  4715. {
  4716. // The friendly name is made of several attributes
  4717. $sRet = $oAttDef->GetKeyAttCode().'->friendlyname';
  4718. }
  4719. else
  4720. {
  4721. // The friendly name is made of a single attribute
  4722. $sRet = $oAttDef->GetKeyAttCode().'->'.$sFriendlyNameAttCode;
  4723. }
  4724. }
  4725. elseif ($oAttDef->IsExternalField())
  4726. {
  4727. $sRet = $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode();
  4728. }
  4729. }
  4730. return $sRet;
  4731. }
  4732. } // class MetaModel
  4733. // Standard attribute lists
  4734. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  4735. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  4736. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  4737. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  4738. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  4739. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));