metamodel.class.php 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734
  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. self::Init_CheckZListItems($aItems, $sTargetClass);
  1228. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  1229. }
  1230. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  1231. {
  1232. foreach($aItems as $iFoo => $attCode)
  1233. {
  1234. if (is_array($attCode))
  1235. {
  1236. self::Init_CheckZListItems($attCode, $sTargetClass);
  1237. }
  1238. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  1239. {
  1240. unset($aItems[$iFoo]);
  1241. }
  1242. }
  1243. }
  1244. public static function Init_DefineState($sStateCode, $aStateDef)
  1245. {
  1246. $sTargetClass = self::GetCallersPHPClass("Init");
  1247. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  1248. $sParentState = $aStateDef['attribute_inherit'];
  1249. if (!empty($sParentState))
  1250. {
  1251. // Inherit from the given state (must be defined !)
  1252. //
  1253. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  1254. // Reset the constraint when it was mandatory to set the value at the previous state
  1255. //
  1256. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  1257. {
  1258. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  1259. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  1260. $aToInherit['attribute_list'][$sState] = $iFlags;
  1261. }
  1262. // The inherited configuration could be overriden
  1263. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  1264. }
  1265. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  1266. {
  1267. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  1268. {
  1269. unset($aStateDef['attribute_list'][$sAttCode]);
  1270. }
  1271. }
  1272. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  1273. // by default, create an empty set of transitions associated to that state
  1274. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  1275. }
  1276. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  1277. {
  1278. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  1279. $sTargetClass = self::GetCallersPHPClass("Init");
  1280. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  1281. }
  1282. public static function Init_DefineStimulus($oStimulus)
  1283. {
  1284. $sTargetClass = self::GetCallersPHPClass("Init");
  1285. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  1286. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1287. // Therefore, the reference to the host class is set there
  1288. $oStimulus->SetHostClass($sTargetClass);
  1289. }
  1290. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  1291. {
  1292. $sTargetClass = self::GetCallersPHPClass("Init");
  1293. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  1294. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  1295. }
  1296. public static function Init_InheritLifecycle($sSourceClass = '')
  1297. {
  1298. $sTargetClass = self::GetCallersPHPClass("Init");
  1299. if (empty($sSourceClass))
  1300. {
  1301. // Default: inherit from parent class
  1302. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1303. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1304. }
  1305. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  1306. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  1307. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  1308. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  1309. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  1310. }
  1311. //
  1312. // Static API
  1313. //
  1314. public static function GetRootClass($sClass = null)
  1315. {
  1316. self::_check_subclass($sClass);
  1317. return self::$m_aRootClasses[$sClass];
  1318. }
  1319. public static function IsRootClass($sClass)
  1320. {
  1321. self::_check_subclass($sClass);
  1322. return (self::GetRootClass($sClass) == $sClass);
  1323. }
  1324. public static function EnumRootClasses()
  1325. {
  1326. return array_unique(self::$m_aRootClasses);
  1327. }
  1328. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF)
  1329. {
  1330. self::_check_subclass($sClass);
  1331. if ($iOption == ENUM_PARENT_CLASSES_EXCLUDELEAF)
  1332. {
  1333. return self::$m_aParentClasses[$sClass];
  1334. }
  1335. $aRes = self::$m_aParentClasses[$sClass];
  1336. $aRes[] = $sClass;
  1337. return $aRes;
  1338. }
  1339. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  1340. {
  1341. self::_check_subclass($sClass);
  1342. $aRes = self::$m_aChildClasses[$sClass];
  1343. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  1344. {
  1345. // Add it to the list
  1346. $aRes[] = $sClass;
  1347. }
  1348. return $aRes;
  1349. }
  1350. public static function HasChildrenClasses($sClass)
  1351. {
  1352. return (count(self::$m_aChildClasses[$sClass]) > 0);
  1353. }
  1354. public static function EnumCategories()
  1355. {
  1356. return array_keys(self::$m_Category2Class);
  1357. }
  1358. // Note: use EnumChildClasses to take the compound objects into account
  1359. public static function GetSubclasses($sClass)
  1360. {
  1361. self::_check_subclass($sClass);
  1362. $aSubClasses = array();
  1363. foreach(get_declared_classes() as $sSubClass) {
  1364. if (is_subclass_of($sSubClass, $sClass))
  1365. {
  1366. $aSubClasses[] = $sSubClass;
  1367. }
  1368. }
  1369. return $aSubClasses;
  1370. }
  1371. public static function GetClasses($sCategory = '')
  1372. {
  1373. if (array_key_exists($sCategory, self::$m_Category2Class))
  1374. {
  1375. return self::$m_Category2Class[$sCategory];
  1376. }
  1377. //if (count(self::$m_Category2Class) > 0)
  1378. //{
  1379. // throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  1380. //}
  1381. return array();
  1382. }
  1383. public static function HasTable($sClass)
  1384. {
  1385. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  1386. return true;
  1387. }
  1388. public static function IsAbstract($sClass)
  1389. {
  1390. $oReflection = new ReflectionClass($sClass);
  1391. return $oReflection->isAbstract();
  1392. }
  1393. protected static $m_aQueryStructCache = array();
  1394. protected static function PrepareQueryArguments($aArgs)
  1395. {
  1396. // Translate any object into scalars
  1397. //
  1398. $aScalarArgs = array();
  1399. foreach($aArgs as $sArgName => $value)
  1400. {
  1401. if (self::IsValidObject($value))
  1402. {
  1403. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgs($sArgName));
  1404. }
  1405. else
  1406. {
  1407. $aScalarArgs[$sArgName] = (string) $value;
  1408. }
  1409. }
  1410. // Add standard contextual arguments
  1411. //
  1412. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1413. return $aScalarArgs;
  1414. }
  1415. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  1416. {
  1417. // Hide objects that are not visible to the current user
  1418. //
  1419. if (!$oFilter->IsAllDataAllowed())
  1420. {
  1421. $oVisibleObjects = UserRights::GetSelectFilter($oFilter->GetClass());
  1422. if ($oVisibleObjects === false)
  1423. {
  1424. // Make sure this is a valid search object, saying NO for all
  1425. $oVisibleObjects = DBObjectSearch::FromEmptySet($oFilter->GetClass());
  1426. }
  1427. if (is_object($oVisibleObjects))
  1428. {
  1429. $oFilter->MergeWith($oVisibleObjects);
  1430. }
  1431. else
  1432. {
  1433. // should be true at this point, meaning that no additional filtering
  1434. // is required
  1435. }
  1436. }
  1437. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  1438. {
  1439. // Need to identify the query
  1440. $sOqlQuery = $oFilter->ToOql();
  1441. $sOqlId = md5($sOqlQuery);
  1442. }
  1443. else
  1444. {
  1445. $sOqlQuery = "SELECTING... ".$oFilter->GetClass();
  1446. $sOqlId = "query id ? n/a";
  1447. }
  1448. // Query caching
  1449. //
  1450. if (self::$m_bQueryCacheEnabled)
  1451. {
  1452. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  1453. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  1454. // to use a hash (like md5) of the string as the key !
  1455. //
  1456. // Example of two queries that were found as similar by the hash array:
  1457. // 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
  1458. // and
  1459. // 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
  1460. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  1461. //
  1462. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  1463. {
  1464. // hit!
  1465. $oSelect = clone self::$m_aQueryStructCache[$sOqlId];
  1466. }
  1467. }
  1468. if (!isset($oSelect))
  1469. {
  1470. $aTranslation = array();
  1471. $aClassAliases = array();
  1472. $aTableAliases = array();
  1473. $oConditionTree = $oFilter->GetCriteria();
  1474. $oKPI = new ExecutionKPI();
  1475. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), array(), true /* main query */);
  1476. $oKPI->ComputeStats('MakeQuery (select)', $sOqlQuery);
  1477. self::$m_aQueryStructCache[$sOqlId] = clone $oSelect;
  1478. }
  1479. // Check the order by specification, and prefix with the class alias
  1480. //
  1481. $aOrderSpec = array();
  1482. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1483. {
  1484. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($oFilter->GetFirstJoinedClass()));
  1485. if (!is_bool($bAscending))
  1486. {
  1487. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1488. }
  1489. $aOrderSpec[$oFilter->GetFirstJoinedClassAlias().$sFieldAlias] = $bAscending;
  1490. }
  1491. // By default, force the name attribute to be the ordering key
  1492. //
  1493. if (empty($aOrderSpec))
  1494. {
  1495. foreach ($oFilter->GetSelectedClasses() as $sSelectedAlias => $sSelectedClass)
  1496. {
  1497. $sNameAttCode = self::GetNameAttributeCode($sSelectedClass);
  1498. if (!empty($sNameAttCode))
  1499. {
  1500. // By default, simply order on the "name" attribute, ascending
  1501. $aOrderSpec[$sSelectedAlias.$sNameAttCode] = true;
  1502. }
  1503. }
  1504. }
  1505. // Go
  1506. //
  1507. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1508. try
  1509. {
  1510. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount);
  1511. }
  1512. catch (MissingQueryArgument $e)
  1513. {
  1514. // Add some information...
  1515. $e->addInfo('OQL', $sOqlQuery);
  1516. throw $e;
  1517. }
  1518. if (self::$m_bTraceQueries)
  1519. {
  1520. $sQueryId = md5($sRes);
  1521. if(!isset(self::$m_aQueriesLog[$sOqlId]))
  1522. {
  1523. self::$m_aQueriesLog[$sOqlId]['oql'] = $sOqlQuery;
  1524. self::$m_aQueriesLog[$sOqlId]['hits'] = 1;
  1525. }
  1526. else
  1527. {
  1528. self::$m_aQueriesLog[$sOqlId]['hits']++;
  1529. }
  1530. if(!isset(self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]))
  1531. {
  1532. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['sql'] = $sRes;
  1533. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['count'] = 1;
  1534. }
  1535. else
  1536. {
  1537. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['count']++;
  1538. }
  1539. }
  1540. return $sRes;
  1541. }
  1542. public static function ShowQueryTrace()
  1543. {
  1544. if (!self::$m_bTraceQueries) return;
  1545. $iOqlCount = count(self::$m_aQueriesLog);
  1546. if ($iOqlCount == 0)
  1547. {
  1548. echo "<p>Trace activated, but no query found</p>\n";
  1549. return;
  1550. }
  1551. $iSqlCount = 0;
  1552. foreach (self::$m_aQueriesLog as $aOqlData)
  1553. {
  1554. $iSqlCount += $aOqlData['hits'];
  1555. }
  1556. echo "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  1557. foreach (self::$m_aQueriesLog as $aOqlData)
  1558. {
  1559. $sOql = $aOqlData['oql'];
  1560. $sHits = $aOqlData['hits'];
  1561. echo "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  1562. echo "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  1563. foreach($aOqlData['queries'] as $aSqlData)
  1564. {
  1565. $sQuery = $aSqlData['sql'];
  1566. $sSqlHits = $aSqlData['count'];
  1567. echo "<li><b>$sSqlHits</b> hits for SQL: <span style=\"font-size:60%\">$sQuery</span><li>\n";
  1568. }
  1569. echo "</ul>\n";
  1570. }
  1571. }
  1572. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1573. {
  1574. $aTranslation = array();
  1575. $aClassAliases = array();
  1576. $aTableAliases = array();
  1577. $oConditionTree = $oFilter->GetCriteria();
  1578. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), array(), true /* main query */);
  1579. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1580. return $oSelect->RenderDelete($aScalarArgs);
  1581. }
  1582. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1583. {
  1584. // $aValues is an array of $sAttCode => $value
  1585. $aTranslation = array();
  1586. $aClassAliases = array();
  1587. $aTableAliases = array();
  1588. $oConditionTree = $oFilter->GetCriteria();
  1589. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), $aValues, true /* main query */);
  1590. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1591. return $oSelect->RenderUpdate($aScalarArgs);
  1592. }
  1593. private static function MakeQuery($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, DBObjectSearch $oFilter, $aExpectedAtts = array(), $aValues = array(), $bIsMainQuery = false)
  1594. {
  1595. // Note: query class might be different than the class of the filter
  1596. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1597. // $aExpectedAtts is an array of sAttCode=>array of columns
  1598. $sClass = $oFilter->GetFirstJoinedClass();
  1599. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  1600. $bIsOnQueriedClass = array_key_exists($sClassAlias, $aSelectedClasses);
  1601. if ($bIsOnQueriedClass)
  1602. {
  1603. $aClassAliases = array_merge($aClassAliases, $oFilter->GetJoinedClasses());
  1604. }
  1605. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1606. $sRootClass = self::GetRootClass($sClass);
  1607. $sKeyField = self::DBGetKey($sClass);
  1608. if ($bIsOnQueriedClass)
  1609. {
  1610. // default to the whole list of attributes + the very std id/finalclass
  1611. $aExpectedAtts['id'][] = $sClassAlias.'id';
  1612. foreach (self::GetAttributesList($sClass) as $sAttCode)
  1613. {
  1614. $aExpectedAtts[$sAttCode][] = $sClassAlias.$sAttCode; // alias == class and attcode
  1615. }
  1616. }
  1617. // Compute a clear view of external keys, and external attributes
  1618. // Build the list of external keys:
  1619. // -> ext keys required by a closed join ???
  1620. // -> ext keys mentionned in a 'pointing to' condition
  1621. // -> ext keys required for an external field
  1622. //
  1623. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1624. //
  1625. // Optimization: could be computed once for all (cached)
  1626. // Could be done in MakeQuerySingleTable ???
  1627. //
  1628. if ($bIsOnQueriedClass)
  1629. {
  1630. // Get all Ext keys for the queried class (??)
  1631. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1632. {
  1633. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1634. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1635. }
  1636. }
  1637. // Get all Ext keys used by the filter
  1638. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1639. {
  1640. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1641. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1642. }
  1643. // Add the ext fields used in the select (eventually adds an external key)
  1644. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1645. {
  1646. if ($oAttDef->IsExternalField())
  1647. {
  1648. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1649. if (array_key_exists($sAttCode, $aExpectedAtts) || $oConditionTree->RequiresField($sClassAlias, $sAttCode))
  1650. {
  1651. // Add the external attribute
  1652. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1653. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1654. }
  1655. }
  1656. }
  1657. // First query built upon on the leaf (ie current) class
  1658. //
  1659. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1660. if (self::HasTable($sClass))
  1661. {
  1662. $oSelectBase = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sClass, $aExpectedAtts, $aExtKeys, $aValues);
  1663. }
  1664. else
  1665. {
  1666. $oSelectBase = null;
  1667. // As the join will not filter on the expected classes, we have to specify it explicitely
  1668. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1669. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1670. $oConditionTree = $oConditionTree->LogAnd($oFinalClassRestriction);
  1671. }
  1672. // Then we join the queries of the eventual parent classes (compound model)
  1673. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1674. {
  1675. if (!self::HasTable($sParentClass)) continue;
  1676. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1677. $oSelectParentTable = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sParentClass, $aExpectedAtts, $aExtKeys, $aValues);
  1678. if (is_null($oSelectBase))
  1679. {
  1680. $oSelectBase = $oSelectParentTable;
  1681. }
  1682. else
  1683. {
  1684. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1685. }
  1686. }
  1687. // Filter on objects referencing me
  1688. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1689. {
  1690. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1691. {
  1692. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1693. // We don't want any attribute from the foreign class, just filter on an inner join
  1694. $aExpAtts = array();
  1695. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1696. //self::DbgTrace($oForeignFilter);
  1697. //self::DbgTrace($oForeignFilter->ToOQL());
  1698. //self::DbgTrace($oSelectForeign);
  1699. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1700. $oSelectForeign = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oForeignFilter, $aExpAtts);
  1701. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1702. $sForeignKeyTable = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][0];
  1703. $sForeignKeyColumn = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][1];
  1704. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1705. }
  1706. }
  1707. // Filter on related objects
  1708. //
  1709. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1710. {
  1711. $oSubFilter = $aCritInfo['flt'];
  1712. $sRelCode = $aCritInfo['relcode'];
  1713. $iMaxDepth = $aCritInfo['maxdepth'];
  1714. // Get the starting point objects
  1715. $oStartSet = new CMDBObjectSet($oSubFilter);
  1716. // Get the objects related to those objects... recursively...
  1717. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1718. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1719. // #@# todo - related objects and expressions...
  1720. // Create condition
  1721. if (count($aRestriction) > 0)
  1722. {
  1723. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1724. }
  1725. else
  1726. {
  1727. // Quick N'dirty -> generate an empty set
  1728. $oSelectBase->AddCondition('false');
  1729. }
  1730. }
  1731. // Translate the conditions... and go
  1732. //
  1733. if ($bIsMainQuery)
  1734. {
  1735. $oConditionTranslated = $oConditionTree->Translate($aTranslation);
  1736. $oSelectBase->SetCondition($oConditionTranslated);
  1737. }
  1738. // That's all... cross fingers and we'll get some working query
  1739. //MyHelpers::var_dump_html($oSelectBase, true);
  1740. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1741. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1742. return $oSelectBase;
  1743. }
  1744. protected static function MakeQuerySingleTable($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, $oFilter, $sTableClass, $aExpectedAtts, $aExtKeys, $aValues)
  1745. {
  1746. // $aExpectedAtts is an array of sAttCode=>sAlias
  1747. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1748. // Prepare the query for a single table (compound objects)
  1749. // Ignores the items (attributes/filters) that are not on the target table
  1750. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1751. //
  1752. // Returns an SQLQuery
  1753. //
  1754. $sTargetClass = $oFilter->GetFirstJoinedClass();
  1755. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  1756. $sTable = self::DBGetTable($sTableClass);
  1757. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1758. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $aSelectedClasses);
  1759. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1760. // 1 - SELECT and UPDATE
  1761. //
  1762. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1763. //
  1764. $aSelect = array();
  1765. $aUpdateValues = array();
  1766. // 1/a - Get the key
  1767. //
  1768. if ($bIsOnQueriedClass)
  1769. {
  1770. $aSelect[$aExpectedAtts['id'][0]] = new FieldExpression(self::DBGetKey($sTableClass), $sTableAlias);
  1771. }
  1772. // We need one pkey to be the key, let's take the one corresponding to the root class
  1773. // (used to be based on the leaf, but it may happen that this one has no table defined)
  1774. $sRootClass = self::GetRootClass($sTargetClass);
  1775. if ($sTableClass == $sRootClass)
  1776. {
  1777. $aTranslation[$sTargetAlias]['id'] = array($sTableAlias, self::DBGetKey($sTableClass));
  1778. }
  1779. // 1/b - Get the other attributes
  1780. //
  1781. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1782. {
  1783. // Skip this attribute if not defined in this table
  1784. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1785. // Skip this attribute if not writable (means that it does not correspond
  1786. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1787. // Update...
  1788. //
  1789. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1790. {
  1791. assert ($oAttDef->IsDirectField());
  1792. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1793. {
  1794. $aUpdateValues[$sColumn] = $sValue;
  1795. }
  1796. }
  1797. // Select...
  1798. //
  1799. // Skip, if a list of fields has been specified and it is not there
  1800. if (!array_key_exists($sAttCode, $aExpectedAtts)) continue;
  1801. if ($oAttDef->IsExternalField())
  1802. {
  1803. // skip, this will be handled in the joined tables
  1804. }
  1805. else
  1806. {
  1807. // standard field, or external key
  1808. // add it to the output
  1809. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1810. {
  1811. foreach ($aExpectedAtts[$sAttCode] as $sAttAlias)
  1812. {
  1813. $aSelect[$sAttAlias.$sColId] = new FieldExpression($sSQLExpr, $sTableAlias);
  1814. }
  1815. }
  1816. }
  1817. }
  1818. // 2 - WHERE
  1819. //
  1820. foreach(self::$m_aFilterDefs[$sTargetClass] as $sFltCode => $oFltAtt)
  1821. {
  1822. // Skip this filter if not defined in this table
  1823. if (self::$m_aFilterOrigins[$sTargetClass][$sFltCode] != $sTableClass) continue;
  1824. // #@# todo - aller plus loin... a savoir que la table de translation doit contenir une "Expression"
  1825. foreach($oFltAtt->GetSQLExpressions() as $sColID => $sFltExpr)
  1826. {
  1827. // Note: I did not test it with filters relying on several expressions...
  1828. // as long as sColdID is empty, this is working, otherwise... ?
  1829. $aTranslation[$sTargetAlias][$sFltCode.$sColID] = array($sTableAlias, $sFltExpr);
  1830. }
  1831. }
  1832. // #@# todo - See what a full text search condition should be
  1833. // 2' - WHERE / Full text search condition
  1834. //
  1835. if ($bIsOnQueriedClass)
  1836. {
  1837. $aFullText = $oFilter->GetCriteria_FullText();
  1838. }
  1839. else
  1840. {
  1841. // Pourquoi ???
  1842. $aFullText = array();
  1843. }
  1844. // 3 - The whole stuff, for this table only
  1845. //
  1846. $oSelectBase = new SQLQuery($sTable, $sTableAlias, $aSelect, null, $aFullText, $bIsOnQueriedClass, $aUpdateValues);
  1847. // 4 - The external keys -> joins...
  1848. //
  1849. if (array_key_exists($sTableClass, $aExtKeys))
  1850. {
  1851. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1852. {
  1853. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1854. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  1855. // In case the join was not explicitely defined in the filter,
  1856. // we need to do it now
  1857. if (empty($oExtFilter))
  1858. {
  1859. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1860. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1861. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1862. }
  1863. else
  1864. {
  1865. // The aliases should not conflict because normalization occured while building the filter
  1866. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1867. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1868. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1869. }
  1870. // Specify expected attributes for the target class query
  1871. // ... and use the current alias !
  1872. $aExpAtts = array();
  1873. $aIntermediateTranslation = array();
  1874. foreach($aExtFields as $sAttCode => $oAtt)
  1875. {
  1876. $sExtAttCode = $oAtt->GetExtAttCode();
  1877. if (array_key_exists($sAttCode, $aExpectedAtts))
  1878. {
  1879. // Request this attribute... transmit the alias !
  1880. $aExpAtts[$sExtAttCode] = $aExpectedAtts[$sAttCode];
  1881. }
  1882. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1883. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  1884. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  1885. {
  1886. $aIntermediateTranslation[$sTargetAlias.$sColID][$sAttCode] = array($sKeyClassAlias, $sRemoteAttExpr);
  1887. }
  1888. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  1889. }
  1890. $oConditionTree = $oConditionTree->Translate($aIntermediateTranslation, false);
  1891. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  1892. $oSelectExtKey = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oExtFilter, $aExpAtts);
  1893. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  1894. $sLocalKeyField = current($aCols); // get the first column for an external key
  1895. $sExternalKeyField = self::DBGetKey($sKeyClass);
  1896. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1897. if ($oKeyAttDef->IsNullAllowed())
  1898. {
  1899. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1900. }
  1901. else
  1902. {
  1903. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1904. }
  1905. }
  1906. }
  1907. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1908. return $oSelectBase;
  1909. }
  1910. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  1911. {
  1912. if (!array_key_exists($sNewName, $aAliases))
  1913. {
  1914. $aAliases[$sNewName] = $sRealName;
  1915. return $sNewName;
  1916. }
  1917. for ($i = 1 ; $i < 100 ; $i++)
  1918. {
  1919. $sAnAlias = $sNewName.$i;
  1920. if (!array_key_exists($sAnAlias, $aAliases))
  1921. {
  1922. // Create that new alias
  1923. $aAliases[$sAnAlias] = $sRealName;
  1924. return $sAnAlias;
  1925. }
  1926. }
  1927. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  1928. }
  1929. public static function CheckDefinitions()
  1930. {
  1931. if (count(self::GetClasses()) == 0)
  1932. {
  1933. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  1934. }
  1935. $aErrors = array();
  1936. $aSugFix = array();
  1937. foreach (self::GetClasses() as $sClass)
  1938. {
  1939. $sNameAttCode = self::GetNameAttributeCode($sClass);
  1940. if (empty($sNameAttCode))
  1941. {
  1942. // let's try this !!!
  1943. // $aErrors[$sClass][] = "Missing value for name definition: the framework will (should...) replace it by the id";
  1944. // $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1945. }
  1946. else if(!self::IsValidAttCode($sClass, $sNameAttCode))
  1947. {
  1948. $aErrors[$sClass][] = "Unkown attribute code '".$sNameAttCode."' for the name definition";
  1949. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1950. }
  1951. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  1952. {
  1953. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  1954. {
  1955. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  1956. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1957. }
  1958. }
  1959. $bHasWritableAttribute = false;
  1960. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1961. {
  1962. // It makes no sense to check the attributes again and again in the subclasses
  1963. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1964. if ($oAttDef->IsExternalKey())
  1965. {
  1966. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  1967. {
  1968. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  1969. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  1970. }
  1971. }
  1972. elseif ($oAttDef->IsExternalField())
  1973. {
  1974. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1975. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  1976. {
  1977. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  1978. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  1979. }
  1980. else
  1981. {
  1982. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1983. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1984. $sExtAttCode = $oAttDef->GetExtAttCode();
  1985. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  1986. {
  1987. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  1988. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  1989. }
  1990. }
  1991. }
  1992. else // standard attributes
  1993. {
  1994. // Check that the default values definition is a valid object!
  1995. $oValSetDef = $oAttDef->GetValuesDef();
  1996. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  1997. {
  1998. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  1999. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  2000. }
  2001. else
  2002. {
  2003. // Default value must be listed in the allowed values (if defined)
  2004. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2005. if (!is_null($aAllowedValues))
  2006. {
  2007. $sDefaultValue = $oAttDef->GetDefaultValue();
  2008. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  2009. {
  2010. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  2011. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  2012. }
  2013. }
  2014. }
  2015. }
  2016. // Check dependencies
  2017. if ($oAttDef->IsWritable())
  2018. {
  2019. $bHasWritableAttribute = true;
  2020. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  2021. {
  2022. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  2023. {
  2024. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  2025. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2026. }
  2027. }
  2028. }
  2029. }
  2030. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  2031. {
  2032. if (method_exists($oFilterDef, '__GetRefAttribute'))
  2033. {
  2034. $oAttDef = $oFilterDef->__GetRefAttribute();
  2035. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  2036. {
  2037. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  2038. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2039. }
  2040. }
  2041. }
  2042. // Lifecycle
  2043. //
  2044. $sStateAttCode = self::GetStateAttributeCode($sClass);
  2045. if (strlen($sStateAttCode) > 0)
  2046. {
  2047. // Lifecycle - check that the state attribute does exist as an attribute
  2048. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  2049. {
  2050. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  2051. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2052. }
  2053. else
  2054. {
  2055. // Lifecycle - check that there is a value set constraint on the state attribute
  2056. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  2057. $aStates = array_keys(self::EnumStates($sClass));
  2058. if (is_null($aAllowedValuesRaw))
  2059. {
  2060. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  2061. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  2062. }
  2063. else
  2064. {
  2065. $aAllowedValues = array_keys($aAllowedValuesRaw);
  2066. // Lifecycle - check the the state attribute allowed values are defined states
  2067. foreach($aAllowedValues as $sValue)
  2068. {
  2069. if (!in_array($sValue, $aStates))
  2070. {
  2071. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  2072. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2073. }
  2074. }
  2075. // Lifecycle - check that defined states are allowed values
  2076. foreach($aStates as $sStateValue)
  2077. {
  2078. if (!in_array($sStateValue, $aAllowedValues))
  2079. {
  2080. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  2081. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2082. }
  2083. }
  2084. }
  2085. // Lifcycle - check that the action handlers are defined
  2086. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  2087. {
  2088. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  2089. {
  2090. foreach ($aTransitionDef['actions'] as $sActionHandler)
  2091. {
  2092. if (!method_exists($sClass, $sActionHandler))
  2093. {
  2094. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2095. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  2096. }
  2097. }
  2098. }
  2099. }
  2100. }
  2101. }
  2102. if ($bHasWritableAttribute)
  2103. {
  2104. if (!self::HasTable($sClass))
  2105. {
  2106. $aErrors[$sClass][] = "No table has been defined for this class";
  2107. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  2108. }
  2109. }
  2110. // ZList
  2111. //
  2112. foreach(self::EnumZLists() as $sListCode)
  2113. {
  2114. foreach (self::GetZListItems($sClass, $sListCode) as $sMyAttCode)
  2115. {
  2116. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  2117. {
  2118. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  2119. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2120. }
  2121. }
  2122. }
  2123. }
  2124. if (count($aErrors) > 0)
  2125. {
  2126. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2127. echo "<h3>Business model inconsistencies have been found</h3>\n";
  2128. // #@# later -> this is the responsibility of the caller to format the output
  2129. foreach ($aErrors as $sClass => $aMessages)
  2130. {
  2131. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  2132. echo "<ul class=\"treeview\">\n";
  2133. $i = 0;
  2134. foreach ($aMessages as $sMsg)
  2135. {
  2136. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  2137. $i++;
  2138. }
  2139. echo "</ul>\n";
  2140. }
  2141. echo "<p>Aborting...</p>\n";
  2142. echo "</div>\n";
  2143. exit;
  2144. }
  2145. }
  2146. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  2147. {
  2148. if (empty($sRepairUrl)) return;
  2149. // By design, some queries might be blank, we have to ignore them
  2150. $aCleanFixes = array();
  2151. foreach($aSQLFixes as $sSQLFix)
  2152. {
  2153. if (!empty($sSQLFix))
  2154. {
  2155. $aCleanFixes[] = $sSQLFix;
  2156. }
  2157. }
  2158. if (count($aCleanFixes) == 0) return;
  2159. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  2160. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes))."\">\n";
  2161. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  2162. echo "</form>\n";
  2163. }
  2164. public static function DBExists($bMustBeComplete = true)
  2165. {
  2166. // returns true if at least one table exists
  2167. //
  2168. if (!CMDBSource::IsDB(self::$m_sDBName))
  2169. {
  2170. return false;
  2171. }
  2172. CMDBSource::SelectDB(self::$m_sDBName);
  2173. $aFound = array();
  2174. $aMissing = array();
  2175. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2176. {
  2177. if (CMDBSource::IsTable($sTable))
  2178. {
  2179. $aFound[] = $sTable;
  2180. }
  2181. else
  2182. {
  2183. $aMissing[] = $sTable;
  2184. }
  2185. }
  2186. if (count($aFound) == 0)
  2187. {
  2188. // no expected table has been found
  2189. return false;
  2190. }
  2191. else
  2192. {
  2193. if (count($aMissing) == 0)
  2194. {
  2195. // the database is complete (still, could be some fields missing!)
  2196. return true;
  2197. }
  2198. else
  2199. {
  2200. // not all the tables, could be an older version
  2201. if ($bMustBeComplete)
  2202. {
  2203. return false;
  2204. }
  2205. else
  2206. {
  2207. return true;
  2208. }
  2209. }
  2210. }
  2211. }
  2212. public static function DBDrop()
  2213. {
  2214. $bDropEntireDB = true;
  2215. if (!empty(self::$m_sTablePrefix))
  2216. {
  2217. // Do drop only tables corresponding to the sub-database (table prefix)
  2218. // then possibly drop the DB itself (if no table remain)
  2219. foreach (CMDBSource::EnumTables() as $sTable)
  2220. {
  2221. // perform a case insensitive test because on Windows the table names become lowercase :-(
  2222. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  2223. {
  2224. CMDBSource::DropTable($sTable);
  2225. }
  2226. else
  2227. {
  2228. // There is at least one table which is out of the scope of the current application
  2229. $bDropEntireDB = false;
  2230. }
  2231. }
  2232. }
  2233. if ($bDropEntireDB)
  2234. {
  2235. CMDBSource::DropDB(self::$m_sDBName);
  2236. }
  2237. }
  2238. public static function DBCreate()
  2239. {
  2240. // Note: we have to check if the DB does exist, because we may share the DB
  2241. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  2242. if (!CMDBSource::IsDB(self::$m_sDBName))
  2243. {
  2244. CMDBSource::CreateDB(self::$m_sDBName);
  2245. }
  2246. self::DBCreateTables();
  2247. self::DBCreateViews();
  2248. }
  2249. protected static function DBCreateTables()
  2250. {
  2251. list($aErrors, $aSugFix) = self::DBCheckFormat();
  2252. $aSQL = array();
  2253. foreach ($aSugFix as $sClass => $aTarget)
  2254. {
  2255. foreach ($aTarget as $aQueries)
  2256. {
  2257. foreach ($aQueries as $sQuery)
  2258. {
  2259. if (!empty($sQuery))
  2260. {
  2261. //$aSQL[] = $sQuery;
  2262. // forces a refresh of cached information
  2263. CMDBSource::CreateTable($sQuery);
  2264. }
  2265. }
  2266. }
  2267. }
  2268. // does not work -how to have multiple statements in a single query?
  2269. // $sDoCreateAll = implode(" ; ", $aSQL);
  2270. }
  2271. protected static function DBCreateViews()
  2272. {
  2273. list($aErrors, $aSugFix) = self::DBCheckViews();
  2274. $aSQL = array();
  2275. foreach ($aSugFix as $sClass => $aTarget)
  2276. {
  2277. foreach ($aTarget as $aQueries)
  2278. {
  2279. foreach ($aQueries as $sQuery)
  2280. {
  2281. if (!empty($sQuery))
  2282. {
  2283. //$aSQL[] = $sQuery;
  2284. // forces a refresh of cached information
  2285. CMDBSource::CreateTable($sQuery);
  2286. }
  2287. }
  2288. }
  2289. }
  2290. }
  2291. public static function DBDump()
  2292. {
  2293. $aDataDump = array();
  2294. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2295. {
  2296. $aRows = CMDBSource::DumpTable($sTable);
  2297. $aDataDump[$sTable] = $aRows;
  2298. }
  2299. return $aDataDump;
  2300. }
  2301. /*
  2302. * Determines wether the target DB is frozen or not
  2303. * 1 - consider the DB property 'status'
  2304. * 2 - check the setting 'database_read_only'
  2305. */
  2306. public static function DBIsReadOnly()
  2307. {
  2308. $sStatus = DBProperty::GetProperty('status', null);
  2309. if (!is_null($sStatus))
  2310. {
  2311. switch (strtolower(trim($sStatus)))
  2312. {
  2313. case 'fullaccess':
  2314. $ret = false;
  2315. break;
  2316. default:
  2317. $ret = true;
  2318. }
  2319. }
  2320. else
  2321. {
  2322. $ret = self::$m_oConfig->Get('database_read_only');
  2323. }
  2324. return $ret;
  2325. }
  2326. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  2327. {
  2328. $sValue = Dict::S($sKey, 'x-no-nothing');
  2329. if ($sValue == 'x-no-nothing')
  2330. {
  2331. $bNotInDico = true;
  2332. $sValue = $sValueFromOldSystem;
  2333. if (strlen($sValue) == 0)
  2334. {
  2335. $sValue = $sDefaultValue;
  2336. }
  2337. }
  2338. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  2339. }
  2340. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  2341. {
  2342. $sRes = '';
  2343. $sRes .= "// Dictionnay conventions\n";
  2344. $sRes .= htmlentities("// Class:<class_name>\n");
  2345. $sRes .= htmlentities("// Class:<class_name>+\n");
  2346. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n");
  2347. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n");
  2348. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n");
  2349. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n");
  2350. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n");
  2351. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n");
  2352. $sRes .= "\n";
  2353. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  2354. // Need to invent the "module", to characterize the origins of a class
  2355. if (strlen($sModules) == 0)
  2356. {
  2357. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  2358. }
  2359. else
  2360. {
  2361. $aModules = explode(', ', $sModules);
  2362. }
  2363. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2364. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  2365. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2366. foreach ($aModules as $sCategory)
  2367. {
  2368. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2369. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  2370. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2371. $sRes .= "//\n";
  2372. $sRes .= "\n";
  2373. foreach (self::GetClasses($sCategory) as $sClass)
  2374. {
  2375. if (!self::HasTable($sClass)) continue;
  2376. $bNotInDico = false;
  2377. $sClassRes = "//\n";
  2378. $sClassRes .= "// Class: $sClass\n";
  2379. $sClassRes .= "//\n";
  2380. $sClassRes .= "\n";
  2381. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  2382. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  2383. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  2384. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2385. {
  2386. // Skip this attribute if not originaly defined in this class
  2387. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2388. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  2389. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  2390. if ($oAttDef instanceof AttributeEnum)
  2391. {
  2392. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  2393. {
  2394. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  2395. {
  2396. if (array_key_exists('label', $aStateData))
  2397. {
  2398. $sValue = $aStateData['label'];
  2399. }
  2400. else
  2401. {
  2402. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  2403. }
  2404. if (array_key_exists('description', $aStateData))
  2405. {
  2406. $sValuePlus = $aStateData['description'];
  2407. }
  2408. else
  2409. {
  2410. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  2411. }
  2412. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  2413. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  2414. }
  2415. }
  2416. else
  2417. {
  2418. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  2419. {
  2420. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  2421. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  2422. }
  2423. }
  2424. }
  2425. }
  2426. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  2427. {
  2428. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  2429. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  2430. }
  2431. $sClassRes .= "));\n";
  2432. $sClassRes .= "\n";
  2433. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  2434. {
  2435. $sRes .= $sClassRes;
  2436. }
  2437. }
  2438. }
  2439. return $sRes;
  2440. }
  2441. public static function DBCheckFormat()
  2442. {
  2443. $aErrors = array();
  2444. $aSugFix = array();
  2445. foreach (self::GetClasses() as $sClass)
  2446. {
  2447. if (!self::HasTable($sClass)) continue;
  2448. // Check that the table exists
  2449. //
  2450. $sTable = self::DBGetTable($sClass);
  2451. $sKeyField = self::DBGetKey($sClass);
  2452. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  2453. if (!CMDBSource::IsTable($sTable))
  2454. {
  2455. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  2456. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  2457. }
  2458. // Check that the key field exists
  2459. //
  2460. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  2461. {
  2462. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  2463. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  2464. }
  2465. else
  2466. {
  2467. // Check the key field properties
  2468. //
  2469. if (!CMDBSource::IsKey($sTable, $sKeyField))
  2470. {
  2471. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  2472. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  2473. }
  2474. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  2475. {
  2476. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  2477. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  2478. }
  2479. }
  2480. // Check that any defined field exists
  2481. //
  2482. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  2483. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2484. {
  2485. // Skip this attribute if not originaly defined in this class
  2486. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2487. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  2488. {
  2489. $bIndexNeeded = $oAttDef->RequiresIndex();
  2490. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  2491. if (!CMDBSource::IsField($sTable, $sField))
  2492. {
  2493. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  2494. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  2495. if ($bIndexNeeded)
  2496. {
  2497. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2498. }
  2499. }
  2500. else
  2501. {
  2502. // The field already exists, does it have the relevant properties?
  2503. //
  2504. $bToBeChanged = false;
  2505. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  2506. {
  2507. $bToBeChanged = true;
  2508. if ($oAttDef->IsNullAllowed())
  2509. {
  2510. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  2511. }
  2512. else
  2513. {
  2514. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  2515. }
  2516. }
  2517. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  2518. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  2519. {
  2520. $bToBeChanged = true;
  2521. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  2522. }
  2523. if ($bToBeChanged)
  2524. {
  2525. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  2526. }
  2527. // Create indexes (external keys only... so far)
  2528. //
  2529. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField))
  2530. {
  2531. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  2532. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2533. }
  2534. }
  2535. }
  2536. }
  2537. }
  2538. return array($aErrors, $aSugFix);
  2539. }
  2540. public static function DBCheckViews()
  2541. {
  2542. $aErrors = array();
  2543. $aSugFix = array();
  2544. // Reporting views (must be created after any other table)
  2545. //
  2546. foreach (self::GetClasses('bizmodel') as $sClass)
  2547. {
  2548. $sView = self::DBGetView($sClass);
  2549. if (CMDBSource::IsTable($sView))
  2550. {
  2551. // Check that the view is complete
  2552. //
  2553. $bIsComplete = true;
  2554. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2555. {
  2556. foreach($oAttDef->GetSQLExpressions() as $sSuffix => $sTrash)
  2557. {
  2558. $sCol = $sAttCode.$sSuffix;
  2559. if (!CMDBSource::IsField($sView, $sCol))
  2560. {
  2561. $bIsComplete = false;
  2562. $aErrors[$sClass][$sAttCode][] = "field '$sCol' could not be found in view '$sView'";
  2563. $aSugFix[$sClass][$sAttCode][] = "";
  2564. }
  2565. }
  2566. }
  2567. if (!$bIsComplete)
  2568. {
  2569. // Rework the view
  2570. //
  2571. $oFilter = new DBObjectSearch($sClass, '');
  2572. $oFilter->AllowAllData();
  2573. $sSQL = self::MakeSelectQuery($oFilter);
  2574. $aErrors[$sClass]['*'][] = "View '$sView' is currently not complete";
  2575. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  2576. }
  2577. }
  2578. else
  2579. {
  2580. // Create the view
  2581. //
  2582. $oFilter = new DBObjectSearch($sClass, '');
  2583. $oFilter->AllowAllData();
  2584. $sSQL = self::MakeSelectQuery($oFilter);
  2585. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  2586. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  2587. }
  2588. }
  2589. return array($aErrors, $aSugFix);
  2590. }
  2591. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  2592. {
  2593. $sRootClass = self::GetRootClass($sClass);
  2594. $sTable = self::DBGetTable($sClass);
  2595. $sKeyField = self::DBGetKey($sClass);
  2596. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2597. {
  2598. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2599. }
  2600. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2601. if (count($aWrongRecords) == 0) return;
  2602. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2603. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2604. foreach ($aWrongRecords as $iRecordId)
  2605. {
  2606. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2607. {
  2608. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2609. {
  2610. case 'Delete':
  2611. // Already planned for a deletion
  2612. // Let's concatenate the errors description together
  2613. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2614. break;
  2615. case 'Update':
  2616. // Let's plan a deletion
  2617. break;
  2618. }
  2619. }
  2620. else
  2621. {
  2622. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2623. }
  2624. if (!$bProcessingFriends)
  2625. {
  2626. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  2627. {
  2628. // Something new to be deleted...
  2629. $iNewDelCount++;
  2630. }
  2631. }
  2632. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  2633. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  2634. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2635. $aPlannedDel[$sTable][] = $iRecordId;
  2636. }
  2637. // Now make sure that we would delete the records of the other tables for that class
  2638. //
  2639. if (!$bProcessingFriends)
  2640. {
  2641. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  2642. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  2643. {
  2644. $sFriendTable = self::DBGetTable($sFriendClass);
  2645. $sFriendKey = self::DBGetKey($sFriendClass);
  2646. // skip the current table
  2647. if ($sFriendTable == $sTable) continue;
  2648. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  2649. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  2650. }
  2651. }
  2652. }
  2653. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2654. {
  2655. $sRootClass = self::GetRootClass($sClass);
  2656. $sTable = self::DBGetTable($sClass);
  2657. $sKeyField = self::DBGetKey($sClass);
  2658. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2659. {
  2660. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2661. }
  2662. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2663. if (count($aWrongRecords) == 0) return;
  2664. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2665. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2666. foreach ($aWrongRecords as $iRecordId)
  2667. {
  2668. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2669. {
  2670. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2671. {
  2672. case 'Delete':
  2673. // No need to update, the record will be deleted!
  2674. break;
  2675. case 'Update':
  2676. // Already planned for an update
  2677. // Add this new update spec to the list
  2678. $bFoundSameSpec = false;
  2679. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  2680. {
  2681. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  2682. {
  2683. $bFoundSameSpec = true;
  2684. }
  2685. }
  2686. if (!$bFoundSameSpec)
  2687. {
  2688. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2689. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2690. }
  2691. break;
  2692. }
  2693. }
  2694. else
  2695. {
  2696. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2697. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  2698. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2699. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2700. }
  2701. }
  2702. }
  2703. // returns the count of records found for deletion
  2704. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2705. {
  2706. foreach (self::GetClasses() as $sClass)
  2707. {
  2708. if (!self::HasTable($sClass)) continue;
  2709. $sRootClass = self::GetRootClass($sClass);
  2710. $sTable = self::DBGetTable($sClass);
  2711. $sKeyField = self::DBGetKey($sClass);
  2712. if (!self::IsStandaloneClass($sClass))
  2713. {
  2714. if (self::IsRootClass($sClass))
  2715. {
  2716. // Check that the final class field contains the name of a class which inherited from the current class
  2717. //
  2718. $sFinalClassField = self::DBGetClassField($sClass);
  2719. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2720. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  2721. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  2722. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2723. }
  2724. else
  2725. {
  2726. $sRootTable = self::DBGetTable($sRootClass);
  2727. $sRootKey = self::DBGetKey($sRootClass);
  2728. $sFinalClassField = self::DBGetClassField($sRootClass);
  2729. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2730. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2731. // Check that any record found here has its counterpart in the root table
  2732. // and which refers to a child class
  2733. //
  2734. $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";
  2735. 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);
  2736. // Check that any record found in the root table and referring to a child class
  2737. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2738. //
  2739. $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)";
  2740. 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);
  2741. }
  2742. }
  2743. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2744. {
  2745. // Skip this attribute if not defined in this table
  2746. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2747. if ($oAttDef->IsExternalKey())
  2748. {
  2749. // Check that any external field is pointing to an existing object
  2750. //
  2751. $sRemoteClass = $oAttDef->GetTargetClass();
  2752. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2753. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2754. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2755. $sExtKeyField = current($aCols); // get the first column for an external key
  2756. // Note: a class/table may have an external key on itself
  2757. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2758. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2759. if ($oAttDef->IsNullAllowed())
  2760. {
  2761. // Exclude the records pointing to 0/null from the errors
  2762. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2763. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2764. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2765. }
  2766. else
  2767. {
  2768. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2769. }
  2770. // Do almost the same, taking into account the records planned for deletion
  2771. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2772. {
  2773. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2774. // but in that case you won't be able to track the root cause (cascading)
  2775. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2776. if ($oAttDef->IsNullAllowed())
  2777. {
  2778. // Exclude the records pointing to 0/null from the errors
  2779. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2780. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2781. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2782. }
  2783. else
  2784. {
  2785. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2786. }
  2787. }
  2788. }
  2789. else if ($oAttDef->IsDirectField())
  2790. {
  2791. // Check that the values fit the allowed values
  2792. //
  2793. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2794. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2795. {
  2796. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2797. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2798. $sMyAttributeField = current($aCols); // get the first column for the moment
  2799. $sDefaultValue = $oAttDef->GetDefaultValue();
  2800. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2801. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2802. }
  2803. }
  2804. }
  2805. }
  2806. }
  2807. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2808. {
  2809. // Records in error, and action to be taken: delete or update
  2810. // by RootClass/Table/Record
  2811. $aErrorsAndFixes = array();
  2812. // Records to be ignored in the current/next pass
  2813. // by Table = array of RecordId
  2814. $aPlannedDel = array();
  2815. // Count of errors in the next pass: no error means that we can leave...
  2816. $iErrorCount = 0;
  2817. // Limit in case of a bug in the algorythm
  2818. $iLoopCount = 0;
  2819. $iNewDelCount = 1; // startup...
  2820. while ($iNewDelCount > 0)
  2821. {
  2822. $iNewDelCount = 0;
  2823. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2824. $iErrorCount += $iNewDelCount;
  2825. // Safety net #1 - limit the planned deletions
  2826. //
  2827. $iMaxDel = 1000;
  2828. $iPlannedDel = 0;
  2829. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  2830. {
  2831. $iPlannedDel += count($aPlannedDelOnTable);
  2832. }
  2833. if ($iPlannedDel > $iMaxDel)
  2834. {
  2835. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  2836. break;
  2837. }
  2838. // Safety net #2 - limit the iterations
  2839. //
  2840. $iLoopCount++;
  2841. $iMaxLoops = 10;
  2842. if ($iLoopCount > $iMaxLoops)
  2843. {
  2844. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  2845. break;
  2846. }
  2847. }
  2848. // Display the results
  2849. //
  2850. $iIssueCount = 0;
  2851. $aFixesDelete = array();
  2852. $aFixesUpdate = array();
  2853. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  2854. {
  2855. foreach ($aTables as $sTable => $aRecords)
  2856. {
  2857. foreach ($aRecords as $iRecord => $aError)
  2858. {
  2859. $sAction = $aError['Action'];
  2860. $sReason = $aError['Reason'];
  2861. $iPass = $aError['Pass'];
  2862. switch ($sAction)
  2863. {
  2864. case 'Delete':
  2865. $sActionDetails = "";
  2866. $aFixesDelete[$sTable][] = $iRecord;
  2867. break;
  2868. case 'Update':
  2869. $aUpdateDesc = array();
  2870. foreach($aError['Action_Details'] as $aUpdateSpec)
  2871. {
  2872. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  2873. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  2874. }
  2875. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  2876. break;
  2877. default:
  2878. $sActionDetails = "bug: unknown action '$sAction'";
  2879. }
  2880. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  2881. $iIssueCount++;
  2882. }
  2883. }
  2884. }
  2885. if ($iIssueCount > 0)
  2886. {
  2887. // Build the queries to fix in the database
  2888. //
  2889. // First step, be able to get class data out of the table name
  2890. // Could be optimized, because we've made the job earlier... but few benefits, so...
  2891. $aTable2ClassProp = array();
  2892. foreach (self::GetClasses() as $sClass)
  2893. {
  2894. if (!self::HasTable($sClass)) continue;
  2895. $sRootClass = self::GetRootClass($sClass);
  2896. $sTable = self::DBGetTable($sClass);
  2897. $sKeyField = self::DBGetKey($sClass);
  2898. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2899. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  2900. }
  2901. // Second step, build a flat list of SQL queries
  2902. $aSQLFixes = array();
  2903. $iPlannedUpdate = 0;
  2904. foreach ($aFixesUpdate as $sTable => $aColumns)
  2905. {
  2906. foreach ($aColumns as $sColumn => $aNewValues)
  2907. {
  2908. foreach ($aNewValues as $sNewValue => $aRecords)
  2909. {
  2910. $iPlannedUpdate += count($aRecords);
  2911. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2912. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2913. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  2914. }
  2915. }
  2916. }
  2917. $iPlannedDel = 0;
  2918. foreach ($aFixesDelete as $sTable => $aRecords)
  2919. {
  2920. $iPlannedDel += count($aRecords);
  2921. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2922. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2923. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  2924. }
  2925. // Report the results
  2926. //
  2927. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2928. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  2929. // #@# later -> this is the responsibility of the caller to format the output
  2930. echo "<ul class=\"treeview\">\n";
  2931. foreach ($aIssues as $sIssueDesc)
  2932. {
  2933. echo "<li>$sIssueDesc</li>\n";
  2934. }
  2935. echo "</ul>\n";
  2936. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  2937. echo "<p>Aborting...</p>\n";
  2938. echo "</div>\n";
  2939. exit;
  2940. }
  2941. }
  2942. public static function Startup($sConfigFile, $bModelOnly = false)
  2943. {
  2944. self::LoadConfig($sConfigFile);
  2945. if ($bModelOnly) return;
  2946. CMDBSource::SelectDB(self::$m_sDBName);
  2947. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  2948. self::InitPlugins();
  2949. if (false)
  2950. {
  2951. echo "Debug<br/>\n";
  2952. self::static_var_dump();
  2953. }
  2954. }
  2955. public static function LoadConfig($sConfigFile)
  2956. {
  2957. self::$m_oConfig = new Config($sConfigFile);
  2958. // Set log ASAP
  2959. if (self::$m_oConfig->GetLogGlobal())
  2960. {
  2961. if (self::$m_oConfig->GetLogIssue())
  2962. {
  2963. self::$m_bLogIssue = true;
  2964. IssueLog::Enable(APPROOT.'/error.log');
  2965. }
  2966. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  2967. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  2968. }
  2969. else
  2970. {
  2971. self::$m_bLogIssue = false;
  2972. self::$m_bLogNotification = false;
  2973. self::$m_bLogWebService = false;
  2974. }
  2975. if (self::$m_oConfig->GetLogKPIDuration())
  2976. {
  2977. ExecutionKPI::EnableDuration();
  2978. }
  2979. if (self::$m_oConfig->GetLogKPIMemory())
  2980. {
  2981. ExecutionKPI::EnableMemory();
  2982. }
  2983. self::$m_bTraceQueries = self::$m_oConfig->GetDebugQueries();
  2984. self::$m_bQueryCacheEnabled = self::$m_oConfig->GetQueryCacheEnabled();
  2985. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  2986. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  2987. // Note: load the dictionary as soon as possible, because it might be
  2988. // needed when some error occur
  2989. foreach (self::$m_oConfig->GetDictionaries() as $sModule => $sToInclude)
  2990. {
  2991. self::Plugin($sConfigFile, 'dictionaries', $sToInclude);
  2992. }
  2993. // Set the language... after the dictionaries have been loaded!
  2994. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  2995. // Romain: this is the only way I've found to cope with the fact that
  2996. // classes have to be derived from cmdbabstract (to be editable in the UI)
  2997. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  2998. foreach (self::$m_oConfig->GetAppModules() as $sModule => $sToInclude)
  2999. {
  3000. self::Plugin($sConfigFile, 'application', $sToInclude);
  3001. }
  3002. foreach (self::$m_oConfig->GetDataModels() as $sModule => $sToInclude)
  3003. {
  3004. self::Plugin($sConfigFile, 'business', $sToInclude);
  3005. }
  3006. foreach (self::$m_oConfig->GetWebServiceCategories() as $sModule => $sToInclude)
  3007. {
  3008. self::Plugin($sConfigFile, 'webservice', $sToInclude);
  3009. }
  3010. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  3011. {
  3012. self::Plugin($sConfigFile, 'addons', $sToInclude);
  3013. }
  3014. $sServer = self::$m_oConfig->GetDBHost();
  3015. $sUser = self::$m_oConfig->GetDBUser();
  3016. $sPwd = self::$m_oConfig->GetDBPwd();
  3017. $sSource = self::$m_oConfig->GetDBName();
  3018. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  3019. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  3020. $sCollation = self::$m_oConfig->GetDBCollation();
  3021. $oKPI = new ExecutionKPI();
  3022. // The include have been included, let's browse the existing classes and
  3023. // develop some data based on the proposed model
  3024. self::InitClasses($sTablePrefix);
  3025. $oKPI->ComputeAndReport('Initialization of Data model structures');
  3026. self::$m_sDBName = $sSource;
  3027. self::$m_sTablePrefix = $sTablePrefix;
  3028. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  3029. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  3030. }
  3031. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  3032. {
  3033. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  3034. }
  3035. public static function GetConfig()
  3036. {
  3037. return self::$m_oConfig;
  3038. }
  3039. protected static $m_aPlugins = array();
  3040. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  3041. {
  3042. self::$m_aPlugins[$sName] = array(
  3043. 'type' => $sType,
  3044. 'init' => $aInitCallSpec,
  3045. );
  3046. }
  3047. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  3048. {
  3049. $sFirstChar = substr($sToInclude, 0, 1);
  3050. $sSecondChar = substr($sToInclude, 1, 1);
  3051. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  3052. {
  3053. // It is a relative path, prepend APPROOT
  3054. if (substr($sToInclude, 0, 3) == '../')
  3055. {
  3056. // Preserve compatibility with config files written before 1.0.1
  3057. // Replace '../' by '<root>/'
  3058. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  3059. }
  3060. else
  3061. {
  3062. $sFile = APPROOT.'/'.$sToInclude;
  3063. }
  3064. }
  3065. else
  3066. {
  3067. // Leave as is - should be an absolute path
  3068. $sFile = $sToInclude;
  3069. }
  3070. if (!file_exists($sFile))
  3071. {
  3072. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sFile));
  3073. }
  3074. require_once($sFile);
  3075. }
  3076. protected static function InitPlugins()
  3077. {
  3078. foreach(self::$m_aPlugins as $sName => $aData)
  3079. {
  3080. $aCallSpec = @$aData['init'];
  3081. if (count($aCallSpec) == 2)
  3082. {
  3083. if (!is_callable($aCallSpec))
  3084. {
  3085. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  3086. }
  3087. call_user_func($aCallSpec);
  3088. }
  3089. }
  3090. }
  3091. // Building an object
  3092. //
  3093. //
  3094. private static $aQueryCacheGetObject = array();
  3095. private static $aQueryCacheGetObjectHits = array();
  3096. public static function GetQueryCacheStatus()
  3097. {
  3098. $aRes = array();
  3099. $iTotalHits = 0;
  3100. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  3101. {
  3102. $aRes[] = "$sClass: $iHits";
  3103. $iTotalHits += $iHits;
  3104. }
  3105. return $iTotalHits.' ('.implode(', ', $aRes).')';
  3106. }
  3107. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false)
  3108. {
  3109. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  3110. {
  3111. // NOTE: Quick and VERY dirty caching mechanism which relies on
  3112. // the fact that the string '987654321' will never appear in the
  3113. // standard query
  3114. // This will be replaced for sure with a prepared statement
  3115. // or a view... next optimization to come!
  3116. $oFilter = new DBObjectSearch($sClass);
  3117. $oFilter->AddCondition('id', 987654321, '=');
  3118. if ($bAllowAllData)
  3119. {
  3120. $oFilter->AllowAllData();
  3121. }
  3122. $sSQL = self::MakeSelectQuery($oFilter);
  3123. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  3124. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  3125. }
  3126. else
  3127. {
  3128. $sSQL = self::$aQueryCacheGetObject[$sClass];
  3129. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  3130. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  3131. }
  3132. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  3133. $res = CMDBSource::Query($sSQL);
  3134. $aRow = CMDBSource::FetchArray($res);
  3135. CMDBSource::FreeResult($res);
  3136. if ($bMustBeFound && empty($aRow))
  3137. {
  3138. throw new CoreException("No result for the single row query: '$sSQL'");
  3139. }
  3140. return $aRow;
  3141. }
  3142. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '')
  3143. {
  3144. self::_check_subclass($sClass);
  3145. if (strlen($sClassAlias) == 0)
  3146. {
  3147. $sClassAlias = $sClass;
  3148. }
  3149. // Compound objects: if available, get the final object class
  3150. //
  3151. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  3152. {
  3153. // Either this is a bug (forgot to specify a root class with a finalclass field
  3154. // Or this is the expected behavior, because the object is not made of several tables
  3155. }
  3156. elseif (empty($aRow[$sClassAlias."finalclass"]))
  3157. {
  3158. // The data is missing in the DB
  3159. // @#@ possible improvement: check that the class is valid !
  3160. $sRootClass = self::GetRootClass($sClass);
  3161. $sFinalClassField = self::DBGetClassField($sRootClass);
  3162. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  3163. }
  3164. else
  3165. {
  3166. // do the job for the real target class
  3167. $sClass = $aRow[$sClassAlias."finalclass"];
  3168. }
  3169. return new $sClass($aRow, $sClassAlias);
  3170. }
  3171. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false)
  3172. {
  3173. self::_check_subclass($sClass);
  3174. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData);
  3175. if (empty($aRow))
  3176. {
  3177. return null;
  3178. }
  3179. return self::GetObjectByRow($sClass, $aRow);
  3180. }
  3181. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  3182. {
  3183. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  3184. if ($bAllowAllData)
  3185. {
  3186. $oFilter->AllowAllData();
  3187. }
  3188. $oSet = new DBObjectSet($oFilter);
  3189. $oObject = $oSet->Fetch();
  3190. return $oObject;
  3191. }
  3192. public static function GetHyperLink($sTargetClass, $iKey)
  3193. {
  3194. if ($iKey < 0)
  3195. {
  3196. return "$sTargetClass: $iKey (invalid value)";
  3197. }
  3198. $oObj = self::GetObject($sTargetClass, $iKey, false);
  3199. if (is_null($oObj))
  3200. {
  3201. return "$sTargetClass: $iKey (not found)";
  3202. }
  3203. return $oObj->GetHyperLink();
  3204. }
  3205. public static function NewObject($sClass)
  3206. {
  3207. self::_check_subclass($sClass);
  3208. return new $sClass();
  3209. }
  3210. public static function GetNextKey($sClass)
  3211. {
  3212. $sRootClass = MetaModel::GetRootClass($sClass);
  3213. $sRootTable = MetaModel::DBGetTable($sRootClass);
  3214. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  3215. return $iNextKey;
  3216. }
  3217. public static function BulkDelete(DBObjectSearch $oFilter)
  3218. {
  3219. $sSQL = self::MakeDeleteQuery($oFilter);
  3220. if (!self::DBIsReadOnly())
  3221. {
  3222. CMDBSource::Query($sSQL);
  3223. }
  3224. }
  3225. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  3226. {
  3227. // $aValues is an array of $sAttCode => $value
  3228. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  3229. if (!self::DBIsReadOnly())
  3230. {
  3231. CMDBSource::Query($sSQL);
  3232. }
  3233. }
  3234. // Links
  3235. //
  3236. //
  3237. public static function EnumReferencedClasses($sClass)
  3238. {
  3239. self::_check_subclass($sClass);
  3240. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  3241. $aResult = array();
  3242. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  3243. {
  3244. if ($oAttDef->IsExternalKey())
  3245. {
  3246. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  3247. }
  3248. }
  3249. return $aResult;
  3250. }
  3251. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  3252. {
  3253. self::_check_subclass($sClass);
  3254. if ($bSkipLinkingClasses)
  3255. {
  3256. $aLinksClasses = self::EnumLinksClasses();
  3257. }
  3258. // 1-N links (referencing my class), array of sClass => array of sAttcode
  3259. $aResult = array();
  3260. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  3261. {
  3262. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  3263. $aExtKeys = array();
  3264. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  3265. {
  3266. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3267. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  3268. {
  3269. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  3270. // Ok, I want this one
  3271. $aExtKeys[$sAttCode] = $oAttDef;
  3272. }
  3273. }
  3274. if (count($aExtKeys) != 0)
  3275. {
  3276. $aResult[$sSomeClass] = $aExtKeys;
  3277. }
  3278. }
  3279. return $aResult;
  3280. }
  3281. public static function EnumLinksClasses()
  3282. {
  3283. // Returns a flat array of classes having at least two external keys
  3284. $aResult = array();
  3285. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  3286. {
  3287. $iExtKeyCount = 0;
  3288. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  3289. {
  3290. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3291. if ($oAttDef->IsExternalKey())
  3292. {
  3293. $iExtKeyCount++;
  3294. }
  3295. }
  3296. if ($iExtKeyCount >= 2)
  3297. {
  3298. $aResult[] = $sSomeClass;
  3299. }
  3300. }
  3301. return $aResult;
  3302. }
  3303. public static function EnumLinkingClasses($sClass = "")
  3304. {
  3305. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  3306. $aResult = array();
  3307. foreach (self::EnumLinksClasses() as $sSomeClass)
  3308. {
  3309. $aTargets = array();
  3310. $bFoundClass = false;
  3311. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  3312. {
  3313. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3314. if ($oAttDef->IsExternalKey())
  3315. {
  3316. $sRemoteClass = $oAttDef->GetTargetClass();
  3317. if (empty($sClass))
  3318. {
  3319. $aTargets[$sAttCode] = $sRemoteClass;
  3320. }
  3321. elseif ($sClass == $sRemoteClass)
  3322. {
  3323. $bFoundClass = true;
  3324. }
  3325. else
  3326. {
  3327. $aTargets[$sAttCode] = $sRemoteClass;
  3328. }
  3329. }
  3330. }
  3331. if (empty($sClass) || $bFoundClass)
  3332. {
  3333. $aResult[$sSomeClass] = $aTargets;
  3334. }
  3335. }
  3336. return $aResult;
  3337. }
  3338. public static function GetLinkLabel($sLinkClass, $sAttCode)
  3339. {
  3340. self::_check_subclass($sLinkClass);
  3341. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  3342. return self::GetLabel($sLinkClass, $sAttCode);
  3343. }
  3344. /**
  3345. * Replaces all the parameters by the values passed in the hash array
  3346. */
  3347. static public function ApplyParams($aInput, $aParams)
  3348. {
  3349. $aSearches = array();
  3350. $aReplacements = array();
  3351. foreach($aParams as $sSearch => $replace)
  3352. {
  3353. // Some environment parameters are objects, we just need scalars
  3354. if (is_object($replace)) continue;
  3355. $aSearches[] = '$'.$sSearch.'$';
  3356. $aReplacements[] = (string) $replace;
  3357. }
  3358. return str_replace($aSearches, $aReplacements, $aInput);
  3359. }
  3360. } // class MetaModel
  3361. // Standard attribute lists
  3362. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  3363. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  3364. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  3365. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  3366. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  3367. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  3368. ?>