metamodel.class.php 162 KB

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