metamodel.class.php 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725
  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. /**
  17. * Metamodel
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. // #@# todo: change into class const (see Doctrine)
  25. // Doctrine example
  26. // class toto
  27. // {
  28. // /**
  29. // * VERSION
  30. // */
  31. // const VERSION = '1.0.0';
  32. // }
  33. /**
  34. * add some description here...
  35. *
  36. * @package iTopORM
  37. */
  38. define('ENUM_CHILD_CLASSES_EXCLUDETOP', 1);
  39. /**
  40. * add some description here...
  41. *
  42. * @package iTopORM
  43. */
  44. define('ENUM_CHILD_CLASSES_ALL', 2);
  45. /**
  46. * add some description here...
  47. *
  48. * @package iTopORM
  49. */
  50. define('ENUM_PARENT_CLASSES_EXCLUDELEAF', 1);
  51. /**
  52. * add some description here...
  53. *
  54. * @package iTopORM
  55. */
  56. define('ENUM_PARENT_CLASSES_ALL', 2);
  57. /**
  58. * Specifies that this attribute is visible/editable.... normal (default config)
  59. *
  60. * @package iTopORM
  61. */
  62. define('OPT_ATT_NORMAL', 0);
  63. /**
  64. * Specifies that this attribute is hidden in that state
  65. *
  66. * @package iTopORM
  67. */
  68. define('OPT_ATT_HIDDEN', 1);
  69. /**
  70. * Specifies that this attribute is not editable in that state
  71. *
  72. * @package iTopORM
  73. */
  74. define('OPT_ATT_READONLY', 2);
  75. /**
  76. * Specifieds that the attribute must be set (different than default value?) when arriving into that state
  77. *
  78. * @package iTopORM
  79. */
  80. define('OPT_ATT_MANDATORY', 4);
  81. /**
  82. * Specifies that the attribute must change when arriving into that state
  83. *
  84. * @package iTopORM
  85. */
  86. define('OPT_ATT_MUSTCHANGE', 8);
  87. /**
  88. * Specifies that the attribute must be proposed when arriving into that state
  89. *
  90. * @package iTopORM
  91. */
  92. define('OPT_ATT_MUSTPROMPT', 16);
  93. /**
  94. * DB Engine -should be moved into CMDBSource
  95. *
  96. * @package iTopORM
  97. */
  98. define('MYSQL_ENGINE', 'innodb');
  99. //define('MYSQL_ENGINE', 'myisam');
  100. /**
  101. * (API) The objects definitions as well as their mapping to the database
  102. *
  103. * @package iTopORM
  104. */
  105. abstract class MetaModel
  106. {
  107. ///////////////////////////////////////////////////////////////////////////
  108. //
  109. // STATIC Members
  110. //
  111. ///////////////////////////////////////////////////////////////////////////
  112. // Purpose: workaround the following limitation = PHP5 does not allow to know the class (derived from the current one)
  113. // from which a static function is called (__CLASS__ and self are interpreted during parsing)
  114. private static function GetCallersPHPClass($sExpectedFunctionName = null)
  115. {
  116. //var_dump(debug_backtrace());
  117. $aBacktrace = debug_backtrace();
  118. // $aBacktrace[0] is where we are
  119. // $aBacktrace[1] is the caller of GetCallersPHPClass
  120. // $aBacktrace[1] is the info we want
  121. if (!empty($sExpectedFunctionName))
  122. {
  123. assert('$aBacktrace[2]["function"] == $sExpectedFunctionName');
  124. }
  125. return $aBacktrace[2]["class"];
  126. }
  127. // Static init -why and how it works
  128. //
  129. // We found the following limitations:
  130. //- it is not possible to define non scalar constants
  131. //- it is not possible to declare a static variable as '= new myclass()'
  132. // Then we had do propose this model, in which a derived (non abstract)
  133. // class should implement Init(), to call InheritAttributes or AddAttribute.
  134. private static function _check_subclass($sClass)
  135. {
  136. // See also IsValidClass()... ???? #@#
  137. // class is mandatory
  138. // (it is not possible to guess it when called as myderived::...)
  139. if (!array_key_exists($sClass, self::$m_aClassParams))
  140. {
  141. throw new CoreException("Unknown class '$sClass', expected a value in {".implode(', ', array_keys(self::$m_aClassParams))."}");
  142. }
  143. }
  144. public static function static_var_dump()
  145. {
  146. var_dump(get_class_vars(__CLASS__));
  147. }
  148. private static $m_bDebugQuery = false;
  149. private static $m_iStackDepthRef = 0;
  150. public static function StartDebugQuery()
  151. {
  152. $aBacktrace = debug_backtrace();
  153. self::$m_iStackDepthRef = count($aBacktrace);
  154. self::$m_bDebugQuery = true;
  155. }
  156. public static function StopDebugQuery()
  157. {
  158. self::$m_bDebugQuery = false;
  159. }
  160. public static function DbgTrace($value)
  161. {
  162. if (!self::$m_bDebugQuery) return;
  163. $aBacktrace = debug_backtrace();
  164. $iCallStackPos = count($aBacktrace) - self::$m_bDebugQuery;
  165. $sIndent = "";
  166. for ($i = 0 ; $i < $iCallStackPos ; $i++)
  167. {
  168. $sIndent .= " .-=^=-. ";
  169. }
  170. $aCallers = array();
  171. foreach($aBacktrace as $aStackInfo)
  172. {
  173. $aCallers[] = $aStackInfo["function"];
  174. }
  175. $sCallers = "Callstack: ".implode(', ', $aCallers);
  176. $sFunction = "<b title=\"$sCallers\">".$aBacktrace[1]["function"]."</b>";
  177. if (is_string($value))
  178. {
  179. echo "$sIndent$sFunction: $value<br/>\n";
  180. }
  181. else if (is_object($value))
  182. {
  183. echo "$sIndent$sFunction:\n<pre>\n";
  184. print_r($value);
  185. echo "</pre>\n";
  186. }
  187. else
  188. {
  189. echo "$sIndent$sFunction: $value<br/>\n";
  190. }
  191. }
  192. private static $m_oConfig = null;
  193. private static $m_bSkipCheckToWrite = false;
  194. private static $m_bSkipCheckExtKeys = false;
  195. private static $m_bQueryCacheEnabled = false;
  196. private static $m_bTraceQueries = false;
  197. private static $m_aQueriesLog = array();
  198. private static $m_bLogIssue = false;
  199. private static $m_bLogNotification = false;
  200. private static $m_bLogWebService = false;
  201. public static function SkipCheckToWrite()
  202. {
  203. return self::$m_bSkipCheckToWrite;
  204. }
  205. public static function SkipCheckExtKeys()
  206. {
  207. return self::$m_bSkipCheckExtKeys;
  208. }
  209. public static function IsLogEnabledIssue()
  210. {
  211. return self::$m_bLogIssue;
  212. }
  213. public static function IsLogEnabledNotification()
  214. {
  215. return self::$m_bLogNotification;
  216. }
  217. public static function IsLogEnabledWebService()
  218. {
  219. return self::$m_bLogWebService;
  220. }
  221. private static $m_sDBName = "";
  222. private static $m_sTablePrefix = ""; // table prefix for the current application instance (allow several applications on the same DB)
  223. private static $m_Category2Class = array();
  224. private static $m_aRootClasses = array(); // array of "classname" => "rootclass"
  225. private static $m_aParentClasses = array(); // array of ("classname" => array of "parentclass")
  226. private static $m_aChildClasses = array(); // array of ("classname" => array of "childclass")
  227. private static $m_aClassParams = array(); // array of ("classname" => array of class information)
  228. static public function GetParentPersistentClass($sRefClass)
  229. {
  230. $sClass = get_parent_class($sRefClass);
  231. if (!$sClass) return '';
  232. if ($sClass == 'DBObject') return ''; // Warning: __CLASS__ is lower case in my version of PHP
  233. // Note: the UI/business model may implement pure PHP classes (intermediate layers)
  234. if (array_key_exists($sClass, self::$m_aClassParams))
  235. {
  236. return $sClass;
  237. }
  238. return self::GetParentPersistentClass($sClass);
  239. }
  240. final static public function GetName($sClass)
  241. {
  242. self::_check_subclass($sClass);
  243. $sStringCode = 'Class:'.$sClass;
  244. return Dict::S($sStringCode, $sClass);
  245. }
  246. final static public function GetName_Obsolete($sClass)
  247. {
  248. // Written for compatibility with a data model written prior to version 0.9.1
  249. self::_check_subclass($sClass);
  250. if (array_key_exists('name', self::$m_aClassParams[$sClass]))
  251. {
  252. return self::$m_aClassParams[$sClass]['name'];
  253. }
  254. else
  255. {
  256. return self::GetName($sClass);
  257. }
  258. }
  259. final static public function GetCategory($sClass)
  260. {
  261. self::_check_subclass($sClass);
  262. return self::$m_aClassParams[$sClass]["category"];
  263. }
  264. final static public function HasCategory($sClass, $sCategory)
  265. {
  266. self::_check_subclass($sClass);
  267. return (strpos(self::$m_aClassParams[$sClass]["category"], $sCategory) !== false);
  268. }
  269. final static public function GetClassDescription($sClass)
  270. {
  271. self::_check_subclass($sClass);
  272. $sStringCode = 'Class:'.$sClass.'+';
  273. return Dict::S($sStringCode, '');
  274. }
  275. final static public function GetClassDescription_Obsolete($sClass)
  276. {
  277. // Written for compatibility with a data model written prior to version 0.9.1
  278. self::_check_subclass($sClass);
  279. if (array_key_exists('description', self::$m_aClassParams[$sClass]))
  280. {
  281. return self::$m_aClassParams[$sClass]['description'];
  282. }
  283. else
  284. {
  285. return self::GetClassDescription($sClass);
  286. }
  287. }
  288. final static public function GetClassIcon($sClass, $bImgTag = true, $sMoreStyles = '')
  289. {
  290. self::_check_subclass($sClass);
  291. $sIcon = '';
  292. if (array_key_exists('icon', self::$m_aClassParams[$sClass]))
  293. {
  294. $sIcon = self::$m_aClassParams[$sClass]['icon'];
  295. }
  296. if (strlen($sIcon) == 0)
  297. {
  298. $sParentClass = self::GetParentPersistentClass($sClass);
  299. if (strlen($sParentClass) > 0)
  300. {
  301. return self::GetClassIcon($sParentClass);
  302. }
  303. }
  304. if ($bImgTag && ($sIcon != ''))
  305. {
  306. $sIcon = "<img src=\"$sIcon\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  307. }
  308. return $sIcon;
  309. }
  310. final static public function IsAutoIncrementKey($sClass)
  311. {
  312. self::_check_subclass($sClass);
  313. return (self::$m_aClassParams[$sClass]["key_type"] == "autoincrement");
  314. }
  315. final static public function GetNameAttributeCode($sClass)
  316. {
  317. self::_check_subclass($sClass);
  318. return self::$m_aClassParams[$sClass]["name_attcode"];
  319. }
  320. final static public function GetStateAttributeCode($sClass)
  321. {
  322. self::_check_subclass($sClass);
  323. return self::$m_aClassParams[$sClass]["state_attcode"];
  324. }
  325. final static public function GetDefaultState($sClass)
  326. {
  327. $sDefaultState = '';
  328. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  329. if (!empty($sStateAttrCode))
  330. {
  331. $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  332. $sDefaultState = $oStateAttrDef->GetDefaultValue();
  333. }
  334. return $sDefaultState;
  335. }
  336. final static public function GetReconcKeys($sClass)
  337. {
  338. self::_check_subclass($sClass);
  339. return self::$m_aClassParams[$sClass]["reconc_keys"];
  340. }
  341. final static public function GetDisplayTemplate($sClass)
  342. {
  343. self::_check_subclass($sClass);
  344. return array_key_exists("display_template", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["display_template"]: '';
  345. }
  346. final static public function GetAttributeOrigin($sClass, $sAttCode)
  347. {
  348. self::_check_subclass($sClass);
  349. return self::$m_aAttribOrigins[$sClass][$sAttCode];
  350. }
  351. final static public function GetPrequisiteAttributes($sClass, $sAttCode)
  352. {
  353. self::_check_subclass($sClass);
  354. $oAtt = self::GetAttributeDef($sClass, $sAttCode);
  355. // Temporary implementation: later, we might be able to compute
  356. // the dependencies, based on the attributes definition
  357. // (allowed values and default values)
  358. if ($oAtt->IsWritable())
  359. {
  360. return $oAtt->GetPrerequisiteAttributes();
  361. }
  362. else
  363. {
  364. return array();
  365. }
  366. }
  367. /**
  368. * Find all attributes that depend on the specified one (reverse of GetPrequisiteAttributes)
  369. * @param string $sClass Name of the class
  370. * @param string $sAttCode Code of the attributes
  371. * @return Array List of attribute codes that depend on the given attribute, empty array if none.
  372. */
  373. final static public function GetDependentAttributes($sClass, $sAttCode)
  374. {
  375. $aResults = array();
  376. self::_check_subclass($sClass);
  377. foreach (self::ListAttributeDefs($sClass) as $sDependentAttCode=>$void)
  378. {
  379. $aPrerequisites = self::GetPrequisiteAttributes($sClass, $sDependentAttCode);
  380. if (in_array($sAttCode, $aPrerequisites))
  381. {
  382. $aResults[] = $sDependentAttCode;
  383. }
  384. }
  385. return $aResults;
  386. }
  387. // #@# restore to private ?
  388. final static public function DBGetTable($sClass, $sAttCode = null)
  389. {
  390. self::_check_subclass($sClass);
  391. if (empty($sAttCode) || ($sAttCode == "id"))
  392. {
  393. $sTableRaw = self::$m_aClassParams[$sClass]["db_table"];
  394. if (empty($sTableRaw))
  395. {
  396. // return an empty string whenever the table is undefined, meaning that there is no table associated to this 'abstract' class
  397. return '';
  398. }
  399. else
  400. {
  401. return self::$m_sTablePrefix.$sTableRaw;
  402. }
  403. }
  404. // This attribute has been inherited (compound objects)
  405. return self::DBGetTable(self::$m_aAttribOrigins[$sClass][$sAttCode]);
  406. }
  407. final static public function DBGetView($sClass)
  408. {
  409. return self::$m_sTablePrefix."view_".$sClass;
  410. }
  411. final static protected function DBEnumTables()
  412. {
  413. // This API do not rely on our capability to query the DB and retrieve
  414. // the list of existing tables
  415. // Rather, it uses the list of expected tables, corresponding to the data model
  416. $aTables = array();
  417. foreach (self::GetClasses() as $sClass)
  418. {
  419. if (!self::HasTable($sClass)) continue;
  420. $sTable = self::DBGetTable($sClass);
  421. // Could be completed later with all the classes that are using a given table
  422. if (!array_key_exists($sTable, $aTables))
  423. {
  424. $aTables[$sTable] = array();
  425. }
  426. $aTables[$sTable][] = $sClass;
  427. }
  428. return $aTables;
  429. }
  430. final static public function DBGetKey($sClass)
  431. {
  432. self::_check_subclass($sClass);
  433. return self::$m_aClassParams[$sClass]["db_key_field"];
  434. }
  435. final static public function DBGetClassField($sClass)
  436. {
  437. self::_check_subclass($sClass);
  438. return self::$m_aClassParams[$sClass]["db_finalclass_field"];
  439. }
  440. final static public function IsStandaloneClass($sClass)
  441. {
  442. self::_check_subclass($sClass);
  443. if (count(self::$m_aChildClasses[$sClass]) == 0)
  444. {
  445. if (count(self::$m_aParentClasses[$sClass]) == 0)
  446. {
  447. return true;
  448. }
  449. }
  450. return false;
  451. }
  452. final static public function IsParentClass($sParentClass, $sChildClass)
  453. {
  454. self::_check_subclass($sChildClass);
  455. self::_check_subclass($sParentClass);
  456. if (in_array($sParentClass, self::$m_aParentClasses[$sChildClass])) return true;
  457. if ($sChildClass == $sParentClass) return true;
  458. return false;
  459. }
  460. final static public function IsSameFamilyBranch($sClassA, $sClassB)
  461. {
  462. self::_check_subclass($sClassA);
  463. self::_check_subclass($sClassB);
  464. if (in_array($sClassA, self::$m_aParentClasses[$sClassB])) return true;
  465. if (in_array($sClassB, self::$m_aParentClasses[$sClassA])) return true;
  466. if ($sClassA == $sClassB) return true;
  467. return false;
  468. }
  469. final static public function IsSameFamily($sClassA, $sClassB)
  470. {
  471. self::_check_subclass($sClassA);
  472. self::_check_subclass($sClassB);
  473. return (self::GetRootClass($sClassA) == self::GetRootClass($sClassB));
  474. }
  475. // Attributes of a given class may contain attributes defined in a parent class
  476. // - Some attributes are a copy of the definition
  477. // - Some attributes correspond to the upper class table definition (compound objects)
  478. // (see also filters definition)
  479. private static $m_aAttribDefs = array(); // array of ("classname" => array of attributes)
  480. private static $m_aAttribOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  481. private static $m_aExtKeyFriends = array(); // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  482. private static $m_aIgnoredAttributes = array(); //array of ("classname" => array of ("attcode")
  483. final static public function ListAttributeDefs($sClass)
  484. {
  485. self::_check_subclass($sClass);
  486. return self::$m_aAttribDefs[$sClass];
  487. }
  488. final public static function GetAttributesList($sClass)
  489. {
  490. self::_check_subclass($sClass);
  491. return array_keys(self::$m_aAttribDefs[$sClass]);
  492. }
  493. final public static function GetFiltersList($sClass)
  494. {
  495. self::_check_subclass($sClass);
  496. return array_keys(self::$m_aFilterDefs[$sClass]);
  497. }
  498. final public static function GetKeysList($sClass)
  499. {
  500. self::_check_subclass($sClass);
  501. $aExtKeys = array();
  502. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  503. {
  504. if ($oAttDef->IsExternalKey())
  505. {
  506. $aExtKeys[] = $sAttCode;
  507. }
  508. }
  509. return $aExtKeys;
  510. }
  511. final static public function IsValidKeyAttCode($sClass, $sAttCode)
  512. {
  513. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  514. if (!array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass])) return false;
  515. return (self::$m_aAttribDefs[$sClass][$sAttCode]->IsExternalKey());
  516. }
  517. final static public function IsValidAttCode($sClass, $sAttCode)
  518. {
  519. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  520. return (array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]));
  521. }
  522. final static public function IsAttributeOrigin($sClass, $sAttCode)
  523. {
  524. return (self::$m_aAttribOrigins[$sClass][$sAttCode] == $sClass);
  525. }
  526. final static public function IsValidFilterCode($sClass, $sFilterCode)
  527. {
  528. if (!array_key_exists($sClass, self::$m_aFilterDefs)) return false;
  529. return (array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]));
  530. }
  531. public static function IsValidClass($sClass)
  532. {
  533. return (array_key_exists($sClass, self::$m_aAttribDefs));
  534. }
  535. public static function IsValidObject($oObject)
  536. {
  537. if (!is_object($oObject)) return false;
  538. return (self::IsValidClass(get_class($oObject)));
  539. }
  540. public static function IsReconcKey($sClass, $sAttCode)
  541. {
  542. return (in_array($sAttCode, self::GetReconcKeys($sClass)));
  543. }
  544. final static public function GetAttributeDef($sClass, $sAttCode)
  545. {
  546. self::_check_subclass($sClass);
  547. return self::$m_aAttribDefs[$sClass][$sAttCode];
  548. }
  549. final static public function GetExternalKeys($sClass)
  550. {
  551. $aExtKeys = array();
  552. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  553. {
  554. if ($oAtt->IsExternalKey())
  555. {
  556. $aExtKeys[$sAttCode] = $oAtt;
  557. }
  558. }
  559. return $aExtKeys;
  560. }
  561. final static public function GetLinkedSets($sClass)
  562. {
  563. $aLinkedSets = array();
  564. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  565. {
  566. if (is_subclass_of($oAtt, 'AttributeLinkedSet'))
  567. {
  568. $aLinkedSets[$sAttCode] = $oAtt;
  569. }
  570. }
  571. return $aLinkedSets;
  572. }
  573. final static public function GetExternalFields($sClass, $sKeyAttCode)
  574. {
  575. $aExtFields = array();
  576. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  577. {
  578. if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode))
  579. {
  580. $aExtFields[] = $oAtt;
  581. }
  582. }
  583. return $aExtFields;
  584. }
  585. final static public function GetExtKeyFriends($sClass, $sExtKeyAttCode)
  586. {
  587. if (array_key_exists($sExtKeyAttCode, self::$m_aExtKeyFriends[$sClass]))
  588. {
  589. return self::$m_aExtKeyFriends[$sClass][$sExtKeyAttCode];
  590. }
  591. else
  592. {
  593. return array();
  594. }
  595. }
  596. public static function GetLabel($sClass, $sAttCode)
  597. {
  598. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  599. if ($oAttDef) return $oAttDef->GetLabel();
  600. return "";
  601. }
  602. public static function GetDescription($sClass, $sAttCode)
  603. {
  604. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  605. if ($oAttDef) return $oAttDef->GetDescription();
  606. return "";
  607. }
  608. // Filters of a given class may contain filters defined in a parent class
  609. // - Some filters are a copy of the definition
  610. // - Some filters correspond to the upper class table definition (compound objects)
  611. // (see also attributes definition)
  612. private static $m_aFilterDefs = array(); // array of ("classname" => array filterdef)
  613. private static $m_aFilterOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  614. public static function GetClassFilterDefs($sClass)
  615. {
  616. self::_check_subclass($sClass);
  617. return self::$m_aFilterDefs[$sClass];
  618. }
  619. final static public function GetClassFilterDef($sClass, $sFilterCode)
  620. {
  621. self::_check_subclass($sClass);
  622. return self::$m_aFilterDefs[$sClass][$sFilterCode];
  623. }
  624. public static function GetFilterLabel($sClass, $sFilterCode)
  625. {
  626. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  627. if ($oFilter) return $oFilter->GetLabel();
  628. return "";
  629. }
  630. public static function GetFilterDescription($sClass, $sFilterCode)
  631. {
  632. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  633. if ($oFilter) return $oFilter->GetDescription();
  634. return "";
  635. }
  636. // returns an array of opcode=>oplabel (e.g. "differs from")
  637. public static function GetFilterOperators($sClass, $sFilterCode)
  638. {
  639. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  640. if ($oFilter) return $oFilter->GetOperators();
  641. return array();
  642. }
  643. // returns an opcode
  644. public static function GetFilterLooseOperator($sClass, $sFilterCode)
  645. {
  646. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  647. if ($oFilter) return $oFilter->GetLooseOperator();
  648. return array();
  649. }
  650. public static function GetFilterOpDescription($sClass, $sFilterCode, $sOpCode)
  651. {
  652. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  653. if ($oFilter) return $oFilter->GetOpDescription($sOpCode);
  654. return "";
  655. }
  656. public static function GetFilterHTMLInput($sFilterCode)
  657. {
  658. return "<INPUT name=\"$sFilterCode\">";
  659. }
  660. // Lists of attributes/search filters
  661. //
  662. private static $m_aListInfos = array(); // array of ("listcode" => various info on the list, common to every classes)
  663. private static $m_aListData = array(); // array of ("classname" => array of "listcode" => list)
  664. // list may be an array of attcode / fltcode
  665. // list may be an array of "groupname" => (array of attcode / fltcode)
  666. public static function EnumZLists()
  667. {
  668. return array_keys(self::$m_aListInfos);
  669. }
  670. final static public function GetZListInfo($sListCode)
  671. {
  672. return self::$m_aListInfos[$sListCode];
  673. }
  674. public static function GetZListItems($sClass, $sListCode)
  675. {
  676. if (array_key_exists($sClass, self::$m_aListData))
  677. {
  678. if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
  679. {
  680. return self::$m_aListData[$sClass][$sListCode];
  681. }
  682. }
  683. $sParentClass = self::GetParentPersistentClass($sClass);
  684. if (empty($sParentClass)) return array(); // nothing for the mother of all classes
  685. // Dig recursively
  686. return self::GetZListItems($sParentClass, $sListCode);
  687. }
  688. public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
  689. {
  690. $aZList = self::GetZListItems($sClass, $sListCode);
  691. if (!$sGroup)
  692. {
  693. return (in_array($sAttCodeOrFltCode, $aZList));
  694. }
  695. return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
  696. }
  697. //
  698. // Relations
  699. //
  700. private static $m_aRelationInfos = array(); // array of ("relcode" => various info on the list, common to every classes)
  701. public static function EnumRelations($sClass = '')
  702. {
  703. $aResult = array_keys(self::$m_aRelationInfos);
  704. if (!empty($sClass))
  705. {
  706. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  707. // for the specified class
  708. $aClassRelations = array();
  709. foreach($aResult as $sRelCode)
  710. {
  711. $aQueries = self::EnumRelationQueries($sClass, $sRelCode);
  712. if (count($aQueries) > 0)
  713. {
  714. $aClassRelations[] = $sRelCode;
  715. }
  716. }
  717. return $aClassRelations;
  718. }
  719. return $aResult;
  720. }
  721. public static function EnumRelationProperties($sRelCode)
  722. {
  723. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  724. return self::$m_aRelationInfos[$sRelCode];
  725. }
  726. final static public function GetRelationDescription($sRelCode)
  727. {
  728. return Dict::S("Relation:$sRelCode/Description");
  729. }
  730. final static public function GetRelationVerbUp($sRelCode)
  731. {
  732. return Dict::S("Relation:$sRelCode/VerbUp");
  733. }
  734. final static public function GetRelationVerbDown($sRelCode)
  735. {
  736. return Dict::S("Relation:$sRelCode/VerbDown");
  737. }
  738. public static function EnumRelationQueries($sClass, $sRelCode)
  739. {
  740. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  741. return call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRelCode));
  742. }
  743. //
  744. // Object lifecycle model
  745. //
  746. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  747. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  748. 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)))
  749. public static function EnumStates($sClass)
  750. {
  751. if (array_key_exists($sClass, self::$m_aStates))
  752. {
  753. return self::$m_aStates[$sClass];
  754. }
  755. else
  756. {
  757. return array();
  758. }
  759. }
  760. public static function EnumStimuli($sClass)
  761. {
  762. if (array_key_exists($sClass, self::$m_aStimuli))
  763. {
  764. return self::$m_aStimuli[$sClass];
  765. }
  766. else
  767. {
  768. return array();
  769. }
  770. }
  771. public static function GetStateLabel($sClass, $sStateValue)
  772. {
  773. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  774. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  775. // Be consistent with what is done for enums, since states are defined as enums...
  776. return Dict::S("Class:".$oAttDef->GetHostClass()."/Attribute:$sStateAttrCode/Value:$sStateValue");
  777. // I've decided the current implementation, because I need
  778. // to get the description as well -GetAllowedValues does not render the description,
  779. // so far...
  780. // Could have been implemented the following way (not tested
  781. // $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  782. // $aAllowedValues = $oStateAttrDef->GetAllowedValues();
  783. // return $aAllowedValues[$sStateValue];
  784. }
  785. public static function GetStateDescription($sClass, $sStateValue)
  786. {
  787. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  788. return Dict::S("Class:$sClass/Attribute:$sStateAttrCode/Value:$sStateValue+", '');
  789. }
  790. public static function EnumTransitions($sClass, $sStateCode)
  791. {
  792. if (array_key_exists($sClass, self::$m_aTransitions))
  793. {
  794. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  795. {
  796. return self::$m_aTransitions[$sClass][$sStateCode];
  797. }
  798. }
  799. return array();
  800. }
  801. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  802. {
  803. $iFlags = 0; // By default (if no life cycle) no flag at all
  804. $sStateAttCode = self::GetStateAttributeCode($sClass);
  805. if (!empty($sStateAttCode))
  806. {
  807. $aStates = MetaModel::EnumStates($sClass);
  808. if (!array_key_exists($sState, $aStates))
  809. {
  810. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  811. }
  812. $aCurrentState = $aStates[$sState];
  813. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  814. {
  815. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  816. }
  817. }
  818. return $iFlags;
  819. }
  820. //
  821. // Allowed values
  822. //
  823. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  824. {
  825. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  826. return $oAttDef->GetAllowedValues($aArgs, $sContains);
  827. }
  828. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sContains = '')
  829. {
  830. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  831. return $oFltDef->GetAllowedValues($aArgs, $sContains);
  832. }
  833. //
  834. // Businezz model declaration verbs (should be static)
  835. //
  836. public static function RegisterZList($sListCode, $aListInfo)
  837. {
  838. // Check mandatory params
  839. $aMandatParams = array(
  840. "description" => "detailed (though one line) description of the list",
  841. "type" => "attributes | filters",
  842. );
  843. foreach($aMandatParams as $sParamName=>$sParamDesc)
  844. {
  845. if (!array_key_exists($sParamName, $aListInfo))
  846. {
  847. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  848. }
  849. }
  850. self::$m_aListInfos[$sListCode] = $aListInfo;
  851. }
  852. public static function RegisterRelation($sRelCode)
  853. {
  854. // Each item used to be an array of properties...
  855. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  856. }
  857. // Must be called once and only once...
  858. public static function InitClasses($sTablePrefix)
  859. {
  860. if (count(self::GetClasses()) > 0)
  861. {
  862. throw new CoreException("InitClasses should not be called more than once -skipped");
  863. return;
  864. }
  865. self::$m_sTablePrefix = $sTablePrefix;
  866. foreach(get_declared_classes() as $sPHPClass) {
  867. if (is_subclass_of($sPHPClass, 'DBObject'))
  868. {
  869. $sParent = get_parent_class($sPHPClass);
  870. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  871. {
  872. // Inherit info about attributes to ignore
  873. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  874. }
  875. if (method_exists($sPHPClass, 'Init'))
  876. {
  877. call_user_func(array($sPHPClass, 'Init'));
  878. }
  879. }
  880. }
  881. // Add a 'class' attribute/filter to the root classes and their children
  882. //
  883. foreach(self::EnumRootClasses() as $sRootClass)
  884. {
  885. if (self::IsStandaloneClass($sRootClass)) continue;
  886. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  887. if (strlen($sDbFinalClassField) == 0)
  888. {
  889. $sDbFinalClassField = 'finalclass';
  890. self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
  891. }
  892. $oClassAtt = new AttributeFinalClass('finalclass', array(
  893. "sql"=>$sDbFinalClassField,
  894. "default_value"=>$sRootClass,
  895. "is_null_allowed"=>false,
  896. "depends_on"=>array()
  897. ));
  898. $oClassAtt->SetHostClass($sRootClass);
  899. self::$m_aAttribDefs[$sRootClass]['finalclass'] = $oClassAtt;
  900. self::$m_aAttribOrigins[$sRootClass]['finalclass'] = $sRootClass;
  901. $oClassFlt = new FilterFromAttribute($oClassAtt);
  902. self::$m_aFilterDefs[$sRootClass]['finalclass'] = $oClassFlt;
  903. self::$m_aFilterOrigins[$sRootClass]['finalclass'] = $sRootClass;
  904. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  905. {
  906. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  907. {
  908. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  909. }
  910. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  911. {
  912. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  913. }
  914. $oCloned = clone $oClassAtt;
  915. $oCloned->SetFixedValue($sChildClass);
  916. self::$m_aAttribDefs[$sChildClass]['finalclass'] = $oCloned;
  917. self::$m_aAttribOrigins[$sChildClass]['finalclass'] = $sRootClass;
  918. $oClassFlt = new FilterFromAttribute($oClassAtt);
  919. self::$m_aFilterDefs[$sChildClass]['finalclass'] = $oClassFlt;
  920. self::$m_aFilterOrigins[$sChildClass]['finalclass'] = self::GetRootClass($sChildClass);
  921. }
  922. }
  923. // Prepare external fields and filters
  924. // Add final class to external keys
  925. //
  926. foreach (self::GetClasses() as $sClass)
  927. {
  928. self::$m_aExtKeyFriends[$sClass] = array();
  929. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  930. {
  931. // Compute the filter codes
  932. //
  933. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  934. {
  935. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  936. if ($oAttDef->IsExternalField())
  937. {
  938. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  939. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  940. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  941. }
  942. else
  943. {
  944. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  945. }
  946. }
  947. // Compute the fields that will be used to display a pointer to another object
  948. //
  949. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  950. {
  951. // oAttDef is either
  952. // - an external KEY / FIELD (direct),
  953. // - an external field pointing to an external KEY / FIELD
  954. // - an external field pointing to an external field pointing to....
  955. if ($oAttDef->IsExternalKey())
  956. {
  957. $sRemoteClass = $oAttDef->GetTargetClass();
  958. if (self::HasChildrenClasses($sRemoteClass))
  959. {
  960. // First, create an external field attribute, that gets the final class
  961. $sClassRecallAttCode = $sAttCode.'_finalclass_recall';
  962. $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
  963. "allowed_values"=>null,
  964. "extkey_attcode"=>$sAttCode,
  965. "target_attcode"=>"finalclass",
  966. "is_null_allowed"=>true,
  967. "depends_on"=>array()
  968. ));
  969. $oClassRecall->SetHostClass($sClass);
  970. self::$m_aAttribDefs[$sClass][$sClassRecallAttCode] = $oClassRecall;
  971. self::$m_aAttribOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  972. $oClassFlt = new FilterFromAttribute($oClassRecall);
  973. self::$m_aFilterDefs[$sClass][$sClassRecallAttCode] = $oClassFlt;
  974. self::$m_aFilterOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  975. // Add it to the ZLists where the external key is present
  976. //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
  977. $sListCode = 'list';
  978. if (isset(self::$m_aListData[$sClass][$sListCode]))
  979. {
  980. $aAttributes = self::$m_aListData[$sClass][$sListCode];
  981. // temporary.... no loop
  982. {
  983. if (in_array($sAttCode, $aAttributes))
  984. {
  985. $aNewList = array();
  986. foreach($aAttributes as $iPos => $sAttToDisplay)
  987. {
  988. if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
  989. {
  990. // Insert the final class right before
  991. $aNewList[] = $sClassRecallAttCode;
  992. }
  993. $aNewList[] = $sAttToDisplay;
  994. }
  995. self::$m_aListData[$sClass][$sListCode] = $aNewList;
  996. }
  997. }
  998. }
  999. }
  1000. }
  1001. // Get the real external key attribute
  1002. // It will be our reference to determine the other ext fields related to the same ext key
  1003. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1004. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  1005. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  1006. {
  1007. // skip : those extfields will be processed as external keys
  1008. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1009. // Note: I could not compare the objects by the mean of '==='
  1010. // because they are copied for the inheritance, and the internal references are NOT updated
  1011. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  1012. {
  1013. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  1014. }
  1015. }
  1016. }
  1017. }
  1018. // Add a 'id' filter
  1019. //
  1020. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  1021. {
  1022. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  1023. }
  1024. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  1025. {
  1026. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  1027. }
  1028. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  1029. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  1030. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  1031. // Define defaults values for the standard ZLists
  1032. //
  1033. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  1034. //{
  1035. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  1036. // {
  1037. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  1038. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  1039. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  1040. // }
  1041. //}
  1042. }
  1043. }
  1044. // To be overriden, must be called for any object class (optimization)
  1045. public static function Init()
  1046. {
  1047. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1048. }
  1049. // To be overloaded by biz model declarations
  1050. public static function GetRelationQueries($sRelCode)
  1051. {
  1052. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1053. return array();
  1054. }
  1055. public static function Init_Params($aParams)
  1056. {
  1057. // Check mandatory params
  1058. $aMandatParams = array(
  1059. "category" => "group classes by modules defining their visibility in the UI",
  1060. "key_type" => "autoincrement | string",
  1061. "name_attcode" => "define wich attribute is the class name, may be an inherited attribute",
  1062. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1063. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1064. "db_table" => "database table",
  1065. "db_key_field" => "database field which is the key",
  1066. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1067. );
  1068. $sClass = self::GetCallersPHPClass("Init");
  1069. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1070. {
  1071. if (!array_key_exists($sParamName, $aParams))
  1072. {
  1073. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1074. }
  1075. }
  1076. $aCategories = explode(',', $aParams['category']);
  1077. foreach ($aCategories as $sCategory)
  1078. {
  1079. self::$m_Category2Class[$sCategory][] = $sClass;
  1080. }
  1081. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1082. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1083. self::$m_aParentClasses[$sClass] = array();
  1084. self::$m_aChildClasses[$sClass] = array();
  1085. self::$m_aClassParams[$sClass]= $aParams;
  1086. self::$m_aAttribDefs[$sClass] = array();
  1087. self::$m_aAttribOrigins[$sClass] = array();
  1088. self::$m_aExtKeyFriends[$sClass] = array();
  1089. self::$m_aFilterDefs[$sClass] = array();
  1090. self::$m_aFilterOrigins[$sClass] = array();
  1091. }
  1092. protected static function object_array_mergeclone($aSource1, $aSource2)
  1093. {
  1094. $aRes = array();
  1095. foreach ($aSource1 as $key=>$object)
  1096. {
  1097. $aRes[$key] = clone $object;
  1098. }
  1099. foreach ($aSource2 as $key=>$object)
  1100. {
  1101. $aRes[$key] = clone $object;
  1102. }
  1103. return $aRes;
  1104. }
  1105. public static function Init_InheritAttributes($sSourceClass = null)
  1106. {
  1107. $sTargetClass = self::GetCallersPHPClass("Init");
  1108. if (empty($sSourceClass))
  1109. {
  1110. // Default: inherit from parent class
  1111. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1112. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1113. }
  1114. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1115. {
  1116. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1117. {
  1118. self::$m_aAttribDefs[$sTargetClass] = array();
  1119. self::$m_aAttribOrigins[$sTargetClass] = array();
  1120. }
  1121. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1122. // Note: while investigating on some issues related to attribute inheritance,
  1123. // I found out that the notion of "host class" is unclear
  1124. // For stability reasons, and also because a workaround has been found
  1125. // I leave it unchanged, but later it could be a good thing to force
  1126. // attribute host class to the new class (See code below)
  1127. // In that case, we will have to review the attribute labels
  1128. // (currently relying on host class => the original declaration
  1129. // of the attribute)
  1130. // See TRAC #148
  1131. // foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1132. // {
  1133. // $oAttDef->SetHostClass($sTargetClass);
  1134. // }
  1135. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1136. }
  1137. // Build root class information
  1138. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1139. {
  1140. // Inherit...
  1141. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1142. }
  1143. else
  1144. {
  1145. // This class will be the root class
  1146. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1147. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1148. }
  1149. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1150. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1151. // I am the child of each and every parent...
  1152. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1153. {
  1154. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1155. }
  1156. }
  1157. public static function Init_OverloadAttributeParams($sAttCode, $aParams)
  1158. {
  1159. $sTargetClass = self::GetCallersPHPClass("Init");
  1160. if (!self::IsValidAttCode($sTargetClass, $sAttCode))
  1161. {
  1162. throw new CoreException("Could not overload '$sAttCode', expecting a code from {".implode(", ", self::GetAttributesList($sTargetClass))."}");
  1163. }
  1164. self::$m_aAttribDefs[$sTargetClass][$sAttCode]->OverloadParams($aParams);
  1165. }
  1166. protected static function Init_IsKnownClass($sClass)
  1167. {
  1168. // Differs from self::IsValidClass()
  1169. // because it is being called before all the classes have been initialized
  1170. if (!class_exists($sClass)) return false;
  1171. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1172. return true;
  1173. }
  1174. public static function Init_AddAttribute(AttributeDefinition $oAtt)
  1175. {
  1176. $sTargetClass = self::GetCallersPHPClass("Init");
  1177. // Some attributes could refer to a class
  1178. // declared in a module which is currently not installed/active
  1179. // We simply discard those attributes
  1180. //
  1181. if ($oAtt->IsLinkSet())
  1182. {
  1183. $sRemoteClass = $oAtt->GetLinkedClass();
  1184. if (!self::Init_IsKnownClass($sRemoteClass))
  1185. {
  1186. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1187. return;
  1188. }
  1189. }
  1190. elseif($oAtt->IsExternalKey())
  1191. {
  1192. $sRemoteClass = $oAtt->GetTargetClass();
  1193. if (!self::Init_IsKnownClass($sRemoteClass))
  1194. {
  1195. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1196. return;
  1197. }
  1198. }
  1199. elseif($oAtt->IsExternalField())
  1200. {
  1201. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  1202. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  1203. {
  1204. // The corresponding external key has already been ignored
  1205. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  1206. return;
  1207. }
  1208. // #@# todo - Check if the target attribute is still there
  1209. // this is not simple to implement because is involves
  1210. // several passes (the load order has a significant influence on that)
  1211. }
  1212. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  1213. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  1214. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1215. // Specific case of external fields:
  1216. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1217. // Therefore, the reference to the host class is set there
  1218. $oAtt->SetHostClass($sTargetClass);
  1219. }
  1220. public static function Init_SetZListItems($sListCode, $aItems)
  1221. {
  1222. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  1223. $sTargetClass = self::GetCallersPHPClass("Init");
  1224. // Discard attributes that do not make sense
  1225. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  1226. //
  1227. foreach($aItems as $iFoo => $sAttCode)
  1228. {
  1229. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  1230. {
  1231. unset($aItems[$iFoo]);
  1232. }
  1233. }
  1234. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  1235. }
  1236. public static function Init_DefineState($sStateCode, $aStateDef)
  1237. {
  1238. $sTargetClass = self::GetCallersPHPClass("Init");
  1239. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  1240. $sParentState = $aStateDef['attribute_inherit'];
  1241. if (!empty($sParentState))
  1242. {
  1243. // Inherit from the given state (must be defined !)
  1244. //
  1245. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  1246. // Reset the constraint when it was mandatory to set the value at the previous state
  1247. //
  1248. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  1249. {
  1250. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  1251. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  1252. $aToInherit['attribute_list'][$sState] = $iFlags;
  1253. }
  1254. // The inherited configuration could be overriden
  1255. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  1256. }
  1257. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  1258. {
  1259. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  1260. {
  1261. unset($aStateDef['attribute_list'][$sAttCode]);
  1262. }
  1263. }
  1264. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  1265. // by default, create an empty set of transitions associated to that state
  1266. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  1267. }
  1268. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  1269. {
  1270. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  1271. $sTargetClass = self::GetCallersPHPClass("Init");
  1272. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  1273. }
  1274. public static function Init_DefineStimulus($oStimulus)
  1275. {
  1276. $sTargetClass = self::GetCallersPHPClass("Init");
  1277. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  1278. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1279. // Therefore, the reference to the host class is set there
  1280. $oStimulus->SetHostClass($sTargetClass);
  1281. }
  1282. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  1283. {
  1284. $sTargetClass = self::GetCallersPHPClass("Init");
  1285. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  1286. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  1287. }
  1288. public static function Init_InheritLifecycle($sSourceClass = '')
  1289. {
  1290. $sTargetClass = self::GetCallersPHPClass("Init");
  1291. if (empty($sSourceClass))
  1292. {
  1293. // Default: inherit from parent class
  1294. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1295. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1296. }
  1297. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  1298. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  1299. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  1300. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  1301. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  1302. }
  1303. //
  1304. // Static API
  1305. //
  1306. public static function GetRootClass($sClass = null)
  1307. {
  1308. self::_check_subclass($sClass);
  1309. return self::$m_aRootClasses[$sClass];
  1310. }
  1311. public static function IsRootClass($sClass)
  1312. {
  1313. self::_check_subclass($sClass);
  1314. return (self::GetRootClass($sClass) == $sClass);
  1315. }
  1316. public static function EnumRootClasses()
  1317. {
  1318. return array_unique(self::$m_aRootClasses);
  1319. }
  1320. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF)
  1321. {
  1322. self::_check_subclass($sClass);
  1323. if ($iOption == ENUM_PARENT_CLASSES_EXCLUDELEAF)
  1324. {
  1325. return self::$m_aParentClasses[$sClass];
  1326. }
  1327. $aRes = self::$m_aParentClasses[$sClass];
  1328. $aRes[] = $sClass;
  1329. return $aRes;
  1330. }
  1331. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  1332. {
  1333. self::_check_subclass($sClass);
  1334. $aRes = self::$m_aChildClasses[$sClass];
  1335. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  1336. {
  1337. // Add it to the list
  1338. $aRes[] = $sClass;
  1339. }
  1340. return $aRes;
  1341. }
  1342. public static function HasChildrenClasses($sClass)
  1343. {
  1344. return (count(self::$m_aChildClasses[$sClass]) > 0);
  1345. }
  1346. public static function EnumCategories()
  1347. {
  1348. return array_keys(self::$m_Category2Class);
  1349. }
  1350. // Note: use EnumChildClasses to take the compound objects into account
  1351. public static function GetSubclasses($sClass)
  1352. {
  1353. self::_check_subclass($sClass);
  1354. $aSubClasses = array();
  1355. foreach(get_declared_classes() as $sSubClass) {
  1356. if (is_subclass_of($sSubClass, $sClass))
  1357. {
  1358. $aSubClasses[] = $sSubClass;
  1359. }
  1360. }
  1361. return $aSubClasses;
  1362. }
  1363. public static function GetClasses($sCategory = '')
  1364. {
  1365. if (array_key_exists($sCategory, self::$m_Category2Class))
  1366. {
  1367. return self::$m_Category2Class[$sCategory];
  1368. }
  1369. //if (count(self::$m_Category2Class) > 0)
  1370. //{
  1371. // throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  1372. //}
  1373. return array();
  1374. }
  1375. public static function HasTable($sClass)
  1376. {
  1377. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  1378. return true;
  1379. }
  1380. public static function IsAbstract($sClass)
  1381. {
  1382. $oReflection = new ReflectionClass($sClass);
  1383. return $oReflection->isAbstract();
  1384. }
  1385. protected static $m_aQueryStructCache = array();
  1386. protected static function PrepareQueryArguments($aArgs)
  1387. {
  1388. // Translate any object into scalars
  1389. //
  1390. $aScalarArgs = array();
  1391. foreach($aArgs as $sArgName => $value)
  1392. {
  1393. if (self::IsValidObject($value))
  1394. {
  1395. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgs($sArgName));
  1396. }
  1397. else
  1398. {
  1399. $aScalarArgs[$sArgName] = (string) $value;
  1400. }
  1401. }
  1402. // Add standard contextual arguments
  1403. //
  1404. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1405. return $aScalarArgs;
  1406. }
  1407. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  1408. {
  1409. // Hide objects that are not visible to the current user
  1410. //
  1411. if (!$oFilter->IsAllDataAllowed())
  1412. {
  1413. $oVisibleObjects = UserRights::GetSelectFilter($oFilter->GetClass());
  1414. if ($oVisibleObjects === false)
  1415. {
  1416. // Make sure this is a valid search object, saying NO for all
  1417. $oVisibleObjects = DBObjectSearch::FromEmptySet($oFilter->GetClass());
  1418. }
  1419. if (is_object($oVisibleObjects))
  1420. {
  1421. $oFilter->MergeWith($oVisibleObjects);
  1422. }
  1423. else
  1424. {
  1425. // should be true at this point, meaning that no additional filtering
  1426. // is required
  1427. }
  1428. }
  1429. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  1430. {
  1431. // Need to identify the query
  1432. $sOqlQuery = $oFilter->ToOql();
  1433. $sOqlId = md5($sOqlQuery);
  1434. }
  1435. else
  1436. {
  1437. $sOqlQuery = "SELECTING... ".$oFilter->GetClass();
  1438. $sOqlId = "query id ? n/a";
  1439. }
  1440. // Query caching
  1441. //
  1442. if (self::$m_bQueryCacheEnabled)
  1443. {
  1444. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  1445. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  1446. // to use a hash (like md5) of the string as the key !
  1447. //
  1448. // Example of two queries that were found as similar by the hash array:
  1449. // 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
  1450. // and
  1451. // 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
  1452. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  1453. //
  1454. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  1455. {
  1456. // hit!
  1457. $oSelect = clone self::$m_aQueryStructCache[$sOqlId];
  1458. }
  1459. }
  1460. if (!isset($oSelect))
  1461. {
  1462. $aTranslation = array();
  1463. $aClassAliases = array();
  1464. $aTableAliases = array();
  1465. $oConditionTree = $oFilter->GetCriteria();
  1466. $oKPI = new ExecutionKPI();
  1467. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), array(), true /* main query */);
  1468. $oKPI->ComputeStats('MakeQuery (select)', $sOqlQuery);
  1469. self::$m_aQueryStructCache[$sOqlId] = clone $oSelect;
  1470. }
  1471. // Check the order by specification, and prefix with the class alias
  1472. //
  1473. $aOrderSpec = array();
  1474. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1475. {
  1476. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($oFilter->GetFirstJoinedClass()));
  1477. if (!is_bool($bAscending))
  1478. {
  1479. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1480. }
  1481. $aOrderSpec[$oFilter->GetFirstJoinedClassAlias().$sFieldAlias] = $bAscending;
  1482. }
  1483. // By default, force the name attribute to be the ordering key
  1484. //
  1485. if (empty($aOrderSpec))
  1486. {
  1487. foreach ($oFilter->GetSelectedClasses() as $sSelectedAlias => $sSelectedClass)
  1488. {
  1489. $sNameAttCode = self::GetNameAttributeCode($sSelectedClass);
  1490. if (!empty($sNameAttCode))
  1491. {
  1492. // By default, simply order on the "name" attribute, ascending
  1493. $aOrderSpec[$sSelectedAlias.$sNameAttCode] = true;
  1494. }
  1495. }
  1496. }
  1497. // Go
  1498. //
  1499. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1500. try
  1501. {
  1502. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount);
  1503. }
  1504. catch (MissingQueryArgument $e)
  1505. {
  1506. // Add some information...
  1507. $e->addInfo('OQL', $sOqlQuery);
  1508. throw $e;
  1509. }
  1510. if (self::$m_bTraceQueries)
  1511. {
  1512. $sQueryId = md5($sRes);
  1513. if(!isset(self::$m_aQueriesLog[$sOqlId]))
  1514. {
  1515. self::$m_aQueriesLog[$sOqlId]['oql'] = $sOqlQuery;
  1516. self::$m_aQueriesLog[$sOqlId]['hits'] = 1;
  1517. }
  1518. else
  1519. {
  1520. self::$m_aQueriesLog[$sOqlId]['hits']++;
  1521. }
  1522. if(!isset(self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]))
  1523. {
  1524. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['sql'] = $sRes;
  1525. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['count'] = 1;
  1526. }
  1527. else
  1528. {
  1529. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['count']++;
  1530. }
  1531. }
  1532. return $sRes;
  1533. }
  1534. public static function ShowQueryTrace()
  1535. {
  1536. if (!self::$m_bTraceQueries) return;
  1537. $iOqlCount = count(self::$m_aQueriesLog);
  1538. if ($iOqlCount == 0)
  1539. {
  1540. echo "<p>Trace activated, but no query found</p>\n";
  1541. return;
  1542. }
  1543. $iSqlCount = 0;
  1544. foreach (self::$m_aQueriesLog as $aOqlData)
  1545. {
  1546. $iSqlCount += $aOqlData['hits'];
  1547. }
  1548. echo "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  1549. foreach (self::$m_aQueriesLog as $aOqlData)
  1550. {
  1551. $sOql = $aOqlData['oql'];
  1552. $sHits = $aOqlData['hits'];
  1553. echo "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  1554. echo "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  1555. foreach($aOqlData['queries'] as $aSqlData)
  1556. {
  1557. $sQuery = $aSqlData['sql'];
  1558. $sSqlHits = $aSqlData['count'];
  1559. echo "<li><b>$sSqlHits</b> hits for SQL: <span style=\"font-size:60%\">$sQuery</span><li>\n";
  1560. }
  1561. echo "</ul>\n";
  1562. }
  1563. }
  1564. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1565. {
  1566. $aTranslation = array();
  1567. $aClassAliases = array();
  1568. $aTableAliases = array();
  1569. $oConditionTree = $oFilter->GetCriteria();
  1570. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), array(), true /* main query */);
  1571. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1572. return $oSelect->RenderDelete($aScalarArgs);
  1573. }
  1574. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1575. {
  1576. // $aValues is an array of $sAttCode => $value
  1577. $aTranslation = array();
  1578. $aClassAliases = array();
  1579. $aTableAliases = array();
  1580. $oConditionTree = $oFilter->GetCriteria();
  1581. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), $aValues, true /* main query */);
  1582. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1583. return $oSelect->RenderUpdate($aScalarArgs);
  1584. }
  1585. private static function MakeQuery($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, DBObjectSearch $oFilter, $aExpectedAtts = array(), $aValues = array(), $bIsMainQuery = false)
  1586. {
  1587. // Note: query class might be different than the class of the filter
  1588. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1589. // $aExpectedAtts is an array of sAttCode=>array of columns
  1590. $sClass = $oFilter->GetFirstJoinedClass();
  1591. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  1592. $bIsOnQueriedClass = array_key_exists($sClassAlias, $aSelectedClasses);
  1593. if ($bIsOnQueriedClass)
  1594. {
  1595. $aClassAliases = array_merge($aClassAliases, $oFilter->GetJoinedClasses());
  1596. }
  1597. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1598. $sRootClass = self::GetRootClass($sClass);
  1599. $sKeyField = self::DBGetKey($sClass);
  1600. if ($bIsOnQueriedClass)
  1601. {
  1602. // default to the whole list of attributes + the very std id/finalclass
  1603. $aExpectedAtts['id'][] = $sClassAlias.'id';
  1604. foreach (self::GetAttributesList($sClass) as $sAttCode)
  1605. {
  1606. $aExpectedAtts[$sAttCode][] = $sClassAlias.$sAttCode; // alias == class and attcode
  1607. }
  1608. }
  1609. // Compute a clear view of external keys, and external attributes
  1610. // Build the list of external keys:
  1611. // -> ext keys required by a closed join ???
  1612. // -> ext keys mentionned in a 'pointing to' condition
  1613. // -> ext keys required for an external field
  1614. //
  1615. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1616. //
  1617. // Optimization: could be computed once for all (cached)
  1618. // Could be done in MakeQuerySingleTable ???
  1619. //
  1620. if ($bIsOnQueriedClass)
  1621. {
  1622. // Get all Ext keys for the queried class (??)
  1623. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1624. {
  1625. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1626. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1627. }
  1628. }
  1629. // Get all Ext keys used by the filter
  1630. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1631. {
  1632. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1633. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1634. }
  1635. // Add the ext fields used in the select (eventually adds an external key)
  1636. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1637. {
  1638. if ($oAttDef->IsExternalField())
  1639. {
  1640. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1641. if (array_key_exists($sAttCode, $aExpectedAtts) || $oConditionTree->RequiresField($sClassAlias, $sAttCode))
  1642. {
  1643. // Add the external attribute
  1644. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1645. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1646. }
  1647. }
  1648. }
  1649. // First query built upon on the leaf (ie current) class
  1650. //
  1651. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1652. if (self::HasTable($sClass))
  1653. {
  1654. $oSelectBase = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sClass, $aExpectedAtts, $aExtKeys, $aValues);
  1655. }
  1656. else
  1657. {
  1658. $oSelectBase = null;
  1659. // As the join will not filter on the expected classes, we have to specify it explicitely
  1660. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1661. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1662. $oConditionTree = $oConditionTree->LogAnd($oFinalClassRestriction);
  1663. }
  1664. // Then we join the queries of the eventual parent classes (compound model)
  1665. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1666. {
  1667. if (!self::HasTable($sParentClass)) continue;
  1668. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1669. $oSelectParentTable = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sParentClass, $aExpectedAtts, $aExtKeys, $aValues);
  1670. if (is_null($oSelectBase))
  1671. {
  1672. $oSelectBase = $oSelectParentTable;
  1673. }
  1674. else
  1675. {
  1676. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1677. }
  1678. }
  1679. // Filter on objects referencing me
  1680. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1681. {
  1682. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1683. {
  1684. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1685. // We don't want any attribute from the foreign class, just filter on an inner join
  1686. $aExpAtts = array();
  1687. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1688. //self::DbgTrace($oForeignFilter);
  1689. //self::DbgTrace($oForeignFilter->ToOQL());
  1690. //self::DbgTrace($oSelectForeign);
  1691. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1692. $oSelectForeign = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oForeignFilter, $aExpAtts);
  1693. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1694. $sForeignKeyTable = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][0];
  1695. $sForeignKeyColumn = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][1];
  1696. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1697. }
  1698. }
  1699. // Filter on related objects
  1700. //
  1701. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1702. {
  1703. $oSubFilter = $aCritInfo['flt'];
  1704. $sRelCode = $aCritInfo['relcode'];
  1705. $iMaxDepth = $aCritInfo['maxdepth'];
  1706. // Get the starting point objects
  1707. $oStartSet = new CMDBObjectSet($oSubFilter);
  1708. // Get the objects related to those objects... recursively...
  1709. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1710. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1711. // #@# todo - related objects and expressions...
  1712. // Create condition
  1713. if (count($aRestriction) > 0)
  1714. {
  1715. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1716. }
  1717. else
  1718. {
  1719. // Quick N'dirty -> generate an empty set
  1720. $oSelectBase->AddCondition('false');
  1721. }
  1722. }
  1723. // Translate the conditions... and go
  1724. //
  1725. if ($bIsMainQuery)
  1726. {
  1727. $oConditionTranslated = $oConditionTree->Translate($aTranslation);
  1728. $oSelectBase->SetCondition($oConditionTranslated);
  1729. }
  1730. // That's all... cross fingers and we'll get some working query
  1731. //MyHelpers::var_dump_html($oSelectBase, true);
  1732. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1733. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1734. return $oSelectBase;
  1735. }
  1736. protected static function MakeQuerySingleTable($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, $oFilter, $sTableClass, $aExpectedAtts, $aExtKeys, $aValues)
  1737. {
  1738. // $aExpectedAtts is an array of sAttCode=>sAlias
  1739. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1740. // Prepare the query for a single table (compound objects)
  1741. // Ignores the items (attributes/filters) that are not on the target table
  1742. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1743. //
  1744. // Returns an SQLQuery
  1745. //
  1746. $sTargetClass = $oFilter->GetFirstJoinedClass();
  1747. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  1748. $sTable = self::DBGetTable($sTableClass);
  1749. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1750. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $aSelectedClasses);
  1751. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1752. // 1 - SELECT and UPDATE
  1753. //
  1754. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1755. //
  1756. $aSelect = array();
  1757. $aUpdateValues = array();
  1758. // 1/a - Get the key
  1759. //
  1760. if ($bIsOnQueriedClass)
  1761. {
  1762. $aSelect[$aExpectedAtts['id'][0]] = new FieldExpression(self::DBGetKey($sTableClass), $sTableAlias);
  1763. }
  1764. // We need one pkey to be the key, let's take the one corresponding to the root class
  1765. // (used to be based on the leaf, but it may happen that this one has no table defined)
  1766. $sRootClass = self::GetRootClass($sTargetClass);
  1767. if ($sTableClass == $sRootClass)
  1768. {
  1769. $aTranslation[$sTargetAlias]['id'] = array($sTableAlias, self::DBGetKey($sTableClass));
  1770. }
  1771. // 1/b - Get the other attributes
  1772. //
  1773. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1774. {
  1775. // Skip this attribute if not defined in this table
  1776. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1777. // Skip this attribute if not writable (means that it does not correspond
  1778. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1779. // Update...
  1780. //
  1781. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1782. {
  1783. assert ($oAttDef->IsDirectField());
  1784. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1785. {
  1786. $aUpdateValues[$sColumn] = $sValue;
  1787. }
  1788. }
  1789. // Select...
  1790. //
  1791. // Skip, if a list of fields has been specified and it is not there
  1792. if (!array_key_exists($sAttCode, $aExpectedAtts)) continue;
  1793. if ($oAttDef->IsExternalField())
  1794. {
  1795. // skip, this will be handled in the joined tables
  1796. }
  1797. else
  1798. {
  1799. // standard field, or external key
  1800. // add it to the output
  1801. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1802. {
  1803. foreach ($aExpectedAtts[$sAttCode] as $sAttAlias)
  1804. {
  1805. $aSelect[$sAttAlias.$sColId] = new FieldExpression($sSQLExpr, $sTableAlias);
  1806. }
  1807. }
  1808. }
  1809. }
  1810. // 2 - WHERE
  1811. //
  1812. foreach(self::$m_aFilterDefs[$sTargetClass] as $sFltCode => $oFltAtt)
  1813. {
  1814. // Skip this filter if not defined in this table
  1815. if (self::$m_aFilterOrigins[$sTargetClass][$sFltCode] != $sTableClass) continue;
  1816. // #@# todo - aller plus loin... a savoir que la table de translation doit contenir une "Expression"
  1817. foreach($oFltAtt->GetSQLExpressions() as $sColID => $sFltExpr)
  1818. {
  1819. // Note: I did not test it with filters relying on several expressions...
  1820. // as long as sColdID is empty, this is working, otherwise... ?
  1821. $aTranslation[$sTargetAlias][$sFltCode.$sColID] = array($sTableAlias, $sFltExpr);
  1822. }
  1823. }
  1824. // #@# todo - See what a full text search condition should be
  1825. // 2' - WHERE / Full text search condition
  1826. //
  1827. if ($bIsOnQueriedClass)
  1828. {
  1829. $aFullText = $oFilter->GetCriteria_FullText();
  1830. }
  1831. else
  1832. {
  1833. // Pourquoi ???
  1834. $aFullText = array();
  1835. }
  1836. // 3 - The whole stuff, for this table only
  1837. //
  1838. $oSelectBase = new SQLQuery($sTable, $sTableAlias, $aSelect, null, $aFullText, $bIsOnQueriedClass, $aUpdateValues);
  1839. // 4 - The external keys -> joins...
  1840. //
  1841. if (array_key_exists($sTableClass, $aExtKeys))
  1842. {
  1843. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1844. {
  1845. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1846. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  1847. // In case the join was not explicitely defined in the filter,
  1848. // we need to do it now
  1849. if (empty($oExtFilter))
  1850. {
  1851. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1852. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1853. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1854. }
  1855. else
  1856. {
  1857. // The aliases should not conflict because normalization occured while building the filter
  1858. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1859. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1860. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1861. }
  1862. // Specify expected attributes for the target class query
  1863. // ... and use the current alias !
  1864. $aExpAtts = array();
  1865. $aIntermediateTranslation = array();
  1866. foreach($aExtFields as $sAttCode => $oAtt)
  1867. {
  1868. $sExtAttCode = $oAtt->GetExtAttCode();
  1869. if (array_key_exists($sAttCode, $aExpectedAtts))
  1870. {
  1871. // Request this attribute... transmit the alias !
  1872. $aExpAtts[$sExtAttCode] = $aExpectedAtts[$sAttCode];
  1873. }
  1874. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1875. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  1876. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  1877. {
  1878. $aIntermediateTranslation[$sTargetAlias.$sColID][$sAttCode] = array($sKeyClassAlias, $sRemoteAttExpr);
  1879. }
  1880. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  1881. }
  1882. $oConditionTree = $oConditionTree->Translate($aIntermediateTranslation, false);
  1883. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  1884. $oSelectExtKey = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oExtFilter, $aExpAtts);
  1885. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  1886. $sLocalKeyField = current($aCols); // get the first column for an external key
  1887. $sExternalKeyField = self::DBGetKey($sKeyClass);
  1888. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1889. if ($oKeyAttDef->IsNullAllowed())
  1890. {
  1891. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1892. }
  1893. else
  1894. {
  1895. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1896. }
  1897. }
  1898. }
  1899. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1900. return $oSelectBase;
  1901. }
  1902. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  1903. {
  1904. if (!array_key_exists($sNewName, $aAliases))
  1905. {
  1906. $aAliases[$sNewName] = $sRealName;
  1907. return $sNewName;
  1908. }
  1909. for ($i = 1 ; $i < 100 ; $i++)
  1910. {
  1911. $sAnAlias = $sNewName.$i;
  1912. if (!array_key_exists($sAnAlias, $aAliases))
  1913. {
  1914. // Create that new alias
  1915. $aAliases[$sAnAlias] = $sRealName;
  1916. return $sAnAlias;
  1917. }
  1918. }
  1919. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  1920. }
  1921. public static function CheckDefinitions()
  1922. {
  1923. if (count(self::GetClasses()) == 0)
  1924. {
  1925. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  1926. }
  1927. $aErrors = array();
  1928. $aSugFix = array();
  1929. foreach (self::GetClasses() as $sClass)
  1930. {
  1931. $sNameAttCode = self::GetNameAttributeCode($sClass);
  1932. if (empty($sNameAttCode))
  1933. {
  1934. // let's try this !!!
  1935. // $aErrors[$sClass][] = "Missing value for name definition: the framework will (should...) replace it by the id";
  1936. // $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1937. }
  1938. else if(!self::IsValidAttCode($sClass, $sNameAttCode))
  1939. {
  1940. $aErrors[$sClass][] = "Unkown attribute code '".$sNameAttCode."' for the name definition";
  1941. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1942. }
  1943. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  1944. {
  1945. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  1946. {
  1947. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  1948. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1949. }
  1950. }
  1951. $bHasWritableAttribute = false;
  1952. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1953. {
  1954. // It makes no sense to check the attributes again and again in the subclasses
  1955. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1956. if ($oAttDef->IsExternalKey())
  1957. {
  1958. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  1959. {
  1960. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  1961. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  1962. }
  1963. }
  1964. elseif ($oAttDef->IsExternalField())
  1965. {
  1966. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1967. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  1968. {
  1969. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  1970. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  1971. }
  1972. else
  1973. {
  1974. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1975. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1976. $sExtAttCode = $oAttDef->GetExtAttCode();
  1977. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  1978. {
  1979. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  1980. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  1981. }
  1982. }
  1983. }
  1984. else // standard attributes
  1985. {
  1986. // Check that the default values definition is a valid object!
  1987. $oValSetDef = $oAttDef->GetValuesDef();
  1988. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  1989. {
  1990. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  1991. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  1992. }
  1993. else
  1994. {
  1995. // Default value must be listed in the allowed values (if defined)
  1996. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  1997. if (!is_null($aAllowedValues))
  1998. {
  1999. $sDefaultValue = $oAttDef->GetDefaultValue();
  2000. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  2001. {
  2002. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  2003. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  2004. }
  2005. }
  2006. }
  2007. }
  2008. // Check dependencies
  2009. if ($oAttDef->IsWritable())
  2010. {
  2011. $bHasWritableAttribute = true;
  2012. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  2013. {
  2014. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  2015. {
  2016. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  2017. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2018. }
  2019. }
  2020. }
  2021. }
  2022. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  2023. {
  2024. if (method_exists($oFilterDef, '__GetRefAttribute'))
  2025. {
  2026. $oAttDef = $oFilterDef->__GetRefAttribute();
  2027. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  2028. {
  2029. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  2030. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2031. }
  2032. }
  2033. }
  2034. // Lifecycle
  2035. //
  2036. $sStateAttCode = self::GetStateAttributeCode($sClass);
  2037. if (strlen($sStateAttCode) > 0)
  2038. {
  2039. // Lifecycle - check that the state attribute does exist as an attribute
  2040. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  2041. {
  2042. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  2043. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2044. }
  2045. else
  2046. {
  2047. // Lifecycle - check that there is a value set constraint on the state attribute
  2048. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  2049. $aStates = array_keys(self::EnumStates($sClass));
  2050. if (is_null($aAllowedValuesRaw))
  2051. {
  2052. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  2053. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  2054. }
  2055. else
  2056. {
  2057. $aAllowedValues = array_keys($aAllowedValuesRaw);
  2058. // Lifecycle - check the the state attribute allowed values are defined states
  2059. foreach($aAllowedValues as $sValue)
  2060. {
  2061. if (!in_array($sValue, $aStates))
  2062. {
  2063. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  2064. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2065. }
  2066. }
  2067. // Lifecycle - check that defined states are allowed values
  2068. foreach($aStates as $sStateValue)
  2069. {
  2070. if (!in_array($sStateValue, $aAllowedValues))
  2071. {
  2072. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  2073. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2074. }
  2075. }
  2076. }
  2077. // Lifcycle - check that the action handlers are defined
  2078. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  2079. {
  2080. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  2081. {
  2082. foreach ($aTransitionDef['actions'] as $sActionHandler)
  2083. {
  2084. if (!method_exists($sClass, $sActionHandler))
  2085. {
  2086. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2087. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  2088. }
  2089. }
  2090. }
  2091. }
  2092. }
  2093. }
  2094. if ($bHasWritableAttribute)
  2095. {
  2096. if (!self::HasTable($sClass))
  2097. {
  2098. $aErrors[$sClass][] = "No table has been defined for this class";
  2099. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  2100. }
  2101. }
  2102. // ZList
  2103. //
  2104. foreach(self::EnumZLists() as $sListCode)
  2105. {
  2106. foreach (self::GetZListItems($sClass, $sListCode) as $sMyAttCode)
  2107. {
  2108. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  2109. {
  2110. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  2111. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2112. }
  2113. }
  2114. }
  2115. }
  2116. if (count($aErrors) > 0)
  2117. {
  2118. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2119. echo "<h3>Business model inconsistencies have been found</h3>\n";
  2120. // #@# later -> this is the responsibility of the caller to format the output
  2121. foreach ($aErrors as $sClass => $aMessages)
  2122. {
  2123. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  2124. echo "<ul class=\"treeview\">\n";
  2125. $i = 0;
  2126. foreach ($aMessages as $sMsg)
  2127. {
  2128. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  2129. $i++;
  2130. }
  2131. echo "</ul>\n";
  2132. }
  2133. echo "<p>Aborting...</p>\n";
  2134. echo "</div>\n";
  2135. exit;
  2136. }
  2137. }
  2138. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  2139. {
  2140. if (empty($sRepairUrl)) return;
  2141. // By design, some queries might be blank, we have to ignore them
  2142. $aCleanFixes = array();
  2143. foreach($aSQLFixes as $sSQLFix)
  2144. {
  2145. if (!empty($sSQLFix))
  2146. {
  2147. $aCleanFixes[] = $sSQLFix;
  2148. }
  2149. }
  2150. if (count($aCleanFixes) == 0) return;
  2151. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  2152. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes))."\">\n";
  2153. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  2154. echo "</form>\n";
  2155. }
  2156. public static function DBExists($bMustBeComplete = true)
  2157. {
  2158. // returns true if at least one table exists
  2159. //
  2160. if (!CMDBSource::IsDB(self::$m_sDBName))
  2161. {
  2162. return false;
  2163. }
  2164. CMDBSource::SelectDB(self::$m_sDBName);
  2165. $aFound = array();
  2166. $aMissing = array();
  2167. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2168. {
  2169. if (CMDBSource::IsTable($sTable))
  2170. {
  2171. $aFound[] = $sTable;
  2172. }
  2173. else
  2174. {
  2175. $aMissing[] = $sTable;
  2176. }
  2177. }
  2178. if (count($aFound) == 0)
  2179. {
  2180. // no expected table has been found
  2181. return false;
  2182. }
  2183. else
  2184. {
  2185. if (count($aMissing) == 0)
  2186. {
  2187. // the database is complete (still, could be some fields missing!)
  2188. return true;
  2189. }
  2190. else
  2191. {
  2192. // not all the tables, could be an older version
  2193. if ($bMustBeComplete)
  2194. {
  2195. return false;
  2196. }
  2197. else
  2198. {
  2199. return true;
  2200. }
  2201. }
  2202. }
  2203. }
  2204. public static function DBDrop()
  2205. {
  2206. $bDropEntireDB = true;
  2207. if (!empty(self::$m_sTablePrefix))
  2208. {
  2209. // Do drop only tables corresponding to the sub-database (table prefix)
  2210. // then possibly drop the DB itself (if no table remain)
  2211. foreach (CMDBSource::EnumTables() as $sTable)
  2212. {
  2213. // perform a case insensitive test because on Windows the table names become lowercase :-(
  2214. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  2215. {
  2216. CMDBSource::DropTable($sTable);
  2217. }
  2218. else
  2219. {
  2220. // There is at least one table which is out of the scope of the current application
  2221. $bDropEntireDB = false;
  2222. }
  2223. }
  2224. }
  2225. if ($bDropEntireDB)
  2226. {
  2227. CMDBSource::DropDB(self::$m_sDBName);
  2228. }
  2229. }
  2230. public static function DBCreate()
  2231. {
  2232. // Note: we have to check if the DB does exist, because we may share the DB
  2233. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  2234. if (!CMDBSource::IsDB(self::$m_sDBName))
  2235. {
  2236. CMDBSource::CreateDB(self::$m_sDBName);
  2237. }
  2238. self::DBCreateTables();
  2239. self::DBCreateViews();
  2240. }
  2241. protected static function DBCreateTables()
  2242. {
  2243. list($aErrors, $aSugFix) = self::DBCheckFormat();
  2244. $aSQL = array();
  2245. foreach ($aSugFix as $sClass => $aTarget)
  2246. {
  2247. foreach ($aTarget as $aQueries)
  2248. {
  2249. foreach ($aQueries as $sQuery)
  2250. {
  2251. if (!empty($sQuery))
  2252. {
  2253. //$aSQL[] = $sQuery;
  2254. // forces a refresh of cached information
  2255. CMDBSource::CreateTable($sQuery);
  2256. }
  2257. }
  2258. }
  2259. }
  2260. // does not work -how to have multiple statements in a single query?
  2261. // $sDoCreateAll = implode(" ; ", $aSQL);
  2262. }
  2263. protected static function DBCreateViews()
  2264. {
  2265. list($aErrors, $aSugFix) = self::DBCheckViews();
  2266. $aSQL = array();
  2267. foreach ($aSugFix as $sClass => $aTarget)
  2268. {
  2269. foreach ($aTarget as $aQueries)
  2270. {
  2271. foreach ($aQueries as $sQuery)
  2272. {
  2273. if (!empty($sQuery))
  2274. {
  2275. //$aSQL[] = $sQuery;
  2276. // forces a refresh of cached information
  2277. CMDBSource::CreateTable($sQuery);
  2278. }
  2279. }
  2280. }
  2281. }
  2282. }
  2283. public static function DBDump()
  2284. {
  2285. $aDataDump = array();
  2286. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2287. {
  2288. $aRows = CMDBSource::DumpTable($sTable);
  2289. $aDataDump[$sTable] = $aRows;
  2290. }
  2291. return $aDataDump;
  2292. }
  2293. /*
  2294. * Determines wether the target DB is frozen or not
  2295. * 1 - consider the DB property 'status'
  2296. * 2 - check the setting 'database_read_only'
  2297. */
  2298. public static function DBIsReadOnly()
  2299. {
  2300. $sStatus = DBProperty::GetProperty('status', null);
  2301. if (!is_null($sStatus))
  2302. {
  2303. switch (strtolower(trim($sStatus)))
  2304. {
  2305. case 'fullaccess':
  2306. $ret = false;
  2307. break;
  2308. default:
  2309. $ret = true;
  2310. }
  2311. }
  2312. else
  2313. {
  2314. $ret = self::$m_oConfig->Get('database_read_only');
  2315. }
  2316. return $ret;
  2317. }
  2318. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  2319. {
  2320. $sValue = Dict::S($sKey, 'x-no-nothing');
  2321. if ($sValue == 'x-no-nothing')
  2322. {
  2323. $bNotInDico = true;
  2324. $sValue = $sValueFromOldSystem;
  2325. if (strlen($sValue) == 0)
  2326. {
  2327. $sValue = $sDefaultValue;
  2328. }
  2329. }
  2330. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  2331. }
  2332. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  2333. {
  2334. $sRes = '';
  2335. $sRes .= "// Dictionnay conventions\n";
  2336. $sRes .= htmlentities("// Class:<class_name>\n");
  2337. $sRes .= htmlentities("// Class:<class_name>+\n");
  2338. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n");
  2339. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n");
  2340. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n");
  2341. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n");
  2342. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n");
  2343. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n");
  2344. $sRes .= "\n";
  2345. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  2346. // Need to invent the "module", to characterize the origins of a class
  2347. if (strlen($sModules) == 0)
  2348. {
  2349. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  2350. }
  2351. else
  2352. {
  2353. $aModules = explode(', ', $sModules);
  2354. }
  2355. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2356. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  2357. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2358. foreach ($aModules as $sCategory)
  2359. {
  2360. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2361. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  2362. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2363. $sRes .= "//\n";
  2364. $sRes .= "\n";
  2365. foreach (self::GetClasses($sCategory) as $sClass)
  2366. {
  2367. if (!self::HasTable($sClass)) continue;
  2368. $bNotInDico = false;
  2369. $sClassRes = "//\n";
  2370. $sClassRes .= "// Class: $sClass\n";
  2371. $sClassRes .= "//\n";
  2372. $sClassRes .= "\n";
  2373. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  2374. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  2375. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  2376. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2377. {
  2378. // Skip this attribute if not originaly defined in this class
  2379. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2380. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  2381. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  2382. if ($oAttDef instanceof AttributeEnum)
  2383. {
  2384. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  2385. {
  2386. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  2387. {
  2388. if (array_key_exists('label', $aStateData))
  2389. {
  2390. $sValue = $aStateData['label'];
  2391. }
  2392. else
  2393. {
  2394. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  2395. }
  2396. if (array_key_exists('description', $aStateData))
  2397. {
  2398. $sValuePlus = $aStateData['description'];
  2399. }
  2400. else
  2401. {
  2402. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  2403. }
  2404. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  2405. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  2406. }
  2407. }
  2408. else
  2409. {
  2410. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  2411. {
  2412. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  2413. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  2414. }
  2415. }
  2416. }
  2417. }
  2418. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  2419. {
  2420. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  2421. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  2422. }
  2423. $sClassRes .= "));\n";
  2424. $sClassRes .= "\n";
  2425. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  2426. {
  2427. $sRes .= $sClassRes;
  2428. }
  2429. }
  2430. }
  2431. return $sRes;
  2432. }
  2433. public static function DBCheckFormat()
  2434. {
  2435. $aErrors = array();
  2436. $aSugFix = array();
  2437. foreach (self::GetClasses() as $sClass)
  2438. {
  2439. if (!self::HasTable($sClass)) continue;
  2440. // Check that the table exists
  2441. //
  2442. $sTable = self::DBGetTable($sClass);
  2443. $sKeyField = self::DBGetKey($sClass);
  2444. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  2445. if (!CMDBSource::IsTable($sTable))
  2446. {
  2447. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  2448. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  2449. }
  2450. // Check that the key field exists
  2451. //
  2452. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  2453. {
  2454. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  2455. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  2456. }
  2457. else
  2458. {
  2459. // Check the key field properties
  2460. //
  2461. if (!CMDBSource::IsKey($sTable, $sKeyField))
  2462. {
  2463. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  2464. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  2465. }
  2466. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  2467. {
  2468. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  2469. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  2470. }
  2471. }
  2472. // Check that any defined field exists
  2473. //
  2474. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  2475. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2476. {
  2477. // Skip this attribute if not originaly defined in this class
  2478. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2479. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  2480. {
  2481. $bIndexNeeded = $oAttDef->RequiresIndex();
  2482. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  2483. if (!CMDBSource::IsField($sTable, $sField))
  2484. {
  2485. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  2486. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  2487. if ($bIndexNeeded)
  2488. {
  2489. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2490. }
  2491. }
  2492. else
  2493. {
  2494. // The field already exists, does it have the relevant properties?
  2495. //
  2496. $bToBeChanged = false;
  2497. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  2498. {
  2499. $bToBeChanged = true;
  2500. if ($oAttDef->IsNullAllowed())
  2501. {
  2502. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  2503. }
  2504. else
  2505. {
  2506. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  2507. }
  2508. }
  2509. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  2510. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  2511. {
  2512. $bToBeChanged = true;
  2513. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  2514. }
  2515. if ($bToBeChanged)
  2516. {
  2517. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  2518. }
  2519. // Create indexes (external keys only... so far)
  2520. //
  2521. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField))
  2522. {
  2523. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  2524. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2525. }
  2526. }
  2527. }
  2528. }
  2529. }
  2530. return array($aErrors, $aSugFix);
  2531. }
  2532. public static function DBCheckViews()
  2533. {
  2534. $aErrors = array();
  2535. $aSugFix = array();
  2536. // Reporting views (must be created after any other table)
  2537. //
  2538. foreach (self::GetClasses('bizmodel') as $sClass)
  2539. {
  2540. $sView = self::DBGetView($sClass);
  2541. if (CMDBSource::IsTable($sView))
  2542. {
  2543. // Check that the view is complete
  2544. //
  2545. $bIsComplete = true;
  2546. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2547. {
  2548. foreach($oAttDef->GetSQLExpressions() as $sSuffix => $sTrash)
  2549. {
  2550. $sCol = $sAttCode.$sSuffix;
  2551. if (!CMDBSource::IsField($sView, $sCol))
  2552. {
  2553. $bIsComplete = false;
  2554. $aErrors[$sClass][$sAttCode][] = "field '$sCol' could not be found in view '$sView'";
  2555. $aSugFix[$sClass][$sAttCode][] = "";
  2556. }
  2557. }
  2558. }
  2559. if (!$bIsComplete)
  2560. {
  2561. // Rework the view
  2562. //
  2563. $oFilter = new DBObjectSearch($sClass, '');
  2564. $oFilter->AllowAllData();
  2565. $sSQL = self::MakeSelectQuery($oFilter);
  2566. $aErrors[$sClass]['*'][] = "View '$sView' is currently not complete";
  2567. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  2568. }
  2569. }
  2570. else
  2571. {
  2572. // Create the view
  2573. //
  2574. $oFilter = new DBObjectSearch($sClass, '');
  2575. $oFilter->AllowAllData();
  2576. $sSQL = self::MakeSelectQuery($oFilter);
  2577. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  2578. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  2579. }
  2580. }
  2581. return array($aErrors, $aSugFix);
  2582. }
  2583. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  2584. {
  2585. $sRootClass = self::GetRootClass($sClass);
  2586. $sTable = self::DBGetTable($sClass);
  2587. $sKeyField = self::DBGetKey($sClass);
  2588. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2589. {
  2590. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2591. }
  2592. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2593. if (count($aWrongRecords) == 0) return;
  2594. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2595. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2596. foreach ($aWrongRecords as $iRecordId)
  2597. {
  2598. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2599. {
  2600. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2601. {
  2602. case 'Delete':
  2603. // Already planned for a deletion
  2604. // Let's concatenate the errors description together
  2605. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2606. break;
  2607. case 'Update':
  2608. // Let's plan a deletion
  2609. break;
  2610. }
  2611. }
  2612. else
  2613. {
  2614. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2615. }
  2616. if (!$bProcessingFriends)
  2617. {
  2618. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  2619. {
  2620. // Something new to be deleted...
  2621. $iNewDelCount++;
  2622. }
  2623. }
  2624. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  2625. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  2626. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2627. $aPlannedDel[$sTable][] = $iRecordId;
  2628. }
  2629. // Now make sure that we would delete the records of the other tables for that class
  2630. //
  2631. if (!$bProcessingFriends)
  2632. {
  2633. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  2634. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  2635. {
  2636. $sFriendTable = self::DBGetTable($sFriendClass);
  2637. $sFriendKey = self::DBGetKey($sFriendClass);
  2638. // skip the current table
  2639. if ($sFriendTable == $sTable) continue;
  2640. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  2641. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  2642. }
  2643. }
  2644. }
  2645. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2646. {
  2647. $sRootClass = self::GetRootClass($sClass);
  2648. $sTable = self::DBGetTable($sClass);
  2649. $sKeyField = self::DBGetKey($sClass);
  2650. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2651. {
  2652. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2653. }
  2654. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2655. if (count($aWrongRecords) == 0) return;
  2656. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2657. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2658. foreach ($aWrongRecords as $iRecordId)
  2659. {
  2660. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2661. {
  2662. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2663. {
  2664. case 'Delete':
  2665. // No need to update, the record will be deleted!
  2666. break;
  2667. case 'Update':
  2668. // Already planned for an update
  2669. // Add this new update spec to the list
  2670. $bFoundSameSpec = false;
  2671. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  2672. {
  2673. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  2674. {
  2675. $bFoundSameSpec = true;
  2676. }
  2677. }
  2678. if (!$bFoundSameSpec)
  2679. {
  2680. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2681. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2682. }
  2683. break;
  2684. }
  2685. }
  2686. else
  2687. {
  2688. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2689. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  2690. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2691. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2692. }
  2693. }
  2694. }
  2695. // returns the count of records found for deletion
  2696. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2697. {
  2698. foreach (self::GetClasses() as $sClass)
  2699. {
  2700. if (!self::HasTable($sClass)) continue;
  2701. $sRootClass = self::GetRootClass($sClass);
  2702. $sTable = self::DBGetTable($sClass);
  2703. $sKeyField = self::DBGetKey($sClass);
  2704. if (!self::IsStandaloneClass($sClass))
  2705. {
  2706. if (self::IsRootClass($sClass))
  2707. {
  2708. // Check that the final class field contains the name of a class which inherited from the current class
  2709. //
  2710. $sFinalClassField = self::DBGetClassField($sClass);
  2711. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2712. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  2713. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  2714. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2715. }
  2716. else
  2717. {
  2718. $sRootTable = self::DBGetTable($sRootClass);
  2719. $sRootKey = self::DBGetKey($sRootClass);
  2720. $sFinalClassField = self::DBGetClassField($sRootClass);
  2721. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2722. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2723. // Check that any record found here has its counterpart in the root table
  2724. // and which refers to a child class
  2725. //
  2726. $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";
  2727. 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);
  2728. // Check that any record found in the root table and referring to a child class
  2729. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2730. //
  2731. $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)";
  2732. 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);
  2733. }
  2734. }
  2735. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2736. {
  2737. // Skip this attribute if not defined in this table
  2738. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2739. if ($oAttDef->IsExternalKey())
  2740. {
  2741. // Check that any external field is pointing to an existing object
  2742. //
  2743. $sRemoteClass = $oAttDef->GetTargetClass();
  2744. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2745. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2746. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2747. $sExtKeyField = current($aCols); // get the first column for an external key
  2748. // Note: a class/table may have an external key on itself
  2749. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2750. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2751. if ($oAttDef->IsNullAllowed())
  2752. {
  2753. // Exclude the records pointing to 0/null from the errors
  2754. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2755. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2756. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2757. }
  2758. else
  2759. {
  2760. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2761. }
  2762. // Do almost the same, taking into account the records planned for deletion
  2763. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2764. {
  2765. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2766. // but in that case you won't be able to track the root cause (cascading)
  2767. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2768. if ($oAttDef->IsNullAllowed())
  2769. {
  2770. // Exclude the records pointing to 0/null from the errors
  2771. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2772. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2773. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2774. }
  2775. else
  2776. {
  2777. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2778. }
  2779. }
  2780. }
  2781. else if ($oAttDef->IsDirectField())
  2782. {
  2783. // Check that the values fit the allowed values
  2784. //
  2785. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2786. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2787. {
  2788. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2789. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2790. $sMyAttributeField = current($aCols); // get the first column for the moment
  2791. $sDefaultValue = $oAttDef->GetDefaultValue();
  2792. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2793. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2794. }
  2795. }
  2796. }
  2797. }
  2798. }
  2799. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2800. {
  2801. // Records in error, and action to be taken: delete or update
  2802. // by RootClass/Table/Record
  2803. $aErrorsAndFixes = array();
  2804. // Records to be ignored in the current/next pass
  2805. // by Table = array of RecordId
  2806. $aPlannedDel = array();
  2807. // Count of errors in the next pass: no error means that we can leave...
  2808. $iErrorCount = 0;
  2809. // Limit in case of a bug in the algorythm
  2810. $iLoopCount = 0;
  2811. $iNewDelCount = 1; // startup...
  2812. while ($iNewDelCount > 0)
  2813. {
  2814. $iNewDelCount = 0;
  2815. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2816. $iErrorCount += $iNewDelCount;
  2817. // Safety net #1 - limit the planned deletions
  2818. //
  2819. $iMaxDel = 1000;
  2820. $iPlannedDel = 0;
  2821. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  2822. {
  2823. $iPlannedDel += count($aPlannedDelOnTable);
  2824. }
  2825. if ($iPlannedDel > $iMaxDel)
  2826. {
  2827. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  2828. break;
  2829. }
  2830. // Safety net #2 - limit the iterations
  2831. //
  2832. $iLoopCount++;
  2833. $iMaxLoops = 10;
  2834. if ($iLoopCount > $iMaxLoops)
  2835. {
  2836. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  2837. break;
  2838. }
  2839. }
  2840. // Display the results
  2841. //
  2842. $iIssueCount = 0;
  2843. $aFixesDelete = array();
  2844. $aFixesUpdate = array();
  2845. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  2846. {
  2847. foreach ($aTables as $sTable => $aRecords)
  2848. {
  2849. foreach ($aRecords as $iRecord => $aError)
  2850. {
  2851. $sAction = $aError['Action'];
  2852. $sReason = $aError['Reason'];
  2853. $iPass = $aError['Pass'];
  2854. switch ($sAction)
  2855. {
  2856. case 'Delete':
  2857. $sActionDetails = "";
  2858. $aFixesDelete[$sTable][] = $iRecord;
  2859. break;
  2860. case 'Update':
  2861. $aUpdateDesc = array();
  2862. foreach($aError['Action_Details'] as $aUpdateSpec)
  2863. {
  2864. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  2865. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  2866. }
  2867. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  2868. break;
  2869. default:
  2870. $sActionDetails = "bug: unknown action '$sAction'";
  2871. }
  2872. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  2873. $iIssueCount++;
  2874. }
  2875. }
  2876. }
  2877. if ($iIssueCount > 0)
  2878. {
  2879. // Build the queries to fix in the database
  2880. //
  2881. // First step, be able to get class data out of the table name
  2882. // Could be optimized, because we've made the job earlier... but few benefits, so...
  2883. $aTable2ClassProp = array();
  2884. foreach (self::GetClasses() as $sClass)
  2885. {
  2886. if (!self::HasTable($sClass)) continue;
  2887. $sRootClass = self::GetRootClass($sClass);
  2888. $sTable = self::DBGetTable($sClass);
  2889. $sKeyField = self::DBGetKey($sClass);
  2890. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2891. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  2892. }
  2893. // Second step, build a flat list of SQL queries
  2894. $aSQLFixes = array();
  2895. $iPlannedUpdate = 0;
  2896. foreach ($aFixesUpdate as $sTable => $aColumns)
  2897. {
  2898. foreach ($aColumns as $sColumn => $aNewValues)
  2899. {
  2900. foreach ($aNewValues as $sNewValue => $aRecords)
  2901. {
  2902. $iPlannedUpdate += count($aRecords);
  2903. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2904. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2905. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  2906. }
  2907. }
  2908. }
  2909. $iPlannedDel = 0;
  2910. foreach ($aFixesDelete as $sTable => $aRecords)
  2911. {
  2912. $iPlannedDel += count($aRecords);
  2913. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2914. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2915. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  2916. }
  2917. // Report the results
  2918. //
  2919. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2920. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  2921. // #@# later -> this is the responsibility of the caller to format the output
  2922. echo "<ul class=\"treeview\">\n";
  2923. foreach ($aIssues as $sIssueDesc)
  2924. {
  2925. echo "<li>$sIssueDesc</li>\n";
  2926. }
  2927. echo "</ul>\n";
  2928. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  2929. echo "<p>Aborting...</p>\n";
  2930. echo "</div>\n";
  2931. exit;
  2932. }
  2933. }
  2934. public static function Startup($sConfigFile, $bModelOnly = false)
  2935. {
  2936. self::LoadConfig($sConfigFile);
  2937. if ($bModelOnly) return;
  2938. CMDBSource::SelectDB(self::$m_sDBName);
  2939. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  2940. self::InitPlugins();
  2941. if (false)
  2942. {
  2943. echo "Debug<br/>\n";
  2944. self::static_var_dump();
  2945. }
  2946. }
  2947. public static function LoadConfig($sConfigFile)
  2948. {
  2949. self::$m_oConfig = new Config($sConfigFile);
  2950. // Set log ASAP
  2951. if (self::$m_oConfig->GetLogGlobal())
  2952. {
  2953. if (self::$m_oConfig->GetLogIssue())
  2954. {
  2955. self::$m_bLogIssue = true;
  2956. IssueLog::Enable(APPROOT.'/error.log');
  2957. }
  2958. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  2959. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  2960. }
  2961. else
  2962. {
  2963. self::$m_bLogIssue = false;
  2964. self::$m_bLogNotification = false;
  2965. self::$m_bLogWebService = false;
  2966. }
  2967. if (self::$m_oConfig->GetLogKPIDuration())
  2968. {
  2969. ExecutionKPI::EnableDuration();
  2970. }
  2971. if (self::$m_oConfig->GetLogKPIMemory())
  2972. {
  2973. ExecutionKPI::EnableMemory();
  2974. }
  2975. self::$m_bTraceQueries = self::$m_oConfig->GetDebugQueries();
  2976. self::$m_bQueryCacheEnabled = self::$m_oConfig->GetQueryCacheEnabled();
  2977. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  2978. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  2979. // Note: load the dictionary as soon as possible, because it might be
  2980. // needed when some error occur
  2981. foreach (self::$m_oConfig->GetDictionaries() as $sModule => $sToInclude)
  2982. {
  2983. self::Plugin($sConfigFile, 'dictionaries', $sToInclude);
  2984. }
  2985. // Set the language... after the dictionaries have been loaded!
  2986. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  2987. // Romain: this is the only way I've found to cope with the fact that
  2988. // classes have to be derived from cmdbabstract (to be editable in the UI)
  2989. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  2990. foreach (self::$m_oConfig->GetAppModules() as $sModule => $sToInclude)
  2991. {
  2992. self::Plugin($sConfigFile, 'application', $sToInclude);
  2993. }
  2994. foreach (self::$m_oConfig->GetDataModels() as $sModule => $sToInclude)
  2995. {
  2996. self::Plugin($sConfigFile, 'business', $sToInclude);
  2997. }
  2998. foreach (self::$m_oConfig->GetWebServiceCategories() as $sModule => $sToInclude)
  2999. {
  3000. self::Plugin($sConfigFile, 'webservice', $sToInclude);
  3001. }
  3002. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  3003. {
  3004. self::Plugin($sConfigFile, 'addons', $sToInclude);
  3005. }
  3006. $sServer = self::$m_oConfig->GetDBHost();
  3007. $sUser = self::$m_oConfig->GetDBUser();
  3008. $sPwd = self::$m_oConfig->GetDBPwd();
  3009. $sSource = self::$m_oConfig->GetDBName();
  3010. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  3011. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  3012. $sCollation = self::$m_oConfig->GetDBCollation();
  3013. $oKPI = new ExecutionKPI();
  3014. // The include have been included, let's browse the existing classes and
  3015. // develop some data based on the proposed model
  3016. self::InitClasses($sTablePrefix);
  3017. $oKPI->ComputeAndReport('Initialization of Data model structures');
  3018. self::$m_sDBName = $sSource;
  3019. self::$m_sTablePrefix = $sTablePrefix;
  3020. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  3021. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  3022. }
  3023. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  3024. {
  3025. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  3026. }
  3027. public static function GetConfig()
  3028. {
  3029. return self::$m_oConfig;
  3030. }
  3031. protected static $m_aPlugins = array();
  3032. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  3033. {
  3034. self::$m_aPlugins[$sName] = array(
  3035. 'type' => $sType,
  3036. 'init' => $aInitCallSpec,
  3037. );
  3038. }
  3039. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  3040. {
  3041. $sFirstChar = substr($sToInclude, 0, 1);
  3042. $sSecondChar = substr($sToInclude, 1, 1);
  3043. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  3044. {
  3045. // It is a relative path, prepend APPROOT
  3046. if (substr($sToInclude, 0, 3) == '../')
  3047. {
  3048. // Preserve compatibility with config files written before 1.0.1
  3049. // Replace '../' by '<root>/'
  3050. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  3051. }
  3052. else
  3053. {
  3054. $sFile = APPROOT.'/'.$sToInclude;
  3055. }
  3056. }
  3057. else
  3058. {
  3059. // Leave as is - should be an absolute path
  3060. $sFile = $sToInclude;
  3061. }
  3062. if (!file_exists($sFile))
  3063. {
  3064. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sFile));
  3065. }
  3066. require_once($sFile);
  3067. }
  3068. protected static function InitPlugins()
  3069. {
  3070. foreach(self::$m_aPlugins as $sName => $aData)
  3071. {
  3072. $aCallSpec = @$aData['init'];
  3073. if (count($aCallSpec) == 2)
  3074. {
  3075. if (!is_callable($aCallSpec))
  3076. {
  3077. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  3078. }
  3079. call_user_func($aCallSpec);
  3080. }
  3081. }
  3082. }
  3083. // Building an object
  3084. //
  3085. //
  3086. private static $aQueryCacheGetObject = array();
  3087. private static $aQueryCacheGetObjectHits = array();
  3088. public static function GetQueryCacheStatus()
  3089. {
  3090. $aRes = array();
  3091. $iTotalHits = 0;
  3092. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  3093. {
  3094. $aRes[] = "$sClass: $iHits";
  3095. $iTotalHits += $iHits;
  3096. }
  3097. return $iTotalHits.' ('.implode(', ', $aRes).')';
  3098. }
  3099. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false)
  3100. {
  3101. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  3102. {
  3103. // NOTE: Quick and VERY dirty caching mechanism which relies on
  3104. // the fact that the string '987654321' will never appear in the
  3105. // standard query
  3106. // This will be replaced for sure with a prepared statement
  3107. // or a view... next optimization to come!
  3108. $oFilter = new DBObjectSearch($sClass);
  3109. $oFilter->AddCondition('id', 987654321, '=');
  3110. if ($bAllowAllData)
  3111. {
  3112. $oFilter->AllowAllData();
  3113. }
  3114. $sSQL = self::MakeSelectQuery($oFilter);
  3115. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  3116. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  3117. }
  3118. else
  3119. {
  3120. $sSQL = self::$aQueryCacheGetObject[$sClass];
  3121. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  3122. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  3123. }
  3124. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  3125. $res = CMDBSource::Query($sSQL);
  3126. $aRow = CMDBSource::FetchArray($res);
  3127. CMDBSource::FreeResult($res);
  3128. if ($bMustBeFound && empty($aRow))
  3129. {
  3130. throw new CoreException("No result for the single row query: '$sSQL'");
  3131. }
  3132. return $aRow;
  3133. }
  3134. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '')
  3135. {
  3136. self::_check_subclass($sClass);
  3137. if (strlen($sClassAlias) == 0)
  3138. {
  3139. $sClassAlias = $sClass;
  3140. }
  3141. // Compound objects: if available, get the final object class
  3142. //
  3143. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  3144. {
  3145. // Either this is a bug (forgot to specify a root class with a finalclass field
  3146. // Or this is the expected behavior, because the object is not made of several tables
  3147. }
  3148. elseif (empty($aRow[$sClassAlias."finalclass"]))
  3149. {
  3150. // The data is missing in the DB
  3151. // @#@ possible improvement: check that the class is valid !
  3152. $sRootClass = self::GetRootClass($sClass);
  3153. $sFinalClassField = self::DBGetClassField($sRootClass);
  3154. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  3155. }
  3156. else
  3157. {
  3158. // do the job for the real target class
  3159. $sClass = $aRow[$sClassAlias."finalclass"];
  3160. }
  3161. return new $sClass($aRow, $sClassAlias);
  3162. }
  3163. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false)
  3164. {
  3165. self::_check_subclass($sClass);
  3166. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData);
  3167. if (empty($aRow))
  3168. {
  3169. return null;
  3170. }
  3171. return self::GetObjectByRow($sClass, $aRow);
  3172. }
  3173. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  3174. {
  3175. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  3176. if ($bAllowAllData)
  3177. {
  3178. $oFilter->AllowAllData();
  3179. }
  3180. $oSet = new DBObjectSet($oFilter);
  3181. $oObject = $oSet->Fetch();
  3182. return $oObject;
  3183. }
  3184. public static function GetHyperLink($sTargetClass, $iKey)
  3185. {
  3186. if ($iKey < 0)
  3187. {
  3188. return "$sTargetClass: $iKey (invalid value)";
  3189. }
  3190. $oObj = self::GetObject($sTargetClass, $iKey, false);
  3191. if (is_null($oObj))
  3192. {
  3193. return "$sTargetClass: $iKey (not found)";
  3194. }
  3195. return $oObj->GetHyperLink();
  3196. }
  3197. public static function NewObject($sClass)
  3198. {
  3199. self::_check_subclass($sClass);
  3200. return new $sClass();
  3201. }
  3202. public static function GetNextKey($sClass)
  3203. {
  3204. $sRootClass = MetaModel::GetRootClass($sClass);
  3205. $sRootTable = MetaModel::DBGetTable($sRootClass);
  3206. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  3207. return $iNextKey;
  3208. }
  3209. public static function BulkDelete(DBObjectSearch $oFilter)
  3210. {
  3211. $sSQL = self::MakeDeleteQuery($oFilter);
  3212. if (!self::DBIsReadOnly())
  3213. {
  3214. CMDBSource::Query($sSQL);
  3215. }
  3216. }
  3217. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  3218. {
  3219. // $aValues is an array of $sAttCode => $value
  3220. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  3221. if (!self::DBIsReadOnly())
  3222. {
  3223. CMDBSource::Query($sSQL);
  3224. }
  3225. }
  3226. // Links
  3227. //
  3228. //
  3229. public static function EnumReferencedClasses($sClass)
  3230. {
  3231. self::_check_subclass($sClass);
  3232. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  3233. $aResult = array();
  3234. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  3235. {
  3236. if ($oAttDef->IsExternalKey())
  3237. {
  3238. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  3239. }
  3240. }
  3241. return $aResult;
  3242. }
  3243. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  3244. {
  3245. self::_check_subclass($sClass);
  3246. if ($bSkipLinkingClasses)
  3247. {
  3248. $aLinksClasses = self::EnumLinksClasses();
  3249. }
  3250. // 1-N links (referencing my class), array of sClass => array of sAttcode
  3251. $aResult = array();
  3252. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  3253. {
  3254. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  3255. $aExtKeys = array();
  3256. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  3257. {
  3258. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3259. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  3260. {
  3261. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  3262. // Ok, I want this one
  3263. $aExtKeys[$sAttCode] = $oAttDef;
  3264. }
  3265. }
  3266. if (count($aExtKeys) != 0)
  3267. {
  3268. $aResult[$sSomeClass] = $aExtKeys;
  3269. }
  3270. }
  3271. return $aResult;
  3272. }
  3273. public static function EnumLinksClasses()
  3274. {
  3275. // Returns a flat array of classes having at least two external keys
  3276. $aResult = array();
  3277. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  3278. {
  3279. $iExtKeyCount = 0;
  3280. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  3281. {
  3282. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3283. if ($oAttDef->IsExternalKey())
  3284. {
  3285. $iExtKeyCount++;
  3286. }
  3287. }
  3288. if ($iExtKeyCount >= 2)
  3289. {
  3290. $aResult[] = $sSomeClass;
  3291. }
  3292. }
  3293. return $aResult;
  3294. }
  3295. public static function EnumLinkingClasses($sClass = "")
  3296. {
  3297. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  3298. $aResult = array();
  3299. foreach (self::EnumLinksClasses() as $sSomeClass)
  3300. {
  3301. $aTargets = array();
  3302. $bFoundClass = false;
  3303. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  3304. {
  3305. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3306. if ($oAttDef->IsExternalKey())
  3307. {
  3308. $sRemoteClass = $oAttDef->GetTargetClass();
  3309. if (empty($sClass))
  3310. {
  3311. $aTargets[$sAttCode] = $sRemoteClass;
  3312. }
  3313. elseif ($sClass == $sRemoteClass)
  3314. {
  3315. $bFoundClass = true;
  3316. }
  3317. else
  3318. {
  3319. $aTargets[$sAttCode] = $sRemoteClass;
  3320. }
  3321. }
  3322. }
  3323. if (empty($sClass) || $bFoundClass)
  3324. {
  3325. $aResult[$sSomeClass] = $aTargets;
  3326. }
  3327. }
  3328. return $aResult;
  3329. }
  3330. public static function GetLinkLabel($sLinkClass, $sAttCode)
  3331. {
  3332. self::_check_subclass($sLinkClass);
  3333. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  3334. return self::GetLabel($sLinkClass, $sAttCode);
  3335. }
  3336. /**
  3337. * Replaces all the parameters by the values passed in the hash array
  3338. */
  3339. static public function ApplyParams($aInput, $aParams)
  3340. {
  3341. $aSearches = array();
  3342. $aReplacements = array();
  3343. foreach($aParams as $sSearch => $replace)
  3344. {
  3345. // Some environment parameters are objects, we just need scalars
  3346. if (is_object($replace)) continue;
  3347. $aSearches[] = '$'.$sSearch.'$';
  3348. $aReplacements[] = (string) $replace;
  3349. }
  3350. return str_replace($aSearches, $aReplacements, $aInput);
  3351. }
  3352. } // class MetaModel
  3353. // Standard attribute lists
  3354. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  3355. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  3356. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  3357. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  3358. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  3359. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  3360. ?>