synchrodatasource.class.inc.php 83 KB

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