synchrodatasource.class.inc.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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. );
  40. MetaModel::Init_Params($aParams);
  41. //MetaModel::Init_InheritAttributes();
  42. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  43. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  44. 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())));
  45. 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())));
  46. 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())));
  47. MetaModel::Init_AddAttribute(new AttributeString("scope_restriction", array("allowed_values"=>null, "sql"=>"scope_restriction", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  48. //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())));
  49. // Format: '1 hour', '2 weeks', '3 hoursABCDEF'... Cf DateTime->Modify()
  50. 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())));
  51. // MetaModel::Init_AddAttribute(new AttributeString("reconciliation_list", array("allowed_values"=>null, "sql"=>"reconciliation_list", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  52. 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())));
  53. 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())));
  54. 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())));
  55. 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())));
  56. 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())));
  57. 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())));
  58. // Format: '1 hour', '2 weeks', '3 hoursABCDEF'... Cf DateTime->Modify()
  59. 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())));
  60. 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())));
  61. // Display lists
  62. MetaModel::Init_SetZListItems('details', array('name', 'description', 'status', 'user_id', 'scope_class', 'scope_restriction', 'full_load_periodicity', 'reconciliation_policy', 'action_on_zero', 'action_on_one', 'action_on_multiple', 'delete_policy', 'delete_policy_update', 'delete_policy_retention', 'attribute_list')); // Attributes to be displayed for the complete details
  63. MetaModel::Init_SetZListItems('list', array('name', 'status', 'scope_class', 'user_id')); // Attributes to be displayed for a list
  64. // Search criteria
  65. MetaModel::Init_SetZListItems('standard_search', array('name', 'status', 'scope_class', 'user_id')); // Criteria of the std search form
  66. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  67. }
  68. public function GetTargetClass()
  69. {
  70. return $this->Get('scope_class');
  71. }
  72. public function GetDataTable()
  73. {
  74. $sName = strtolower($this->GetTargetClass());
  75. $sName = str_replace('\'"&@|\\/ ', '_', $sName); // Remove forbidden characters from the table name
  76. $sName .= '_'.$this->GetKey(); // Add a suffix for unicity
  77. $sTable = MetaModel::GetConfig()->GetDBSubName()."synchro_data_$sName"; // Add the prefix if any
  78. return $sTable;
  79. }
  80. protected function AfterInsert()
  81. {
  82. parent::AfterInsert();
  83. $sTable = $this->GetDataTable();
  84. $aColumns = $this->GetSQLColumns();
  85. $aFieldDefs = array();
  86. // Allow '0', otherwise mysql will render an error when the id is not given
  87. // (the trigger is expected to set the value, but it is not executed soon enough)
  88. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  89. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  90. foreach($aColumns as $sColumn => $ColSpec)
  91. {
  92. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  93. }
  94. $aFieldDefs[] = "INDEX (id)";
  95. $aFieldDefs[] = "INDEX (primary_key)";
  96. $sFieldDefs = implode(', ', $aFieldDefs);
  97. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = innodb;";
  98. CMDBSource::Query($sCreateTable);
  99. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON $sTable";
  100. $sTriggerInsert .= " FOR EACH ROW";
  101. $sTriggerInsert .= " BEGIN";
  102. $sTriggerInsert .= " INSERT INTO priv_sync_replica (sync_source_id, status_last_seen, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  103. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  104. $sTriggerInsert .= " END;";
  105. CMDBSource::Query($sTriggerInsert);
  106. $aModified = array();
  107. foreach($aColumns as $sColumn => $ColSpec)
  108. {
  109. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  110. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  111. }
  112. $sIsModified = '('.implode(') OR (', $aModified).')';
  113. // Update the replica
  114. //
  115. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  116. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  117. // otherwise, the status is left as is
  118. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON $sTable";
  119. $sTriggerUpdate .= " FOR EACH ROW";
  120. $sTriggerUpdate .= " BEGIN";
  121. $sTriggerUpdate .= " IF @itopuser is null THEN";
  122. $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;";
  123. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  124. $sTriggerUpdate .= " END IF;";
  125. $sTriggerUpdate .= " END;";
  126. CMDBSource::Query($sTriggerUpdate);
  127. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON $sTable";
  128. $sTriggerInsert .= " FOR EACH ROW";
  129. $sTriggerInsert .= " BEGIN";
  130. $sTriggerInsert .= " DELETE FROM priv_sync_replica WHERE id = OLD.id;";
  131. $sTriggerInsert .= " END;";
  132. CMDBSource::Query($sTriggerInsert);
  133. }
  134. protected function AfterDelete()
  135. {
  136. parent::AfterInsert();
  137. $sTable = $this->GetDataTable();
  138. $sDropTable = "DROP TABLE `$sTable`";
  139. CMDBSource::Query($sDropTable);
  140. // TO DO - check that triggers get dropped with the table
  141. }
  142. /**
  143. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  144. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  145. * is used to determine which records are obsolete.
  146. * @param Hash $aDataToReplica Debugs/Trace information, one entry per replica
  147. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  148. * @return void
  149. */
  150. public function Synchronize(&$aDataToReplica, $oLastFullLoadStartDate = null)
  151. {
  152. // Create a change used for logging all the modifications/creations happening during the synchro
  153. $oMyChange = MetaModel::NewObject("CMDBChange");
  154. $oMyChange->Set("date", time());
  155. $sUserString = CMDBChange::GetCurrentUserName();
  156. $oMyChange->Set("userinfo", $sUserString);
  157. $iChangeId = $oMyChange->DBInsert();
  158. // Get all the replicas that were not seen in the last import and mark them as obsolete
  159. if ($oLastFullLoadStartDate == null)
  160. {
  161. // No previous import known, use the full_load_periodicity value... and the current date
  162. $oLastFullLoadStartDate = new DateTime(); // Now
  163. // TO DO: how do we support localization here ??
  164. $sLoadPeriodicity = trim($this->Get('full_load_periodicity'));
  165. if (strlen($sLoadPeriodicity) > 0)
  166. {
  167. $sInterval = '-'.$sLoadPeriodicity;
  168. // Note: the PHP doc states that Modify return FALSE in case of error
  169. // but, this is actually NOT the case
  170. // Therefore, I do compare before and after, considering that the
  171. // format is incorrect when the datetime remains unchanged
  172. $sBefore = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  173. $oLastFullLoadStartDate->Modify($sInterval);
  174. $sAfter = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  175. if ($sBefore == $sAfter)
  176. {
  177. throw new CoreException("Data exchange: Wrong interval specification", array('interval' => $sInterval, 'source_id' => $this->GetKey()));
  178. }
  179. }
  180. }
  181. $sLimitDate = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  182. // TO DO: remove trace
  183. echo "<p>sLimitDate: $sLimitDate</p>\n";
  184. $sSelectToObsolete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  185. $oSetToObsolete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  186. while($oReplica = $oSetToObsolete->Fetch())
  187. {
  188. // TO DO: take the appropriate action based on the 'delete_policy' field
  189. $sUpdateOnObsolete = $this->Get('delete_policy');
  190. if ( ($sUpdateOnObsolete == 'update') || ($sUpdateOnObsolete == 'update_then_delete') )
  191. {
  192. // TO DO: remove trace
  193. echo "<p>Destination object: (dest_id:".$oReplica->Get('dest_id').") to be updated.</p>";
  194. $aToUpdate = array();
  195. $aToUpdate = explode(';', $this->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  196. foreach($aToUpdate as $sUpdateSpec)
  197. {
  198. $aUpdateSpec = explode(':', $sUpdateSpec);
  199. if (count($aUpdateSpec) == 2)
  200. {
  201. $sAttCode = $aUpdateSpec[0];
  202. $sValue = $aUpdateSpec[1];
  203. $aToUpdate[$sAttCode] = $sValue;
  204. }
  205. }
  206. $oReplica->UpdateDestObject($aToUpdate, $oMyChange);
  207. }
  208. // TO DO: remove trace
  209. echo "<p>Replica id:".$oReplica->GetKey()." (dest_id:".$oReplica->Get('dest_id').") marked as obsolete</p>";
  210. $oReplica->Set('status', 'obsolete');
  211. $oReplica->DBUpdateTracked($oMyChange);
  212. }
  213. // Get all the replicas that are 'new' or modified
  214. //
  215. // Get the list of SQL columns
  216. $sClass = $this->GetTargetClass();
  217. // TO DO: remove trace
  218. echo "<p>TargetClass: $sClass</p>";
  219. $aAttCodes = array();
  220. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND update = 1";
  221. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */);
  222. while ($oSyncAtt = $oSetAtt->Fetch())
  223. {
  224. $aAttCodes[] = $oSyncAtt->Get('attcode');
  225. }
  226. $aColumns = $this->GetSQLColumns($aAttCodes);
  227. $aExtDataFields = array_keys($aColumns);
  228. $aExtDataFields[] = 'primary_key';
  229. $aExtDataSpec = array(
  230. 'table' => $this->GetDataTable(),
  231. 'join_key' => 'id',
  232. 'fields' => $aExtDataFields
  233. );
  234. // Get the list of reconciliation keys
  235. $aReconciliationKeys = array();
  236. if ($this->Get('reconciliation_policy') == 'use_attributes')
  237. {
  238. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND reconcile = 1";
  239. $oAttSet = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */);
  240. while ($oSyncAtt = $oAttSet->Fetch())
  241. {
  242. $aReconciliationKeys[] = $oSyncAtt->Get('attcode');
  243. }
  244. }
  245. elseif ($this->Get('reconciliation_policy') == 'use_primary_key')
  246. {
  247. $aReconciliationKeys[] = "primary_key";
  248. }
  249. // TO DO: remove trace
  250. echo "Reconciliation on: {".implode(', ', $aReconciliationKeys)."}<br/>\n";
  251. $aAttributes = array();
  252. foreach($aAttCodes as $sAttCode)
  253. {
  254. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  255. if ($oAttDef->IsWritable() && $oAttDef->IsScalar())
  256. {
  257. $aAttributes[] = $sAttCode;
  258. }
  259. }
  260. $sSelectToSync = "SELECT SynchroReplica WHERE (status = 'new' OR status = 'modified') AND sync_source_id = :source_id";
  261. $oSetToSync = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, $aExtDataSpec, 0 /* limitCount */, 0 /* limitStart */);
  262. while($oReplica = $oSetToSync->Fetch())
  263. {
  264. $oReplica->Synchro($this, $aReconciliationKeys, $aAttributes, $oMyChange);
  265. }
  266. // Get all the replicas that are to be deleted
  267. //
  268. $oDeletionDate = $oLastFullLoadStartDate;
  269. $sDeleteRetention = trim($this->Get('delete_policy_retention'));
  270. if (strlen($sDeleteRetention) > 0)
  271. {
  272. $sInterval = '-'.$sDeleteRetention;
  273. // Note: the PHP doc states that Modify return FALSE in case of error
  274. // but, this is actually NOT the case
  275. // Therefore, I do compare before and after, considering that the
  276. // format is incorrect when the datetime remains unchanged
  277. $sBefore = $oDeletionDate->Format('Y-m-d H:i:s');
  278. $oDeletionDate->Modify($sInterval);
  279. $sAfter = $oDeletionDate->Format('Y-m-d H:i:s');
  280. if ($sBefore == $sAfter)
  281. {
  282. throw new CoreException("Data exchange: Wrong interval specification", array('interval' => $sInterval, 'source_id' => $this->GetKey()));
  283. }
  284. }
  285. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  286. // TO DO: remove trace
  287. echo "<p>sDeletionDate: $sDeletionDate</p>\n";
  288. $sSelectToDelete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  289. $oSetToDelete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sDeletionDate));
  290. while($oReplica = $oSetToDelete->Fetch())
  291. {
  292. $sUpdateOnObsolete = $this->Get('delete_policy');
  293. if ( ($sUpdateOnObsolete == 'delete') || ($sUpdateOnObsolete == 'update_then_delete') )
  294. {
  295. // TO DO: remove trace
  296. echo "<p>Destination object: (dest_id:".$oReplica->Get('dest_id').") to be DELETED.</p>";
  297. // TO DO: delete the dest object for real...
  298. $oReplica->DeleteDestObject($oMyChange);
  299. }
  300. // TO DO: remove trace
  301. echo "<p>Replica id:".$oReplica->GetKey()." (dest_id:".$oReplica->Get('dest_id').") to be deleted</p>";
  302. $oReplica->DBDeleteTracked($oMyChange);
  303. }
  304. return;
  305. }
  306. /**
  307. * Get the list of SQL columns corresponding to a particular list of attribute codes
  308. * Defaults to the whole list of columns for the current class
  309. */
  310. public function GetSQLColumns($aAttributeCodes = null)
  311. {
  312. $aColumns = array();
  313. $sClass = $this->GetTargetClass();
  314. if (is_null($aAttributeCodes))
  315. {
  316. $aAttributeCodes = array();
  317. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  318. {
  319. if ($sAttCode == 'finalclass') continue;
  320. $aAttributeCodes[] = $sAttCode;
  321. }
  322. }
  323. foreach($aAttributeCodes as $sAttCode)
  324. {
  325. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  326. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  327. {
  328. $aColumns[$sField] = $sDBFieldType;
  329. }
  330. }
  331. return $aColumns;
  332. }
  333. public function IsRunning()
  334. {
  335. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  336. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  337. if ($oSet->Count() < 1)
  338. {
  339. $bRet = false;
  340. }
  341. else
  342. {
  343. $bRet = true;
  344. }
  345. return $bRet;
  346. }
  347. public function GetLatestLog()
  348. {
  349. $oLog = null;
  350. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  351. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  352. if ($oSet->Count() >= 1)
  353. {
  354. $oLog = $oSet->Fetch();
  355. }
  356. return $oLog;
  357. }
  358. /**
  359. * Retrieve from the log, the date of the last completed import
  360. * @return DateTime
  361. */
  362. public function GetLastCompletedImportDate()
  363. {
  364. $date = null;
  365. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  366. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  367. if ($oSet->Count() >= 1)
  368. {
  369. $oLog = $oSet->Fetch();
  370. $date = $oLog->Get('end_date');
  371. }
  372. else
  373. {
  374. // TO DO: remove trace
  375. echo "<p>No completed log found</p>\n";
  376. }
  377. return $date;
  378. }
  379. }
  380. class SynchroAttribute extends cmdbAbstractObject
  381. {
  382. public static function Init()
  383. {
  384. $aParams = array
  385. (
  386. "category" => "core/cmdb,view_in_gui",
  387. "key_type" => "autoincrement",
  388. "name_attcode" => "",
  389. "state_attcode" => "",
  390. "reconc_keys" => array(),
  391. "db_table" => "priv_sync_att",
  392. "db_key_field" => "id",
  393. "db_finalclass_field" => "",
  394. "display_template" => "",
  395. );
  396. MetaModel::Init_Params($aParams);
  397. MetaModel::Init_InheritAttributes();
  398. 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())));
  399. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  400. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  401. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  402. 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())));
  403. // Display lists
  404. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  405. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  406. // Search criteria
  407. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  408. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  409. }
  410. }
  411. class SynchroAttExtKey extends SynchroAttribute
  412. {
  413. public static function Init()
  414. {
  415. $aParams = array
  416. (
  417. "category" => "core/cmdb,view_in_gui",
  418. "key_type" => "autoincrement",
  419. "name_attcode" => "",
  420. "state_attcode" => "",
  421. "reconc_keys" => array(),
  422. "db_table" => "priv_sync_att_extkey",
  423. "db_key_field" => "id",
  424. "db_finalclass_field" => "",
  425. "display_template" => "",
  426. );
  427. MetaModel::Init_Params($aParams);
  428. MetaModel::Init_InheritAttributes();
  429. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  430. // Display lists
  431. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  432. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  433. // Search criteria
  434. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  435. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  436. }
  437. }
  438. class SynchroAttLinkSet extends SynchroAttribute
  439. {
  440. public static function Init()
  441. {
  442. $aParams = array
  443. (
  444. "category" => "core/cmdb,view_in_gui",
  445. "key_type" => "autoincrement",
  446. "name_attcode" => "",
  447. "state_attcode" => "",
  448. "reconc_keys" => array(),
  449. "db_table" => "priv_sync_att_linkset",
  450. "db_key_field" => "id",
  451. "db_finalclass_field" => "",
  452. "display_template" => "",
  453. );
  454. MetaModel::Init_Params($aParams);
  455. MetaModel::Init_InheritAttributes();
  456. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  457. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  458. // Display lists
  459. 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
  460. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  461. // Search criteria
  462. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  463. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  464. }
  465. }
  466. class SynchroLog extends CmdbAbstractObject
  467. {
  468. public static function Init()
  469. {
  470. $aParams = array
  471. (
  472. "category" => "core/cmdb,view_in_gui",
  473. "key_type" => "autoincrement",
  474. "name_attcode" => "",
  475. "state_attcode" => "",
  476. "reconc_keys" => array(),
  477. "db_table" => "priv_sync_log",
  478. "db_key_field" => "id",
  479. "db_finalclass_field" => "",
  480. "display_template" => "",
  481. );
  482. MetaModel::Init_Params($aParams);
  483. MetaModel::Init_InheritAttributes();
  484. 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())));
  485. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  486. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  487. 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())));
  488. 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())));
  489. 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())));
  490. 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())));
  491. 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())));
  492. 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())));
  493. 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())));
  494. // Display lists
  495. 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
  496. 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
  497. // Search criteria
  498. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  499. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  500. }
  501. }
  502. class SynchroReplica extends cmdbAbstractObject
  503. {
  504. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  505. public static function Init()
  506. {
  507. $aParams = array
  508. (
  509. "category" => "core/cmdb,view_in_gui",
  510. "key_type" => "autoincrement",
  511. "name_attcode" => "",
  512. "state_attcode" => "",
  513. "reconc_keys" => array(),
  514. "db_table" => "priv_sync_replica",
  515. "db_key_field" => "id",
  516. "db_finalclass_field" => "",
  517. "display_template" => "",
  518. );
  519. MetaModel::Init_Params($aParams);
  520. MetaModel::Init_InheritAttributes();
  521. 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())));
  522. MetaModel::Init_AddAttribute(new AttributeInteger("dest_id", array("allowed_values"=>null, "sql"=>"dest_id", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  523. 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())));
  524. 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())));
  525. 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())));
  526. 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())));
  527. 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())));
  528. 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())));
  529. 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())));
  530. 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())));
  531. // Display lists
  532. 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
  533. 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
  534. // Search criteria
  535. 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
  536. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  537. }
  538. public function DBInsert()
  539. {
  540. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  541. }
  542. // Overload the deletion -> the replica has been created by the mean of a trigger,
  543. // it will be deleted by the mean of a trigger too
  544. public function DBDeleteTracked_Internal()
  545. {
  546. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  547. $sTable = $oDataSource->GetDataTable();
  548. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  549. CMDBSource::Query($sSQL);
  550. $this->m_bIsInDB = false;
  551. $this->m_iKey = null;
  552. }
  553. public function SetLastError($sMessage, $oException = null)
  554. {
  555. if ($oException)
  556. {
  557. $sText = $sMessage.$oException->getMessage();
  558. }
  559. else
  560. {
  561. $sText = $sMessage;
  562. }
  563. if (strlen($sText) > 255)
  564. {
  565. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  566. }
  567. $this->Set('status_last_error', $sText);
  568. }
  569. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange)
  570. {
  571. switch($this->Get('status'))
  572. {
  573. case 'new':
  574. // If needed, construct the query used for the reconciliation
  575. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  576. {
  577. foreach($aReconciliationKeys as $sFilterCode)
  578. {
  579. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  580. }
  581. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  582. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  583. }
  584. // Get the criterias for the search
  585. $aFilterValues = array();
  586. foreach($aReconciliationKeys as $sFilterCode)
  587. {
  588. $aFilterValues[$sFilterCode] = $this->GetValueFromExtData($sFilterCode);
  589. }
  590. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  591. $iCount = $oDestSet->Count();
  592. // How many objects match the reconciliation criterias
  593. switch($iCount)
  594. {
  595. case 0:
  596. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange);
  597. break;
  598. case 1:
  599. $oDestObj = $oDestSet->Fetch();
  600. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange);
  601. $this->Set('dest_id', $oDestObj->GetKey());
  602. $this->Set('status_dest_creator', false);
  603. $this->Set('dest_class', get_class($oDestObj));
  604. break;
  605. default:
  606. $aConditions = array();
  607. foreach($aFilterValues as $sCode => $sValue)
  608. {
  609. $aConditions[] = $sCode.'='.$sValue;
  610. }
  611. $sCondition = implode(' AND ', $aConditions);
  612. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sCondition);
  613. }
  614. break;
  615. case 'modified':
  616. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  617. if ($oDestObj == null)
  618. {
  619. $this->Set('status', 'orphan'); // The destination object has been deleted !
  620. $this->SetLastError('Destination object deleted unexpectedly');
  621. }
  622. else
  623. {
  624. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange);
  625. }
  626. break;
  627. default: // Do nothing in all other cases
  628. }
  629. $this->DBUpdateTracked($oChange);
  630. }
  631. /**
  632. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  633. */
  634. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange)
  635. {
  636. // TO DO: remove trace
  637. echo "<p>Update object ".$oDestObj->GetHyperLink()."</p>";
  638. foreach($aAttributes as $sAttCode)
  639. {
  640. $value = $this->GetValueFromExtData($sAttCode);
  641. $oDestObj->Set($sAttCode, $value);
  642. // TO DO: remove trace
  643. echo "<p>&nbsp;&nbsp;&nbsp;Setting $sAttCode to $value</p>";
  644. }
  645. try
  646. {
  647. $oDestObj->DBUpdateTracked($oChange);
  648. $this->Set('status_last_error', '');
  649. $this->Set('status', 'synchronized');
  650. }
  651. catch(Exception $e)
  652. {
  653. $this->SetLastError('Unable to update destination object: ', $e);
  654. }
  655. }
  656. /**
  657. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  658. */
  659. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange)
  660. {
  661. // TO DO: remove trace
  662. echo "<p>Creating new $sClass</p>";
  663. $oDestObj = MetaModel::NewObject($sClass);
  664. foreach($aAttributes as $sAttCode)
  665. {
  666. $value = $this->GetValueFromExtData($sAttCode);
  667. $oDestObj->Set($sAttCode, $value);
  668. // TO DO: remove trace
  669. echo "<p>&nbsp;&nbsp;&nbsp;Setting $sAttCode to $value</p>";
  670. }
  671. try
  672. {
  673. $iNew = $oDestObj->DBInsertTracked($oChange);
  674. // TO DO: remove trace
  675. echo "<p>Created: $iNew</p>";
  676. $this->Set('dest_id', $oDestObj->GetKey());
  677. $this->Set('dest_class', get_class($oDestObj));
  678. $this->Set('status_dest_creator', true);
  679. $this->Set('status_last_error', '');
  680. $this->Set('status', 'synchronized');
  681. }
  682. catch(Exception $e)
  683. {
  684. $this->SetLastError('Unable to create destination object: ', $e);
  685. }
  686. }
  687. /**
  688. * Update the destination object with given values
  689. */
  690. public function UpdateDestObject($aValues, $oChange)
  691. {
  692. try
  693. {
  694. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  695. foreach($aValues as $sAttCode => $value)
  696. {
  697. $oDestObj->Set($sAttCode, $value);
  698. }
  699. $oDestObj->DBUpdateTracked($oChange);
  700. }
  701. catch(Exception $e)
  702. {
  703. $this->SetLastError('Unable to update the destination object: ', $e);
  704. }
  705. }
  706. /**
  707. * Delete the destination object
  708. */
  709. public function DeleteDestObject($oChange)
  710. {
  711. if($this->Get('status_dest_creator'))
  712. {
  713. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  714. try
  715. {
  716. $oDestObj->DBDeleteTracked($oChange);
  717. }
  718. catch(Exception $e)
  719. {
  720. $this->SetLastError('Unable to delete the destination object: ', $e);
  721. }
  722. }
  723. }
  724. /**
  725. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  726. */
  727. protected function GetValueFromExtData($sColumnName)
  728. {
  729. $aData = $this->GetExtendedData();
  730. return $aData[$sColumnName];
  731. }
  732. }
  733. //if (UserRights::IsAdministrator())
  734. {
  735. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */);
  736. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  737. new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */);
  738. }
  739. ?>