synchrodatasource.class.inc.php 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Data Exchange - synchronization with external applications (incoming data)
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  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. MetaModel::Init_AddAttribute(new AttributeString("database_table_name", array("allowed_values"=>null, "sql"=>"database_table_name", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array(), "validation_pattern" => "^[A-Za-z0-9_]*$")));
  53. // Declared here for a future usage, but ignored so far
  54. MetaModel::Init_AddAttribute(new AttributeString("scope_restriction", array("allowed_values"=>null, "sql"=>"scope_restriction", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  55. //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())));
  56. // Format: seconds (int)
  57. MetaModel::Init_AddAttribute(new AttributeDuration("full_load_periodicity", array("allowed_values"=>null, "sql"=>"full_load_periodicity", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  58. // MetaModel::Init_AddAttribute(new AttributeString("reconciliation_list", array("allowed_values"=>null, "sql"=>"reconciliation_list", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  59. 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())));
  60. 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())));
  61. 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())));
  62. 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())));
  63. 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())));
  64. 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())));
  65. // Format: seconds (unsigned int)
  66. 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())));
  67. 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(), 'tracking_level' => LINKSET_TRACKING_DETAILS)));
  68. // Not used yet !
  69. 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())));
  70. 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())));
  71. // 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
  72. MetaModel::Init_AddAttribute(new AttributeString("url_application", array("allowed_values"=>null, "sql"=>"url_application", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  73. // Display lists
  74. MetaModel::Init_SetZListItems('details', array(
  75. 'col:0'=> array(
  76. 'fieldset:SynchroDataSource:Description' => array('name','description','status','scope_class','user_id','notify_contact_id','url_icon','url_application', 'database_table_name')),
  77. 'col:1'=> array(
  78. 'fieldset:SynchroDataSource:Reconciliation' => array('reconciliation_policy','action_on_zero','action_on_one','action_on_multiple'),
  79. 'fieldset:SynchroDataSource:Deletion' => array('user_delete_policy','full_load_periodicity','delete_policy','delete_policy_update','delete_policy_retention'))
  80. )
  81. );
  82. MetaModel::Init_SetZListItems('list', array('scope_class', 'status', 'user_id', 'full_load_periodicity')); // Attributes to be displayed for a list
  83. // Search criteria
  84. MetaModel::Init_SetZListItems('standard_search', array('name', 'status', 'scope_class', 'user_id')); // Criteria of the std search form
  85. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  86. }
  87. public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  88. {
  89. if (!$this->IsNew())
  90. {
  91. $this->Set('database_table_name', $this->GetDataTable());
  92. }
  93. return parent::DisplayBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams);
  94. }
  95. public function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  96. {
  97. if (!$this->IsNew())
  98. {
  99. $oPage->SetCurrentTab(Dict::S('Core:SynchroAttributes'));
  100. $oAttributeSet = $this->Get('attribute_list');
  101. $aAttributes = array();
  102. while($oAttribute = $oAttributeSet->Fetch())
  103. {
  104. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  105. }
  106. // Columns of the form
  107. $aAttribs = array();
  108. foreach(array('attcode', 'reconciliation', 'update', 'update_policy', 'reconciliation_attcode') as $s )
  109. {
  110. $aAttribs[$s] = array( 'label' => Dict::S("Core:SynchroAtt:$s"), "description" => Dict::S("Core:SynchroAtt:$s+"));
  111. }
  112. // Rows of the form
  113. $aValues = array();
  114. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  115. {
  116. if ($oAttDef->IsWritable())
  117. {
  118. if (isset($aAttributes[$sAttCode]))
  119. {
  120. $oAttribute = $aAttributes[$sAttCode];
  121. }
  122. else
  123. {
  124. if ($oAttDef->IsExternalKey())
  125. {
  126. $oAttribute = new SynchroAttExtKey();
  127. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  128. }
  129. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  130. {
  131. $oAttribute = new SynchroAttLinkSet();
  132. // Todo - add these settings into the form
  133. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  134. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  135. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  136. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  137. }
  138. elseif ($oAttDef->IsScalar())
  139. {
  140. $oAttribute = new SynchroAttribute();
  141. }
  142. else
  143. {
  144. $oAttribute = null;
  145. }
  146. if (!is_null($oAttribute))
  147. {
  148. $oAttribute->Set('sync_source_id', $this->GetKey());
  149. $oAttribute->Set('attcode', $sAttCode);
  150. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  151. $oAttribute->Set('update', 1);
  152. $oAttribute->Set('update_policy', 'master_locked');
  153. }
  154. }
  155. if (!is_null($oAttribute))
  156. {
  157. if (!$bEditMode)
  158. {
  159. // Read-only mode
  160. $aRow['reconciliation'] = $oAttribute->Get('reconcile') == 1 ? Dict::S('Core:SynchroReconcile:Yes') : Dict::S('Core:SynchroReconcile:No');
  161. $aRow['update'] = $oAttribute->Get('update') == 1 ? Dict::S('Core:SynchroUpdate:Yes') : Dict::S('Core:SynchroUpdate:No');
  162. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode')).' ('.$oAttribute->Get('attcode').')';
  163. $aRow['update_policy'] = $oAttribute->GetAsHTML('update_policy');
  164. if ($oAttDef->IsExternalKey())
  165. {
  166. $aRow['reconciliation_attcode'] = $oAttribute->GetAsHTML('reconciliation_attcode');
  167. }
  168. else
  169. {
  170. $aRow['reconciliation_attcode'] = '&nbsp;';
  171. }
  172. }
  173. else
  174. {
  175. // Edit mode
  176. $sAttCode = $oAttribute->Get('attcode');
  177. $sChecked = $oAttribute->Get('reconcile') == 1 ? 'checked' : '';
  178. $aRow['reconciliation'] = "<input type=\"checkbox\" name=\"reconciliation[$sAttCode]\" $sChecked/>";
  179. $sChecked = $oAttribute->Get('update') == 1 ? 'checked' : '';
  180. $aRow['update'] = "<input type=\"checkbox\" name=\"update[$sAttCode]\" $sChecked/>";
  181. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode')).' ('.$oAttribute->Get('attcode').')';
  182. $oUpdateAttDef = MetaModel::GetAttributeDef(get_class($oAttribute), 'update_policy');
  183. $aRow['update_policy'] = cmdbAbstractObject::GetFormElementForField($oPage, get_class($oAttribute), 'update_policy', $oUpdateAttDef, $oAttribute->Get('update_policy'), '', 'update_policy_'.$sAttCode, "[$sAttCode]");
  184. if ($oAttDef->IsExternalKey())
  185. {
  186. $aRow['reconciliation_attcode'] = $oAttribute->GetReconciliationFormElement($oAttDef->GetTargetClass(), "attr_reconciliation_attcode[$sAttCode]");
  187. }
  188. else
  189. {
  190. $aRow['reconciliation_attcode'] = '&nbsp;';
  191. }
  192. }
  193. $aValues[] = $aRow;
  194. }
  195. }
  196. }
  197. $oPage->p(Dict::Format('Class:SynchroDataSource:DataTable', $this->GetDataTable()));
  198. $oPage->Table($aAttribs, $aValues);
  199. $this->DisplayStatusTab($oPage);
  200. }
  201. parent::DisplayBareRelations($oPage, $bEditMode);
  202. }
  203. /**
  204. * Displays the status (SynchroLog) of the datasource in a graphical manner
  205. * @param $oPage WebPage
  206. * @return void
  207. */
  208. protected function DisplayStatusTab(WebPage $oPage)
  209. {
  210. $oPage->SetCurrentTab(Dict::S('Core:SynchroStatus'));
  211. $sSelectSynchroLog = 'SELECT SynchroLog WHERE sync_source_id = :source_id';
  212. $oSetSynchroLog = new CMDBObjectSet(DBObjectSearch::FromOQL($sSelectSynchroLog), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()));
  213. $oSetSynchroLog->SetLimit(100); // Display only the 100 latest runs
  214. if ($oSetSynchroLog->Count() > 0)
  215. {
  216. $oLastLog = $oSetSynchroLog->Fetch();
  217. $sStartDate = $oLastLog->Get('start_date');
  218. $oLastLog->Get('stats_nb_replica_seen');
  219. $iLastLog = 0;
  220. $iDSid = $this->GetKey();
  221. if ($oLastLog->Get('status') == 'running')
  222. {
  223. // Still running !
  224. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroRunningStartedOn_Date', $sStartDate).'</h2>');
  225. }
  226. else
  227. {
  228. $sEndDate = $oLastLog->Get('end_date');
  229. $iLastLog = $oLastLog->GetKey();
  230. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroEndedOn_Date', $sEndDate).'</h2>');
  231. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid";
  232. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  233. $iCountAllReplicas = $oSet->Count();
  234. $sAllReplicas = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllReplicas</a>";
  235. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid AND status_last_error !=''";
  236. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  237. $iCountAllErrors = $oSet->Count();
  238. $sAllErrors = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllErrors</a>";
  239. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid AND status_last_warning !=''";
  240. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  241. $iCountAllWarnings = $oSet->Count();
  242. $sAllWarnings = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllWarnings</a>";
  243. $oPage->p('<h2>'.Dict::Format('Core:Synchro:ListReplicas_AllReplicas_Errors_Warnings', $sAllReplicas, $sAllErrors, $sAllWarnings).'</h2>');
  244. }
  245. $oPage->add('<table class="synoptics"><tr><td style="color:#333;vertical-align:top">');
  246. // List all the log entries for the user to select
  247. $oPage->add('<h2 style="line-height:55px;">'.Dict::S('Core:Synchro:History').'</h2>');
  248. $oSetSynchroLog->Rewind();
  249. $oPage->add('<select size="25" onChange="UpdateSynoptics(this.value);">');
  250. $sSelected = ' selected'; // First log is selected by default
  251. $sScript = "var aSynchroLog = {\n";
  252. while($oLog = $oSetSynchroLog->Fetch())
  253. {
  254. $sLogTitle = Dict::Format('Core:SynchroLogTitle', $oLog->Get('status'), $oLog->Get('start_date'));
  255. $oPage->add('<option value="'.$oLog->GetKey().'"'.$sSelected.'>'.$sLogTitle.'</option>');
  256. $sSelected = ''; // only the first log is selected by default
  257. $aData = $this->ProcessLog($oLog);
  258. $sScript .= '"'.$oLog->GetKey().'": '.json_encode($aData).",\n";
  259. }
  260. $sScript .= "end: 'Done'";
  261. $sScript .= "};\n";
  262. $sScript .= <<<EOF
  263. var sLastLog = '$iLastLog';
  264. function ToggleSynoptics(sId, bShow)
  265. {
  266. if (bShow)
  267. {
  268. $(sId).show();
  269. }
  270. else
  271. {
  272. $(sId).hide();
  273. }
  274. }
  275. function UpdateSynoptics(id)
  276. {
  277. var aValues = aSynchroLog[id];
  278. if (aValues == undefined) return;
  279. for (var sKey in aValues)
  280. {
  281. $('#c_'+sKey).html(aValues[sKey]);
  282. var fOpacity = (aValues[sKey] == 0) ? 0.3 : 1;
  283. $('#'+sKey).fadeTo("slow", fOpacity);
  284. }
  285. //alert('id = '+id+', lastLog='+sLastLog+', id==sLastLog: '+(id==sLastLog)+' obj_updated_errors: '+aValues['obj_updated_errors']);
  286. if ( (id == sLastLog) && (aValues['obj_new_errors'] > 0) )
  287. {
  288. $('#new_errors_link').show();
  289. }
  290. else
  291. {
  292. $('#new_errors_link').hide();
  293. }
  294. if ( (id == sLastLog) && (aValues['obj_updated_errors'] > 0) )
  295. {
  296. $('#updated_errors_link').show();
  297. }
  298. else
  299. {
  300. $('#updated_errors_link').hide();
  301. }
  302. if ( (id == sLastLog) && (aValues['obj_disappeared_errors'] > 0) )
  303. {
  304. $('#disappeared_errors_link').show();
  305. }
  306. else
  307. {
  308. $('#disappeared_errors_link').hide();
  309. }
  310. ToggleSynoptics('#cw_obj_created_warnings', aValues['obj_created_warnings'] > 0);
  311. ToggleSynoptics('#cw_obj_new_updated_warnings', aValues['obj_new_updated_warnings'] > 0);
  312. ToggleSynoptics('#cw_obj_new_unchanged_warnings', aValues['obj_new_unchanged_warnings'] > 0);
  313. ToggleSynoptics('#cw_obj_updated_warnings', aValues['obj_updated_warnings'] > 0);
  314. ToggleSynoptics('#cw_obj_unchanged_warnings', aValues['obj_unchanged_warnings'] > 0);
  315. }
  316. EOF
  317. ;
  318. $oPage->add_script($sScript);
  319. $oPage->add('</select>');
  320. $oPage->add('</td><td style="vertical-align:top;">');
  321. // Now build the big "synoptics" view
  322. $aData = $this->ProcessLog($oLastLog);
  323. $sNbReplica = $this->GetIcon()."&nbsp;".Dict::Format('Core:Synchro:Nb_Replica', "<span id=\"c_nb_replica_total\">{$aData['nb_replica_total']}</span>");
  324. $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>");
  325. $oPage->add(
  326. <<<EOF
  327. <table class="synoptics">
  328. <tr class="synoptics_header">
  329. <td>$sNbReplica</td><td>&nbsp;</td><td>$sNbObjects</td>
  330. </tr>
  331. <tr>
  332. EOF
  333. );
  334. $sBaseOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->GetKey()." AND status_last_error!=''";
  335. $oPage->add($this->HtmlBox('repl_ignored', $aData, '#999').'<td colspan="2">&nbsp;</td>');
  336. $oPage->add("</tr>\n<tr>");
  337. $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'));
  338. $oPage->add("</tr>\n<tr>");
  339. $oPage->add($this->HtmlBox('obj_deleted', $aData, '#000'));
  340. $oPage->add("</tr>\n<tr>");
  341. $oPage->add($this->HtmlBox('obj_obsoleted', $aData, '#630'));
  342. $oPage->add("</tr>\n<tr>");
  343. $sOQL = urlencode($sBaseOQL." AND status='obsolete'");
  344. $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>"));
  345. $oPage->add("</tr>\n<tr>");
  346. $oPage->add($this->HtmlBox('repl_existing', $aData, '#093', 'rowspan="3"').'<td rowspan="3" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_unchanged', $aData, '#393'));
  347. $oPage->add("</tr>\n<tr>");
  348. $oPage->add($this->HtmlBox('obj_updated', $aData, '#3C3'));
  349. $oPage->add("</tr>\n<tr>");
  350. $sOQL = urlencode($sBaseOQL." AND status='modified'");
  351. $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>"));
  352. $oPage->add("</tr>\n<tr>");
  353. $oPage->add($this->HtmlBox('repl_new', $aData, '#339', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_new_unchanged', $aData, '#393'));
  354. $oPage->add("</tr>\n<tr>");
  355. $oPage->add($this->HtmlBox('obj_new_updated', $aData, '#3C3'));
  356. $oPage->add("</tr>\n<tr>");
  357. $oPage->add($this->HtmlBox('obj_created', $aData, '#339'));
  358. $oPage->add("</tr>\n<tr>");
  359. $sOQL = urlencode($sBaseOQL." AND status='new'");
  360. $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>"));
  361. $oPage->add("</tr>\n</table>\n");
  362. $oPage->add('</td></tr></table>');
  363. $oPage->add_ready_script("UpdateSynoptics('$iLastLog')");
  364. }
  365. else
  366. {
  367. $oPage->p('<h2>'.Dict::S('Core:Synchro:NeverRun').'</h2>');
  368. }
  369. }
  370. protected function HtmlBox($sId, $aData, $sColor, $sHTMLAttribs = '', $sErrorLink = '')
  371. {
  372. $iCount = $aData[$sId];
  373. $sCount = "<span id=\"c_{$sId}\">$iCount</span>";
  374. $sLabel = Dict::Format('Core:Synchro:label_'.$sId, $sCount);
  375. $sOpacity = ($iCount==0) ? "opacity:0.3;" : "";
  376. if (isset($aData[$sId.'_warnings']))
  377. {
  378. $sLabel .= " <span id=\"cw_{$sId}_warnings\"><img src=\"../images/error.png\" style=\"vertical-align:middle\"/> (<span id=\"c_{$sId}_warnings\">".$aData[$sId.'_warnings']."</span>)</span>";
  379. }
  380. return "<td id=\"$sId\" style=\"background-color:$sColor;$sOpacity;\" {$sHTMLAttribs}>{$sLabel}{$sErrorLink}</td>";
  381. }
  382. protected function ProcessLog($oLastLog)
  383. {
  384. $aData = array(
  385. 'obj_deleted' => $oLastLog->Get('stats_nb_obj_deleted'),
  386. 'obj_obsoleted' => $oLastLog->Get('stats_nb_obj_obsoleted'),
  387. 'obj_disappeared_errors' => $oLastLog->Get('stats_nb_obj_obsoleted_errors') + $oLastLog->Get('stats_nb_obj_deleted_errors'),
  388. 'obj_disappeared_no_action' => $oLastLog->Get('stats_nb_replica_disappeared_no_action'),
  389. 'obj_updated' => $oLastLog->Get('stats_nb_obj_updated'),
  390. 'obj_updated_warnings' => $oLastLog->Get('stats_nb_obj_updated_warnings'),
  391. 'obj_updated_errors' => $oLastLog->Get('stats_nb_obj_updated_errors'),
  392. 'obj_new_updated' => $oLastLog->Get('stats_nb_obj_new_updated'),
  393. 'obj_new_updated_warnings' => $oLastLog->Get('stats_nb_obj_new_updated_warnings'),
  394. 'obj_new_unchanged' => $oLastLog->Get('stats_nb_obj_new_unchanged'),
  395. 'obj_created' => $oLastLog->Get('stats_nb_obj_created'),
  396. 'obj_created_warnings' => $oLastLog->Get('stats_nb_obj_created_warnings'),
  397. 'obj_created_errors' => $oLastLog->Get('stats_nb_obj_created_errors'),
  398. 'obj_unchanged_warnings' => $oLastLog->Get('stats_nb_obj_unchanged_warnings'),
  399. );
  400. $iReconciledErrors = $oLastLog->Get('stats_nb_replica_reconciled_errors');
  401. $iDisappeared = $aData['obj_disappeared_errors'] + $aData['obj_obsoleted'] + $aData['obj_deleted'] + $aData['obj_disappeared_no_action'];
  402. $aData['repl_disappeared'] = $iDisappeared;
  403. $iNewErrors = $aData['obj_created_errors'] + $oLastLog->Get('stats_nb_replica_reconciled_errors');
  404. $aData['obj_new_errors'] = $iNewErrors;
  405. $iNew = $aData['obj_created'] + $iNewErrors + $aData['obj_new_updated'] + $aData['obj_new_unchanged'];
  406. $aData['repl_new'] = $iNew;
  407. $iExisting = $oLastLog->Get('stats_nb_replica_seen') - $iNew;
  408. $aData['repl_existing'] = $iExisting;
  409. $aData['obj_unchanged'] = $iExisting - $aData['obj_updated'] - $aData['obj_updated_errors'];
  410. $iIgnored = $oLastLog->Get('stats_nb_replica_total') - $iNew - $iExisting - $iDisappeared;
  411. $aData['repl_ignored'] = $iIgnored;
  412. $aData['nb_obj_total'] = $iNew + $iExisting + $iDisappeared;
  413. $aData['nb_replica_total'] = $aData['nb_obj_total'] + $iIgnored;
  414. return $aData;
  415. }
  416. public function GetIcon($bImgTag = true, $sMoreStyles = '')
  417. {
  418. if ($this->Get('url_icon') == '') return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  419. if ($bImgTag)
  420. {
  421. return "<img src=\"".$this->Get('url_icon')."\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  422. }
  423. return $this->Get('url_icon');
  424. }
  425. /**
  426. * Get the actual hyperlink to the remote application for the given replica and dest object
  427. */
  428. public function GetApplicationUrl(DBObject $oDestObj, SynchroReplica $oReplica)
  429. {
  430. if ($this->Get('url_application') == '') return '';
  431. $aSearches = array();
  432. $aReplacements = array();
  433. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  434. {
  435. if ($oAttDef->IsScalar())
  436. {
  437. $aSearches[] = '$this->'.$sAttCode.'$';
  438. $aReplacements[] = $oDestObj->Get($sAttCode);
  439. }
  440. }
  441. $aData = $oReplica->LoadExtendedDataFromTable($this->GetDataTable());
  442. foreach($aData as $sColumn => $value)
  443. {
  444. $aSearches[] = '$replica->'.$sColumn.'$';
  445. $aReplacements[] = $value;
  446. }
  447. return str_replace($aSearches, $aReplacements, $this->Get('url_application'));
  448. }
  449. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  450. {
  451. if ( (($sAttCode == 'scope_class') || ($sAttCode == 'database_table_name')) && (!$this->IsNew()))
  452. {
  453. return OPT_ATT_READONLY;
  454. }
  455. return parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState);
  456. }
  457. public function UpdateObjectFromPostedForm($sFormPrefix = '', $sAttList = null, $sTargetState = '')
  458. {
  459. parent::UpdateObjectFromPostedForm($sFormPrefix, $sAttList, $sTargetState);
  460. // And now read the other post parameters...
  461. $oAttributeSet = $this->Get('attribute_list');
  462. $aAttributes = array();
  463. while($oAttribute = $oAttributeSet->Fetch())
  464. {
  465. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  466. }
  467. $aReconcile = utils::ReadPostedParam('reconciliation', array());
  468. $aUpdate = utils::ReadPostedParam('update', array());
  469. $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array());
  470. $aReconciliation = utils::ReadPostedParam('attr_reconciliation_attcode', array());
  471. // update_policy cannot be empty, so there is one entry per attribute, use this to iterate
  472. // through all the writable attributes
  473. foreach($aUpdatePolicy as $sAttCode => $sValue)
  474. {
  475. if(!isset($aAttributes[$sAttCode]))
  476. {
  477. $oAttribute = $this->CreateSynchroAtt($sAttCode);
  478. }
  479. else
  480. {
  481. $oAttribute = $aAttributes[$sAttCode];
  482. }
  483. $bReconcile = 0;
  484. if (isset($aReconcile[$sAttCode]))
  485. {
  486. $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0;
  487. }
  488. $bUpdate = 0 ; // Default / initial value
  489. if (isset($aUpdate[$sAttCode]))
  490. {
  491. $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0;
  492. }
  493. $oAttribute->Set('reconcile', $bReconcile);
  494. $oAttribute->Set('update', $bUpdate);
  495. $oAttribute->Set('update_policy', $sValue);
  496. if ($oAttribute instanceof SynchroAttExtKey)
  497. {
  498. $oAttribute->Set('reconciliation_attcode', $aReconciliation[$sAttCode]);
  499. }
  500. elseif ($oAttribute instanceof SynchroAttLinkSet)
  501. {
  502. }
  503. $oAttributeSet->AddObject($oAttribute);
  504. }
  505. $this->Set('attribute_list', $oAttributeSet);
  506. }
  507. /**
  508. * Creates a new SynchroAttXXX object in memory with the default values
  509. */
  510. protected function CreateSynchroAtt($sAttCode)
  511. {
  512. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  513. if ($oAttDef->IsExternalKey())
  514. {
  515. $oAttribute = new SynchroAttExtKey();
  516. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  517. }
  518. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  519. {
  520. $oAttribute = new SynchroAttLinkSet();
  521. // Todo - set those value from the form
  522. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  523. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  524. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  525. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  526. }
  527. else
  528. {
  529. $oAttribute = new SynchroAttribute();
  530. }
  531. $oAttribute->Set('sync_source_id', $this->GetKey());
  532. $oAttribute->Set('attcode', $sAttCode);
  533. $oAttribute->Set('reconcile', 0);
  534. $oAttribute->Set('update', 0);
  535. $oAttribute->Set('update_policy', 'master_locked');
  536. return $oAttribute;
  537. }
  538. /**
  539. * Overload the standard behavior
  540. */
  541. public function ComputeValues()
  542. {
  543. parent::ComputeValues();
  544. if ($this->IsNew())
  545. {
  546. // Compute the database_table_name
  547. $sDataTable = $this->Get('database_table_name');
  548. if (!empty($sDataTable))
  549. {
  550. $this->Set('database_table_name', $this->ComputeDataTableName());
  551. }
  552. // When inserting a new datasource object, also create the SynchroAttribute objects
  553. // for each field of the target class
  554. // Create all the SynchroAttribute records
  555. $oAttributeSet = $this->Get('attribute_list');
  556. if ($oAttributeSet->Count() == 0)
  557. {
  558. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  559. {
  560. if ($oAttDef->IsWritable())
  561. {
  562. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  563. if ($oAttDef->IsExternalKey())
  564. {
  565. $oAttribute = new SynchroAttExtKey();
  566. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  567. }
  568. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  569. {
  570. $oAttribute = new SynchroAttLinkSet();
  571. // Todo - set those value from the form
  572. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  573. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  574. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  575. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  576. }
  577. elseif ($oAttDef->IsScalar())
  578. {
  579. $oAttribute = new SynchroAttribute();
  580. }
  581. else
  582. {
  583. $oAttribute = null;
  584. }
  585. if (!is_null($oAttribute))
  586. {
  587. $oAttribute->Set('sync_source_id', $this->GetKey());
  588. $oAttribute->Set('attcode', $sAttCode);
  589. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  590. $oAttribute->Set('update', 1);
  591. $oAttribute->Set('update_policy', 'master_locked');
  592. $oAttributeSet->AddObject($oAttribute);
  593. }
  594. }
  595. }
  596. $this->Set('attribute_list', $oAttributeSet);
  597. }
  598. }
  599. }
  600. public function DoCheckToWrite()
  601. {
  602. parent::DoCheckToWrite();
  603. // Check that there is at least one reconciliation key defined
  604. if ($this->Get('reconciliation_policy') == 'use_attributes')
  605. {
  606. $oSet = $this->Get('attribute_list');
  607. $oSynchroAttributeList = $oSet->ToArray();
  608. $bReconciliationKey = false;
  609. foreach($oSynchroAttributeList as $oSynchroAttribute)
  610. {
  611. if ($oSynchroAttribute->Get('reconcile') == 1)
  612. {
  613. $bReconciliationKey = true; // At least one key is defined
  614. break;
  615. }
  616. }
  617. if (!$bReconciliationKey)
  618. {
  619. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:AtLeastOneReconciliationKeyMustBeSpecified');
  620. }
  621. }
  622. // If 'update_then_delete' is specified there must be a delete_retention_period
  623. if (($this->Get('delete_policy') == 'update_then_delete') && ($this->Get('delete_policy_retention') == 0))
  624. {
  625. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeleteRetentionDurationMustBeSpecified');
  626. }
  627. // If update is specified, then something to update must be defined
  628. if ((($this->Get('delete_policy') == 'update_then_delete') || ($this->Get('delete_policy') == 'update'))
  629. && ($this->Get('delete_policy_update') == ''))
  630. {
  631. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeletePolicyUpdateMustBeSpecified');
  632. }
  633. // When creating the data source with a specified database_table_name, this table must NOT exist
  634. if ($this->IsNew())
  635. {
  636. $sDataTable = $this->GetDataTable();
  637. if (!empty($sDataTable) && CMDBSource::IsTable($this->GetDataTable()))
  638. {
  639. // Hmm, the synchro_data_xxx table already exists !!
  640. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DataTableAlreadyExists', $this->GetDataTable());
  641. }
  642. }
  643. }
  644. public function GetTargetClass()
  645. {
  646. return $this->Get('scope_class');
  647. }
  648. public function GetDataTable()
  649. {
  650. $sTable = $this->Get('database_table_name');
  651. if (empty($sTable))
  652. {
  653. $sTable = $this->ComputeDataTableName();
  654. }
  655. return $sTable;
  656. }
  657. protected function ComputeDataTableName()
  658. {
  659. $sDBTableName = $this->Get('database_table_name');
  660. if (empty($sDBTableName))
  661. {
  662. $sDBTableName = strtolower($this->GetTargetClass());
  663. $sDBTableName = preg_replace('/[^A-za-z0-9_]/', '_', $sDBTableName); // Remove forbidden characters from the table name
  664. $sDBTableName .= '_'.$this->GetKey(); // Add a suffix for unicity
  665. }
  666. else
  667. {
  668. $sDBTableName = preg_replace('/[^A-za-z0-9_]/', '_', $sDBTableName); // Remove forbidden characters from the table name
  669. }
  670. $sPrefix = MetaModel::GetConfig()->GetDBSubName()."synchro_data_";
  671. if (strpos($sDBTableName, $sPrefix) !== 0)
  672. {
  673. $sDBTableName = $sPrefix.$sDBTableName;
  674. }
  675. return $sDBTableName;
  676. }
  677. /**
  678. * When the new datasource has been created, let's create the synchro_data table
  679. * that will hold the data records and the correspoding triggers which will maintain
  680. * both tables in sync
  681. */
  682. protected function AfterInsert()
  683. {
  684. parent::AfterInsert();
  685. $sTable = $this->GetDataTable();
  686. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  687. $aColumns = $this->GetSQLColumns();
  688. $aFieldDefs = array();
  689. // Allow '0', otherwise mysql will render an error when the id is not given
  690. // (the trigger is expected to set the value, but it is not executed soon enough)
  691. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  692. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  693. foreach($aColumns as $sColumn => $ColSpec)
  694. {
  695. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  696. }
  697. $aFieldDefs[] = "INDEX (id)";
  698. $aFieldDefs[] = "INDEX (primary_key)";
  699. $sFieldDefs = implode(', ', $aFieldDefs);
  700. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
  701. CMDBSource::Query($sCreateTable);
  702. $aTriggers = $this->GetTriggersDefinition();
  703. foreach($aTriggers as $key => $sTriggerSQL)
  704. {
  705. CMDBSource::Query($sTriggerSQL);
  706. }
  707. }
  708. /**
  709. * Gets the definitions of the 3 triggers: before insert, before update and after delete
  710. * @return array An array with 3 entries, one for each of the SQL queries
  711. */
  712. protected function GetTriggersDefinition()
  713. {
  714. $sTable = $this->GetDataTable();
  715. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  716. $aColumns = $this->GetSQLColumns();
  717. $aResult = array();
  718. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON `$sTable`";
  719. $sTriggerInsert .= " FOR EACH ROW";
  720. $sTriggerInsert .= " BEGIN";
  721. $sTriggerInsert .= " INSERT INTO `{$sReplicaTable}` (`sync_source_id`, `status_last_seen`, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  722. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  723. $sTriggerInsert .= " END;";
  724. $aResult['bi'] = $sTriggerInsert;
  725. $aModified = array();
  726. foreach($aColumns as $sColumn => $ColSpec)
  727. {
  728. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  729. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  730. }
  731. $sIsModified = '('.implode(') OR (', $aModified).')';
  732. // Update the replica
  733. //
  734. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  735. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  736. // otherwise, the status is left as is
  737. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON `$sTable`";
  738. $sTriggerUpdate .= " FOR EACH ROW";
  739. $sTriggerUpdate .= " BEGIN";
  740. $sTriggerUpdate .= " IF @itopuser is null THEN";
  741. $sTriggerUpdate .= " UPDATE `{$sReplicaTable}` 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;";
  742. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  743. $sTriggerUpdate .= " END IF;";
  744. $sTriggerUpdate .= " END;";
  745. $aResult['bu'] = $sTriggerUpdate;
  746. $sTriggerDelete = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON `$sTable`";
  747. $sTriggerDelete .= " FOR EACH ROW";
  748. $sTriggerDelete .= " BEGIN";
  749. $sTriggerDelete .= " DELETE FROM `{$sReplicaTable}` WHERE id = OLD.id;";
  750. $sTriggerDelete .= " END;";
  751. $aResult['ad'] = $sTriggerDelete;
  752. return $aResult;
  753. }
  754. protected function AfterDelete()
  755. {
  756. parent::AfterDelete();
  757. $sTable = $this->GetDataTable();
  758. $sDropTable = "DROP TABLE `$sTable`";
  759. CMDBSource::Query($sDropTable);
  760. // TO DO - check that triggers get dropped with the table
  761. }
  762. /**
  763. * Checks if the data source definition is consistent with the schema of the target class
  764. * @param $bDiagnostics boolean True to only diagnose the consistency, false to actually apply some changes
  765. * @param $bVerbose boolean True to get some information in the std output (echo)
  766. * @return bool Whether or not the database needs fixing for this data source
  767. */
  768. public function CheckDBConsistency($bDiagnostics, $bVerbose, $oChange = null)
  769. {
  770. $bFixNeeded = false;
  771. $aMissingFields = array();
  772. $oAttributeSet = $this->Get('attribute_list');
  773. $aAttributes = array();
  774. while($oAttribute = $oAttributeSet->Fetch())
  775. {
  776. $sAttCode = $oAttribute->Get('attcode');
  777. if (MetaModel::IsValidAttCode($this->GetTargetClass(), $sAttCode))
  778. {
  779. $aAttributes[$sAttCode] = $oAttribute;
  780. }
  781. else
  782. {
  783. // Old field remaining
  784. if ($bVerbose)
  785. {
  786. echo "Irrelevant field description for the field '$sAttCode', for the data synchro task ".$this->GetName()." (".$this->GetKey()."), will be removed.\n";
  787. }
  788. $bFixNeeded = true;
  789. if (!$bDiagnostics)
  790. {
  791. if ($oChange == null)
  792. {
  793. $oChange = MetaModel::NewObject("CMDBChange");
  794. $oChange->Set("date", time());
  795. $sUserString = CMDBChange::GetCurrentUserName();
  796. $oChange->Set("userinfo", $sUserString);
  797. $oChange->DBInsert();
  798. }
  799. // Fix the issue
  800. $oAttribute->DBDeleteTracked($oChange);
  801. }
  802. }
  803. }
  804. $sTable = $this->GetDataTable();
  805. foreach($this->ListTargetAttributes() as $sAttCode=>$oAttDef)
  806. {
  807. if (!isset($aAttributes[$sAttCode]))
  808. {
  809. $bFixNeeded = true;
  810. $aMissingFields[] = $sAttCode;
  811. // New field missing...
  812. if ($bVerbose)
  813. {
  814. echo "Missing field description for the field '$sAttCode', for the data synchro task ".$this->GetName()." (".$this->GetKey()."), will be created with default values.\n";
  815. }
  816. if (!$bDiagnostics)
  817. {
  818. if ($oChange == null)
  819. {
  820. $oChange = MetaModel::NewObject("CMDBChange");
  821. $oChange->Set("date", time());
  822. $sUserString = CMDBChange::GetCurrentUserName();
  823. $oChange->Set("userinfo", $sUserString);
  824. $oChange->DBInsert();
  825. }
  826. // Fix the issue
  827. $oAttribute = $this->CreateSynchroAtt($sAttCode);
  828. $oAttribute->DBInsertTracked($oChange);
  829. }
  830. }
  831. else
  832. {
  833. $aColumns = $this->GetSQLColumns(array($sAttCode));
  834. foreach($aColumns as $sColName => $sColumnDef)
  835. {
  836. $bOneColIsMissing = false;
  837. if (!CMDBSource::IsField($sTable, $sColName))
  838. {
  839. $bFixNeeded = true;
  840. $bOneColIsMissing = true;
  841. if ($bVerbose)
  842. {
  843. if (count($aColumns) > 1)
  844. {
  845. echo "Missing column '$sColName', in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The columns '".implode("', '", $aColumns )." will be re-created.'.\n";
  846. }
  847. else
  848. {
  849. echo "Missing column '$sColName', in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The column '$sColName' will be added.\n";
  850. }
  851. }
  852. }
  853. else if (strcasecmp(CMDBSource::GetFieldType($sTable, $sColName), $sColumnDef) != 0)
  854. {
  855. $bFixNeeded = true;
  856. $bOneColIsMissing = true;
  857. if (count($aColumns) > 1)
  858. {
  859. echo "Incorrect column '$sColName' (".CMDBSource::GetFieldType($sTable, $sColName)." instead of ".$sColumnDef."), in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The columns '".implode("', '", $aColumns )." will be re-created.'.\n";
  860. }
  861. else
  862. {
  863. echo "Incorrect column '$sColName' (".CMDBSource::GetFieldType($sTable, $sColName)." instead of ".$sColumnDef."), in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The column '$sColName' will be added.\n";
  864. }
  865. }
  866. if ($bOneColIsMissing)
  867. {
  868. $aMissingFields[] = $sAttCode;
  869. }
  870. }
  871. }
  872. }
  873. if ($bFixNeeded && (count($aMissingFields) > 0))
  874. {
  875. $aRepairQueries = array();
  876. // The structure of the table needs adjusting
  877. $aColumns = $this->GetSQLColumns($aMissingFields);
  878. $aFieldDefs = array();
  879. foreach($aColumns as $sAttCode => $sColumnDef)
  880. {
  881. if (CMDBSource::IsField($sTable, $sAttCode))
  882. {
  883. $aRepairQueries[] = "ALTER TABLE `$sTable` CHANGE `$sAttCode` `$sAttCode` $sColumnDef";
  884. }
  885. else
  886. {
  887. $aFieldDefs[] = "`$sAttCode` $sColumnDef";
  888. }
  889. }
  890. if (count($aFieldDefs) > 0)
  891. {
  892. $aRepairQueries[] = "ALTER TABLE `$sTable` ADD (".implode(',', $aFieldDefs).");";
  893. }
  894. // The triggers as well must be adjusted
  895. $aTriggersDefs = $this->GetTriggersDefinition();
  896. $aRepairQueries[] = "DROP TRIGGER IF EXISTS `{$sTable}_bi`;";
  897. $aRepairQueries[] = $aTriggersDefs['bi'];
  898. $aRepairQueries[] = "DROP TRIGGER IF EXISTS `{$sTable}_bu`;";
  899. $aRepairQueries[] = $aTriggersDefs['bu'];
  900. $aRepairQueries[] = "DROP TRIGGER IF EXISTS `{$sTable}_ad`;";
  901. $aRepairQueries[] = $aTriggersDefs['ad'];
  902. if ($bDiagnostics)
  903. {
  904. if ($bVerbose)
  905. {
  906. // Report the issue
  907. echo "The structure of the table $sTable for the data synchro task ".$this->GetName()." (".$this->GetKey().") must be altered (missing or incorrect fields: ".implode(',', $aMissingFields).").\n";
  908. echo "The trigger {$sTable}_bi, {$sTable}_bu, {$sTable}_ad for the data synchro task ".$this->GetName()." (".$this->GetKey().") must be re-created.\n";
  909. echo implode("\n", $aRepairQueries)."\n";
  910. }
  911. }
  912. else
  913. {
  914. // Fix the issue
  915. foreach($aRepairQueries as $sSQL)
  916. {
  917. CMDBSource::Query($sSQL);
  918. if ($bVerbose)
  919. {
  920. echo "$sSQL\n";
  921. }
  922. }
  923. }
  924. }
  925. return $bFixNeeded;
  926. }
  927. public function SendNotification($sSubject, $sBody)
  928. {
  929. $iContact = $this->Get('notify_contact_id');
  930. if ($iContact == 0)
  931. {
  932. // Leave silently...
  933. return;
  934. }
  935. $oContact = MetaModel::GetObject('Contact', $iContact);
  936. // Determine the email attribute (the first one will be our choice)
  937. $sEmailAttCode = null;
  938. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  939. {
  940. if ($oAttDef instanceof AttributeEmailAddress)
  941. {
  942. $sEmailAttCode = $sAttCode;
  943. // we've got one, exit the loop
  944. break;
  945. }
  946. }
  947. if (is_null($sEmailAttCode))
  948. {
  949. // Leave silently...
  950. return;
  951. }
  952. $sTo = $oContact->Get($sEmailAttCode);
  953. $sFrom = $sTo;
  954. $sBody = '<p>Data synchronization: '.$this->GetHyperlink().'</p>'.$sBody;
  955. $sSubject = 'iTop Data Sync - '.$this->GetName().' - '.$sSubject;
  956. $oEmail = new Email();
  957. $oEmail->SetRecipientTO($sTo);
  958. $oEmail->SetRecipientFrom($sFrom);
  959. $oEmail->SetSubject($sSubject);
  960. $oEmail->SetBody($sBody);
  961. if ($oEmail->Send($aIssues) == EMAIL_SEND_ERROR)
  962. {
  963. // mmmm, what can I do?
  964. }
  965. }
  966. /**
  967. * Get the list of attributes eligible to the synchronization
  968. */
  969. public function ListTargetAttributes()
  970. {
  971. $aRet = array();
  972. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode => $oAttDef)
  973. {
  974. if ($sAttCode == 'finalclass') continue;
  975. if (!$oAttDef->IsWritable()) continue;
  976. if ($oAttDef->IsLinkSet() && !$oAttDef->IsIndirect()) continue;
  977. $aRet[$sAttCode] = $oAttDef;
  978. }
  979. return $aRet;
  980. }
  981. /**
  982. * Get the list of SQL columns corresponding to a particular list of attribute codes
  983. * Defaults to the whole list of columns for the current class
  984. */
  985. public function GetSQLColumns($aAttributeCodes = null)
  986. {
  987. $aColumns = array();
  988. $sClass = $this->GetTargetClass();
  989. if (is_null($aAttributeCodes))
  990. {
  991. $aAttributeCodes = array();
  992. foreach($this->ListTargetAttributes() as $sAttCode => $oAttDef)
  993. {
  994. $aAttributeCodes[] = $sAttCode;
  995. }
  996. }
  997. foreach($aAttributeCodes as $sAttCode)
  998. {
  999. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1000. if ($oAttDef->IsExternalKey())
  1001. {
  1002. // The pkey might be used as well as any other key column
  1003. $aColumns[$sAttCode] = 'VARCHAR(255)';
  1004. }
  1005. else
  1006. {
  1007. foreach($oAttDef->GetImportColumns() as $sField => $sDBFieldType)
  1008. {
  1009. $aColumns[$sField] = $sDBFieldType;
  1010. }
  1011. }
  1012. }
  1013. return $aColumns;
  1014. }
  1015. /**
  1016. * Get the list of Date and Datetime SQL columns
  1017. */
  1018. public function GetDateSQLColumns()
  1019. {
  1020. $aDateAttributes = array();
  1021. $sClass = $this->GetTargetClass();
  1022. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1023. {
  1024. if ($oAttDef instanceof AttributeDateTime)
  1025. {
  1026. $aDateAttributes[] = $sAttCode;
  1027. }
  1028. }
  1029. return $this->GetSQLColumns($aDateAttributes);
  1030. }
  1031. public function IsRunning()
  1032. {
  1033. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  1034. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1035. if ($oSet->Count() < 1)
  1036. {
  1037. $bRet = false;
  1038. }
  1039. else
  1040. {
  1041. $bRet = true;
  1042. }
  1043. return $bRet;
  1044. }
  1045. public function GetLatestLog()
  1046. {
  1047. $oLog = null;
  1048. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  1049. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1050. if ($oSet->Count() >= 1)
  1051. {
  1052. $oLog = $oSet->Fetch();
  1053. }
  1054. return $oLog;
  1055. }
  1056. // TO DO: remove if still unused
  1057. /**
  1058. * Retrieve from the log, the date of the last completed import
  1059. * @return DateTime
  1060. */
  1061. public function GetLastCompletedImportDate()
  1062. {
  1063. $date = null;
  1064. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  1065. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  1066. if ($oSet->Count() >= 1)
  1067. {
  1068. $oLog = $oSet->Fetch();
  1069. $date = $oLog->Get('end_date');
  1070. }
  1071. return $date;
  1072. }
  1073. }
  1074. class SynchroAttribute extends cmdbAbstractObject
  1075. {
  1076. public static function Init()
  1077. {
  1078. $aParams = array
  1079. (
  1080. "category" => "core/cmdb,view_in_gui",
  1081. "key_type" => "autoincrement",
  1082. "name_attcode" => "attcode",
  1083. "state_attcode" => "",
  1084. "reconc_keys" => array(),
  1085. "db_table" => "priv_sync_att",
  1086. "db_key_field" => "id",
  1087. "db_finalclass_field" => "",
  1088. "display_template" => "",
  1089. );
  1090. MetaModel::Init_Params($aParams);
  1091. MetaModel::Init_InheritAttributes();
  1092. 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())));
  1093. MetaModel::Init_AddAttribute(new AttributeExternalField("sync_source_name", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"name")));
  1094. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  1095. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  1096. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  1097. 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())));
  1098. // Display lists
  1099. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  1100. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1101. // Search criteria
  1102. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1103. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1104. }
  1105. }
  1106. class SynchroAttExtKey extends SynchroAttribute
  1107. {
  1108. public static function Init()
  1109. {
  1110. $aParams = array
  1111. (
  1112. "category" => "core/cmdb,view_in_gui",
  1113. "key_type" => "autoincrement",
  1114. "name_attcode" => "attcode",
  1115. "state_attcode" => "",
  1116. "reconc_keys" => array(),
  1117. "db_table" => "priv_sync_att_extkey",
  1118. "db_key_field" => "id",
  1119. "db_finalclass_field" => "",
  1120. "display_template" => "",
  1121. );
  1122. MetaModel::Init_Params($aParams);
  1123. MetaModel::Init_InheritAttributes();
  1124. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1125. // Display lists
  1126. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  1127. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1128. // Search criteria
  1129. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1130. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1131. }
  1132. public function GetReconciliationFormElement($sTargetClass, $sFieldName)
  1133. {
  1134. $sHtml = "<select name=\"$sFieldName\">\n";
  1135. $sSelected = (''== $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1136. $sHtml .= "<option value=\"\" $sSelected>".Dict::S('Core:SynchroAttExtKey:ReconciliationById')."</option>\n";
  1137. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  1138. {
  1139. if ($oAttDef->IsScalar())
  1140. {
  1141. $sSelected = ($sAttCode == $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1142. $sHtml .= "<option value=\"$sAttCode\" $sSelected>".MetaModel::GetLabel($sTargetClass, $sAttCode)."</option>\n";
  1143. }
  1144. }
  1145. $sHtml .= "</select>\n";
  1146. return $sHtml;
  1147. }
  1148. }
  1149. class SynchroAttLinkSet extends SynchroAttribute
  1150. {
  1151. public static function Init()
  1152. {
  1153. $aParams = array
  1154. (
  1155. "category" => "core/cmdb,view_in_gui",
  1156. "key_type" => "autoincrement",
  1157. "name_attcode" => "attcode",
  1158. "state_attcode" => "",
  1159. "reconc_keys" => array(),
  1160. "db_table" => "priv_sync_att_linkset",
  1161. "db_key_field" => "id",
  1162. "db_finalclass_field" => "",
  1163. "display_template" => "",
  1164. );
  1165. MetaModel::Init_Params($aParams);
  1166. MetaModel::Init_InheritAttributes();
  1167. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  1168. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  1169. MetaModel::Init_AddAttribute(new AttributeString("value_separator", array("allowed_values"=>null, "sql"=>"value_separator", "default_value"=>':', "is_null_allowed"=>true, "depends_on"=>array())));
  1170. MetaModel::Init_AddAttribute(new AttributeString("attribute_qualifier", array("allowed_values"=>null, "sql"=>"attribute_qualifier", "default_value"=>'\'', "is_null_allowed"=>true, "depends_on"=>array())));
  1171. // Display lists
  1172. 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
  1173. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1174. // Search criteria
  1175. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1176. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1177. }
  1178. }
  1179. //class SynchroLog extends Event
  1180. class SynchroLog extends DBObject
  1181. {
  1182. public static function Init()
  1183. {
  1184. $aParams = array
  1185. (
  1186. "category" => "core/cmdb,view_in_gui",
  1187. "key_type" => "autoincrement",
  1188. "name_attcode" => "",
  1189. "state_attcode" => "",
  1190. "reconc_keys" => array(),
  1191. "db_table" => "priv_sync_log",
  1192. "db_key_field" => "id",
  1193. "db_finalclass_field" => "",
  1194. "display_template" => "",
  1195. );
  1196. MetaModel::Init_Params($aParams);
  1197. MetaModel::Init_InheritAttributes();
  1198. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1199. 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())));
  1200. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1201. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1202. 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())));
  1203. MetaModel::Init_AddAttribute(new AttributeInteger("status_curr_job", array("allowed_values"=>null, "sql"=>"status_curr_job", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1204. MetaModel::Init_AddAttribute(new AttributeInteger("status_curr_pos", array("allowed_values"=>null, "sql"=>"status_curr_pos", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1205. 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())));
  1206. 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())));
  1207. 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())));
  1208. 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())));
  1209. 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())));
  1210. 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())));
  1211. 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())));
  1212. 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())));
  1213. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1214. 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())));
  1215. 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())));
  1216. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1217. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_unchanged_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_unchanged_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1218. // 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())));
  1219. 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())));
  1220. 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())));
  1221. 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())));
  1222. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_updated_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_updated_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1223. 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())));
  1224. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_unchanged_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_unchanged_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1225. MetaModel::Init_AddAttribute(new AttributeText("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1226. MetaModel::Init_AddAttribute(new AttributeLongText("traces", array("allowed_values"=>null, "sql"=>"traces", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1227. MetaModel::Init_AddAttribute(new AttributeInteger("memory_usage_peak", array("allowed_values"=>null, "sql"=>"memory_usage_peak", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1228. // Display lists
  1229. 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',
  1230. '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
  1231. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  1232. // Search criteria
  1233. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1234. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1235. }
  1236. /**
  1237. * Helper
  1238. */
  1239. function GetErrorCount()
  1240. {
  1241. return $this->Get('stats_nb_obj_deleted_errors')
  1242. + $this->Get('stats_nb_obj_obsoleted_errors')
  1243. + $this->Get('stats_nb_obj_created_errors')
  1244. + $this->Get('stats_nb_obj_updated_errors')
  1245. + $this->Get('stats_nb_replica_reconciled_errors');
  1246. }
  1247. /**
  1248. * Increments a statistics counter
  1249. */
  1250. function Inc($sCode)
  1251. {
  1252. $this->Set($sCode, 1+$this->Get($sCode));
  1253. }
  1254. /**
  1255. * Implement traces management
  1256. */
  1257. protected $m_aTraces = array();
  1258. public function AddTrace($sMsg, $oReplica = null)
  1259. {
  1260. if (MetaModel::GetConfig()->Get('synchro_trace') == 'none')
  1261. {
  1262. return;
  1263. }
  1264. if ($oReplica)
  1265. {
  1266. $sDestClass = $oReplica->Get('dest_class');
  1267. if (!empty($sDestClass))
  1268. {
  1269. $sPrefix = $oReplica->GetKey().','.$sDestClass.'::'.$oReplica->Get('dest_id').',';
  1270. }
  1271. else
  1272. {
  1273. $sPrefix = $oReplica->GetKey().',,';
  1274. }
  1275. }
  1276. else
  1277. {
  1278. $sPrefix = ',,';
  1279. }
  1280. $this->m_aTraces[] = $sPrefix.$sMsg;
  1281. }
  1282. public function GetTraces()
  1283. {
  1284. return $this->m_aTraces;
  1285. }
  1286. protected function TraceToText()
  1287. {
  1288. if (MetaModel::GetConfig()->Get('synchro_trace') != 'save')
  1289. {
  1290. // none, or display only
  1291. return;
  1292. }
  1293. $sPrevTrace = $this->Get('traces');
  1294. $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'traces');
  1295. $iMaxSize = $oAttDef->GetMaxSize();
  1296. if (strlen($sPrevTrace) > 0)
  1297. {
  1298. $sTrace = $sPrevTrace."\n".implode("\n", $this->m_aTraces);
  1299. }
  1300. else
  1301. {
  1302. $sTrace = implode("\n", $this->m_aTraces);
  1303. }
  1304. if (strlen($sTrace) >= $iMaxSize)
  1305. {
  1306. $sTrace = substr($sTrace, 0, $iMaxSize - 255)."...\nTruncated (size: ".strlen($sTrace).')';
  1307. }
  1308. $this->Set('traces', $sTrace);
  1309. //DBUpdate may be called many times... the operation should not be repeated
  1310. $this->m_aTraces = array();
  1311. }
  1312. protected function OnInsert()
  1313. {
  1314. $this->TraceToText();
  1315. parent::OnInsert();
  1316. }
  1317. protected function OnUpdate()
  1318. {
  1319. $this->TraceToText();
  1320. $sMemPeak = max($this->Get('memory_usage_peak'), ExecutionKPI::memory_get_peak_usage());
  1321. $this->Set('memory_usage_peak', $sMemPeak);
  1322. parent::OnUpdate();
  1323. }
  1324. }
  1325. class SynchroReplica extends DBObject implements iDisplay
  1326. {
  1327. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  1328. protected $aWarnings;
  1329. public static function Init()
  1330. {
  1331. $aParams = array
  1332. (
  1333. "category" => "core/cmdb,view_in_gui",
  1334. "key_type" => "autoincrement",
  1335. "name_attcode" => "",
  1336. "state_attcode" => "",
  1337. "reconc_keys" => array(),
  1338. "db_table" => "priv_sync_replica",
  1339. "db_key_field" => "id",
  1340. "db_finalclass_field" => "",
  1341. "display_template" => "",
  1342. );
  1343. MetaModel::Init_Params($aParams);
  1344. MetaModel::Init_InheritAttributes();
  1345. 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())));
  1346. MetaModel::Init_AddAttribute(new AttributeExternalField("base_class", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"scope_class")));
  1347. MetaModel::Init_AddAttribute(new AttributeInteger("dest_id", array("allowed_values"=>null, "sql"=>"dest_id", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1348. 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())));
  1349. 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())));
  1350. 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())));
  1351. 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())));
  1352. 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())));
  1353. MetaModel::Init_AddAttribute(new AttributeString("status_last_warning", array("allowed_values"=>null, "sql"=>"status_last_warning", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1354. 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())));
  1355. 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())));
  1356. // Display lists
  1357. MetaModel::Init_SetZListItems('details', array('' .
  1358. 'col:0'=> array(
  1359. 'fieldset:SynchroDataSource:Definition' => array('sync_source_id','dest_id','dest_class'),
  1360. 'fieldset:SynchroDataSource:Status' => array('status','status_last_seen','status_dest_creator','status_last_error','status_last_warning'),
  1361. 'fieldset:SynchroDataSource:Information' => array('info_creation_date','info_last_modified'))
  1362. )
  1363. );
  1364. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error', 'status_last_warning')); // Attributes to be displayed for a list
  1365. // Search criteria
  1366. MetaModel::Init_SetZListItems('standard_search', array('sync_source_id', 'status_last_seen', 'status', 'status_dest_creator', 'dest_class', 'dest_id', 'status_last_error', 'status_last_warning')); // Criteria of the std search form
  1367. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1368. }
  1369. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  1370. {
  1371. parent::__construct($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  1372. $this->aWarnings = array();
  1373. }
  1374. protected function AddWarning($sWarningMessage)
  1375. {
  1376. $this->aWarnings[] = $sWarningMessage;
  1377. }
  1378. protected function ResetWarnings()
  1379. {
  1380. $this->aWarnings = array();
  1381. }
  1382. protected function HasWarnings()
  1383. {
  1384. return (count($this->aWarnings) > 0);
  1385. }
  1386. protected function RecordWarnings()
  1387. {
  1388. $sWarningMessage = '';
  1389. $MAX_WARNING_LENGTH = 255;
  1390. switch(count($this->aWarnings))
  1391. {
  1392. case 0:
  1393. $sWarningMessage = '';
  1394. break;
  1395. case 1:
  1396. $sWarningMessage = $this->aWarnings[0];
  1397. break;
  1398. default:
  1399. $sWarningMessage = count($this->aWarnings)." warnings: ".implode(' ', $this->aWarnings);
  1400. break;
  1401. }
  1402. if (strlen($sWarningMessage) > $MAX_WARNING_LENGTH)
  1403. {
  1404. $sWarningMessage = substr($sWarningMessage, 0, $MAX_WARNING_LENGTH - 3).'...';
  1405. }
  1406. $this->Set('status_last_warning', $sWarningMessage);
  1407. }
  1408. public function DBInsert()
  1409. {
  1410. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  1411. }
  1412. // Overload the deletion -> the replica has been created by the mean of a trigger,
  1413. // it will be deleted by the mean of a trigger too
  1414. protected function DBDeleteSingleObject()
  1415. {
  1416. $this->OnDelete();
  1417. if (!MetaModel::DBIsReadOnly())
  1418. {
  1419. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'), false);
  1420. if ($oDataSource)
  1421. {
  1422. $sTable = $oDataSource->GetDataTable();
  1423. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  1424. CMDBSource::Query($sSQL);
  1425. }
  1426. // else the whole datasource has probably been already deleted
  1427. }
  1428. $this->AfterDelete();
  1429. $this->m_bIsInDB = false;
  1430. $this->m_iKey = null;
  1431. }
  1432. public function SetLastError($sMessage, $oException = null)
  1433. {
  1434. if ($oException)
  1435. {
  1436. $sText = $sMessage.$oException->getMessage();
  1437. }
  1438. else
  1439. {
  1440. $sText = $sMessage;
  1441. }
  1442. if (strlen($sText) > 255)
  1443. {
  1444. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  1445. }
  1446. $this->Set('status_last_error', $sText);
  1447. }
  1448. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog)
  1449. {
  1450. $this->ResetWarnings();
  1451. switch($this->Get('status'))
  1452. {
  1453. case 'new':
  1454. $this->Set('status_dest_creator', false);
  1455. // If needed, construct the query used for the reconciliation
  1456. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  1457. {
  1458. $aCriterias = array();
  1459. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1460. {
  1461. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  1462. }
  1463. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  1464. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  1465. }
  1466. // Get the criterias for the search
  1467. $aFilterValues = array();
  1468. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1469. {
  1470. $value = $this->GetValueFromExtData($sFilterCode, $oSyncAtt, $oStatLog);
  1471. if (!is_null($value))
  1472. {
  1473. $aFilterValues[$sFilterCode] = $value;
  1474. }
  1475. else
  1476. {
  1477. // TO DO: can we retry this ??
  1478. // Reconciliation could not be performed - log and EXIT
  1479. $oStatLog->AddTrace("Could not reconcile on null value for attribute '$sFilterCode'", $this);
  1480. $this->SetLastError("Could not reconcile on null value for attribute '$sFilterCode'");
  1481. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1482. return;
  1483. }
  1484. }
  1485. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  1486. $iCount = $oDestSet->Count();
  1487. $aConditions = array();
  1488. foreach($aFilterValues as $sCode => $sValue)
  1489. {
  1490. $aConditions[] = $sCode.'='.$sValue;
  1491. }
  1492. $sConditionDesc = implode(' AND ', $aConditions);
  1493. // How many objects match the reconciliation criterias
  1494. switch($iCount)
  1495. {
  1496. case 0:
  1497. $oStatLog->AddTrace("Nothing found on: $sConditionDesc", $this);
  1498. if ($oDataSource->Get('action_on_zero') == 'create')
  1499. {
  1500. $bCreated = $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1501. if ($bCreated)
  1502. {
  1503. if ($this->HasWarnings())
  1504. {
  1505. $oStatLog->Inc('stats_nb_obj_created_warnings');
  1506. }
  1507. }
  1508. else
  1509. {
  1510. // Creation error has precedence over any warning
  1511. $this->ResetWarnings();
  1512. }
  1513. }
  1514. else // assumed to be 'error'
  1515. {
  1516. $oStatLog->AddTrace("Failed to reconcile (no match)", $this);
  1517. // Recoverable error
  1518. $this->SetLastError('Could not find a match for reconciliation');
  1519. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1520. }
  1521. break;
  1522. case 1:
  1523. $oStatLog->AddTrace("Found 1 object on: $sConditionDesc", $this);
  1524. if ($oDataSource->Get('action_on_one') == 'update')
  1525. {
  1526. $oDestObj = $oDestSet->Fetch();
  1527. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1528. $this->Set('dest_id', $oDestObj->GetKey());
  1529. $this->Set('dest_class', get_class($oDestObj));
  1530. if ($this->HasWarnings())
  1531. {
  1532. if ($bModified)
  1533. {
  1534. $oStatLog->Inc('stats_nb_obj_new_updated_warnings');
  1535. }
  1536. else
  1537. {
  1538. $oStatLog->Inc('stats_nb_obj_new_unchanged_warnings');
  1539. }
  1540. }
  1541. }
  1542. else
  1543. {
  1544. // assumed to be 'error'
  1545. $oStatLog->AddTrace("Failed to reconcile (1 match)", $this);
  1546. // Recoverable error
  1547. $this->SetLastError('Found a match while expecting several');
  1548. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1549. }
  1550. break;
  1551. default:
  1552. $oStatLog->AddTrace("Found $iCount objects on: $sConditionDesc", $this);
  1553. if ($oDataSource->Get('action_on_multiple') == 'error')
  1554. {
  1555. $oStatLog->AddTrace("Failed to reconcile (N>1 matches)", $this);
  1556. // Recoverable error
  1557. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  1558. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1559. }
  1560. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  1561. {
  1562. $bCreated = $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1563. if ($bCreated)
  1564. {
  1565. if ($this->HasWarnings())
  1566. {
  1567. $oStatLog->Inc('stats_nb_obj_created_warnings');
  1568. }
  1569. }
  1570. else
  1571. {
  1572. // Creation error has precedence over any warning
  1573. $this->ResetWarnings();
  1574. }
  1575. }
  1576. else
  1577. {
  1578. // assumed to be 'take_first'
  1579. $oDestObj = $oDestSet->Fetch();
  1580. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1581. $this->Set('dest_id', $oDestObj->GetKey());
  1582. $this->Set('dest_class', get_class($oDestObj));
  1583. if ($this->HasWarnings())
  1584. {
  1585. if ($bModified)
  1586. {
  1587. $oStatLog->Inc('stats_nb_obj_new_updated_warnings');
  1588. }
  1589. else
  1590. {
  1591. $oStatLog->Inc('stats_nb_obj_new_unchanged_warnings');
  1592. }
  1593. }
  1594. }
  1595. }
  1596. $this->RecordWarnings();
  1597. break;
  1598. case 'synchronized': // try to recover synchronized replicas with warnings
  1599. case 'modified':
  1600. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  1601. if ($oDestObj == null)
  1602. {
  1603. $this->Set('status', 'orphan'); // The destination object has been deleted !
  1604. $this->SetLastError('Destination object deleted unexpectedly');
  1605. $oStatLog->Inc('stats_nb_obj_updated_errors');
  1606. }
  1607. else
  1608. {
  1609. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj', 'stats_nb_obj_updated_errors');
  1610. if ($this->HasWarnings())
  1611. {
  1612. if ($bModified)
  1613. {
  1614. $oStatLog->Inc('stats_nb_obj_updated_warnings');
  1615. }
  1616. else
  1617. {
  1618. $oStatLog->Inc('stats_nb_obj_unchanged_warnings');
  1619. }
  1620. }
  1621. }
  1622. $this->RecordWarnings();
  1623. break;
  1624. default: // Do nothing in all other cases
  1625. }
  1626. }
  1627. /**
  1628. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  1629. */
  1630. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, $sStatsCode, $sStatsCodeError)
  1631. {
  1632. $aValueTrace = array();
  1633. $bModified = false;
  1634. try
  1635. {
  1636. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1637. {
  1638. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1639. if (!is_null($value))
  1640. {
  1641. if ($oSyncAtt->Get('update_policy') == 'write_if_empty')
  1642. {
  1643. $oAttDef = MetaModel::GetAttributeDef(get_class($oDestObj), $sAttCode);
  1644. if ($oAttDef->IsNull($oDestObj->Get($sAttCode)))
  1645. {
  1646. // The value is still "empty" in the target object, we are allowed to write the new value
  1647. $oDestObj->Set($sAttCode, $value);
  1648. $aValueTrace[] = "$sAttCode: $value";
  1649. }
  1650. }
  1651. else
  1652. {
  1653. $oDestObj->Set($sAttCode, $value);
  1654. $aValueTrace[] = "$sAttCode: $value";
  1655. }
  1656. }
  1657. }
  1658. // Really modified ?
  1659. if ($oDestObj->IsModified())
  1660. {
  1661. $oDestObj->DBUpdateTracked($oChange);
  1662. $bModified = true;
  1663. $oStatLog->AddTrace('Updated object - Values: {'.implode(', ', $aValueTrace).'}', $this);
  1664. if (($sStatsCode != '') &&(MetaModel::IsValidAttCode(get_class($oStatLog), $sStatsCode.'_updated')))
  1665. {
  1666. $oStatLog->Inc($sStatsCode.'_updated');
  1667. }
  1668. $this->Set('info_last_modified', date('Y-m-d H:i:s'));
  1669. }
  1670. else
  1671. {
  1672. $oStatLog->AddTrace('Unchanged object', $this);
  1673. if (($sStatsCode != '') &&(MetaModel::IsValidAttCode(get_class($oStatLog), $sStatsCode.'_unchanged')))
  1674. {
  1675. $oStatLog->Inc($sStatsCode.'_unchanged');
  1676. }
  1677. }
  1678. $this->Set('status_last_error', '');
  1679. $this->Set('status', 'synchronized');
  1680. }
  1681. catch(Exception $e)
  1682. {
  1683. $oStatLog->AddTrace("Failed to update destination object: {$e->getMessage()}", $this);
  1684. $this->SetLastError('Unable to update destination object: ', $e);
  1685. $oStatLog->Inc($sStatsCodeError);
  1686. }
  1687. return $bModified;
  1688. }
  1689. /**
  1690. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1691. * @return bool Whether or not the object was created
  1692. */
  1693. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog)
  1694. {
  1695. $bCreated = false;
  1696. $oDestObj = MetaModel::NewObject($sClass);
  1697. try
  1698. {
  1699. $aValueTrace = array();
  1700. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1701. {
  1702. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1703. if (!is_null($value))
  1704. {
  1705. $oDestObj->Set($sAttCode, $value);
  1706. $aValueTrace[] = "$sAttCode: $value";
  1707. }
  1708. }
  1709. $iNew = $oDestObj->DBInsertTracked($oChange);
  1710. $this->Set('dest_id', $oDestObj->GetKey());
  1711. $this->Set('dest_class', get_class($oDestObj));
  1712. $this->Set('status_dest_creator', true);
  1713. $this->Set('status_last_error', '');
  1714. $this->Set('status', 'synchronized');
  1715. $this->Set('info_creation_date', date('Y-m-d H:i:s'));
  1716. $bCreated = true;
  1717. $oStatLog->AddTrace("Created (".implode(', ', $aValueTrace).")", $this);
  1718. $oStatLog->Inc('stats_nb_obj_created');
  1719. }
  1720. catch(Exception $e)
  1721. {
  1722. $oStatLog->AddTrace("Failed to create $sClass ({$e->getMessage()})", $this);
  1723. $this->SetLastError('Unable to create destination object: ', $e);
  1724. $oStatLog->Inc('stats_nb_obj_created_errors');
  1725. }
  1726. return $bCreated;
  1727. }
  1728. /**
  1729. * Update the destination object with given values
  1730. */
  1731. public function UpdateDestObject($aValues, $oChange, &$oStatLog)
  1732. {
  1733. try
  1734. {
  1735. if ($this->Get('dest_class') == '')
  1736. {
  1737. $this->SetLastError('No destination object to update');
  1738. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1739. }
  1740. else
  1741. {
  1742. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1743. foreach($aValues as $sAttCode => $value)
  1744. {
  1745. if (!MetaModel::IsValidAttCode(get_class($oDestObj), $sAttCode))
  1746. {
  1747. throw new Exception("Unknown attribute code '$sAttCode'");
  1748. }
  1749. $oDestObj->Set($sAttCode, $value);
  1750. }
  1751. $this->Set('info_last_modified', date('Y-m-d H:i:s'));
  1752. $oDestObj->DBUpdateTracked($oChange);
  1753. $oStatLog->AddTrace("Replica marked as obsolete", $this);
  1754. $oStatLog->Inc('stats_nb_obj_obsoleted');
  1755. }
  1756. }
  1757. catch(Exception $e)
  1758. {
  1759. $this->SetLastError('Unable to update the destination object: ', $e);
  1760. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1761. }
  1762. }
  1763. /**
  1764. * Delete the destination object
  1765. */
  1766. public function DeleteDestObject($oChange, &$oStatLog)
  1767. {
  1768. if($this->Get('status_dest_creator'))
  1769. {
  1770. try
  1771. {
  1772. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1773. $oCheckDeletionPlan = new DeletionPlan();
  1774. if ($oDestObj->CheckToDelete($oCheckDeletionPlan))
  1775. {
  1776. $oActualDeletionPlan = new DeletionPlan();
  1777. $oDestObj->DBDeleteTracked($oChange, null, $oActualDeletionPlan);
  1778. $this->DBDeleteTracked($oChange);
  1779. $oStatLog->Inc('stats_nb_obj_deleted');
  1780. }
  1781. else
  1782. {
  1783. $sIssues = implode("\n", $oCheckDeletionPlan->GetIssues());
  1784. throw(new Exception($sIssues));
  1785. }
  1786. }
  1787. catch(Exception $e)
  1788. {
  1789. $this->SetLastError('Unable to delete the destination object: ', $e);
  1790. $this->Set('status', 'obsolete');
  1791. $this->DBUpdateTracked($oChange);
  1792. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1793. }
  1794. }
  1795. else
  1796. {
  1797. $this->DBDeleteTracked($oChange);
  1798. $oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  1799. }
  1800. }
  1801. /**
  1802. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1803. * Note: sExtAttCode could be a standard attcode, or 'primary_key'
  1804. */
  1805. protected function GetValueFromExtData($sExtAttCode, $oSyncAtt, &$oStatLog)
  1806. {
  1807. // $aData should contain attributes defined either for reconciliation or create/update
  1808. $aData = $this->GetExtendedData();
  1809. if ($sExtAttCode == 'primary_key')
  1810. {
  1811. return $aData['primary_key'];
  1812. }
  1813. // $sExtAttCode is a valid attribute code
  1814. //
  1815. $sClass = $this->Get('base_class');
  1816. $oAttDef = MetaModel::GetAttributeDef($sClass, $sExtAttCode);
  1817. if (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttExtKey))
  1818. {
  1819. $rawValue = $aData[$sExtAttCode];
  1820. if (is_null($rawValue))
  1821. {
  1822. // Null means "ignore" this attribute
  1823. return null;
  1824. }
  1825. $sReconcAttCode = $oSyncAtt->Get('reconciliation_attcode');
  1826. if (!empty($sReconcAttCode))
  1827. {
  1828. $sRemoteClass = $oAttDef->GetTargetClass();
  1829. $oObj = MetaModel::GetObjectByColumn($sRemoteClass, $sReconcAttCode, $rawValue, false);
  1830. if ($oObj)
  1831. {
  1832. $retValue = $oObj->GetKey();
  1833. }
  1834. else
  1835. {
  1836. if ($rawValue != '')
  1837. {
  1838. // Note: differs from null (in which case the value would be left unchanged)
  1839. $oStatLog->AddTrace("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'", $this);
  1840. $this->AddWarning("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'");
  1841. }
  1842. $retValue = 0;
  1843. }
  1844. }
  1845. else
  1846. {
  1847. $retValue = $rawValue;
  1848. }
  1849. }
  1850. elseif (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttLinkSet))
  1851. {
  1852. $rawValue = $aData[$sExtAttCode];
  1853. if (is_null($rawValue))
  1854. {
  1855. // Null means "ignore" this attribute
  1856. return null;
  1857. }
  1858. // MakeValueFromString() throws an exception in case of failure
  1859. $bLocalizedValue = false;
  1860. $retValue = $oAttDef->MakeValueFromString($rawValue, $bLocalizedValue, $oSyncAtt->Get('row_separator'), $oSyncAtt->Get('attribute_separator'), $oSyncAtt->Get('value_separator'), $oSyncAtt->Get('attribute_qualifier'));
  1861. }
  1862. else
  1863. {
  1864. $aColumns = $oAttDef->GetImportColumns();
  1865. foreach($aColumns as $sColumn => $sFormat)
  1866. {
  1867. // In any case, a null column means "ignore this attribute"
  1868. //
  1869. if (is_null($aData[$sColumn]))
  1870. {
  1871. return null;
  1872. }
  1873. }
  1874. $retValue = $oAttDef->FromImportToValue($aData, $sExtAttCode);
  1875. }
  1876. return $retValue;
  1877. }
  1878. /**
  1879. * Maps the given context parameter name to the appropriate filter/search code for this class
  1880. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  1881. * @return string Filter code, i.e. 'customer_id'
  1882. */
  1883. public static function MapContextParam($sContextParam)
  1884. {
  1885. if ($sContextParam == 'menu')
  1886. {
  1887. return null;
  1888. }
  1889. else
  1890. {
  1891. return $sContextParam;
  1892. }
  1893. }
  1894. /**
  1895. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1896. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1897. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1898. * To Be overridden by derived classes
  1899. * @param void
  1900. * @return String The desired higlight class for the object/row
  1901. */
  1902. public function GetHilightClass()
  1903. {
  1904. // Possible return values are:
  1905. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1906. return HILIGHT_CLASS_NONE; // Not hilighted by default
  1907. }
  1908. public static function GetUIPage()
  1909. {
  1910. return '../synchro/replica.php';
  1911. }
  1912. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  1913. {
  1914. // Object's details
  1915. //$this->DisplayBareHeader($oPage, $bEditMode);
  1916. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  1917. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1918. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1919. $this->DisplayBareProperties($oPage, $bEditMode);
  1920. }
  1921. function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  1922. {
  1923. if ($bEditMode) return; // Not editable
  1924. $oPage->add('<table style="vertical-align:top"><tr style="vertical-align:top"><td>');
  1925. $aDetails = array();
  1926. $sClass = get_class($this);
  1927. $oPage->add('<fieldset>');
  1928. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PrivateDetails').'</legend>');
  1929. $aZList = MetaModel::FlattenZlist(MetaModel::GetZListItems($sClass, 'details'));
  1930. foreach( $aZList as $sAttCode)
  1931. {
  1932. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1933. $aDetails[] = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1934. }
  1935. $oPage->Details($aDetails);
  1936. $oPage->add('</fieldset>');
  1937. if (strlen($this->Get('dest_class')) > 0)
  1938. {
  1939. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'), false);
  1940. if (is_object($oDestObj))
  1941. {
  1942. $oPage->add('<fieldset>');
  1943. $oPage->add('<legend>'.Dict::Format('Core:SynchroReplica:TargetObject', $oDestObj->GetHyperlink()).'</legend>');
  1944. $oDestObj->DisplayBareProperties($oPage, false, $sPrefix, $aExtraParams);
  1945. $oPage->add('<fieldset>');
  1946. }
  1947. }
  1948. $oPage->add('</td><td>');
  1949. $oPage->add('<fieldset>');
  1950. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PublicData').'</legend>');
  1951. $oSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  1952. $sSQLTable = $oSource->GetDataTable();
  1953. $aData = $this->LoadExtendedDataFromTable($sSQLTable);
  1954. $aHeaders = array('attcode' => array('label' => 'Attribute Code', 'description' => ''),
  1955. 'data' => array('label' => 'Value', 'description' => ''));
  1956. $aRows = array();
  1957. foreach($aData as $sKey => $value)
  1958. {
  1959. $aRows[] = array('attcode' => $sKey, 'data' => $value);
  1960. }
  1961. $oPage->Table($aHeaders, $aRows);
  1962. $oPage->add('</fieldset>');
  1963. $oPage->add('</td></tr></table>');
  1964. }
  1965. public function LoadExtendedDataFromTable($sSQLTable)
  1966. {
  1967. $sSQL = "SELECT * FROM $sSQLTable WHERE id=".$this->GetKey();
  1968. $rQuery = CMDBSource::Query($sSQL);
  1969. return CMDBSource::FetchArray($rQuery);
  1970. }
  1971. }
  1972. /**
  1973. * Context of an ongoing synchronization
  1974. * Two usages:
  1975. * 1) Public usage: execute the synchronization
  1976. * $oSynchroExec = new SynchroExecution($oDataSource[, $iLastFullLoad]);
  1977. * $oSynchroExec->Process($iMaxChunkSize);
  1978. *
  1979. * 2) Internal usage: continue the synchronization (split into chunks, each performed in a separate process)
  1980. * This is implemented in the page priv_sync_chunk.php
  1981. * $oSynchroExec = SynchroExecution::Resume($oDataSource, $iLastFullLoad, $iSynchroLog, $iChange, $iMaxToProcess, $iJob, $iNextInJob);
  1982. * $oSynchroExec->Process()
  1983. */
  1984. class SynchroExecution
  1985. {
  1986. protected $m_oDataSource = null;
  1987. protected $m_oLastFullLoadStartDate = null;
  1988. protected $m_oChange = null;
  1989. protected $m_oStatLog = null;
  1990. // Context computed one for optimization and report inconsistencies ASAP
  1991. protected $m_aExtDataSpec = array();
  1992. protected $m_aReconciliationKeys = array();
  1993. protected $m_aAttributes = array();
  1994. protected $m_iCountAllReplicas = 0;
  1995. /**
  1996. * Constructor
  1997. * @param SynchroDataSource $oDataSource Synchronization task
  1998. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  1999. * @return void
  2000. */
  2001. public function __construct($oDataSource, $oLastFullLoadStartDate = null)
  2002. {
  2003. $this->m_oDataSource = $oDataSource;
  2004. $this->m_oLastFullLoadStartDate = $oLastFullLoadStartDate;
  2005. }
  2006. /**
  2007. * Create the persistant information records, for the current synchronization
  2008. * In fact, those records ARE defining what is the "current" synchronization
  2009. */
  2010. protected function PrepareLogs()
  2011. {
  2012. if (!is_null($this->m_oChange))
  2013. {
  2014. return;
  2015. }
  2016. // Create a change used for logging all the modifications/creations happening during the synchro
  2017. $this->m_oChange = MetaModel::NewObject("CMDBChange");
  2018. $this->m_oChange->Set("date", time());
  2019. $sUserString = CMDBChange::GetCurrentUserName();
  2020. $this->m_oChange->Set("userinfo", $sUserString.' '.Dict::S('Core:SyncDataExchangeComment'));
  2021. $iChangeId = $this->m_oChange->DBInsert();
  2022. // Start logging this execution (stats + protection against reentrance)
  2023. //
  2024. $this->m_oStatLog = new SynchroLog();
  2025. $this->m_oStatLog->Set('sync_source_id', $this->m_oDataSource->GetKey());
  2026. $this->m_oStatLog->Set('start_date', time());
  2027. $this->m_oStatLog->Set('status', 'running');
  2028. $this->m_oStatLog->Set('stats_nb_replica_seen', 0);
  2029. $this->m_oStatLog->Set('stats_nb_replica_total', 0);
  2030. $this->m_oStatLog->Set('stats_nb_obj_deleted', 0);
  2031. $this->m_oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  2032. $this->m_oStatLog->Set('stats_nb_obj_obsoleted', 0);
  2033. $this->m_oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  2034. $this->m_oStatLog->Set('stats_nb_obj_created', 0);
  2035. $this->m_oStatLog->Set('stats_nb_obj_created_errors', 0);
  2036. $this->m_oStatLog->Set('stats_nb_obj_created_warnings', 0);
  2037. $this->m_oStatLog->Set('stats_nb_obj_updated', 0);
  2038. $this->m_oStatLog->Set('stats_nb_obj_updated_warnings', 0);
  2039. $this->m_oStatLog->Set('stats_nb_obj_updated_errors', 0);
  2040. $this->m_oStatLog->Set('stats_nb_obj_unchanged_warnings', 0);
  2041. // $this->m_oStatLog->Set('stats_nb_replica_reconciled', 0);
  2042. $this->m_oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  2043. $this->m_oStatLog->Set('stats_nb_replica_disappeared_no_action', 0);
  2044. $this->m_oStatLog->Set('stats_nb_obj_new_updated', 0);
  2045. $this->m_oStatLog->Set('stats_nb_obj_new_updated_warnings', 0);
  2046. $this->m_oStatLog->Set('stats_nb_obj_new_unchanged',0);
  2047. $this->m_oStatLog->Set('stats_nb_obj_new_unchanged_warnings',0);
  2048. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  2049. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey()));
  2050. $this->m_iCountAllReplicas = $oSetTotal->Count();
  2051. $this->m_oStatLog->Set('stats_nb_replica_total', $this->m_iCountAllReplicas);
  2052. $this->m_oStatLog->DBInsertTracked($this->m_oChange);
  2053. }
  2054. /**
  2055. * Prevent against the reentrance... or allow the current task to do things forbidden by the others !
  2056. */
  2057. public static $m_oCurrentTask = null;
  2058. public static function GetCurrentTaskId()
  2059. {
  2060. if (is_object(self::$m_oCurrentTask))
  2061. {
  2062. return self::$m_oCurrentTask->GetKey();
  2063. }
  2064. else
  2065. {
  2066. return null;
  2067. }
  2068. }
  2069. /**
  2070. * Prepare structures in memory, to speedup the processing of a given replica
  2071. */
  2072. public function PrepareProcessing($bFirstPass = true)
  2073. {
  2074. if ($this->m_oDataSource->Get('status') == 'obsolete')
  2075. {
  2076. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
  2077. }
  2078. if (!UserRights::IsAdministrator() && $this->m_oDataSource->Get('user_id') != UserRights::GetUserId())
  2079. {
  2080. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
  2081. }
  2082. // Get the list of SQL columns
  2083. $sClass = $this->m_oDataSource->GetTargetClass();
  2084. $aAttCodesExpected = array();
  2085. $aAttCodesToReconcile = array();
  2086. $aAttCodesToUpdate = array();
  2087. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
  2088. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey()) /* aArgs */);
  2089. while ($oSyncAtt = $oSetAtt->Fetch())
  2090. {
  2091. if ($oSyncAtt->Get('update'))
  2092. {
  2093. $aAttCodesToUpdate[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2094. }
  2095. if ($oSyncAtt->Get('reconcile'))
  2096. {
  2097. $aAttCodesToReconcile[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2098. }
  2099. $aAttCodesExpected[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2100. }
  2101. $aColumns = $this->m_oDataSource->GetSQLColumns(array_keys($aAttCodesExpected));
  2102. $aExtDataFields = array_keys($aColumns);
  2103. $aExtDataFields[] = 'primary_key';
  2104. $this->m_aExtDataSpec = array(
  2105. 'table' => $this->m_oDataSource->GetDataTable(),
  2106. 'join_key' => 'id',
  2107. 'fields' => $aExtDataFields
  2108. );
  2109. // Get the list of attributes, determine reconciliation keys and update targets
  2110. //
  2111. if ($this->m_oDataSource->Get('reconciliation_policy') == 'use_attributes')
  2112. {
  2113. $this->m_aReconciliationKeys = $aAttCodesToReconcile;
  2114. }
  2115. elseif ($this->m_oDataSource->Get('reconciliation_policy') == 'use_primary_key')
  2116. {
  2117. // Override the settings made at the attribute level !
  2118. $this->m_aReconciliationKeys = array("primary_key" => null);
  2119. }
  2120. if ($bFirstPass)
  2121. {
  2122. $this->m_oStatLog->AddTrace("Update of: {".implode(', ', array_keys($aAttCodesToUpdate))."}");
  2123. $this->m_oStatLog->AddTrace("Reconciliation on: {".implode(', ', array_keys($this->m_aReconciliationKeys))."}");
  2124. }
  2125. if (count($aAttCodesToUpdate) == 0)
  2126. {
  2127. $this->m_oStatLog->AddTrace("No attribute to update");
  2128. throw new SynchroExceptionNotStarted('There is no attribute to update');
  2129. }
  2130. if (count($this->m_aReconciliationKeys) == 0)
  2131. {
  2132. $this->m_oStatLog->AddTrace("No attribute for reconciliation");
  2133. throw new SynchroExceptionNotStarted('No attribute for reconciliation');
  2134. }
  2135. $this->m_aAttributes = array();
  2136. foreach($aAttCodesToUpdate as $sAttCode => $oSyncAtt)
  2137. {
  2138. $oAttDef = MetaModel::GetAttributeDef($this->m_oDataSource->GetTargetClass(), $sAttCode);
  2139. if ($oAttDef->IsWritable())
  2140. {
  2141. $this->m_aAttributes[$sAttCode] = $oSyncAtt;
  2142. }
  2143. }
  2144. // Compute and keep track of the limit date taken into account for obsoleting replicas
  2145. //
  2146. if ($this->m_oLastFullLoadStartDate == null)
  2147. {
  2148. // No previous import known, use the full_load_periodicity value... and the current date
  2149. $this->m_oLastFullLoadStartDate = new DateTime(); // Now
  2150. $iLoadPeriodicity = $this->m_oDataSource->Get('full_load_periodicity'); // Duration in seconds
  2151. if ($iLoadPeriodicity > 0)
  2152. {
  2153. $sInterval = "-$iLoadPeriodicity seconds";
  2154. $this->m_oLastFullLoadStartDate->Modify($sInterval);
  2155. }
  2156. else
  2157. {
  2158. $this->m_oLastFullLoadStartDate = new DateTime('1970-01-01');
  2159. }
  2160. }
  2161. if ($bFirstPass)
  2162. {
  2163. $this->m_oStatLog->AddTrace("Limit Date: ".$this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s'));
  2164. }
  2165. }
  2166. /**
  2167. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  2168. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  2169. * is used to determine which records are obsolete.
  2170. * @return void
  2171. */
  2172. public function Process()
  2173. {
  2174. $this->PrepareLogs();
  2175. self::$m_oCurrentTask = $this->m_oDataSource;
  2176. try
  2177. {
  2178. $this->DoSynchronize();
  2179. $this->m_oStatLog->Set('end_date', time());
  2180. $this->m_oStatLog->Set('status', 'completed');
  2181. $this->m_oStatLog->DBUpdateTracked($this->m_oChange);
  2182. $iErrors = $this->m_oStatLog->GetErrorCount();
  2183. if ($iErrors > 0)
  2184. {
  2185. $sIssuesOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->m_oDataSource->GetKey()." AND status_last_error!=''";
  2186. $sAbsoluteUrl = utils::GetAbsoluteUrlAppRoot();
  2187. $sIssuesURL = "{$sAbsoluteUrl}synchro/replica.php?operation=oql&datasource=".$this->m_oDataSource->GetKey()."&oql=".urlencode($sIssuesOQL);
  2188. $sSeeIssues = "<p></p>";
  2189. $sStatistics = "<h1>Statistics</h1>\n";
  2190. $sStatistics .= "<ul>\n";
  2191. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('start_date').": ".$this->m_oStatLog->Get('start_date')."</li>\n";
  2192. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('end_date').": ".$this->m_oStatLog->Get('end_date')."</li>\n";
  2193. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_seen').": ".$this->m_oStatLog->Get('stats_nb_replica_seen')."</li>\n";
  2194. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_total').": ".$this->m_oStatLog->Get('stats_nb_replica_total')."</li>\n";
  2195. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_deleted').": ".$this->m_oStatLog->Get('stats_nb_obj_deleted')."</li>\n";
  2196. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_deleted_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_deleted_errors')."</li>\n";
  2197. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_obsoleted').": ".$this->m_oStatLog->Get('stats_nb_obj_obsoleted')."</li>\n";
  2198. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_obsoleted_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_obsoleted_errors')."</li>\n";
  2199. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_created').": ".$this->m_oStatLog->Get('stats_nb_obj_created')." (".$this->m_oStatLog->Get('stats_nb_obj_created_warnings')." warnings)"."</li>\n";
  2200. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_created_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_created_errors')."</li>\n";
  2201. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_updated').": ".$this->m_oStatLog->Get('stats_nb_obj_updated')." (".$this->m_oStatLog->Get('stats_nb_obj_updated_warnings')." warnings)"."</li>\n";
  2202. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_updated_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_updated_errors')."</li>\n";
  2203. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_reconciled_errors').": ".$this->m_oStatLog->Get('stats_nb_replica_reconciled_errors')."</li>\n";
  2204. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_disappeared_no_action').": ".$this->m_oStatLog->Get('stats_nb_replica_disappeared_no_action')."</li>\n";
  2205. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_new_updated').": ".$this->m_oStatLog->Get('stats_nb_obj_new_updated')." (".$this->m_oStatLog->Get('stats_nb_obj_new_updated_warnings')." warnings)"."</li>\n";
  2206. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_new_unchanged').": ".$this->m_oStatLog->Get('stats_nb_obj_new_unchanged')." (".$this->m_oStatLog->Get('stats_nb_obj_new_unchanged_warnings')." warnings)"."</li>\n";
  2207. $sStatistics .= "</ul>\n";
  2208. $this->m_oDataSource->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);
  2209. }
  2210. else
  2211. {
  2212. //$this->m_oDataSource->SendNotification('success', '<p>The synchronization has been successfully executed.</p>');
  2213. }
  2214. }
  2215. catch (SynchroExceptionNotStarted $e)
  2216. {
  2217. // Set information for reporting... but delete the object in DB
  2218. $this->m_oStatLog->Set('end_date', time());
  2219. $this->m_oStatLog->Set('status', 'error');
  2220. $this->m_oStatLog->Set('last_error', $e->getMessage());
  2221. $this->m_oStatLog->DBDeleteTracked($this->m_oChange);
  2222. $this->m_oDataSource->SendNotification('fatal error', '<p>The synchronization could not start: \''.$e->getMessage().'\'</p><p>Please check its configuration</p>');
  2223. }
  2224. catch (Exception $e)
  2225. {
  2226. $this->m_oStatLog->Set('end_date', time());
  2227. $this->m_oStatLog->Set('status', 'error');
  2228. $this->m_oStatLog->Set('last_error', $e->getMessage());
  2229. $this->m_oStatLog->DBUpdateTracked($this->m_oChange);
  2230. $this->m_oDataSource->SendNotification('exception', '<p>The synchronization has been interrupted: \''.$e->getMessage().'\'</p><p>Please contact the application support team</p>');
  2231. }
  2232. self::$m_oCurrentTask = null;
  2233. return $this->m_oStatLog;
  2234. }
  2235. /**
  2236. * Do the entire synchronization job
  2237. */
  2238. protected function DoSynchronize()
  2239. {
  2240. $this->m_oStatLog->Set('status_curr_job', 1);
  2241. $this->m_oStatLog->Set('status_curr_pos', -1);
  2242. $iMaxChunkSize = utils::ReadParam('max_chunk_size', 0, true /* allow CLI */);
  2243. if ($iMaxChunkSize > 0)
  2244. {
  2245. // Split the execution into several processes
  2246. // Each process will call DoSynchronizeChunk()
  2247. // The loop will end when a process does not reply "continue" on the last line of its output
  2248. if (!utils::IsModeCLI())
  2249. {
  2250. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncSplitModeCLIOnly'));
  2251. }
  2252. $aArguments = array();
  2253. $aArguments['source'] = $this->m_oDataSource->GetKey();
  2254. $aArguments['log'] = $this->m_oStatLog->GetKey();
  2255. $aArguments['change'] = $this->m_oChange->GetKey();
  2256. $aArguments['chunk'] = $iMaxChunkSize;
  2257. if ($this->m_oLastFullLoadStartDate)
  2258. {
  2259. $aArguments['last_full_load'] = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2260. }
  2261. else
  2262. {
  2263. $aArguments['last_full_load'] = '';
  2264. }
  2265. $this->m_oStatLog->DBUpdate($this->m_oChange);
  2266. $iStepCount = 0;
  2267. do
  2268. {
  2269. $aArguments['step_count'] = $iStepCount;
  2270. $iStepCount++;
  2271. list ($iRes, $aOut) = utils::ExecITopScript('synchro/priv_sync_chunk.php', $aArguments);
  2272. // Reload the log that has been modified by the processes
  2273. $this->m_oStatLog->Reload();
  2274. $sLastRes = strtolower(trim(end($aOut)));
  2275. switch($sLastRes)
  2276. {
  2277. case 'continue':
  2278. $bContinue = true;
  2279. break;
  2280. case 'finished':
  2281. $bContinue = false;
  2282. break;
  2283. default:
  2284. $this->m_oStatLog->AddTrace("The script did not reply with the expected keywords:");
  2285. $aIndentedOut = array();
  2286. foreach ($aOut as $sOut)
  2287. {
  2288. $aIndentedOut[] = "-> $sOut";
  2289. $this->m_oStatLog->AddTrace(">>> $sOut");
  2290. }
  2291. throw new Exception("Encountered an error in an underspinned process:\n".implode("\n", $aIndentedOut));
  2292. }
  2293. }
  2294. while ($bContinue);
  2295. }
  2296. else
  2297. {
  2298. $this->PrepareProcessing(/* first pass */);
  2299. $this->DoJob1();
  2300. $this->DoJob2();
  2301. $this->DoJob3();
  2302. }
  2303. }
  2304. /**
  2305. * Do the synchronization job, limited to some amount of work
  2306. * This verb has been designed to be called from within a separate process
  2307. * @return true if the process has to be continued
  2308. */
  2309. public function DoSynchronizeChunk($oLog, $oChange, $iMaxChunkSize)
  2310. {
  2311. // Initialize the structures...
  2312. self::$m_oCurrentTask = $this->m_oDataSource;
  2313. $this->m_oStatLog = $oLog;
  2314. $this->m_oChange = $oChange;
  2315. // Prepare internal structures (not the first pass)
  2316. $this->PrepareProcessing(false);
  2317. $iCurrJob = $this->m_oStatLog->Get('status_curr_job');
  2318. $iCurrPos = $this->m_oStatLog->Get('status_curr_pos');
  2319. $this->m_oStatLog->AddTrace("Synchronizing chunk - curr_job:$iCurrJob, curr_pos:$iCurrPos, max_chunk_size:$iMaxChunkSize");
  2320. $bContinue = false;
  2321. switch ($iCurrJob)
  2322. {
  2323. case 1:
  2324. default:
  2325. $this->DoJob1($iMaxChunkSize, $iCurrPos);
  2326. $bContinue = true;
  2327. break;
  2328. case 2:
  2329. $this->DoJob2($iMaxChunkSize, $iCurrPos);
  2330. $bContinue = true;
  2331. break;
  2332. case 3:
  2333. $bContinue = $this->DoJob3($iMaxChunkSize, $iCurrPos);
  2334. break;
  2335. }
  2336. $this->m_oStatLog->DBUpdate($this->m_oChange);
  2337. self::$m_oCurrentTask = null;
  2338. return $bContinue;
  2339. }
  2340. /**
  2341. * Do the synchronization job #1: Obsolete replica "untouched" for some time
  2342. * @param integer $iMaxReplica Limit the number of replicas to process
  2343. * @param integer $iCurrPos Current position where to resume the processing
  2344. * @return true if the process must be continued
  2345. */
  2346. protected function DoJob1($iMaxReplica = null, $iCurrPos = -1)
  2347. {
  2348. $sLimitDate = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2349. // Get all the replicas that were not seen in the last import and mark them as obsolete
  2350. $sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
  2351. if ($sDeletePolicy != 'ignore')
  2352. {
  2353. $sSelectToObsolete = "SELECT SynchroReplica WHERE id > :curr_pos AND sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  2354. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos));
  2355. $iCountScope = $oSetScope->Count();
  2356. if (($this->m_iCountAllReplicas > 10) && ($this->m_iCountAllReplicas == $iCountScope) && MetaModel::GetConfig()->Get('synchro_prevent_delete_all'))
  2357. {
  2358. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncTooManyMissingReplicas'));
  2359. }
  2360. if ($iMaxReplica)
  2361. {
  2362. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2363. // The replica have to be ordered by id
  2364. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos));
  2365. $oSetToProcess->SetLimit($iMaxReplica);
  2366. }
  2367. else
  2368. {
  2369. $oSetToProcess = $oSetScope;
  2370. }
  2371. $iLastReplicaProcessed = -1;
  2372. while($oReplica = $oSetToProcess->Fetch())
  2373. {
  2374. $iLastReplicaProcessed = $oReplica->GetKey();
  2375. switch ($sDeletePolicy)
  2376. {
  2377. case 'update':
  2378. case 'update_then_delete':
  2379. $this->m_oStatLog->AddTrace("Destination object to be updated", $oReplica);
  2380. $aToUpdate = array();
  2381. $aToUpdateSpec = explode(';', $this->m_oDataSource->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  2382. foreach($aToUpdateSpec as $sUpdateSpec)
  2383. {
  2384. $aUpdateSpec = explode(':', $sUpdateSpec);
  2385. if (count($aUpdateSpec) == 2)
  2386. {
  2387. $sAttCode = $aUpdateSpec[0];
  2388. $sValue = $aUpdateSpec[1];
  2389. $aToUpdate[$sAttCode] = $sValue;
  2390. }
  2391. }
  2392. $oReplica->Set('status_last_error', '');
  2393. if ($oReplica->Get('dest_id') == '')
  2394. {
  2395. $oReplica->Set('status', 'obsolete');
  2396. $this->m_oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  2397. }
  2398. else
  2399. {
  2400. $oReplica->UpdateDestObject($aToUpdate, $this->m_oChange, $this->m_oStatLog);
  2401. if ($oReplica->Get('status_last_error') == '')
  2402. {
  2403. // Change the status of the replica IIF
  2404. $oReplica->Set('status', 'obsolete');
  2405. }
  2406. }
  2407. $oReplica->DBUpdateTracked($this->m_oChange);
  2408. break;
  2409. case 'delete':
  2410. default:
  2411. $this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  2412. $oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
  2413. }
  2414. }
  2415. if ($iMaxReplica)
  2416. {
  2417. if ($iMaxReplica < $iCountScope)
  2418. {
  2419. // Continue with this job!
  2420. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2421. return true;
  2422. }
  2423. }
  2424. } // if ($sDeletePolicy != 'ignore'
  2425. //Count "seen" objects
  2426. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  2427. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate));
  2428. $this->m_oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  2429. // Job complete!
  2430. $this->m_oStatLog->Set('status_curr_job', 2);
  2431. $this->m_oStatLog->Set('status_curr_pos', -1);
  2432. return false;
  2433. }
  2434. /**
  2435. * Do the synchronization job #2: Create and modify object for new/modified replicas
  2436. * @param integer $iMaxReplica Limit the number of replicas to process
  2437. * @param integer $iCurrPos Current position where to resume the processing
  2438. * @return true if the process must be continued
  2439. */
  2440. protected function DoJob2($iMaxReplica = null, $iCurrPos = -1)
  2441. {
  2442. $sLimitDate = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2443. // Get all the replicas that are 'new' or modified or synchronized with a warning
  2444. //
  2445. $sSelectToSync = "SELECT SynchroReplica WHERE id > :curr_pos AND (status = 'new' OR status = 'modified' OR (status = 'synchronized' AND status_last_warning != '')) AND sync_source_id = :source_id AND status_last_seen >= :last_import";
  2446. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos), $this->m_aExtDataSpec);
  2447. $iCountScope = $oSetScope->Count();
  2448. if ($iMaxReplica)
  2449. {
  2450. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2451. // The replica have to be ordered by id
  2452. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos), $this->m_aExtDataSpec);
  2453. $oSetToProcess->SetLimit($iMaxReplica);
  2454. }
  2455. else
  2456. {
  2457. $oSetToProcess = $oSetScope;
  2458. }
  2459. $iLastReplicaProcessed = -1;
  2460. while($oReplica = $oSetToProcess->Fetch())
  2461. {
  2462. $iLastReplicaProcessed = $oReplica->GetKey();
  2463. $oReplica->Synchro($this->m_oDataSource, $this->m_aReconciliationKeys, $this->m_aAttributes, $this->m_oChange, $this->m_oStatLog);
  2464. $oReplica->DBUpdateTracked($this->m_oChange);
  2465. }
  2466. if ($iMaxReplica)
  2467. {
  2468. if ($iMaxReplica < $iCountScope)
  2469. {
  2470. // Continue with this job!
  2471. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2472. return true;
  2473. }
  2474. }
  2475. // Job complete!
  2476. $this->m_oStatLog->Set('status_curr_job', 3);
  2477. $this->m_oStatLog->Set('status_curr_pos', -1);
  2478. return false;
  2479. }
  2480. /**
  2481. * Do the synchronization job #3: Delete replica depending on the obsolescence scheme
  2482. * @param integer $iMaxReplica Limit the number of replicas to process
  2483. * @param integer $iCurrPos Current position where to resume the processing
  2484. * @return true if the process must be continued
  2485. */
  2486. protected function DoJob3($iMaxReplica = null, $iCurrPos = -1)
  2487. {
  2488. $sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
  2489. if ($sDeletePolicy != 'update_then_delete')
  2490. {
  2491. // Job complete!
  2492. $this->m_oStatLog->Set('status_curr_job', 0);
  2493. $this->m_oStatLog->Set('status_curr_pos', -1);
  2494. return false;
  2495. }
  2496. $bFirstPass = ($iCurrPos == -1);
  2497. // Get all the replicas that are to be deleted
  2498. //
  2499. $oDeletionDate = $this->m_oLastFullLoadStartDate;
  2500. $iDeleteRetention = $this->m_oDataSource->Get('delete_policy_retention'); // Duration in seconds
  2501. if ($iDeleteRetention > 0)
  2502. {
  2503. $sInterval = "-$iDeleteRetention seconds";
  2504. $oDeletionDate->Modify($sInterval);
  2505. }
  2506. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  2507. if ($bFirstPass)
  2508. {
  2509. $this->m_oStatLog->AddTrace("Deletion date: $sDeletionDate");
  2510. }
  2511. $sSelectToDelete = "SELECT SynchroReplica WHERE id > :curr_pos AND sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  2512. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
  2513. $iCountScope = $oSetScope->Count();
  2514. if ($iMaxReplica)
  2515. {
  2516. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2517. // The replica have to be ordered by id
  2518. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
  2519. $oSetToProcess->SetLimit($iMaxReplica);
  2520. }
  2521. else
  2522. {
  2523. $oSetToProcess = $oSetScope;
  2524. }
  2525. $iLastReplicaProcessed = -1;
  2526. while($oReplica = $oSetToProcess->Fetch())
  2527. {
  2528. $iLastReplicaProcessed = $oReplica->GetKey();
  2529. $this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  2530. $oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
  2531. }
  2532. if ($iMaxReplica)
  2533. {
  2534. if ($iMaxReplica < $iCountScope)
  2535. {
  2536. // Continue with this job!
  2537. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2538. return true;
  2539. }
  2540. }
  2541. // Job complete!
  2542. $this->m_oStatLog->Set('status_curr_job', 0);
  2543. $this->m_oStatLog->Set('status_curr_pos', -1);
  2544. return false;
  2545. }
  2546. }
  2547. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2548. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2549. // new OQLMenuNode('Replicas', 'SELECT SynchroReplica', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroReplica', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2550. // new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  2551. ?>