synchrodatasource.class.inc.php 120 KB

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