synchrodatasource.class.inc.php 50 KB

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