synchrodatasource.class.inc.php 79 KB

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