synchrodatasource.class.inc.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  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", "more_values"=>"", "sql"=>"scope_class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  51. MetaModel::Init_AddAttribute(new AttributeString("scope_restriction", array("allowed_values"=>null, "sql"=>"scope_restriction", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  52. //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())));
  53. // Format: '1 hour', '2 weeks', '3 hoursABCDEF'... Cf DateTime->Modify()
  54. MetaModel::Init_AddAttribute(new AttributeString("full_load_periodicity", array("allowed_values"=>null, "sql"=>"full_load_periodicity", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  55. // MetaModel::Init_AddAttribute(new AttributeString("reconciliation_list", array("allowed_values"=>null, "sql"=>"reconciliation_list", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  56. 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())));
  57. 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())));
  58. 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())));
  59. 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())));
  60. 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())));
  61. 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())));
  62. // Format: '1 hour', '2 weeks', '3 hoursABCDEF'... Cf DateTime->Modify()
  63. MetaModel::Init_AddAttribute(new AttributeString("delete_policy_retention", array("allowed_values"=>null, "sql"=>"delete_policy_retention", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  64. 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())));
  65. MetaModel::Init_AddAttribute(new AttributeLinkedSet("status_list", array("linked_class"=>"SynchroLog", "ext_key_to_me"=>"sync_source_id", "allowed_values"=>null, "count_min"=>0, "count_max"=>0, "depends_on"=>array())));
  66. // Display lists
  67. MetaModel::Init_SetZListItems('details', array('name', 'description', 'scope_class', 'scope_restriction', 'status', 'user_id', 'full_load_periodicity', 'reconciliation_policy', 'action_on_zero', 'action_on_one', 'action_on_multiple', 'delete_policy', 'delete_policy_update', 'delete_policy_retention' /*'attribute_list'*/, 'status_list')); // Attributes to be displayed for the complete details
  68. MetaModel::Init_SetZListItems('list', array('scope_class', 'status', 'user_id', 'full_load_periodicity')); // Attributes to be displayed for a list
  69. // Search criteria
  70. MetaModel::Init_SetZListItems('standard_search', array('name', 'status', 'scope_class', 'user_id')); // Criteria of the std search form
  71. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  72. }
  73. public function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  74. {
  75. if (!$this->IsNew())
  76. {
  77. $oPage->SetCurrentTab(Dict::S('Core:SynchroAttributes'));
  78. $oAttributeSet = $this->Get('attribute_list');
  79. $aAttributes = array();
  80. while($oAttribute = $oAttributeSet->Fetch())
  81. {
  82. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  83. }
  84. $aAttribs = array(
  85. 'attcode' => array('label'=>'Attribute', 'description' => 'Field of the object'),
  86. 'reconciliation' => array('label'=>'Reconciliation ?', 'description' => 'Used for searching'),
  87. 'update' => array('label'=>'Update ?', 'description' => 'Used to update the object'),
  88. 'update_policy' => array('label'=>'Update Policy', 'description' => 'Behavior of the updated field'),
  89. );
  90. $aValues = array();
  91. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  92. {
  93. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  94. {
  95. if (isset($aAttributes[$sAttCode]))
  96. {
  97. $oAttribute = $aAttributes[$sAttCode];
  98. }
  99. else
  100. {
  101. $oAttribute = new SynchroAttribute();
  102. $oAttribute->Set('sync_source_id', $this->GetKey());
  103. $oAttribute->Set('attcode', $sAttCode);
  104. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  105. $oAttribute->Set('update', 1);
  106. $oAttribute->Set('update_policy', 'master_locked');
  107. }
  108. if (!$bEditMode)
  109. {
  110. // Read-only mode
  111. $aRow['reconciliation'] = $oAttribute->Get('reconcile') == 1 ? Dict::S('Core:SynchroReconcile:Yes') : Dict::S('Core:SynchroReconcile:No');
  112. $aRow['update'] = $oAttribute->Get('update') == 1 ? Dict::S('Core:SynchroUpdate:Yes') : Dict::S('Core:SynchroUpdate:No');
  113. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  114. $aRow['update_policy'] = $oAttribute->GetAsHTML('update_policy');
  115. }
  116. else
  117. {
  118. // Read-only mode
  119. $sAttCode = $oAttribute->Get('attcode');
  120. $sChecked = $oAttribute->Get('reconcile') == 1 ? 'checked' : '';
  121. $aRow['reconciliation'] = "<input type=\"checkbox\" name=\"reconciliation[$sAttCode]\" $sChecked/>";
  122. $sChecked = $oAttribute->Get('update') == 1 ? 'checked' : '';
  123. $aRow['update'] = "<input type=\"checkbox\" name=\"update[$sAttCode]\" $sChecked/>";
  124. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  125. $oAttDef = MetaModel::GetAttributeDef(get_class($oAttribute), 'update_policy');
  126. $aRow['update_policy'] = cmdbAbstractObject::GetFormElementForField($oPage, get_class($oAttribute), 'update_policy', $oAttDef, $oAttribute->Get('update_policy'), '', 'update_policy_'.$sAttCode, "[$sAttCode]");
  127. }
  128. $aValues[] = $aRow;
  129. }
  130. }
  131. $oPage->Table($aAttribs, $aValues);
  132. $this->DisplayStatusTab($oPage);
  133. }
  134. parent::DisplayBareRelations($oPage, $bEditMode);
  135. }
  136. /**
  137. * Displays the status (SynchroLog) of the datasource in a graphical manner
  138. * @param $oPage WebPage
  139. * @return void
  140. */
  141. protected function DisplayStatusTab(WebPage $oPage)
  142. {
  143. $oPage->SetCurrentTab(Dict::S('Core:SynchroStatus'));
  144. $sSelectSynchroLog = 'SELECT SynchroLog WHERE sync_source_id = :source_id';
  145. $oSetSynchroLog = new CMDBObjectSet(DBObjectSearch::FromOQL($sSelectSynchroLog), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()));
  146. if ($oSetSynchroLog->Count() > 0)
  147. {
  148. $oLastLog = $oSetSynchroLog->Fetch();
  149. $sStartDate = $oLastLog->Get('start_date');
  150. $oLastLog->Get('stats_nb_replica_seen');
  151. if ($oLastLog->Get('status') == 'running')
  152. {
  153. // Still running !
  154. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroRunningStartedOn_Date', $sStartDate).'</h2>');
  155. }
  156. else
  157. {
  158. $sEndDate = $oLastLog->Get('end_date');
  159. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroEndedOn_Date', $sEndDate).'</h2>');
  160. }
  161. $oPage->add('<table class="synoptics"><tr><td style="color:#333;vertical-align:top">');
  162. $oPage->add('<h2>'.Dict::S('Core:Synchro:History').'</h2>');
  163. $oSetSynchroLog->Rewind();
  164. $oPage->add('<select size="30">');
  165. $sSelected = ' selected'; // First log is selected by default
  166. while($oLog = $oSetSynchroLog->Fetch())
  167. {
  168. $sLogTitle = Dict::Format('Core:SynchroLogTitle', $oLog->Get('status'), $oLog->Get('start_date'));
  169. $oPage->add('<option value="'.$oLog->GetKey().'"'.$sSelected.'>'.$sLogTitle.'</option>');
  170. $sSelected = ''; // only first log is selected by default
  171. }
  172. $oPage->add('</select>');
  173. $oPage->add('</td><td style="vertical-align:top;">');
  174. $iDeleted = $oLastLog->Get('stats_nb_obj_deleted');
  175. $iObsoleted = $oLastLog->Get('stats_nb_obj_obsoleted');
  176. $iDisappearedErrors = $oLastLog->Get('stats_nb_obj_obsoleted_errors') + $oLastLog->Get('stats_nb_obj_deleted_errors');
  177. $iUpdated = $oLastLog->Get('stats_nb_obj_updated');
  178. $iUpdatedErrors = $oLastLog->Get('stats_nb_obj_updated_errors');
  179. $iNewUpdated = $oLastLog->Get('stats_nb_obj_new_updated');
  180. $iNewUnchanged = $oLastLog->Get('stats_nb_obj_new_unchanged');
  181. $iReconciledErrors = $oLastLog->Get('stats_nb_replica_reconciled_errors');
  182. $iCreated = $oLastLog->Get('stats_nb_obj_created');
  183. $iCreatedErrors = $oLastLog->Get('stats_nb_obj_created_errors');
  184. $iDisappeared = $iDisappearedErrors + $iObsoleted + $iDeleted;
  185. $iNewErrors = $iCreatedErrors + $iReconciledErrors;
  186. $iNew = $iCreated + $iCreatedErrors + $iNewUpdated + $iNewUnchanged + $iReconciledErrors;
  187. $iExisting = $oLastLog->Get('stats_nb_replica_seen') - $iNew;
  188. $iUnchanged = $iExisting - $iUpdated - $iUpdatedErrors;
  189. $iIgnored = $oLastLog->Get('stats_nb_replica_total') - $iNew - $iExisting - $iDisappeared;
  190. $iNbObjects = $iNew + $iExisting + $iDisappeared;
  191. $iReplicas = $iNbObjects + $iIgnored;
  192. $sNbReplica = Dict::Format('Core:Synchro:Nb_Replica', "<span id=\"nb_replica_total\">$iReplicas</span>");
  193. $sNbObjects = Dict::Format('Core:Synchro:Nb_Objects', "<span id=\"nb_obj_total\">$iNbObjects</span>");
  194. $oPage->add(
  195. <<<EOF
  196. <table class="synoptics">
  197. <tr class="synoptics_header">
  198. <td>$sNbReplica</td><td>&nbsp;</td><td>$sNbObjects</td>
  199. </tr>
  200. <tr>
  201. EOF
  202. );
  203. $oPage->add($this->HtmlBox('repl_ignored', $iIgnored, '#999').'<td colspan="2">&nbsp;</td>');
  204. $oPage->add("</tr>\n<tr>");
  205. $oPage->add($this->HtmlBox('repl_disappeared', $iDisappeared, '#630', 'rowspan="3"').'<td rowspan="3" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_deleted', $iDeleted, '#000'));
  206. $oPage->add("</tr>\n<tr>");
  207. $oPage->add($this->HtmlBox('obj_obsoleted', $iDisappeared, '#630'));
  208. $oPage->add("</tr>\n<tr>");
  209. $oPage->add($this->HtmlBox('obj_disappeared_errors', $iDisappearedErrors, '#C00'));
  210. $oPage->add("</tr>\n<tr>");
  211. $oPage->add($this->HtmlBox('repl_existing', $iExisting, '#093', 'rowspan="3"').'<td rowspan="3" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_unchanged', $iUnchanged, '#393'));
  212. $oPage->add("</tr>\n<tr>");
  213. $oPage->add($this->HtmlBox('obj_updated', $iUpdated, '#3C3'));
  214. $oPage->add("</tr>\n<tr>");
  215. $oPage->add($this->HtmlBox('obj_updated_errors', $iUpdatedErrors, '#C00'));
  216. $oPage->add("</tr>\n<tr>");
  217. $oPage->add($this->HtmlBox('repl_new', $iNew, '#339', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_new_unchanged', $iNewUnchanged, '#393'));
  218. $oPage->add("</tr>\n<tr>");
  219. $oPage->add($this->HtmlBox('obj_new_updated', $iNewUpdated, '#3C3'));
  220. $oPage->add("</tr>\n<tr>");
  221. $oPage->add($this->HtmlBox('obj_created', $iCreated, '#339'));
  222. $oPage->add("</tr>\n<tr>");
  223. $oPage->add($this->HtmlBox('obj_new_errors', $iNewErrors, '#C00'));
  224. $oPage->add("</tr>\n</table>\n");
  225. $oPage->add('</td></tr></table>');
  226. }
  227. else
  228. {
  229. $oPage->p('<h2>'.Dict::S('Core:Synchro:NeverRun').'</h2>');
  230. }
  231. }
  232. public function HtmlBox($sId, $iCount, $sColor, $sHTMLAttribs = '')
  233. {
  234. $sCount = "<span id=\"c_{$sId}\">$iCount</span>";
  235. $sLabel = Dict::Format('Core:Synchro:label_'.$sId, $iCount);
  236. $sOpacity = ($iCount==0) ? "opacity:0.3;" : "";
  237. return "<td id=\"$sId\" style=\"background-color:$sColor;$sOpacity;\" {$sHTMLAttribs}>$sLabel</td>";
  238. }
  239. public function GetAttributeFlags($sAttCode)
  240. {
  241. if (($sAttCode == 'scope_class') && (!$this->IsNew()))
  242. {
  243. return OPT_ATT_READONLY;
  244. }
  245. return parent::GetAttributeFlags($sAttCode);
  246. }
  247. public function UpdateObject($sFormPrefix = '')
  248. {
  249. parent::UpdateObject($sFormPrefix);
  250. // And now read the other post parameters...
  251. $oAttributeSet = $this->Get('attribute_list');
  252. $aAttributes = array();
  253. while($oAttribute = $oAttributeSet->Fetch())
  254. {
  255. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  256. }
  257. $aReconcile = utils::ReadPostedParam('reconciliation', array());
  258. $aUpdate = utils::ReadPostedParam('update', array());
  259. $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array());
  260. // update_policy cannot be empty, so there is one entry per attribute, use this to iterate
  261. // through all the writable attributes
  262. foreach($aUpdatePolicy as $sAttCode => $sValue)
  263. {
  264. if(!isset($aAttributes[$sAttCode]))
  265. {
  266. $oAttribute = new SynchroAttribute();
  267. $oAttribute->Set('sync_source_id', $this->GetKey());
  268. $oAttribute->Set('attcode', $sAttCode);
  269. }
  270. else
  271. {
  272. $oAttribute = $aAttributes[$sAttCode];
  273. }
  274. $bReconcile = 0;
  275. if (isset($aReconcile[$sAttCode]))
  276. {
  277. $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0;
  278. }
  279. $bUpdate = 0 ; // Default / initial value
  280. if (isset($aUpdate[$sAttCode]))
  281. {
  282. $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0;
  283. }
  284. $oAttribute->Set('reconcile', $bReconcile);
  285. $oAttribute->Set('update', $bUpdate);
  286. $oAttribute->Set('update_policy', $sValue);
  287. $oAttributeSet->AddObject($oAttribute);
  288. }
  289. $this->Set('attribute_list', $oAttributeSet);
  290. }
  291. public function GetTargetClass()
  292. {
  293. return $this->Get('scope_class');
  294. }
  295. public function GetDataTable()
  296. {
  297. $sName = strtolower($this->GetTargetClass());
  298. $sName = str_replace('\'"&@|\\/ ', '_', $sName); // Remove forbidden characters from the table name
  299. $sName .= '_'.$this->GetKey(); // Add a suffix for unicity
  300. $sTable = MetaModel::GetConfig()->GetDBSubName()."synchro_data_$sName"; // Add the prefix if any
  301. return $sTable;
  302. }
  303. /**
  304. * When inserting a new datasource object, also create the SynchroAttribute objects
  305. * for each field of the target class
  306. */
  307. protected function OnInsert()
  308. {
  309. // Create all the SynchroAttribute records
  310. $oAttributeSet = $this->Get('attribute_list');
  311. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  312. {
  313. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  314. {
  315. $oAttribute = new SynchroAttribute();
  316. $oAttribute->Set('sync_source_id', $this->GetKey());
  317. $oAttribute->Set('attcode', $sAttCode);
  318. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  319. $oAttribute->Set('update', 1);
  320. $oAttribute->Set('update_policy', 'master_locked');
  321. $oAttributeSet->AddObject($oAttribute);
  322. }
  323. }
  324. $this->Set('attribute_list', $oAttributeSet);
  325. }
  326. /**
  327. * When the new datasource has been created, let's create the synchro_data table
  328. * that will hold the data records and the correspoding triggers which will maintain
  329. * both tables in sync
  330. */
  331. protected function AfterInsert()
  332. {
  333. parent::AfterInsert();
  334. $sTable = $this->GetDataTable();
  335. $aColumns = $this->GetSQLColumns();
  336. $aFieldDefs = array();
  337. // Allow '0', otherwise mysql will render an error when the id is not given
  338. // (the trigger is expected to set the value, but it is not executed soon enough)
  339. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  340. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  341. foreach($aColumns as $sColumn => $ColSpec)
  342. {
  343. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  344. }
  345. $aFieldDefs[] = "INDEX (id)";
  346. $aFieldDefs[] = "INDEX (primary_key)";
  347. $sFieldDefs = implode(', ', $aFieldDefs);
  348. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = innodb;";
  349. CMDBSource::Query($sCreateTable);
  350. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON $sTable";
  351. $sTriggerInsert .= " FOR EACH ROW";
  352. $sTriggerInsert .= " BEGIN";
  353. $sTriggerInsert .= " INSERT INTO priv_sync_replica (sync_source_id, status_last_seen, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  354. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  355. $sTriggerInsert .= " END;";
  356. CMDBSource::Query($sTriggerInsert);
  357. $aModified = array();
  358. foreach($aColumns as $sColumn => $ColSpec)
  359. {
  360. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  361. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  362. }
  363. $sIsModified = '('.implode(') OR (', $aModified).')';
  364. // Update the replica
  365. //
  366. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  367. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  368. // otherwise, the status is left as is
  369. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON $sTable";
  370. $sTriggerUpdate .= " FOR EACH ROW";
  371. $sTriggerUpdate .= " BEGIN";
  372. $sTriggerUpdate .= " IF @itopuser is null THEN";
  373. $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;";
  374. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  375. $sTriggerUpdate .= " END IF;";
  376. $sTriggerUpdate .= " END;";
  377. CMDBSource::Query($sTriggerUpdate);
  378. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON $sTable";
  379. $sTriggerInsert .= " FOR EACH ROW";
  380. $sTriggerInsert .= " BEGIN";
  381. $sTriggerInsert .= " DELETE FROM priv_sync_replica WHERE id = OLD.id;";
  382. $sTriggerInsert .= " END;";
  383. CMDBSource::Query($sTriggerInsert);
  384. }
  385. protected function AfterDelete()
  386. {
  387. parent::AfterDelete();
  388. $sTable = $this->GetDataTable();
  389. $sDropTable = "DROP TABLE `$sTable`";
  390. CMDBSource::Query($sDropTable);
  391. // TO DO - check that triggers get dropped with the table
  392. }
  393. /**
  394. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  395. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  396. * is used to determine which records are obsolete.
  397. * @param Hash $aTraces Debugs/Trace information, one or more entries per replica
  398. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  399. * @return void
  400. */
  401. public function Synchronize(&$aTraces, $oLastFullLoadStartDate = null)
  402. {
  403. // Create a change used for logging all the modifications/creations happening during the synchro
  404. $oMyChange = MetaModel::NewObject("CMDBChange");
  405. $oMyChange->Set("date", time());
  406. $sUserString = CMDBChange::GetCurrentUserName();
  407. $oMyChange->Set("userinfo", $sUserString);
  408. $iChangeId = $oMyChange->DBInsert();
  409. // Start logging this execution (stats + protection against reentrance)
  410. //
  411. $oStatLog = new SynchroLog();
  412. $oStatLog->Set('sync_source_id', $this->GetKey());
  413. $oStatLog->Set('start_date', time());
  414. $oStatLog->Set('status', 'running');
  415. $oStatLog->Set('stats_nb_replica_seen', 0);
  416. $oStatLog->Set('stats_nb_replica_total', 0);
  417. $oStatLog->Set('stats_nb_obj_deleted', 0);
  418. $oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  419. $oStatLog->Set('stats_nb_obj_obsoleted', 0);
  420. $oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  421. $oStatLog->Set('stats_nb_obj_created', 0);
  422. $oStatLog->Set('stats_nb_obj_created_errors', 0);
  423. $oStatLog->Set('stats_nb_obj_updated', 0);
  424. $oStatLog->Set('stats_nb_obj_updated_errors', 0);
  425. // $oStatLog->Set('stats_nb_replica_reconciled', 0);
  426. $oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  427. $oStatLog->Set('stats_nb_obj_new_updated', 0);
  428. $oStatLog->Set('stats_nb_obj_new_unchanged',0);
  429. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  430. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->GetKey()));
  431. $oStatLog->Set('stats_nb_replica_total', $oSetTotal->Count());
  432. $oStatLog->DBInsertTracked($oMyChange);
  433. try
  434. {
  435. $this->DoSynchronize($oLastFullLoadStartDate, $oMyChange, $oStatLog, $aTraces);
  436. $oStatLog->Set('end_date', time());
  437. $oStatLog->Set('status', 'completed');
  438. $oStatLog->DBUpdateTracked($oMyChange);
  439. }
  440. catch (SynchroExceptionNotStarted $e)
  441. {
  442. // Set information for reporting... but delete the object in DB
  443. $oStatLog->Set('end_date', time());
  444. $oStatLog->Set('status', 'error');
  445. $oStatLog->Set('last_error', $e->getMessage());
  446. $oStatLog->DBDeleteTracked($oMyChange);
  447. }
  448. catch (Exception $e)
  449. {
  450. $oStatLog->Set('end_date', time());
  451. $oStatLog->Set('status', 'error');
  452. $oStatLog->Set('last_error', $e->getMessage());
  453. $oStatLog->DBUpdateTracked($oMyChange);
  454. }
  455. return $oStatLog;
  456. }
  457. protected function DoSynchronize($oLastFullLoadStartDate, $oMyChange, &$oStatLog, &$aTraces)
  458. {
  459. if ($this->Get('status') == 'obsolete')
  460. {
  461. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
  462. }
  463. if (!UserRights::IsAdministrator() && $this->Get('user_id') != UserRights::GetUserId())
  464. {
  465. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
  466. }
  467. // Count the replicas
  468. $sSelectAll = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  469. $oSetAll = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAll), array() /* order by*/, array('source_id' => $this->GetKey()));
  470. $iCountAllReplicas = $oSetAll->Count();
  471. $oStatLog->Set('stats_nb_replica_total', $iCountAllReplicas);
  472. // Get all the replicas that were not seen in the last import and mark them as obsolete
  473. if ($oLastFullLoadStartDate == null)
  474. {
  475. // No previous import known, use the full_load_periodicity value... and the current date
  476. $oLastFullLoadStartDate = new DateTime(); // Now
  477. // TO DO: how do we support localization here ??
  478. $sLoadPeriodicity = trim($this->Get('full_load_periodicity'));
  479. if (strlen($sLoadPeriodicity) > 0)
  480. {
  481. $sInterval = '-'.$sLoadPeriodicity;
  482. // Note: the PHP doc states that Modify return FALSE in case of error
  483. // but, this is actually NOT the case
  484. // Therefore, I do compare before and after, considering that the
  485. // format is incorrect when the datetime remains unchanged
  486. $sBefore = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  487. $oLastFullLoadStartDate->Modify($sInterval);
  488. $sAfter = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  489. if ($sBefore == $sAfter)
  490. {
  491. throw new SynchroExceptionNotStarted("Data exchange: Wrong interval specification", array('interval' => $sInterval, 'source_id' => $this->GetKey()));
  492. }
  493. }
  494. }
  495. $sLimitDate = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  496. $aTraces[] = "Limit Date: $sLimitDate";
  497. $sSelectToObsolete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  498. $oSetToObsolete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  499. if (($iCountAllReplicas > 10) && ($iCountAllReplicas == $oSetToObsolete->Count()))
  500. {
  501. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncTooManyMissingReplicas'));
  502. }
  503. while($oReplica = $oSetToObsolete->Fetch())
  504. {
  505. // TO DO: take the appropriate action based on the 'delete_policy' field
  506. $sUpdateOnObsolete = $this->Get('delete_policy');
  507. if ( ($sUpdateOnObsolete == 'update') || ($sUpdateOnObsolete == 'update_then_delete') )
  508. {
  509. $aTraces[] = "Destination object: (dest_id:".$oReplica->Get('dest_id').") to be updated";
  510. $aToUpdate = array();
  511. $aToUpdate = explode(';', $this->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  512. foreach($aToUpdate as $sUpdateSpec)
  513. {
  514. $aUpdateSpec = explode(':', $sUpdateSpec);
  515. if (count($aUpdateSpec) == 2)
  516. {
  517. $sAttCode = $aUpdateSpec[0];
  518. $sValue = $aUpdateSpec[1];
  519. $aToUpdate[$sAttCode] = $sValue;
  520. }
  521. }
  522. $oReplica->UpdateDestObject($aToUpdate, $oMyChange, $oStatLog, $aTraces, 'stats_nb_obj_obsoleted');
  523. }
  524. $oReplica->Set('status', 'obsolete');
  525. $oReplica->DBUpdateTracked($oMyChange);
  526. }
  527. //Count "seen" objects
  528. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  529. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  530. $oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  531. // Get all the replicas that are 'new' or modified
  532. //
  533. // Get the list of SQL columns
  534. $sClass = $this->GetTargetClass();
  535. $aAttCodesExpected = array();
  536. $aAttCodesToReconcile = array();
  537. $aAttCodesToUpdate = array();
  538. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
  539. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */);
  540. while ($oSyncAtt = $oSetAtt->Fetch())
  541. {
  542. if ($oSyncAtt->Get('update'))
  543. {
  544. $aAttCodesToUpdate[] = $oSyncAtt->Get('attcode');
  545. }
  546. if ($oSyncAtt->Get('reconcile'))
  547. {
  548. $aAttCodesToReconcile[] = $oSyncAtt->Get('attcode');
  549. }
  550. $aAttCodesExpected[] = $oSyncAtt->Get('attcode');
  551. }
  552. $aColumns = $this->GetSQLColumns($aAttCodesExpected);
  553. $aExtDataFields = array_keys($aColumns);
  554. $aExtDataFields[] = 'primary_key';
  555. $aExtDataSpec = array(
  556. 'table' => $this->GetDataTable(),
  557. 'join_key' => 'id',
  558. 'fields' => $aExtDataFields
  559. );
  560. // Get the list of reconciliation keys
  561. if ($this->Get('reconciliation_policy') == 'use_attributes')
  562. {
  563. $aReconciliationKeys = $aAttCodesToReconcile;
  564. }
  565. elseif ($this->Get('reconciliation_policy') == 'use_primary_key')
  566. {
  567. // Override the setings made at the attribute level !
  568. $aReconciliationKeys = array("primary_key");
  569. }
  570. $aTraces[] = "Reconciliation on: {".implode(', ', $aReconciliationKeys)."}";
  571. $aAttributes = array();
  572. foreach($aAttCodesToUpdate as $sAttCode)
  573. {
  574. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  575. if ($oAttDef->IsWritable() && $oAttDef->IsScalar())
  576. {
  577. $aAttributes[] = $sAttCode;
  578. }
  579. }
  580. $sSelectToSync = "SELECT SynchroReplica WHERE (status = 'new' OR status = 'modified') AND sync_source_id = :source_id";
  581. $oSetToSync = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, $aExtDataSpec, 0 /* limitCount */, 0 /* limitStart */);
  582. while($oReplica = $oSetToSync->Fetch())
  583. {
  584. $oReplica->Synchro($this, $aReconciliationKeys, $aAttributes, $oMyChange, $oStatLog, $aTraces);
  585. }
  586. // Get all the replicas that are to be deleted
  587. //
  588. $oDeletionDate = $oLastFullLoadStartDate;
  589. $sDeleteRetention = trim($this->Get('delete_policy_retention'));
  590. if (strlen($sDeleteRetention) > 0)
  591. {
  592. $sInterval = '-'.$sDeleteRetention;
  593. // Note: the PHP doc states that Modify return FALSE in case of error
  594. // but, this is actually NOT the case
  595. // Therefore, I do compare before and after, considering that the
  596. // format is incorrect when the datetime remains unchanged
  597. $sBefore = $oDeletionDate->Format('Y-m-d H:i:s');
  598. $oDeletionDate->Modify($sInterval);
  599. $sAfter = $oDeletionDate->Format('Y-m-d H:i:s');
  600. if ($sBefore == $sAfter)
  601. {
  602. throw new SynchroExceptionNotStarted("Data exchange: Wrong interval specification", array('interval' => $sInterval, 'source_id' => $this->GetKey()));
  603. }
  604. }
  605. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  606. $aTraces[] = "sDeletionDate: $sDeletionDate";
  607. $sSelectToDelete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  608. $oSetToDelete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sDeletionDate));
  609. while($oReplica = $oSetToDelete->Fetch())
  610. {
  611. $sUpdateOnObsolete = $this->Get('delete_policy');
  612. if ( ($sUpdateOnObsolete == 'delete') || ($sUpdateOnObsolete == 'update_then_delete') )
  613. {
  614. $aTraces[] = "Destination object: (dest_id:".$oReplica->Get('dest_id').") to be DELETED";
  615. $oReplica->DeleteDestObject($oMyChange, $oStatLog, $aTraces);
  616. }
  617. $aTraces[] = "Replica id:".$oReplica->GetKey()." (dest_id:".$oReplica->Get('dest_id').") to be deleted";
  618. $oReplica->DBDeleteTracked($oMyChange);
  619. }
  620. }
  621. /**
  622. * Get the list of SQL columns corresponding to a particular list of attribute codes
  623. * Defaults to the whole list of columns for the current class
  624. */
  625. public function GetSQLColumns($aAttributeCodes = null)
  626. {
  627. $aColumns = array();
  628. $sClass = $this->GetTargetClass();
  629. if (is_null($aAttributeCodes))
  630. {
  631. $aAttributeCodes = array();
  632. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  633. {
  634. if ($sAttCode == 'finalclass') continue;
  635. $aAttributeCodes[] = $sAttCode;
  636. }
  637. }
  638. foreach($aAttributeCodes as $sAttCode)
  639. {
  640. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  641. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  642. {
  643. $aColumns[$sField] = $sDBFieldType;
  644. }
  645. }
  646. return $aColumns;
  647. }
  648. public function IsRunning()
  649. {
  650. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  651. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  652. if ($oSet->Count() < 1)
  653. {
  654. $bRet = false;
  655. }
  656. else
  657. {
  658. $bRet = true;
  659. }
  660. return $bRet;
  661. }
  662. public function GetLatestLog()
  663. {
  664. $oLog = null;
  665. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  666. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  667. if ($oSet->Count() >= 1)
  668. {
  669. $oLog = $oSet->Fetch();
  670. }
  671. return $oLog;
  672. }
  673. // TO DO: remove if still unused
  674. /**
  675. * Retrieve from the log, the date of the last completed import
  676. * @return DateTime
  677. */
  678. public function GetLastCompletedImportDate()
  679. {
  680. $date = null;
  681. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  682. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  683. if ($oSet->Count() >= 1)
  684. {
  685. $oLog = $oSet->Fetch();
  686. $date = $oLog->Get('end_date');
  687. }
  688. else
  689. {
  690. // TO DO: remove trace
  691. echo "<p>No completed log found</p>\n";
  692. }
  693. return $date;
  694. }
  695. }
  696. class SynchroAttribute extends cmdbAbstractObject
  697. {
  698. public static function Init()
  699. {
  700. $aParams = array
  701. (
  702. "category" => "core/cmdb,view_in_gui",
  703. "key_type" => "autoincrement",
  704. "name_attcode" => "",
  705. "state_attcode" => "",
  706. "reconc_keys" => array(),
  707. "db_table" => "priv_sync_att",
  708. "db_key_field" => "id",
  709. "db_finalclass_field" => "",
  710. "display_template" => "",
  711. );
  712. MetaModel::Init_Params($aParams);
  713. MetaModel::Init_InheritAttributes();
  714. 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_AUTO, "depends_on"=>array())));
  715. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  716. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  717. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  718. 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())));
  719. // Display lists
  720. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  721. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  722. // Search criteria
  723. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  724. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  725. }
  726. }
  727. class SynchroAttExtKey extends SynchroAttribute
  728. {
  729. public static function Init()
  730. {
  731. $aParams = array
  732. (
  733. "category" => "core/cmdb,view_in_gui",
  734. "key_type" => "autoincrement",
  735. "name_attcode" => "",
  736. "state_attcode" => "",
  737. "reconc_keys" => array(),
  738. "db_table" => "priv_sync_att_extkey",
  739. "db_key_field" => "id",
  740. "db_finalclass_field" => "",
  741. "display_template" => "",
  742. );
  743. MetaModel::Init_Params($aParams);
  744. MetaModel::Init_InheritAttributes();
  745. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  746. // Display lists
  747. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  748. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  749. // Search criteria
  750. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  751. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  752. }
  753. }
  754. class SynchroAttLinkSet extends SynchroAttribute
  755. {
  756. public static function Init()
  757. {
  758. $aParams = array
  759. (
  760. "category" => "core/cmdb,view_in_gui",
  761. "key_type" => "autoincrement",
  762. "name_attcode" => "",
  763. "state_attcode" => "",
  764. "reconc_keys" => array(),
  765. "db_table" => "priv_sync_att_linkset",
  766. "db_key_field" => "id",
  767. "db_finalclass_field" => "",
  768. "display_template" => "",
  769. );
  770. MetaModel::Init_Params($aParams);
  771. MetaModel::Init_InheritAttributes();
  772. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  773. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  774. // Display lists
  775. 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
  776. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  777. // Search criteria
  778. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  779. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  780. }
  781. }
  782. //class SynchroLog extends Event
  783. class SynchroLog extends cmdbAbstractObject
  784. {
  785. public static function Init()
  786. {
  787. $aParams = array
  788. (
  789. "category" => "core/cmdb,view_in_gui",
  790. "key_type" => "autoincrement",
  791. "name_attcode" => "",
  792. "state_attcode" => "",
  793. "reconc_keys" => array(),
  794. "db_table" => "priv_sync_log",
  795. "db_key_field" => "id",
  796. "db_finalclass_field" => "",
  797. "display_template" => "",
  798. );
  799. MetaModel::Init_Params($aParams);
  800. MetaModel::Init_InheritAttributes();
  801. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  802. 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_AUTO, "depends_on"=>array())));
  803. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  804. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  805. 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())));
  806. 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())));
  807. 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())));
  808. 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())));
  809. 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())));
  810. 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())));
  811. 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())));
  812. 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())));
  813. 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())));
  814. 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())));
  815. 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())));
  816. // 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())));
  817. 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())));
  818. 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())));
  819. 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())));
  820. MetaModel::Init_AddAttribute(new AttributeString("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  821. // Display lists
  822. 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',
  823. 'stats_nb_obj_created_errors', 'stats_nb_replica_reconciled_errors', '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')); // Attributes to be displayed for the complete details
  824. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  825. // Search criteria
  826. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  827. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  828. }
  829. /**
  830. * Increments a statistics counter
  831. */
  832. function Inc($sCode)
  833. {
  834. $this->Set($sCode, 1+$this->Get($sCode));
  835. }
  836. }
  837. class SynchroReplica extends DBObject
  838. {
  839. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  840. public static function Init()
  841. {
  842. $aParams = array
  843. (
  844. "category" => "core/cmdb,view_in_gui",
  845. "key_type" => "autoincrement",
  846. "name_attcode" => "",
  847. "state_attcode" => "",
  848. "reconc_keys" => array(),
  849. "db_table" => "priv_sync_replica",
  850. "db_key_field" => "id",
  851. "db_finalclass_field" => "",
  852. "display_template" => "",
  853. );
  854. MetaModel::Init_Params($aParams);
  855. MetaModel::Init_InheritAttributes();
  856. 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_AUTO, "depends_on"=>array())));
  857. MetaModel::Init_AddAttribute(new AttributeInteger("dest_id", array("allowed_values"=>null, "sql"=>"dest_id", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  858. MetaModel::Init_AddAttribute(new AttributeClass("dest_class", array("class_category"=>"bizmodel", "more_values"=>"", "sql"=>"dest_class", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  859. 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())));
  860. 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())));
  861. 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())));
  862. 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())));
  863. 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())));
  864. 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())));
  865. MetaModel::Init_AddAttribute(new AttributeDateTime("info_last_synchro", array("allowed_values"=>null, "sql"=>"info_last_synchro", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  866. // Display lists
  867. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error', 'info_creation_date', 'info_last_modified', 'info_last_synchro')); // Attributes to be displayed for the complete details
  868. 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
  869. // Search criteria
  870. 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
  871. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  872. }
  873. public function DBInsert()
  874. {
  875. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  876. }
  877. // Overload the deletion -> the replica has been created by the mean of a trigger,
  878. // it will be deleted by the mean of a trigger too
  879. public function DBDelete()
  880. {
  881. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  882. $sTable = $oDataSource->GetDataTable();
  883. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  884. CMDBSource::Query($sSQL);
  885. $this->m_bIsInDB = false;
  886. $this->m_iKey = null;
  887. }
  888. public function SetLastError($sMessage, $oException = null)
  889. {
  890. if ($oException)
  891. {
  892. $sText = $sMessage.$oException->getMessage();
  893. }
  894. else
  895. {
  896. $sText = $sMessage;
  897. }
  898. if (strlen($sText) > 255)
  899. {
  900. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  901. }
  902. $this->Set('status_last_error', $sText);
  903. }
  904. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog, &$aTraces)
  905. {
  906. switch($this->Get('status'))
  907. {
  908. case 'new':
  909. // If needed, construct the query used for the reconciliation
  910. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  911. {
  912. foreach($aReconciliationKeys as $sFilterCode)
  913. {
  914. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  915. }
  916. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  917. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  918. }
  919. // Get the criterias for the search
  920. $aFilterValues = array();
  921. foreach($aReconciliationKeys as $sFilterCode)
  922. {
  923. $value = $this->GetValueFromExtData($sFilterCode);
  924. if (!is_null($value))
  925. {
  926. $aFilterValues[$sFilterCode] = $value;
  927. }
  928. else
  929. {
  930. // Reconciliation could not be performed - log and EXIT
  931. $aTraces[] = "Could not reconcile on null value: ".$sFilterCode;
  932. $this->SetLastError('Could not reconcile on null value: '.$sFilterCode);
  933. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  934. return;
  935. }
  936. }
  937. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  938. $iCount = $oDestSet->Count();
  939. $aConditions = array();
  940. foreach($aFilterValues as $sCode => $sValue)
  941. {
  942. $aConditions[] = $sCode.'='.$sValue;
  943. }
  944. $sConditionDesc = implode(' AND ', $aConditions);
  945. // How many objects match the reconciliation criterias
  946. switch($iCount)
  947. {
  948. case 0:
  949. $aTraces[] = "Nothing found on: $sConditionDesc";
  950. if ($oDataSource->Get('action_on_zero') == 'create')
  951. {
  952. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog, $aTraces);
  953. }
  954. else // assumed to be 'error'
  955. {
  956. $aTraces[] = "Failed to reconcile (no match)";
  957. $this->SetLastError('Could not find a match for reconciliation');
  958. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  959. }
  960. break;
  961. case 1:
  962. $aTraces[] = "Found 1 object on: $sConditionDesc";
  963. if ($oDataSource->Get('action_on_one') == 'update')
  964. {
  965. $oDestObj = $oDestSet->Fetch();
  966. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  967. $this->Set('dest_id', $oDestObj->GetKey());
  968. $this->Set('status_dest_creator', false);
  969. $this->Set('dest_class', get_class($oDestObj));
  970. $oStatLog->Inc('stats_nb_replica_reconciled'); //@@@
  971. }
  972. else
  973. {
  974. // assumed to be 'error'
  975. $aTraces[] = "Failed to reconcile (1 match)";
  976. $this->SetLastError('Found a match while expecting several');
  977. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  978. }
  979. break;
  980. default:
  981. $aTraces[] = "Found $iCount objects on: $sConditionDesc";
  982. if ($oDataSource->Get('action_on_multiple') == 'error')
  983. {
  984. $aTraces[] = "Failed to reconcile (N>1 matches)";
  985. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  986. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  987. }
  988. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  989. {
  990. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog, $aTraces);
  991. }
  992. else
  993. {
  994. // assumed to be 'take_first'
  995. $oDestObj = $oDestSet->Fetch();
  996. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  997. $this->Set('dest_id', $oDestObj->GetKey());
  998. $this->Set('status_dest_creator', false);
  999. $this->Set('dest_class', get_class($oDestObj));
  1000. }
  1001. }
  1002. break;
  1003. case 'modified':
  1004. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  1005. if ($oDestObj == null)
  1006. {
  1007. $this->Set('status', 'orphan'); // The destination object has been deleted !
  1008. $this->SetLastError('Destination object deleted unexpectedly');
  1009. $oStatLog->Inc('stats_nb_obj_updated_errors');
  1010. }
  1011. else
  1012. {
  1013. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_obj', 'stats_nb_obj_updated_errors');
  1014. }
  1015. break;
  1016. default: // Do nothing in all other cases
  1017. }
  1018. $this->DBUpdateTracked($oChange);
  1019. }
  1020. /**
  1021. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  1022. */
  1023. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, &$aTraces, $sStatsCode, $sStatsCodeError)
  1024. {
  1025. $aValueTrace = array();
  1026. foreach($aAttributes as $sAttCode)
  1027. {
  1028. $value = $this->GetValueFromExtData($sAttCode);
  1029. if (!is_null($value))
  1030. {
  1031. $oDestObj->Set($sAttCode, $value);
  1032. $aValueTrace[] = "$sAttCode: $value";
  1033. }
  1034. }
  1035. try
  1036. {
  1037. // Really modified ?
  1038. if ($oDestObj->IsModified())
  1039. {
  1040. $oDestObj->DBUpdateTracked($oChange);
  1041. $aTraces[] = "Updated object ".$oDestObj->GetHyperLink()." (".implode(', ', $aValueTrace).")";
  1042. $oStatLog->Inc($sStatsCode.'_updated');
  1043. }
  1044. else
  1045. {
  1046. $aTraces[] = "Unchanged object ".$oDestObj->GetHyperLink()." (".implode(', ', $aValueTrace).")";
  1047. $oStatLog->Inc($sStatsCode.'_unchanged');
  1048. }
  1049. $this->Set('status_last_error', '');
  1050. $this->Set('status', 'synchronized');
  1051. }
  1052. catch(Exception $e)
  1053. {
  1054. $aTraces[] = "Failed to update destination object: {$e->getMessage()}";
  1055. $this->SetLastError('Unable to update destination object: ', $e);
  1056. $oStatLog->Inc($sStatsCodeError);
  1057. }
  1058. }
  1059. /**
  1060. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1061. */
  1062. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog, &$aTraces)
  1063. {
  1064. $oDestObj = MetaModel::NewObject($sClass);
  1065. try
  1066. {
  1067. $aValueTrace = array();
  1068. foreach($aAttributes as $sAttCode)
  1069. {
  1070. $value = $this->GetValueFromExtData($sAttCode);
  1071. if (!is_null($value))
  1072. {
  1073. $oDestObj->Set($sAttCode, $value);
  1074. $aValueTrace[] = "$sAttCode: $value";
  1075. }
  1076. }
  1077. $iNew = $oDestObj->DBInsertTracked($oChange);
  1078. $aTraces[] = "Created $sClass::$iNew (".implode(', ', $aValueTrace).")";
  1079. $this->Set('dest_id', $oDestObj->GetKey());
  1080. $this->Set('dest_class', get_class($oDestObj));
  1081. $this->Set('status_dest_creator', true);
  1082. $this->Set('status_last_error', '');
  1083. $this->Set('status', 'synchronized');
  1084. $oStatLog->Inc('stats_nb_obj_created');
  1085. }
  1086. catch(Exception $e)
  1087. {
  1088. $aTraces[] = "Failed to create $sClass ({$e->getMessage()})";
  1089. $this->SetLastError('Unable to create destination object: ', $e);
  1090. $oStatLog->Inc('stats_nb_obj_created_errors');
  1091. }
  1092. }
  1093. /**
  1094. * Update the destination object with given values
  1095. */
  1096. public function UpdateDestObject($aValues, $oChange, &$oStatLog, &$aTraces, $sStatCode)
  1097. {
  1098. try
  1099. {
  1100. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1101. foreach($aValues as $sAttCode => $value)
  1102. {
  1103. $oDestObj->Set($sAttCode, $value);
  1104. }
  1105. $oDestObj->DBUpdateTracked($oChange);
  1106. $aTraces[] = "Replica id:".$this->GetKey()." (dest_id:".$this->Get('dest_id').") marked as obsolete";
  1107. $oStatLog->Inc($sStatCode);
  1108. }
  1109. catch(Exception $e)
  1110. {
  1111. $this->SetLastError('Unable to update the destination object: ', $e);
  1112. $oStatLog->Inc($sStatCode.'_errors');
  1113. }
  1114. }
  1115. /**
  1116. * Delete the destination object
  1117. */
  1118. public function DeleteDestObject($oChange, &$oStatLog, &$aTraces)
  1119. {
  1120. if($this->Get('status_dest_creator'))
  1121. {
  1122. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1123. try
  1124. {
  1125. $oDestObj->DBDeleteTracked($oChange);
  1126. $oStatLog->Inc('stats_nb_obj_deleted');
  1127. }
  1128. catch(Exception $e)
  1129. {
  1130. $this->SetLastError('Unable to delete the destination object: ', $e);
  1131. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1132. }
  1133. }
  1134. }
  1135. /**
  1136. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1137. */
  1138. protected function GetValueFromExtData($sColumnName)
  1139. {
  1140. // $aData should contain attributes defined either for reconciliation or update
  1141. $aData = $this->GetExtendedData();
  1142. return $aData[$sColumnName];
  1143. }
  1144. }
  1145. // TO DO: finalize.... admins only ? which options ? troubleshoot WebPageMenuNode::__construct(.... sEnableClass...) ?
  1146. //if (UserRights::IsAdministrator())
  1147. {
  1148. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */);
  1149. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1150. new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  1151. }
  1152. ?>