metamodel.class.php 160 KB

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