synchrodatasource.class.inc.php 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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. * Data Exchange - synchronization with external applications (incoming data)
  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. class SynchroExceptionNotStarted extends CoreException
  25. {
  26. }
  27. class SynchroDataSource extends cmdbAbstractObject
  28. {
  29. public static function Init()
  30. {
  31. $aParams = array
  32. (
  33. "category" => "core/cmdb,view_in_gui",
  34. "key_type" => "autoincrement",
  35. "name_attcode" => array('name'),
  36. "state_attcode" => "",
  37. "reconc_keys" => array(),
  38. "db_table" => "priv_sync_datasource",
  39. "db_key_field" => "id",
  40. "db_finalclass_field" => "realclass",
  41. "display_template" => "",
  42. "icon" => "../images/synchro.png",
  43. );
  44. MetaModel::Init_Params($aParams);
  45. //MetaModel::Init_InheritAttributes();
  46. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  47. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  48. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('implementation,production,obsolete'), "sql"=>"status", "default_value"=>"implementation", "is_null_allowed"=>false, "depends_on"=>array())));
  49. MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", array("targetclass"=>"User", "jointype"=>null, "allowed_values"=>null, "sql"=>"user_id", "is_null_allowed"=>true, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  50. MetaModel::Init_AddAttribute(new AttributeClass("scope_class", array("class_category"=>"bizmodel,addon/authentication", "more_values"=>"", "sql"=>"scope_class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  51. // Declared here for a future usage, but ignored so far
  52. MetaModel::Init_AddAttribute(new AttributeString("scope_restriction", array("allowed_values"=>null, "sql"=>"scope_restriction", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  53. //MetaModel::Init_AddAttribute(new AttributeDateTime("last_synchro_date", array("allowed_values"=>null, "sql"=>"last_synchro_date", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  54. // Format: seconds (int)
  55. MetaModel::Init_AddAttribute(new AttributeDuration("full_load_periodicity", array("allowed_values"=>null, "sql"=>"full_load_periodicity", "default_value"=>86400, "is_null_allowed"=>true, "depends_on"=>array())));
  56. // MetaModel::Init_AddAttribute(new AttributeString("reconciliation_list", array("allowed_values"=>null, "sql"=>"reconciliation_list", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  57. MetaModel::Init_AddAttribute(new AttributeEnum("reconciliation_policy", array("allowed_values"=>new ValueSetEnum('use_primary_key,use_attributes'), "sql"=>"reconciliation_policy", "default_value"=>"use_attributes", "is_null_allowed"=>false, "depends_on"=>array())));
  58. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_zero", array("allowed_values"=>new ValueSetEnum('create,error'), "sql"=>"action_on_zero", "default_value"=>"create", "is_null_allowed"=>false, "depends_on"=>array())));
  59. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_one", array("allowed_values"=>new ValueSetEnum('update,error'), "sql"=>"action_on_one", "default_value"=>"update", "is_null_allowed"=>false, "depends_on"=>array())));
  60. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_multiple", array("allowed_values"=>new ValueSetEnum('take_first,create,error'), "sql"=>"action_on_multiple", "default_value"=>"error", "is_null_allowed"=>false, "depends_on"=>array())));
  61. MetaModel::Init_AddAttribute(new AttributeEnum("delete_policy", array("allowed_values"=>new ValueSetEnum('ignore,delete,update,update_then_delete'), "sql"=>"delete_policy", "default_value"=>"ignore", "is_null_allowed"=>false, "depends_on"=>array())));
  62. MetaModel::Init_AddAttribute(new AttributeString("delete_policy_update", array("allowed_values"=>null, "sql"=>"delete_policy_update", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  63. // Format: seconds (unsigned int)
  64. MetaModel::Init_AddAttribute(new AttributeDuration("delete_policy_retention", array("allowed_values"=>null, "sql"=>"delete_policy_retention", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  65. MetaModel::Init_AddAttribute(new AttributeLinkedSet("attribute_list", array("linked_class"=>"SynchroAttribute", "ext_key_to_me"=>"sync_source_id", "allowed_values"=>null, "count_min"=>0, "count_max"=>0, "depends_on"=>array())));
  66. // Not used yet !
  67. MetaModel::Init_AddAttribute(new AttributeEnum("user_delete_policy", array("allowed_values"=>new ValueSetEnum('everybody,administrators,nobody'), "sql"=>"user_delete_policy", "default_value"=>"nobody", "is_null_allowed"=>true, "depends_on"=>array())));
  68. MetaModel::Init_AddAttribute(new AttributeURL("url_icon", array("allowed_values"=>null, "sql"=>"url_icon", "default_value"=>null, "is_null_allowed"=>true, "target"=> '_top', "depends_on"=>array())));
  69. // The field below is not a real URL since it can contain placeholders like $replica->primary_key$ which are not syntactically allowed in a real URL
  70. MetaModel::Init_AddAttribute(new AttributeString("url_application", array("allowed_values"=>null, "sql"=>"url_application", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  71. // Display lists
  72. MetaModel::Init_SetZListItems('details', array(
  73. 'col:0'=> array(
  74. 'fieldset:SynchroDataSource:Description' => array('name','description','status','scope_class','user_id','url_icon','url_application')),
  75. 'col:1'=> array(
  76. 'fieldset:SynchroDataSource:Reconciliation' => array('reconciliation_policy','action_on_zero','action_on_one','action_on_multiple'),
  77. 'fieldset:SynchroDataSource:Deletion' => array('user_delete_policy','full_load_periodicity','delete_policy','delete_policy_update','delete_policy_retention'))
  78. )
  79. );
  80. MetaModel::Init_SetZListItems('list', array('scope_class', 'status', 'user_id', 'full_load_periodicity')); // Attributes to be displayed for a list
  81. // Search criteria
  82. MetaModel::Init_SetZListItems('standard_search', array('name', 'status', 'scope_class', 'user_id')); // Criteria of the std search form
  83. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  84. }
  85. public static $m_oCurrentTask = null;
  86. public static function GetCurrentTaskId()
  87. {
  88. if (is_object(self::$m_oCurrentTask))
  89. {
  90. return self::$m_oCurrentTask->GetKey();
  91. }
  92. else
  93. {
  94. return null;
  95. }
  96. }
  97. public function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  98. {
  99. if (!$this->IsNew())
  100. {
  101. $oPage->SetCurrentTab(Dict::S('Core:SynchroAttributes'));
  102. $oAttributeSet = $this->Get('attribute_list');
  103. $aAttributes = array();
  104. while($oAttribute = $oAttributeSet->Fetch())
  105. {
  106. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  107. }
  108. // Columns of the form
  109. $aAttribs = array();
  110. foreach(array('attcode', 'reconciliation', 'update', 'update_policy', 'reconciliation_attcode') as $s )
  111. {
  112. $aAttribs[$s] = array( 'label' => Dict::S("Core:SynchroAtt:$s"), "description" => Dict::S("Core:SynchroAtt:$s+"));
  113. }
  114. // Rows of the form
  115. $aValues = array();
  116. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  117. {
  118. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  119. {
  120. if (isset($aAttributes[$sAttCode]))
  121. {
  122. $oAttribute = $aAttributes[$sAttCode];
  123. }
  124. else
  125. {
  126. if ($oAttDef->IsExternalKey())
  127. {
  128. $oAttribute = new SynchroAttExtKey();
  129. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  130. }
  131. else
  132. {
  133. $oAttribute = new SynchroAttribute();
  134. }
  135. $oAttribute->Set('sync_source_id', $this->GetKey());
  136. $oAttribute->Set('attcode', $sAttCode);
  137. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  138. $oAttribute->Set('update', 1);
  139. $oAttribute->Set('update_policy', 'master_locked');
  140. }
  141. if (!$bEditMode)
  142. {
  143. // Read-only mode
  144. $aRow['reconciliation'] = $oAttribute->Get('reconcile') == 1 ? Dict::S('Core:SynchroReconcile:Yes') : Dict::S('Core:SynchroReconcile:No');
  145. $aRow['update'] = $oAttribute->Get('update') == 1 ? Dict::S('Core:SynchroUpdate:Yes') : Dict::S('Core:SynchroUpdate:No');
  146. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  147. $aRow['update_policy'] = $oAttribute->GetAsHTML('update_policy');
  148. if ($oAttDef->IsExternalKey())
  149. {
  150. $aRow['reconciliation_attcode'] = $oAttribute->GetAsHTML('reconciliation_attcode');
  151. }
  152. else
  153. {
  154. $aRow['reconciliation_attcode'] = '&nbsp;';
  155. }
  156. }
  157. else
  158. {
  159. // Edit mode
  160. $sAttCode = $oAttribute->Get('attcode');
  161. $sChecked = $oAttribute->Get('reconcile') == 1 ? 'checked' : '';
  162. $aRow['reconciliation'] = "<input type=\"checkbox\" name=\"reconciliation[$sAttCode]\" $sChecked/>";
  163. $sChecked = $oAttribute->Get('update') == 1 ? 'checked' : '';
  164. $aRow['update'] = "<input type=\"checkbox\" name=\"update[$sAttCode]\" $sChecked/>";
  165. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  166. $oUpdateAttDef = MetaModel::GetAttributeDef(get_class($oAttribute), 'update_policy');
  167. $aRow['update_policy'] = cmdbAbstractObject::GetFormElementForField($oPage, get_class($oAttribute), 'update_policy', $oUpdateAttDef, $oAttribute->Get('update_policy'), '', 'update_policy_'.$sAttCode, "[$sAttCode]");
  168. if ($oAttDef->IsExternalKey())
  169. {
  170. $aRow['reconciliation_attcode'] = $oAttribute->GetReconciliationFormElement($oAttDef->GetTargetClass(), "attr_reconciliation_attcode[$sAttCode]");
  171. }
  172. else
  173. {
  174. $aRow['reconciliation_attcode'] = '&nbsp;';
  175. }
  176. }
  177. $aValues[] = $aRow;
  178. }
  179. }
  180. $oPage->p(Dict::Format('Class:SynchroDataSource:DataTable', $this->GetDataTable()));
  181. $oPage->Table($aAttribs, $aValues);
  182. $this->DisplayStatusTab($oPage);
  183. }
  184. parent::DisplayBareRelations($oPage, $bEditMode);
  185. }
  186. /**
  187. * Displays the status (SynchroLog) of the datasource in a graphical manner
  188. * @param $oPage WebPage
  189. * @return void
  190. */
  191. protected function DisplayStatusTab(WebPage $oPage)
  192. {
  193. $oPage->SetCurrentTab(Dict::S('Core:SynchroStatus'));
  194. $sSelectSynchroLog = 'SELECT SynchroLog WHERE sync_source_id = :source_id';
  195. $oSetSynchroLog = new CMDBObjectSet(DBObjectSearch::FromOQL($sSelectSynchroLog), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()));
  196. if ($oSetSynchroLog->Count() > 0)
  197. {
  198. $oLastLog = $oSetSynchroLog->Fetch();
  199. $sStartDate = $oLastLog->Get('start_date');
  200. $oLastLog->Get('stats_nb_replica_seen');
  201. $iLastLog = 0;
  202. $iDSid = $this->GetKey();
  203. if ($oLastLog->Get('status') == 'running')
  204. {
  205. // Still running !
  206. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroRunningStartedOn_Date', $sStartDate).'</h2>');
  207. }
  208. else
  209. {
  210. $sEndDate = $oLastLog->Get('end_date');
  211. $iLastLog = $oLastLog->GetKey();
  212. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroEndedOn_Date', $sEndDate).'</h2>');
  213. }
  214. $oPage->add('<table class="synoptics"><tr><td style="color:#333;vertical-align:top">');
  215. // List all the log entries for the user to select
  216. $oPage->add('<h2 style="line-height:55px;">'.Dict::S('Core:Synchro:History').'</h2>');
  217. $oSetSynchroLog->Rewind();
  218. $oPage->add('<select size="25" onChange="UpdateSynoptics(this.value);">');
  219. $sSelected = ' selected'; // First log is selected by default
  220. $sScript = "var aSynchroLog = {\n";
  221. while($oLog = $oSetSynchroLog->Fetch())
  222. {
  223. $sLogTitle = Dict::Format('Core:SynchroLogTitle', $oLog->Get('status'), $oLog->Get('start_date'));
  224. $oPage->add('<option value="'.$oLog->GetKey().'"'.$sSelected.'>'.$sLogTitle.'</option>');
  225. $sSelected = ''; // only the first log is selected by default
  226. $aData = $this->ProcessLog($oLog);
  227. $sScript .= '"'.$oLog->GetKey().'": '.json_encode($aData).",\n";
  228. }
  229. $sScript .= "end: 'Done'";
  230. $sScript .= "};\n";
  231. $sScript .= <<<EOF
  232. var sLastLog = '$iLastLog';
  233. function UpdateSynoptics(id)
  234. {
  235. var aValues = aSynchroLog[id];
  236. for (var sKey in aValues)
  237. {
  238. $('#c_'+sKey).html(aValues[sKey]);
  239. var fOpacity = (aValues[sKey] == 0) ? 0.3 : 1;
  240. $('#'+sKey).fadeTo("slow", fOpacity);
  241. }
  242. //alert('id = '+id+', lastLog='+sLastLog+', id==sLastLog: '+(id==sLastLog)+' obj_updated_errors: '+aValues['obj_updated_errors']);
  243. if ( (id == sLastLog) && (aValues['obj_new_errors'] > 0) )
  244. {
  245. $('#new_errors_link').show();
  246. }
  247. else
  248. {
  249. $('#new_errors_link').hide();
  250. }
  251. if ( (id == sLastLog) && (aValues['obj_updated_errors'] > 0) )
  252. {
  253. $('#updated_errors_link').show();
  254. }
  255. else
  256. {
  257. $('#updated_errors_link').hide();
  258. }
  259. if ( (id == sLastLog) && (aValues['obj_disappeared_errors'] > 0) )
  260. {
  261. $('#disappeared_errors_link').show();
  262. }
  263. else
  264. {
  265. $('#disappeared_errors_link').hide();
  266. }
  267. }
  268. EOF
  269. ;
  270. $oPage->add_script($sScript);
  271. $oPage->add('</select>');
  272. $oPage->add('</td><td style="vertical-align:top;">');
  273. // Now build the big "synoptics" view
  274. $aData = $this->ProcessLog($oLastLog);
  275. $sNbReplica = $this->GetIcon()."&nbsp;".Dict::Format('Core:Synchro:Nb_Replica', "<span id=\"c_nb_replica_total\">{$aData['nb_replica_total']}</span>");
  276. $sNbObjects = MetaModel::GetClassIcon($this->GetTargetClass())."&nbsp;".Dict::Format('Core:Synchro:Nb_Class:Objects', $this->GetTargetClass(), "<span id=\"c_nb_obj_total\">{$aData['nb_obj_total']}</span>");
  277. $oPage->add(
  278. <<<EOF
  279. <table class="synoptics">
  280. <tr class="synoptics_header">
  281. <td>$sNbReplica</td><td>&nbsp;</td><td>$sNbObjects</td>
  282. </tr>
  283. <tr>
  284. EOF
  285. );
  286. $sBaseOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->GetKey()." AND status_last_error!=''";
  287. $oPage->add($this->HtmlBox('repl_ignored', $aData, '#999').'<td colspan="2">&nbsp;</td>');
  288. $oPage->add("</tr>\n<tr>");
  289. $oPage->add($this->HtmlBox('repl_disappeared', $aData, '#630', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_disappeared_no_action', $aData, '#333'));
  290. $oPage->add("</tr>\n<tr>");
  291. $oPage->add($this->HtmlBox('obj_deleted', $aData, '#000'));
  292. $oPage->add("</tr>\n<tr>");
  293. $oPage->add($this->HtmlBox('obj_obsoleted', $aData, '#630'));
  294. $oPage->add("</tr>\n<tr>");
  295. $sOQL = urlencode($sBaseOQL." AND status='obsolete'");
  296. $oPage->add($this->HtmlBox('obj_disappeared_errors', $aData, '#C00', '', " <a style=\"color:#fff\" href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\" id=\"disappeared_errors_link\">Show</a>"));
  297. $oPage->add("</tr>\n<tr>");
  298. $oPage->add($this->HtmlBox('repl_existing', $aData, '#093', 'rowspan="3"').'<td rowspan="3" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_unchanged', $aData, '#393'));
  299. $oPage->add("</tr>\n<tr>");
  300. $oPage->add($this->HtmlBox('obj_updated', $aData, '#3C3'));
  301. $oPage->add("</tr>\n<tr>");
  302. $sOQL = urlencode($sBaseOQL." AND status='modified'");
  303. $oPage->add($this->HtmlBox('obj_updated_errors', $aData, '#C00', '', " <a style=\"color:#fff\" href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\" id=\"updated_errors_link\">Show</a>"));
  304. $oPage->add("</tr>\n<tr>");
  305. $oPage->add($this->HtmlBox('repl_new', $aData, '#339', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_new_unchanged', $aData, '#393'));
  306. $oPage->add("</tr>\n<tr>");
  307. $oPage->add($this->HtmlBox('obj_new_updated', $aData, '#3C3'));
  308. $oPage->add("</tr>\n<tr>");
  309. $oPage->add($this->HtmlBox('obj_created', $aData, '#339'));
  310. $oPage->add("</tr>\n<tr>");
  311. $sOQL = urlencode($sBaseOQL." AND status='new'");
  312. $oPage->add($this->HtmlBox('obj_new_errors', $aData, '#C00', '', " <a style=\"color:#fff\" href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\" id=\"new_errors_link\">Show</a>"));
  313. $oPage->add("</tr>\n</table>\n");
  314. $oPage->add('</td></tr></table>');
  315. $oPage->add_ready_script("UpdateSynoptics('$iLastLog')");
  316. }
  317. else
  318. {
  319. $oPage->p('<h2>'.Dict::S('Core:Synchro:NeverRun').'</h2>');
  320. }
  321. }
  322. protected function HtmlBox($sId, $aData, $sColor, $sHTMLAttribs = '', $sErrorLink = '')
  323. {
  324. $iCount = $aData[$sId];
  325. $sCount = "<span id=\"c_{$sId}\">$iCount</span>";
  326. $sLabel = Dict::Format('Core:Synchro:label_'.$sId, $sCount);
  327. $sOpacity = ($iCount==0) ? "opacity:0.3;" : "";
  328. return "<td id=\"$sId\" style=\"background-color:$sColor;$sOpacity;\" {$sHTMLAttribs}>{$sLabel}{$sErrorLink}</td>";
  329. }
  330. protected function ProcessLog($oLastLog)
  331. {
  332. $aData = array(
  333. 'obj_deleted' => $oLastLog->Get('stats_nb_obj_deleted'),
  334. 'obj_obsoleted' => $oLastLog->Get('stats_nb_obj_obsoleted'),
  335. 'obj_disappeared_errors' => $oLastLog->Get('stats_nb_obj_obsoleted_errors') + $oLastLog->Get('stats_nb_obj_deleted_errors'),
  336. 'obj_disappeared_no_action' => $oLastLog->Get('stats_nb_replica_disappeared_no_action'),
  337. 'obj_updated' => $oLastLog->Get('stats_nb_obj_updated'),
  338. 'obj_updated_errors' => $oLastLog->Get('stats_nb_obj_updated_errors'),
  339. 'obj_new_updated' => $oLastLog->Get('stats_nb_obj_new_updated'),
  340. 'obj_new_unchanged' => $oLastLog->Get('stats_nb_obj_new_unchanged'),
  341. 'obj_created' => $oLastLog->Get('stats_nb_obj_created'),
  342. 'obj_created_errors' => $oLastLog->Get('stats_nb_obj_created_errors'),
  343. );
  344. $iReconciledErrors = $oLastLog->Get('stats_nb_replica_reconciled_errors');
  345. $iDisappeared = $aData['obj_disappeared_errors'] + $aData['obj_obsoleted'] + $aData['obj_deleted'] + $aData['obj_disappeared_no_action'];
  346. $aData['repl_disappeared'] = $iDisappeared;
  347. $iNewErrors = $aData['obj_created_errors'] + $oLastLog->Get('stats_nb_replica_reconciled_errors');
  348. $aData['obj_new_errors'] = $iNewErrors;
  349. $iNew = $aData['obj_created'] + $iNewErrors + $aData['obj_new_updated'] + $aData['obj_new_unchanged'];
  350. $aData['repl_new'] = $iNew;
  351. $iExisting = $oLastLog->Get('stats_nb_replica_seen') - $iNew;
  352. $aData['repl_existing'] = $iExisting;
  353. $aData['obj_unchanged'] = $iExisting - $aData['obj_updated'] - $aData['obj_updated_errors'];
  354. $iIgnored = $oLastLog->Get('stats_nb_replica_total') - $iNew - $iExisting - $iDisappeared;
  355. $aData['repl_ignored'] = $iIgnored;
  356. $aData['nb_obj_total'] = $iNew + $iExisting + $iDisappeared;
  357. $aData['nb_replica_total'] = $aData['nb_obj_total'] + $iIgnored;
  358. return $aData;
  359. }
  360. public function GetIcon($bImgTag = true, $sMoreStyles = '')
  361. {
  362. if ($this->Get('url_icon') == '') return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  363. if ($bImgTag)
  364. {
  365. return "<img src=\"".$this->Get('url_icon')."\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  366. }
  367. return $this->Get('url_icon');
  368. }
  369. /**
  370. * Get the actual hyperlink to the remote application for the given replica and dest object
  371. */
  372. public function GetApplicationUrl(DBObject $oDestObj, SynchroReplica $oReplica)
  373. {
  374. if ($this->Get('url_application') == '') return '';
  375. $aSearches = array();
  376. $aReplacements = array();
  377. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  378. {
  379. if ($oAttDef->IsScalar())
  380. {
  381. $aSearches[] = '$this->'.$sAttCode.'$';
  382. $aReplacements[] = $oDestObj->Get($sAttCode);
  383. }
  384. }
  385. $aData = $oReplica->LoadExtendedDataFromTable($this->GetDataTable());
  386. foreach($aData as $sColumn => $value)
  387. {
  388. $aSearches[] = '$replica->'.$sColumn.'$';
  389. $aReplacements[] = $value;
  390. }
  391. return str_replace($aSearches, $aReplacements, $this->Get('url_application'));
  392. }
  393. public function GetAttributeFlags($sAttCode, &$aReasons = array())
  394. {
  395. if (($sAttCode == 'scope_class') && (!$this->IsNew()))
  396. {
  397. return OPT_ATT_READONLY;
  398. }
  399. return parent::GetAttributeFlags($sAttCode, $aReasons);
  400. }
  401. public function UpdateObject($sFormPrefix = '')
  402. {
  403. parent::UpdateObject($sFormPrefix);
  404. // And now read the other post parameters...
  405. $oAttributeSet = $this->Get('attribute_list');
  406. $aAttributes = array();
  407. while($oAttribute = $oAttributeSet->Fetch())
  408. {
  409. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  410. }
  411. $aReconcile = utils::ReadPostedParam('reconciliation', array());
  412. $aUpdate = utils::ReadPostedParam('update', array());
  413. $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array());
  414. $aReconciliation = utils::ReadPostedParam('attr_reconciliation_attcode', array());
  415. // update_policy cannot be empty, so there is one entry per attribute, use this to iterate
  416. // through all the writable attributes
  417. foreach($aUpdatePolicy as $sAttCode => $sValue)
  418. {
  419. if(!isset($aAttributes[$sAttCode]))
  420. {
  421. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  422. if ($oAttDef->IsExternalKey())
  423. {
  424. $oAttribute = new SynchroAttExtKey();
  425. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  426. }
  427. else
  428. {
  429. $oAttribute = new SynchroAttribute();
  430. }
  431. $oAttribute->Set('sync_source_id', $this->GetKey());
  432. $oAttribute->Set('attcode', $sAttCode);
  433. }
  434. else
  435. {
  436. $oAttribute = $aAttributes[$sAttCode];
  437. }
  438. $bReconcile = 0;
  439. if (isset($aReconcile[$sAttCode]))
  440. {
  441. $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0;
  442. }
  443. $bUpdate = 0 ; // Default / initial value
  444. if (isset($aUpdate[$sAttCode]))
  445. {
  446. $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0;
  447. }
  448. $oAttribute->Set('reconcile', $bReconcile);
  449. $oAttribute->Set('update', $bUpdate);
  450. $oAttribute->Set('update_policy', $sValue);
  451. if ($oAttribute instanceof SynchroAttExtKey)
  452. {
  453. $oAttribute->Set('reconciliation_attcode', $aReconciliation[$sAttCode]);
  454. }
  455. $oAttributeSet->AddObject($oAttribute);
  456. }
  457. $this->Set('attribute_list', $oAttributeSet);
  458. }
  459. /*
  460. * Overload the standard behavior
  461. */
  462. public function ComputeValues()
  463. {
  464. parent::ComputeValues();
  465. if ($this->IsNew())
  466. {
  467. // When inserting a new datasource object, also create the SynchroAttribute objects
  468. // for each field of the target class
  469. // Create all the SynchroAttribute records
  470. $oAttributeSet = $this->Get('attribute_list');
  471. if ($oAttributeSet->Count() == 0)
  472. {
  473. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  474. {
  475. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  476. {
  477. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  478. if ($oAttDef->IsExternalKey())
  479. {
  480. $oAttribute = new SynchroAttExtKey();
  481. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  482. }
  483. else
  484. {
  485. $oAttribute = new SynchroAttribute();
  486. }
  487. $oAttribute->Set('sync_source_id', $this->GetKey());
  488. $oAttribute->Set('attcode', $sAttCode);
  489. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  490. $oAttribute->Set('update', 1);
  491. $oAttribute->Set('update_policy', 'master_locked');
  492. $oAttributeSet->AddObject($oAttribute);
  493. }
  494. }
  495. $this->Set('attribute_list', $oAttributeSet);
  496. }
  497. }
  498. }
  499. public function DoCheckToWrite()
  500. {
  501. parent::DoCheckToWrite();
  502. // Check that there is at least one reconciliation key defined
  503. if ($this->Get('reconciliation_policy') == 'use_attributes')
  504. {
  505. $oSet = $this->Get('attribute_list');
  506. $oSynchroAttributeList = $oSet->ToArray();
  507. $bReconciliationKey = false;
  508. foreach($oSynchroAttributeList as $oSynchroAttribute)
  509. {
  510. if ($oSynchroAttribute->Get('reconcile') == 1)
  511. {
  512. $bReconciliationKey = true; // At least one key is defined
  513. }
  514. }
  515. if (!$bReconciliationKey)
  516. {
  517. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:AtLeastOneReconciliationKeyMustBeSpecified');
  518. }
  519. }
  520. // If 'update_then_delete' is specified there must be a delete_retention_period
  521. if (($this->Get('delete_policy') == 'update_then_delete') && ($this->Get('delete_policy_retention') == 0))
  522. {
  523. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeleteRetentionDurationMustBeSpecified');
  524. }
  525. // If update is specified, then something to update must be defined
  526. if ((($this->Get('delete_policy') == 'update_then_delete') || ($this->Get('delete_policy') == 'update'))
  527. && ($this->Get('delete_policy_update') == ''))
  528. {
  529. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeletePolicyUpdateMustBeSpecified');
  530. }
  531. }
  532. public function GetTargetClass()
  533. {
  534. return $this->Get('scope_class');
  535. }
  536. public function GetDataTable()
  537. {
  538. $sName = strtolower($this->GetTargetClass());
  539. $sName = str_replace('\'"&@|\\/ ', '_', $sName); // Remove forbidden characters from the table name
  540. $sName .= '_'.$this->GetKey(); // Add a suffix for unicity
  541. $sTable = MetaModel::GetConfig()->GetDBSubName()."synchro_data_$sName"; // Add the prefix if any
  542. return $sTable;
  543. }
  544. /**
  545. * When the new datasource has been created, let's create the synchro_data table
  546. * that will hold the data records and the correspoding triggers which will maintain
  547. * both tables in sync
  548. */
  549. protected function AfterInsert()
  550. {
  551. parent::AfterInsert();
  552. $sTable = $this->GetDataTable();
  553. $aColumns = $this->GetSQLColumns();
  554. $aFieldDefs = array();
  555. // Allow '0', otherwise mysql will render an error when the id is not given
  556. // (the trigger is expected to set the value, but it is not executed soon enough)
  557. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  558. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  559. foreach($aColumns as $sColumn => $ColSpec)
  560. {
  561. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  562. }
  563. $aFieldDefs[] = "INDEX (id)";
  564. $aFieldDefs[] = "INDEX (primary_key)";
  565. $sFieldDefs = implode(', ', $aFieldDefs);
  566. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = innodb;";
  567. CMDBSource::Query($sCreateTable);
  568. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON $sTable";
  569. $sTriggerInsert .= " FOR EACH ROW";
  570. $sTriggerInsert .= " BEGIN";
  571. $sTriggerInsert .= " INSERT INTO priv_sync_replica (sync_source_id, status_last_seen, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  572. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  573. $sTriggerInsert .= " END;";
  574. CMDBSource::Query($sTriggerInsert);
  575. $aModified = array();
  576. foreach($aColumns as $sColumn => $ColSpec)
  577. {
  578. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  579. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  580. }
  581. $sIsModified = '('.implode(') OR (', $aModified).')';
  582. // Update the replica
  583. //
  584. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  585. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  586. // otherwise, the status is left as is
  587. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON $sTable";
  588. $sTriggerUpdate .= " FOR EACH ROW";
  589. $sTriggerUpdate .= " BEGIN";
  590. $sTriggerUpdate .= " IF @itopuser is null THEN";
  591. $sTriggerUpdate .= " UPDATE priv_sync_replica SET status_last_seen = NOW(), `status` = IF(`status` = 'obsolete', IF(`dest_id` IS NULL, 'new', 'modified'), IF(`status` IN ('synchronized') AND ($sIsModified), 'modified', `status`)) WHERE sync_source_id = {$this->GetKey()} AND id = OLD.id;";
  592. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  593. $sTriggerUpdate .= " END IF;";
  594. $sTriggerUpdate .= " END;";
  595. CMDBSource::Query($sTriggerUpdate);
  596. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON $sTable";
  597. $sTriggerInsert .= " FOR EACH ROW";
  598. $sTriggerInsert .= " BEGIN";
  599. $sTriggerInsert .= " DELETE FROM priv_sync_replica WHERE id = OLD.id;";
  600. $sTriggerInsert .= " END;";
  601. CMDBSource::Query($sTriggerInsert);
  602. }
  603. protected function AfterDelete()
  604. {
  605. parent::AfterDelete();
  606. $sTable = $this->GetDataTable();
  607. $sDropTable = "DROP TABLE `$sTable`";
  608. CMDBSource::Query($sDropTable);
  609. // TO DO - check that triggers get dropped with the table
  610. }
  611. /**
  612. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  613. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  614. * is used to determine which records are obsolete.
  615. * @param Hash $aTraces Debugs/Trace information, one or more entries per replica
  616. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  617. * @return void
  618. */
  619. public function Synchronize($oLastFullLoadStartDate = null)
  620. {
  621. // Create a change used for logging all the modifications/creations happening during the synchro
  622. $oMyChange = MetaModel::NewObject("CMDBChange");
  623. $oMyChange->Set("date", time());
  624. $sUserString = CMDBChange::GetCurrentUserName();
  625. $oMyChange->Set("userinfo", $sUserString.' '.Dict::S('Core:SyncDataExchangeComment'));
  626. $iChangeId = $oMyChange->DBInsert();
  627. // Start logging this execution (stats + protection against reentrance)
  628. //
  629. $oStatLog = new SynchroLog();
  630. $oStatLog->Set('sync_source_id', $this->GetKey());
  631. $oStatLog->Set('start_date', time());
  632. $oStatLog->Set('status', 'running');
  633. $oStatLog->Set('stats_nb_replica_seen', 0);
  634. $oStatLog->Set('stats_nb_replica_total', 0);
  635. $oStatLog->Set('stats_nb_obj_deleted', 0);
  636. $oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  637. $oStatLog->Set('stats_nb_obj_obsoleted', 0);
  638. $oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  639. $oStatLog->Set('stats_nb_obj_created', 0);
  640. $oStatLog->Set('stats_nb_obj_created_errors', 0);
  641. $oStatLog->Set('stats_nb_obj_updated', 0);
  642. $oStatLog->Set('stats_nb_obj_updated_errors', 0);
  643. // $oStatLog->Set('stats_nb_replica_reconciled', 0);
  644. $oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  645. $oStatLog->Set('stats_nb_replica_disappeared_no_action', 0);
  646. $oStatLog->Set('stats_nb_obj_new_updated', 0);
  647. $oStatLog->Set('stats_nb_obj_new_unchanged',0);
  648. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  649. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->GetKey()));
  650. $oStatLog->Set('stats_nb_replica_total', $oSetTotal->Count());
  651. $oStatLog->DBInsertTracked($oMyChange);
  652. self::$m_oCurrentTask = $this;
  653. try
  654. {
  655. $this->DoSynchronize($oLastFullLoadStartDate, $oMyChange, $oStatLog);
  656. $oStatLog->Set('end_date', time());
  657. $oStatLog->Set('status', 'completed');
  658. $oStatLog->DBUpdateTracked($oMyChange);
  659. }
  660. catch (SynchroExceptionNotStarted $e)
  661. {
  662. // Set information for reporting... but delete the object in DB
  663. $oStatLog->Set('end_date', time());
  664. $oStatLog->Set('status', 'error');
  665. $oStatLog->Set('last_error', $e->getMessage());
  666. $oStatLog->DBDeleteTracked($oMyChange);
  667. }
  668. catch (Exception $e)
  669. {
  670. $oStatLog->Set('end_date', time());
  671. $oStatLog->Set('status', 'error');
  672. $oStatLog->Set('last_error', $e->getMessage());
  673. $oStatLog->DBUpdateTracked($oMyChange);
  674. }
  675. self::$m_oCurrentTask = null;
  676. return $oStatLog;
  677. }
  678. protected function DoSynchronize($oLastFullLoadStartDate, $oMyChange, &$oStatLog)
  679. {
  680. if ($this->Get('status') == 'obsolete')
  681. {
  682. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
  683. }
  684. if (!UserRights::IsAdministrator() && $this->Get('user_id') != UserRights::GetUserId())
  685. {
  686. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
  687. }
  688. // Get the list of SQL columns
  689. $sClass = $this->GetTargetClass();
  690. $aAttCodesExpected = array();
  691. $aAttCodesToReconcile = array();
  692. $aAttCodesToUpdate = array();
  693. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
  694. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */);
  695. while ($oSyncAtt = $oSetAtt->Fetch())
  696. {
  697. if ($oSyncAtt->Get('update'))
  698. {
  699. $aAttCodesToUpdate[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  700. }
  701. if ($oSyncAtt->Get('reconcile'))
  702. {
  703. $aAttCodesToReconcile[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  704. }
  705. $aAttCodesExpected[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  706. }
  707. $aColumns = $this->GetSQLColumns(array_keys($aAttCodesExpected));
  708. $aExtDataFields = array_keys($aColumns);
  709. $aExtDataFields[] = 'primary_key';
  710. $aExtDataSpec = array(
  711. 'table' => $this->GetDataTable(),
  712. 'join_key' => 'id',
  713. 'fields' => $aExtDataFields
  714. );
  715. // Get the list of attributes, determine reconciliation keys and update targets
  716. //
  717. if ($this->Get('reconciliation_policy') == 'use_attributes')
  718. {
  719. $aReconciliationKeys = $aAttCodesToReconcile;
  720. }
  721. elseif ($this->Get('reconciliation_policy') == 'use_primary_key')
  722. {
  723. // Override the settings made at the attribute level !
  724. $aReconciliationKeys = array("primary_key" => null);
  725. }
  726. $oStatLog->AddTrace("Update of: {".implode(', ', array_keys($aAttCodesToUpdate))."}");
  727. $oStatLog->AddTrace("Reconciliation on: {".implode(', ', array_keys($aReconciliationKeys))."}");
  728. if (count($aAttCodesToUpdate) == 0)
  729. {
  730. $oStatLog->AddTrace("No attribute to update");
  731. throw new SynchroExceptionNotStarted('There is no attribute to update');
  732. }
  733. if (count($aReconciliationKeys) == 0)
  734. {
  735. $oStatLog->AddTrace("No attribute for reconciliation");
  736. throw new SynchroExceptionNotStarted('No attribute for reconciliation');
  737. }
  738. $aAttributes = array();
  739. foreach($aAttCodesToUpdate as $sAttCode => $oSyncAtt)
  740. {
  741. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  742. if ($oAttDef->IsWritable() && $oAttDef->IsScalar())
  743. {
  744. $aAttributes[$sAttCode] = $oSyncAtt;
  745. }
  746. }
  747. $sDeletePolicy = $this->Get('delete_policy');
  748. // Count the replicas
  749. $sSelectAll = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  750. $oSetAll = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAll), array() /* order by*/, array('source_id' => $this->GetKey()));
  751. $iCountAllReplicas = $oSetAll->Count();
  752. $oStatLog->Set('stats_nb_replica_total', $iCountAllReplicas);
  753. // Get all the replicas that were not seen in the last import and mark them as obsolete
  754. if ($oLastFullLoadStartDate == null)
  755. {
  756. // No previous import known, use the full_load_periodicity value... and the current date
  757. $oLastFullLoadStartDate = new DateTime(); // Now
  758. $iLoadPeriodicity = $this->Get('full_load_periodicity'); // Duration in seconds
  759. if ($iLoadPeriodicity > 0)
  760. {
  761. $sInterval = "-$iLoadPeriodicity seconds";
  762. $oLastFullLoadStartDate->Modify($sInterval);
  763. }
  764. }
  765. $sLimitDate = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  766. $oStatLog->AddTrace("Limit Date: $sLimitDate");
  767. $sSelectToObsolete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  768. $oSetToObsolete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  769. if (($iCountAllReplicas > 10) && ($iCountAllReplicas == $oSetToObsolete->Count()))
  770. {
  771. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncTooManyMissingReplicas'));
  772. }
  773. while($oReplica = $oSetToObsolete->Fetch())
  774. {
  775. switch ($sDeletePolicy)
  776. {
  777. case 'update':
  778. case 'update_then_delete':
  779. $oStatLog->AddTrace("Destination object to be updated", $oReplica);
  780. $aToUpdate = array();
  781. $aToUpdate = explode(';', $this->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  782. foreach($aToUpdate as $sUpdateSpec)
  783. {
  784. $aUpdateSpec = explode(':', $sUpdateSpec);
  785. if (count($aUpdateSpec) == 2)
  786. {
  787. $sAttCode = $aUpdateSpec[0];
  788. $sValue = $aUpdateSpec[1];
  789. $aToUpdate[$sAttCode] = $sValue;
  790. }
  791. }
  792. $oReplica->UpdateDestObject($aToUpdate, $oMyChange, $oStatLog);
  793. $oReplica->Set('status', 'obsolete');
  794. $oReplica->Set('info_last_synchro', date('Y-m-d H:i:s'));
  795. $oReplica->DBUpdateTracked($oMyChange);
  796. break;
  797. case 'delete':
  798. default:
  799. $oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  800. $oReplica->DeleteDestObject($oMyChange, $oStatLog);
  801. }
  802. }
  803. //Count "seen" objects
  804. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  805. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  806. $oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  807. // Get all the replicas that are 'new' or modified
  808. //
  809. $sSelectToSync = "SELECT SynchroReplica WHERE (status = 'new' OR status = 'modified') AND sync_source_id = :source_id";
  810. $oSetToSync = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, $aExtDataSpec, 0 /* limitCount */, 0 /* limitStart */);
  811. while($oReplica = $oSetToSync->Fetch())
  812. {
  813. $oReplica->Synchro($this, $aReconciliationKeys, $aAttributes, $oMyChange, $oStatLog);
  814. }
  815. // Get all the replicas that are to be deleted
  816. //
  817. if ($sDeletePolicy == 'update_then_delete')
  818. {
  819. $oDeletionDate = $oLastFullLoadStartDate;
  820. $iDeleteRetention = $this->Get('delete_policy_retention'); // Duration in seconds
  821. if ($iDeleteRetention > 0)
  822. {
  823. $sInterval = "-$iDeleteRetention seconds";
  824. $oDeletionDate->Modify($sInterval);
  825. }
  826. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  827. $oStatLog->AddTrace("Deletion date: $sDeletionDate");
  828. $sSelectToDelete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  829. $oSetToDelete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sDeletionDate));
  830. while($oReplica = $oSetToDelete->Fetch())
  831. {
  832. $oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  833. $oReplica->DeleteDestObject($oMyChange, $oStatLog);
  834. }
  835. }
  836. }
  837. /**
  838. * Get the list of SQL columns corresponding to a particular list of attribute codes
  839. * Defaults to the whole list of columns for the current class
  840. */
  841. public function GetSQLColumns($aAttributeCodes = null)
  842. {
  843. $aColumns = array();
  844. $sClass = $this->GetTargetClass();
  845. if (is_null($aAttributeCodes))
  846. {
  847. $aAttributeCodes = array();
  848. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  849. {
  850. if ($sAttCode == 'finalclass') continue;
  851. $aAttributeCodes[] = $sAttCode;
  852. }
  853. }
  854. foreach($aAttributeCodes as $sAttCode)
  855. {
  856. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  857. if ($oAttDef->IsExternalKey())
  858. {
  859. // The pkey might be used as well as any other key column
  860. $aColumns[$sAttCode] = 'VARCHAR (255)';
  861. }
  862. else
  863. {
  864. foreach($oAttDef->GetImportColumns() as $sField => $sDBFieldType)
  865. {
  866. $aColumns[$sField] = $sDBFieldType;
  867. }
  868. }
  869. }
  870. return $aColumns;
  871. }
  872. public function IsRunning()
  873. {
  874. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  875. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  876. if ($oSet->Count() < 1)
  877. {
  878. $bRet = false;
  879. }
  880. else
  881. {
  882. $bRet = true;
  883. }
  884. return $bRet;
  885. }
  886. public function GetLatestLog()
  887. {
  888. $oLog = null;
  889. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  890. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  891. if ($oSet->Count() >= 1)
  892. {
  893. $oLog = $oSet->Fetch();
  894. }
  895. return $oLog;
  896. }
  897. // TO DO: remove if still unused
  898. /**
  899. * Retrieve from the log, the date of the last completed import
  900. * @return DateTime
  901. */
  902. public function GetLastCompletedImportDate()
  903. {
  904. $date = null;
  905. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  906. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  907. if ($oSet->Count() >= 1)
  908. {
  909. $oLog = $oSet->Fetch();
  910. $date = $oLog->Get('end_date');
  911. }
  912. else
  913. {
  914. // TO DO: remove trace
  915. echo "<p>No completed log found</p>\n";
  916. }
  917. return $date;
  918. }
  919. }
  920. class SynchroAttribute extends cmdbAbstractObject
  921. {
  922. public static function Init()
  923. {
  924. $aParams = array
  925. (
  926. "category" => "core/cmdb,view_in_gui",
  927. "key_type" => "autoincrement",
  928. "name_attcode" => "",
  929. "state_attcode" => "",
  930. "reconc_keys" => array(),
  931. "db_table" => "priv_sync_att",
  932. "db_key_field" => "id",
  933. "db_finalclass_field" => "",
  934. "display_template" => "",
  935. );
  936. MetaModel::Init_Params($aParams);
  937. MetaModel::Init_InheritAttributes();
  938. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
  939. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  940. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  941. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  942. MetaModel::Init_AddAttribute(new AttributeEnum("update_policy", array("allowed_values"=>new ValueSetEnum('master_locked,master_unlocked,write_if_empty'), "sql"=>"update_policy", "default_value"=>"master_locked", "is_null_allowed"=>false, "depends_on"=>array())));
  943. // Display lists
  944. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  945. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  946. // Search criteria
  947. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  948. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  949. }
  950. }
  951. class SynchroAttExtKey extends SynchroAttribute
  952. {
  953. public static function Init()
  954. {
  955. $aParams = array
  956. (
  957. "category" => "core/cmdb,view_in_gui",
  958. "key_type" => "autoincrement",
  959. "name_attcode" => "",
  960. "state_attcode" => "",
  961. "reconc_keys" => array(),
  962. "db_table" => "priv_sync_att_extkey",
  963. "db_key_field" => "id",
  964. "db_finalclass_field" => "",
  965. "display_template" => "",
  966. );
  967. MetaModel::Init_Params($aParams);
  968. MetaModel::Init_InheritAttributes();
  969. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  970. // Display lists
  971. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  972. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  973. // Search criteria
  974. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  975. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  976. }
  977. public function GetReconciliationFormElement($sTargetClass, $sFieldName)
  978. {
  979. $sHtml = "<select name=\"$sFieldName\">\n";
  980. $sSelected = (''== $this->Get('reconciliation_attcode')) ? ' selected' : '';
  981. $sHtml .= "<option value=\"\" $sSelected>".Dict::S('Core:SynchroAttExtKey:ReconciliationById')."</option>\n";
  982. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  983. {
  984. if ($oAttDef->IsScalar())
  985. {
  986. $sSelected = ($sAttCode == $this->Get('reconciliation_attcode')) ? ' selected' : '';
  987. $sHtml .= "<option value=\"$sAttCode\" $sSelected>".MetaModel::GetLabel($sTargetClass, $sAttCode)."</option>\n";
  988. }
  989. }
  990. $sHtml .= "</select>\n";
  991. return $sHtml;
  992. }
  993. }
  994. class SynchroAttLinkSet extends SynchroAttribute
  995. {
  996. public static function Init()
  997. {
  998. $aParams = array
  999. (
  1000. "category" => "core/cmdb,view_in_gui",
  1001. "key_type" => "autoincrement",
  1002. "name_attcode" => "",
  1003. "state_attcode" => "",
  1004. "reconc_keys" => array(),
  1005. "db_table" => "priv_sync_att_linkset",
  1006. "db_key_field" => "id",
  1007. "db_finalclass_field" => "",
  1008. "display_template" => "",
  1009. );
  1010. MetaModel::Init_Params($aParams);
  1011. MetaModel::Init_InheritAttributes();
  1012. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  1013. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  1014. // Display lists
  1015. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'row_separator', 'attribute_separator')); // Attributes to be displayed for the complete details
  1016. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1017. // Search criteria
  1018. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1019. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1020. }
  1021. }
  1022. //class SynchroLog extends Event
  1023. class SynchroLog extends DBObject
  1024. {
  1025. public static function Init()
  1026. {
  1027. $aParams = array
  1028. (
  1029. "category" => "core/cmdb,view_in_gui",
  1030. "key_type" => "autoincrement",
  1031. "name_attcode" => "",
  1032. "state_attcode" => "",
  1033. "reconc_keys" => array(),
  1034. "db_table" => "priv_sync_log",
  1035. "db_key_field" => "id",
  1036. "db_finalclass_field" => "",
  1037. "display_template" => "",
  1038. );
  1039. MetaModel::Init_Params($aParams);
  1040. MetaModel::Init_InheritAttributes();
  1041. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1042. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
  1043. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1044. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1045. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('running,completed,error'), "sql"=>"status", "default_value"=>"running", "is_null_allowed"=>false, "depends_on"=>array())));
  1046. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_seen", array("allowed_values"=>null, "sql"=>"stats_nb_replica_seen", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1047. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_total", array("allowed_values"=>null, "sql"=>"stats_nb_replica_total", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1048. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_deleted", array("allowed_values"=>null, "sql"=>"stats_nb_obj_deleted", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1049. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_deleted_errors", array("allowed_values"=>null, "sql"=>"stats_deleted_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1050. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_obsoleted", array("allowed_values"=>null, "sql"=>"stats_nb_obj_obsoleted", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1051. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_obsoleted_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_obsoleted_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1052. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1053. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1054. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1055. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1056. // MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_reconciled", array("allowed_values"=>null, "sql"=>"stats_nb_replica_reconciled", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1057. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_reconciled_errors", array("allowed_values"=>null, "sql"=>"stats_nb_replica_reconciled_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1058. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_disappeared_no_action", array("allowed_values"=>null, "sql"=>"stats_nb_replica_disappeared_no_action", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1059. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_updated", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_updated", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1060. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_unchanged", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_unchanged", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1061. MetaModel::Init_AddAttribute(new AttributeString("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1062. MetaModel::Init_AddAttribute(new AttributeLongText("traces", array("allowed_values"=>null, "sql"=>"traces", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1063. // Display lists
  1064. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_total', 'stats_nb_replica_seen', 'stats_nb_obj_created', /*'stats_nb_replica_reconciled',*/ 'stats_nb_obj_updated', 'stats_nb_obj_obsoleted', 'stats_nb_obj_deleted',
  1065. 'stats_nb_obj_created_errors', 'stats_nb_replica_reconciled_errors', 'stats_nb_replica_disappeared_no_action', 'stats_nb_obj_updated_errors', 'stats_nb_obj_obsoleted_errors', 'stats_nb_obj_deleted_errors', 'stats_nb_obj_new_unchanged', 'stats_nb_obj_new_updated', 'traces')); // Attributes to be displayed for the complete details
  1066. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  1067. // Search criteria
  1068. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1069. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1070. }
  1071. /**
  1072. * Increments a statistics counter
  1073. */
  1074. function Inc($sCode)
  1075. {
  1076. $this->Set($sCode, 1+$this->Get($sCode));
  1077. }
  1078. /**
  1079. * Implement traces management
  1080. */
  1081. protected $m_aTraces = array();
  1082. public function AddTrace($sMsg, $oReplica = null)
  1083. {
  1084. if (MetaModel::GetConfig()->Get('synchro_trace') == 'none')
  1085. {
  1086. return;
  1087. }
  1088. if ($oReplica)
  1089. {
  1090. $sDestClass = $oReplica->Get('dest_class');
  1091. if (!empty($sDestClass))
  1092. {
  1093. $sPrefix = $oReplica->GetKey().','.$sDestClass.'::'.$oReplica->Get('dest_id').',';
  1094. }
  1095. else
  1096. {
  1097. $sPrefix = $oReplica->GetKey().',,';
  1098. }
  1099. }
  1100. else
  1101. {
  1102. $sPrefix = ',,';
  1103. }
  1104. $this->m_aTraces[] = $sPrefix.$sMsg;
  1105. }
  1106. public function GetTraces()
  1107. {
  1108. return $this->m_aTraces;
  1109. }
  1110. protected function TraceToText()
  1111. {
  1112. if (MetaModel::GetConfig()->Get('synchro_trace') != 'save')
  1113. {
  1114. // none, or display only
  1115. return;
  1116. }
  1117. $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'traces');
  1118. $iMaxSize = $oAttDef->GetMaxSize();
  1119. $sTrace = implode("\n", $this->m_aTraces);
  1120. if (strlen($sTrace) >= $iMaxSize)
  1121. {
  1122. $sTrace = substr($sTrace, 0, $iMaxSize - 255)."...\nTruncated (size: ".strlen($sTrace).')';
  1123. }
  1124. $this->Set('traces', $sTrace);
  1125. }
  1126. protected function OnInsert()
  1127. {
  1128. $this->TraceToText();
  1129. parent::OnInsert();
  1130. }
  1131. protected function OnUpdate()
  1132. {
  1133. $this->TraceToText();
  1134. parent::OnUpdate();
  1135. }
  1136. }
  1137. class SynchroReplica extends DBObject implements iDisplay
  1138. {
  1139. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  1140. public static function Init()
  1141. {
  1142. $aParams = array
  1143. (
  1144. "category" => "core/cmdb,view_in_gui",
  1145. "key_type" => "autoincrement",
  1146. "name_attcode" => "",
  1147. "state_attcode" => "",
  1148. "reconc_keys" => array(),
  1149. "db_table" => "priv_sync_replica",
  1150. "db_key_field" => "id",
  1151. "db_finalclass_field" => "",
  1152. "display_template" => "",
  1153. );
  1154. MetaModel::Init_Params($aParams);
  1155. MetaModel::Init_InheritAttributes();
  1156. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
  1157. MetaModel::Init_AddAttribute(new AttributeExternalField("base_class", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"scope_class")));
  1158. MetaModel::Init_AddAttribute(new AttributeInteger("dest_id", array("allowed_values"=>null, "sql"=>"dest_id", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1159. MetaModel::Init_AddAttribute(new AttributeClass("dest_class", array("class_category"=>"", "more_values"=>"", "sql"=>"dest_class", "default_value"=>'Organization', "is_null_allowed"=>true, "depends_on"=>array())));
  1160. MetaModel::Init_AddAttribute(new AttributeDateTime("status_last_seen", array("allowed_values"=>null, "sql"=>"status_last_seen", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  1161. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('new,synchronized,modified,orphan,obsolete'), "sql"=>"status", "default_value"=>"new", "is_null_allowed"=>false, "depends_on"=>array())));
  1162. MetaModel::Init_AddAttribute(new AttributeBoolean("status_dest_creator", array("allowed_values"=>null, "sql"=>"status_dest_creator", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1163. MetaModel::Init_AddAttribute(new AttributeString("status_last_error", array("allowed_values"=>null, "sql"=>"status_last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1164. MetaModel::Init_AddAttribute(new AttributeDateTime("info_creation_date", array("allowed_values"=>null, "sql"=>"info_creation_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1165. MetaModel::Init_AddAttribute(new AttributeDateTime("info_last_modified", array("allowed_values"=>null, "sql"=>"info_last_modified", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1166. // Display lists
  1167. MetaModel::Init_SetZListItems('details', array('' .
  1168. 'col:0'=> array(
  1169. 'fieldset:SynchroDataSource:Definition' => array('sync_source_id','dest_id','dest_class'),
  1170. 'fieldset:SynchroDataSource:Status' => array('status','status_last_seen','status_dest_creator','status_last_error'),
  1171. 'fieldset:SynchroDataSource:Information' => array('info_creation_date','info_last_modified'))
  1172. )
  1173. );
  1174. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error')); // Attributes to be displayed for a list
  1175. // Search criteria
  1176. MetaModel::Init_SetZListItems('standard_search', array('sync_source_id', 'status_last_seen', 'status', 'status_dest_creator', 'dest_class', 'dest_id', 'status_last_error')); // Criteria of the std search form
  1177. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1178. }
  1179. public function DBInsert()
  1180. {
  1181. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  1182. }
  1183. // Overload the deletion -> the replica has been created by the mean of a trigger,
  1184. // it will be deleted by the mean of a trigger too
  1185. public function DBDelete(&$oDeletionPlan = null)
  1186. {
  1187. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  1188. $sTable = $oDataSource->GetDataTable();
  1189. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  1190. CMDBSource::Query($sSQL);
  1191. $this->m_bIsInDB = false;
  1192. $this->m_iKey = null;
  1193. }
  1194. public function SetLastError($sMessage, $oException = null)
  1195. {
  1196. if ($oException)
  1197. {
  1198. $sText = $sMessage.$oException->getMessage();
  1199. }
  1200. else
  1201. {
  1202. $sText = $sMessage;
  1203. }
  1204. if (strlen($sText) > 255)
  1205. {
  1206. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  1207. }
  1208. $this->Set('status_last_error', $sText);
  1209. }
  1210. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog)
  1211. {
  1212. switch($this->Get('status'))
  1213. {
  1214. case 'new':
  1215. $this->Set('status_dest_creator', false);
  1216. // If needed, construct the query used for the reconciliation
  1217. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  1218. {
  1219. $aCriterias = array();
  1220. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1221. {
  1222. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  1223. }
  1224. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  1225. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  1226. }
  1227. // Get the criterias for the search
  1228. $aFilterValues = array();
  1229. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1230. {
  1231. $value = $this->GetValueFromExtData($sFilterCode, $oSyncAtt, $oStatLog);
  1232. if (!is_null($value))
  1233. {
  1234. $aFilterValues[$sFilterCode] = $value;
  1235. }
  1236. else
  1237. {
  1238. // Reconciliation could not be performed - log and EXIT
  1239. $oStatLog->AddTrace("Could not reconcile on null value: ".$sFilterCode, $this);
  1240. $this->SetLastError('Could not reconcile on null value: '.$sFilterCode);
  1241. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1242. return;
  1243. }
  1244. }
  1245. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  1246. $iCount = $oDestSet->Count();
  1247. $aConditions = array();
  1248. foreach($aFilterValues as $sCode => $sValue)
  1249. {
  1250. $aConditions[] = $sCode.'='.$sValue;
  1251. }
  1252. $sConditionDesc = implode(' AND ', $aConditions);
  1253. // How many objects match the reconciliation criterias
  1254. switch($iCount)
  1255. {
  1256. case 0:
  1257. $oStatLog->AddTrace("Nothing found on: $sConditionDesc", $this);
  1258. if ($oDataSource->Get('action_on_zero') == 'create')
  1259. {
  1260. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1261. }
  1262. else // assumed to be 'error'
  1263. {
  1264. $oStatLog->AddTrace("Failed to reconcile (no match)", $this);
  1265. $this->SetLastError('Could not find a match for reconciliation');
  1266. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1267. }
  1268. break;
  1269. case 1:
  1270. $oStatLog->AddTrace("Found 1 object on: $sConditionDesc", $this);
  1271. if ($oDataSource->Get('action_on_one') == 'update')
  1272. {
  1273. $oDestObj = $oDestSet->Fetch();
  1274. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1275. $this->Set('dest_id', $oDestObj->GetKey());
  1276. $this->Set('dest_class', get_class($oDestObj));
  1277. }
  1278. else
  1279. {
  1280. // assumed to be 'error'
  1281. $oStatLog->AddTrace("Failed to reconcile (1 match)", $this);
  1282. $this->SetLastError('Found a match while expecting several');
  1283. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1284. }
  1285. break;
  1286. default:
  1287. $oStatLog->AddTrace("Found $iCount objects on: $sConditionDesc", $this);
  1288. if ($oDataSource->Get('action_on_multiple') == 'error')
  1289. {
  1290. $oStatLog->AddTrace("Failed to reconcile (N>1 matches)", $this);
  1291. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  1292. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1293. }
  1294. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  1295. {
  1296. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1297. }
  1298. else
  1299. {
  1300. // assumed to be 'take_first'
  1301. $oDestObj = $oDestSet->Fetch();
  1302. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1303. $this->Set('dest_id', $oDestObj->GetKey());
  1304. $this->Set('dest_class', get_class($oDestObj));
  1305. }
  1306. }
  1307. break;
  1308. case 'modified':
  1309. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  1310. if ($oDestObj == null)
  1311. {
  1312. $this->Set('status', 'orphan'); // The destination object has been deleted !
  1313. $this->SetLastError('Destination object deleted unexpectedly');
  1314. $oStatLog->Inc('stats_nb_obj_updated_errors');
  1315. }
  1316. else
  1317. {
  1318. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj', 'stats_nb_obj_updated_errors');
  1319. }
  1320. break;
  1321. default: // Do nothing in all other cases
  1322. }
  1323. $this->DBUpdateTracked($oChange);
  1324. }
  1325. /**
  1326. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  1327. */
  1328. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, $sStatsCode, $sStatsCodeError)
  1329. {
  1330. $aValueTrace = array();
  1331. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1332. {
  1333. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1334. if (!is_null($value))
  1335. {
  1336. $oDestObj->Set($sAttCode, $value);
  1337. $aValueTrace[] = "$sAttCode: $value";
  1338. }
  1339. }
  1340. try
  1341. {
  1342. // Really modified ?
  1343. if ($oDestObj->IsModified())
  1344. {
  1345. $oDestObj->DBUpdateTracked($oChange);
  1346. $oStatLog->AddTrace('Updated object - Values: {'.implode(', ', $aValueTrace).'}', $this);
  1347. $oStatLog->Inc($sStatsCode.'_updated');
  1348. $this->Set('info_last_modified', date('Y-m-d H:i:s'));
  1349. }
  1350. else
  1351. {
  1352. $oStatLog->AddTrace('Unchanged object', $this);
  1353. $oStatLog->Inc($sStatsCode.'_unchanged');
  1354. }
  1355. $this->Set('status_last_error', '');
  1356. $this->Set('status', 'synchronized');
  1357. }
  1358. catch(Exception $e)
  1359. {
  1360. $oStatLog->AddTrace("Failed to update destination object: {$e->getMessage()}", $this);
  1361. $this->SetLastError('Unable to update destination object: ', $e);
  1362. $oStatLog->Inc($sStatsCodeError);
  1363. }
  1364. }
  1365. /**
  1366. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1367. */
  1368. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog)
  1369. {
  1370. $oDestObj = MetaModel::NewObject($sClass);
  1371. try
  1372. {
  1373. $aValueTrace = array();
  1374. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1375. {
  1376. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1377. if (!is_null($value))
  1378. {
  1379. $oDestObj->Set($sAttCode, $value);
  1380. $aValueTrace[] = "$sAttCode: $value";
  1381. }
  1382. }
  1383. $iNew = $oDestObj->DBInsertTracked($oChange);
  1384. $this->Set('dest_id', $oDestObj->GetKey());
  1385. $this->Set('dest_class', get_class($oDestObj));
  1386. $this->Set('status_dest_creator', true);
  1387. $this->Set('status_last_error', '');
  1388. $this->Set('status', 'synchronized');
  1389. $this->Set('info_creation_date', date('Y-m-d H:i:s'));
  1390. $oStatLog->AddTrace("Created (".implode(', ', $aValueTrace).")", $this);
  1391. $oStatLog->Inc('stats_nb_obj_created');
  1392. }
  1393. catch(Exception $e)
  1394. {
  1395. $oStatLog->AddTrace("Failed to create $sClass ({$e->getMessage()})", $this);
  1396. $this->SetLastError('Unable to create destination object: ', $e);
  1397. $oStatLog->Inc('stats_nb_obj_created_errors');
  1398. }
  1399. }
  1400. /**
  1401. * Update the destination object with given values
  1402. */
  1403. public function UpdateDestObject($aValues, $oChange, &$oStatLog)
  1404. {
  1405. try
  1406. {
  1407. if ($this->Get('dest_class') == '')
  1408. {
  1409. $this->SetLastError('No destination object to update');
  1410. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1411. }
  1412. else
  1413. {
  1414. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1415. foreach($aValues as $sAttCode => $value)
  1416. {
  1417. $oDestObj->Set($sAttCode, $value);
  1418. }
  1419. $this->Set('info_last_modified', date('Y-m-d H:i:s'));
  1420. $oDestObj->DBUpdateTracked($oChange);
  1421. $oStatLog->AddTrace("Replica marked as obsolete", $this);
  1422. $oStatLog->Inc('stats_nb_obj_obsoleted');
  1423. }
  1424. }
  1425. catch(Exception $e)
  1426. {
  1427. $this->SetLastError('Unable to update the destination object: ', $e);
  1428. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1429. }
  1430. }
  1431. /**
  1432. * Delete the destination object
  1433. */
  1434. public function DeleteDestObject($oChange, &$oStatLog)
  1435. {
  1436. if($this->Get('status_dest_creator'))
  1437. {
  1438. try
  1439. {
  1440. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1441. $oDestObj->DBDeleteTracked($oChange);
  1442. $this->DBDeleteTracked($oChange);
  1443. $oStatLog->Inc('stats_nb_obj_deleted');
  1444. }
  1445. catch(Exception $e)
  1446. {
  1447. $this->SetLastError('Unable to delete the destination object: ', $e);
  1448. $this->Set('status', 'obsolete');
  1449. $this->DBUpdateTracked($oChange);
  1450. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1451. }
  1452. }
  1453. else
  1454. {
  1455. $this->DBDeleteTracked($oChange);
  1456. $oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  1457. }
  1458. }
  1459. /**
  1460. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1461. */
  1462. protected function GetValueFromExtData($sAttCode, $oSyncAtt, &$oStatLog)
  1463. {
  1464. // $aData should contain attributes defined either for reconciliation or create/update
  1465. $aData = $this->GetExtendedData();
  1466. $sClass = $this->Get('base_class');
  1467. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1468. if (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttExtKey))
  1469. {
  1470. $rawValue = $aData[$sAttCode];
  1471. if (is_null($rawValue))
  1472. {
  1473. // Null means "ignore" this attribute
  1474. return null;
  1475. }
  1476. $sReconcAttCode = $oSyncAtt->Get('reconciliation_attcode');
  1477. if (!empty($sReconcAttCode))
  1478. {
  1479. $sRemoteClass = $oAttDef->GetTargetClass();
  1480. $oObj = MetaModel::GetObjectByColumn($sRemoteClass, $sReconcAttCode, $rawValue, false);
  1481. if ($oObj)
  1482. {
  1483. $retValue = $oObj->GetKey();
  1484. }
  1485. else
  1486. {
  1487. // Note: differs from null (in which case the value would be left unchanged)
  1488. $oStatLog->AddTrace("Could not find [unique] object for '$sAttCode': searched on $sReconcAttCode = '$rawValue'", $this);
  1489. $retValue = 0;
  1490. }
  1491. }
  1492. else
  1493. {
  1494. $retValue = $rawValue;
  1495. }
  1496. }
  1497. else
  1498. {
  1499. $aColumns = $oAttDef->GetImportColumns();
  1500. foreach($aColumns as $sColumn => $sFormat)
  1501. {
  1502. // In any case, a null column means "ignore this attribute"
  1503. //
  1504. if (is_null($aData[$sColumn]))
  1505. {
  1506. return null;
  1507. }
  1508. }
  1509. $retValue = $oAttDef->FromImportToValue($aData, $sAttCode);
  1510. }
  1511. return $retValue;
  1512. }
  1513. /**
  1514. * Maps the given context parameter name to the appropriate filter/search code for this class
  1515. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  1516. * @return string Filter code, i.e. 'customer_id'
  1517. */
  1518. public static function MapContextParam($sContextParam)
  1519. {
  1520. if ($sContextParam == 'menu')
  1521. {
  1522. return null;
  1523. }
  1524. else
  1525. {
  1526. return $sContextParam;
  1527. }
  1528. }
  1529. /**
  1530. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1531. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1532. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1533. * To Be overridden by derived classes
  1534. * @param void
  1535. * @return String The desired higlight class for the object/row
  1536. */
  1537. public function GetHilightClass()
  1538. {
  1539. // Possible return values are:
  1540. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1541. return HILIGHT_CLASS_NONE; // Not hilighted by default
  1542. }
  1543. public static function GetUIPage()
  1544. {
  1545. return '../synchro/replica.php';
  1546. }
  1547. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  1548. {
  1549. // Object's details
  1550. //$this->DisplayBareHeader($oPage, $bEditMode);
  1551. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  1552. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1553. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1554. $this->DisplayBareProperties($oPage, $bEditMode);
  1555. }
  1556. function DisplayBareProperties(WebPage $oPage, $bEditMode = false)
  1557. {
  1558. if ($bEditMode) return; // Not editable
  1559. $oPage->add('<table style="vertical-align:top"><tr style="vertical-align:top"><td>');
  1560. $aDetails = array();
  1561. $sClass = get_class($this);
  1562. $oPage->add('<fieldset>');
  1563. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PrivateDetails').'</legend>');
  1564. $aZList = MetaModel::FlattenZlist(MetaModel::GetZListItems($sClass, 'details'));
  1565. foreach( $aZList as $sAttCode)
  1566. {
  1567. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1568. $aDetails[] = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1569. }
  1570. $oPage->Details($aDetails);
  1571. $oPage->add('</fieldset>');
  1572. $oPage->add('</td><td>');
  1573. $oPage->add('<fieldset>');
  1574. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PublicData').'</legend>');
  1575. $oSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  1576. $sSQLTable = $oSource->GetDataTable();
  1577. $aData = $this->LoadExtendedDataFromTable($sSQLTable);
  1578. $aHeaders = array('attcode' => array('label' => 'Attribute Code', 'description' => ''),
  1579. 'data' => array('label' => 'Value', 'description' => ''));
  1580. $aRows = array();
  1581. foreach($aData as $sKey => $value)
  1582. {
  1583. $aRows[] = array('attcode' => $sKey, 'data' => $value);
  1584. }
  1585. $oPage->Table($aHeaders, $aRows);
  1586. $oPage->add('</fieldset>');
  1587. $oPage->add('</td></tr></table>');
  1588. }
  1589. public function LoadExtendedDataFromTable($sSQLTable)
  1590. {
  1591. $sSQL = "SELECT * FROM $sSQLTable WHERE id=".$this->GetKey();
  1592. $rQuery = CMDBSource::Query($sSQL);
  1593. return CMDBSource::FetchArray($rQuery);
  1594. }
  1595. }
  1596. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1597. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1598. // new OQLMenuNode('Replicas', 'SELECT SynchroReplica', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroReplica', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1599. // new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  1600. ?>