metamodel.class.php 162 KB

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