[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/modules/Migration/schema/ -> 540_to_600RC.php (source)

   1  <?php
   2  /*+********************************************************************************

   3   * The contents of this file are subject to the vtiger CRM Public License Version 1.0

   4   * ("License"); You may not use this file except in compliance with the License

   5   * The Original Code is:  vtiger CRM Open Source

   6   * The Initial Developer of the Original Code is vtiger.

   7   * Portions created by vtiger are Copyright (C) vtiger.

   8   * All Rights Reserved.

   9   *********************************************************************************/
  10  if (!defined('VTIGER_UPGRADE')) die('Invalid entry point');
  11  
  12  vimport('~~include/utils/utils.php');
  13  vimport('~~modules/com_vtiger_workflow/include.inc');
  14  vimport('~~modules/com_vtiger_workflow/tasks/VTEntityMethodTask.inc');
  15  vimport('~~modules/com_vtiger_workflow/VTEntityMethodManager.inc');
  16  vimport('~~include/Webservices/Utils.php');
  17  vimport('~~modules/Users/Users.php');
  18  
  19  if(defined('VTIGER_UPGRADE')) {
  20      //Collating all module package updates here

  21      updateVtlibModule('Import', 'packages/vtiger/mandatory/Import.zip');
  22      updateVtlibModule('MailManager', 'packages/vtiger/mandatory/MailManager.zip');
  23      updateVtlibModule('Mobile', 'packages/vtiger/mandatory/Mobile.zip');
  24      updateVtlibModule('ModTracker', 'packages/vtiger/mandatory/ModTracker.zip');
  25      updateVtlibModule('Services', "packages/vtiger/mandatory/Services.zip");
  26      updateVtlibModule('ServiceContracts', "packages/vtiger/mandatory/ServiceContracts.zip");
  27      updateVtlibModule('WSAPP', 'packages/vtiger/mandatory/WSAPP.zip');
  28      updateVtlibModule('Assets', 'packages/vtiger/optional/Assets.zip');
  29      updateVtlibModule('CustomerPortal', 'packages/vtiger/optional/CustomerPortal.zip');
  30      updateVtlibModule('ModComments', "packages/vtiger/optional/ModComments.zip");
  31      updateVtlibModule('Projects', "packages/vtiger/optional/Projects.zip");
  32      updateVtlibModule('RecycleBin', 'packages/vtiger/optional/RecycleBin.zip');
  33      updateVtlibModule('SMSNotifier', "packages/vtiger/optional/SMSNotifier.zip");
  34      updateVtlibModule("Webforms","packages/vtiger/optional/Webforms.zip");
  35      installVtlibModule('Google', 'packages/vtiger/optional/Google.zip');
  36      installVtlibModule('EmailTemplates', 'packages/vtiger/optional/EmailTemplates.zip');
  37  
  38      // updated language packs.

  39  
  40      updateVtlibModule('PT Brasil', 'packages/vtiger/optional/BrazilianLanguagePack_bz_bz.zip');
  41      updateVtlibModule('British English', 'packages/vtiger/optional/BritishLanguagePack_br_br.zip');
  42      updateVtlibModule('Dutch', 'packages/vtiger/optional/Dutch.zip');
  43      updateVtlibModule('Deutsch', 'packages/vtiger/optional/Deutsch.zip');
  44      updateVtlibModule('French', 'packages/vtiger/optional/French.zip');
  45      updateVtlibModule('Hungarian', 'packages/vtiger/optional/Hungarian.zip');
  46      updateVtlibModule('Mexican Spanish', 'packages/vtiger/optional/MexicanSpanishLanguagePack_es_mx.zip');
  47      updateVtlibModule('Spanish', 'packages/vtiger/optional/Spanish.zip');
  48      installVtlibModule('Italian', 'packages/vtiger/optional/ItalianLanguagePack_it_it.zip');
  49      installVtlibModule('RomanianLanguagePack_rm_rm', 'packages/vtiger/optional/RomanianLanguagePack_rm_rm.zip');
  50      installVtlibModule('Turkce', 'packages/vtiger/optional/TurkishLanguagePack_tr_tr.zip');
  51      installVtlibModule('Russian', 'packages/vtiger/optional/Russian.zip');
  52      installVtlibModule('Polish', 'packages/vtiger/optional/PolishLanguagePack_pl_pl.zip');
  53      installVtlibModule('Russian', 'packages/vtiger/optional/Russian.zip');
  54  }
  55  
  56  if(!defined('INSTALLATION_MODE')) {
  57      Migration_Index_View::ExecuteQuery('ALTER TABLE com_vtiger_workflows ADD COLUMN filtersavedinnew int(1)', array());
  58  }
  59  
  60  Migration_Index_View::ExecuteQuery('UPDATE com_vtiger_workflows SET filtersavedinnew = 5', array());
  61  
  62  // Core workflow schema dependecy introduced in 6.1.0

  63  $adb=PearDatabase::getInstance();
  64  $result = $adb->pquery("show columns from com_vtiger_workflows like ?", array('schtypeid'));
  65  if (!($adb->num_rows($result))) { $adb->pquery("ALTER TABLE com_vtiger_workflows ADD schtypeid INT(10)", array()); }
  66  $result = $adb->pquery("show columns from com_vtiger_workflows like ?", array('schtime'));
  67  if (!($adb->num_rows($result))) { $adb->pquery("ALTER TABLE com_vtiger_workflows ADD schtime TIME", array()); }
  68  $result = $adb->pquery("show columns from com_vtiger_workflows like ?", array('schdayofmonth'));
  69  if (!($adb->num_rows($result))) {$adb->pquery("ALTER TABLE com_vtiger_workflows ADD schdayofmonth VARCHAR(100)", array());}
  70  $result = $adb->pquery("show columns from com_vtiger_workflows like ?", array('schdayofweek'));
  71  if (!($adb->num_rows($result))) {$adb->pquery("ALTER TABLE com_vtiger_workflows ADD schdayofweek VARCHAR(100)", array());}
  72  $result = $adb->pquery("show columns from com_vtiger_workflows like ?", array('schannualdates'));
  73  if (!($adb->num_rows($result))) {$adb->pquery("ALTER TABLE com_vtiger_workflows ADD schannualdates VARCHAR(100)", array());}
  74  $result = $adb->pquery("show columns from com_vtiger_workflows like ?", array('nexttrigger_time'));
  75  if (!($adb->num_rows($result))) {$adb->pquery("ALTER TABLE com_vtiger_workflows ADD nexttrigger_time DATETIME", array());}
  76  
  77  if(!defined('INSTALLATION_MODE')) {
  78      Migration_Index_View::ExecuteQuery("CREATE TABLE IF NOT EXISTS com_vtiger_workflow_tasktypes (
  79                      id int(11) NOT NULL,
  80                      tasktypename varchar(255) NOT NULL,
  81                      label varchar(255),
  82                      classname varchar(255),
  83                      classpath varchar(255),
  84                      templatepath varchar(255),
  85                      modules text(500),
  86                      sourcemodule varchar(255)
  87              ) ENGINE=InnoDB DEFAULT CHARSET=utf8", array());
  88  
  89      $taskTypes = array();
  90      $defaultModules = array('include' => array(), 'exclude'=>array());
  91      $createToDoModules = array('include' => array("Leads","Accounts","Potentials","Contacts","HelpDesk","Campaigns","Quotes","PurchaseOrder","SalesOrder","Invoice"), 'exclude'=>array("Calendar", "FAQ", "Events"));
  92      $createEventModules = array('include' => array("Leads","Accounts","Potentials","Contacts","HelpDesk","Campaigns"), 'exclude'=>array("Calendar", "FAQ", "Events"));
  93  
  94      $taskTypes[] = array("name"=>"VTEmailTask", "label"=>"Send Mail", "classname"=>"VTEmailTask", "classpath"=>"modules/com_vtiger_workflow/tasks/VTEmailTask.inc", "templatepath"=>"com_vtiger_workflow/taskforms/VTEmailTask.tpl", "modules"=>$defaultModules, "sourcemodule"=>'');
  95      $taskTypes[] = array("name"=>"VTEntityMethodTask", "label"=>"Invoke Custom Function", "classname"=>"VTEntityMethodTask", "classpath"=>"modules/com_vtiger_workflow/tasks/VTEntityMethodTask.inc", "templatepath"=>"com_vtiger_workflow/taskforms/VTEntityMethodTask.tpl", "modules"=>$defaultModules, "sourcemodule"=>'');
  96      $taskTypes[] = array("name"=>"VTCreateTodoTask", "label"=>"Create Todo", "classname"=>"VTCreateTodoTask", "classpath"=>"modules/com_vtiger_workflow/tasks/VTCreateTodoTask.inc", "templatepath"=>"com_vtiger_workflow/taskforms/VTCreateTodoTask.tpl", "modules"=>$createToDoModules, "sourcemodule"=>'');
  97      $taskTypes[] = array("name"=>"VTCreateEventTask", "label"=>"Create Event", "classname"=>"VTCreateEventTask", "classpath"=>"modules/com_vtiger_workflow/tasks/VTCreateEventTask.inc", "templatepath"=>"com_vtiger_workflow/taskforms/VTCreateEventTask.tpl", "modules"=>$createEventModules, "sourcemodule"=>'');
  98      $taskTypes[] = array("name"=>"VTUpdateFieldsTask", "label"=>"Update Fields", "classname"=>"VTUpdateFieldsTask", "classpath"=>"modules/com_vtiger_workflow/tasks/VTUpdateFieldsTask.inc", "templatepath"=>"com_vtiger_workflow/taskforms/VTUpdateFieldsTask.tpl", "modules"=>$defaultModules, "sourcemodule"=>'');
  99      $taskTypes[] = array("name"=>"VTCreateEntityTask", "label"=>"Create Entity", "classname"=>"VTCreateEntityTask", "classpath"=>"modules/com_vtiger_workflow/tasks/VTCreateEntityTask.inc", "templatepath"=>"com_vtiger_workflow/taskforms/VTCreateEntityTask.tpl", "modules"=>$defaultModules, "sourcemodule"=>'');
 100      $taskTypes[] = array("name"=>"VTSMSTask", "label"=>"SMS Task", "classname"=>"VTSMSTask", "classpath"=>"modules/com_vtiger_workflow/tasks/VTSMSTask.inc", "templatepath"=>"com_vtiger_workflow/taskforms/VTSMSTask.tpl", "modules"=>$defaultModules, "sourcemodule"=>'SMSNotifier');
 101  
 102      foreach ($taskTypes as $taskType) {
 103          VTTaskType::registerTaskType($taskType);
 104      }
 105  }
 106  
 107  
 108  Migration_Index_View::ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_shorturls (
 109                      id int(11) NOT NULL AUTO_INCREMENT,
 110                      uid varchar(50) DEFAULT NULL,
 111                      handler_path varchar(400) DEFAULT NULL,
 112                      handler_class varchar(100) DEFAULT NULL,
 113                      handler_function varchar(100) DEFAULT NULL,
 114                      handler_data varchar(255) DEFAULT NULL,
 115                      PRIMARY KEY (id),
 116                      KEY uid (uid)
 117              ) ENGINE=InnoDB DEFAULT CHARSET=utf8", array());
 118  
 119  $moduleInstance = Vtiger_Module::getInstance('Potentials');
 120  $block = Vtiger_Block::getInstance('LBL_OPPORTUNITY_INFORMATION', $moduleInstance);
 121  
 122  $forecast_field = new Vtiger_Field();
 123  $forecast_field->name = 'forecast_amount';
 124  $forecast_field->label = 'Forecast Amount';
 125  $forecast_field->table ='vtiger_potential';
 126  $forecast_field->column = 'forecast_amount';
 127  $forecast_field->columntype = 'decimal(25,4)';
 128  $forecast_field->typeofdata = 'N~O';
 129  $forecast_field->uitype = '71';
 130  $forecast_field->masseditable = '0';
 131  $block->addField($forecast_field);
 132  
 133  global $adb;
 134  $workflowManager = new VTWorkflowManager($adb);
 135  $taskManager = new VTTaskManager($adb);
 136  
 137  $potentailsWorkFlow = $workflowManager->newWorkFlow("Potentials");
 138  $potentailsWorkFlow->test = '';
 139  $potentailsWorkFlow->description = "Calculate or Update forecast amount";
 140  $potentailsWorkFlow->executionCondition = VTWorkflowManager::$ON_EVERY_SAVE;
 141  $potentailsWorkFlow->defaultworkflow = 1;
 142  $workflowManager->save($potentailsWorkFlow);
 143  
 144  $task = $taskManager->createTask('VTUpdateFieldsTask', $potentailsWorkFlow->id);
 145  $task->active = true;
 146  $task->summary = 'update forecast amount';
 147  $task->field_value_mapping = '[{"fieldname":"forecast_amount","valuetype":"expression","value":"amount * probability / 100"}]';
 148  $taskManager->saveTask($task);
 149  
 150  // Change default Sales Man rolename to Sales Person

 151  Migration_Index_View::ExecuteQuery("UPDATE vtiger_role SET rolename=? WHERE rolename=? and roleid=?", array('Sales Person', 'Sales Man', 'H5'));
 152  
 153  if(!defined('INSTALLATION_MODE')) {
 154      $picklistResult = $adb->pquery('SELECT distinct fieldname FROM vtiger_field WHERE uitype IN (15,33)', array());
 155      $numRows = $adb->num_rows($picklistResult);
 156      for($i=0; $i<$numRows; $i++) {
 157          $fieldName = $adb->query_result($picklistResult,$i,'fieldname');
 158          $query = 'ALTER TABLE vtiger_'.$fieldName.' ADD COLUMN sortorderid INT(1)';
 159          Migration_Index_View::ExecuteQuery($query, array());
 160      }
 161  }
 162  
 163  $invoiceModuleInstance = Vtiger_Module::getInstance('Invoice');
 164  $fieldInstance = Vtiger_Field::getInstance('invoicestatus', $invoiceModuleInstance);
 165  $fieldInstance->setPicklistValues( Array ('Cancel'));
 166  
 167  // Email Reporting - added default email reports.

 168  
 169  $sql = "INSERT INTO vtiger_reportfolder (FOLDERNAME,DESCRIPTION,STATE) VALUES(?,?,?)";
 170  $params = array('Email Reports', 'Email Reports', 'SAVED');
 171  Migration_Index_View::ExecuteQuery($sql, $params);
 172  
 173  $reportmodules = Array(
 174      Array('primarymodule' => 'Contacts', 'secondarymodule' => 'Emails'),
 175      Array('primarymodule' => 'Accounts', 'secondarymodule' => 'Emails'),
 176      Array('primarymodule' => 'Leads', 'secondarymodule' => 'Emails'),
 177      Array('primarymodule' => 'Vendors', 'secondarymodule' => 'Emails')
 178  );
 179  
 180  $reports = Array(
 181      Array('reportname' => 'Contacts Email Report',
 182          'reportfolder' => 'Email Reports',
 183          'description' => 'Emails sent to Contacts',
 184          'reporttype' => 'tabular',
 185          'sortid' => '', 'stdfilterid' => '', 'advfilterid' => '0'),
 186      Array('reportname' => 'Accounts Email Report',
 187          'reportfolder' => 'Email Reports',
 188          'description' => 'Emails sent to Organizations',
 189          'reporttype' => 'tabular',
 190          'sortid' => '', 'stdfilterid' => '', 'advfilterid' => '0'),
 191      Array('reportname' => 'Leads Email Report',
 192          'reportfolder' => 'Email Reports',
 193          'description' => 'Emails sent to Leads',
 194          'reporttype' => 'tabular',
 195          'sortid' => '', 'stdfilterid' => '', 'advfilterid' => '0'),
 196      Array('reportname' => 'Vendors Email Report',
 197          'reportfolder' => 'Email Reports',
 198          'description' => 'Emails sent to Vendors',
 199          'reporttype' => 'tabular',
 200          'sortid' => '', 'stdfilterid' => '', 'advfilterid' => '0')
 201  );
 202  
 203  $selectcolumns = Array(
 204      Array('vtiger_contactdetails:lastname:Contacts_Last_Name:lastname:V',
 205          'vtiger_contactdetails:email:Contacts_Email:email:E',
 206          'vtiger_activity:subject:Emails_Subject:subject:V',
 207          'vtiger_email_track:access_count:Emails_Access_Count:access_count:V'),
 208      Array('vtiger_account:accountname:Accounts_Account_Name:accountname:V',
 209          'vtiger_account:phone:Accounts_Phone:phone:V',
 210          'vtiger_account:email1:Accounts_Email:email1:E',
 211          'vtiger_activity:subject:Emails_Subject:subject:V',
 212          'vtiger_email_track:access_count:Emails_Access_Count:access_count:V'),
 213      Array('vtiger_leaddetails:lastname:Leads_Last_Name:lastname:V',
 214          'vtiger_leaddetails:company:Leads_Company:company:V',
 215          'vtiger_leaddetails:email:Leads_Email:email:E',
 216          'vtiger_activity:subject:Emails_Subject:subject:V',
 217          'vtiger_email_track:access_count:Emails_Access_Count:access_count:V'),
 218      Array('vtiger_vendor:vendorname:Vendors_Vendor_Name:vendorname:V',
 219          'vtiger_vendor:glacct:Vendors_GL_Account:glacct:V',
 220          'vtiger_vendor:email:Vendors_Email:email:E',
 221          'vtiger_activity:subject:Emails_Subject:subject:V',
 222          'vtiger_email_track:access_count:Emails_Access_Count:access_count:V'),
 223  );
 224  
 225  $advfilters = Array(
 226      Array(
 227          Array(
 228              'columnname' => 'vtiger_email_track:access_count:Emails_Access_Count:access_count:V',
 229              'comparator' => 'n',
 230              'value' => ''
 231          )
 232      )
 233  );
 234  
 235  foreach ($reports as $key => $report) {
 236      $queryid = Migration_Index_View::insertSelectQuery();
 237      $sql = 'SELECT MAX(folderid) AS count FROM vtiger_reportfolder';
 238      $result = $adb->query($sql);
 239      $folderid = $adb->query_result($result, 0, 'count');
 240      Migration_Index_View::insertReports($queryid, $folderid, $report['reportname'], $report['description'], $report['reporttype']);
 241      Migration_Index_View::insertSelectColumns($queryid, $selectcolumns[$key]);
 242      Migration_Index_View::insertReportModules($queryid, $reportmodules[$key]['primarymodule'], $reportmodules[$key]['secondarymodule']);
 243      if(isset($advfilters[$report['advfilterid']])) {
 244          Migration_Index_View::insertAdvFilter($queryid, $advfilters[$report['advfilterid']]);
 245      }
 246  }
 247  
 248  // TODO : need to review this after adding report sharing feature

 249  Migration_Index_View::ExecuteQuery("UPDATE vtiger_report SET sharingtype='Public'", array());
 250  //End.

 251  
 252  //Currency Decimal places handling

 253  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_account MODIFY COLUMN annualrevenue decimal(25,5)", array());
 254  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_leaddetails MODIFY COLUMN annualrevenue decimal(25,5)", array());
 255  Migration_Index_View::ExecuteQuery("UPDATE vtiger_field SET typeofdata='N~O' WHERE fieldlabel='Annual Revenue' and typeofdata='I~O'",array());
 256  
 257  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_currency_info MODIFY COLUMN conversion_rate decimal(12,5)", array());
 258  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_productcurrencyrel MODIFY COLUMN actual_price decimal(28,5)", array());
 259  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_productcurrencyrel MODIFY COLUMN converted_price decimal(28,5)", array());
 260  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_pricebookproductrel MODIFY COLUMN listprice decimal(27,5)", array());
 261  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_inventoryproductrel MODIFY COLUMN listprice decimal(27,5)", array());
 262  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_inventoryproductrel MODIFY COLUMN discount_amount decimal(27,5)", array());
 263  
 264  $currencyField = new CurrencyField($value);
 265  $result = $adb->pquery("SELECT fieldname,tablename,columnname FROM vtiger_field WHERE uitype IN (?,?)",array('71','72'));
 266  $count = $adb->num_rows($result);
 267  for($i=0;$i<$count;$i++) {
 268      $fieldName = $adb->query_result($result,$i,'fieldname');
 269      $tableName = $adb->query_result($result,$i,'tablename');
 270      $columnName = $adb->query_result($result,$i,'columnname');
 271  
 272      $tableAndColumnSize = array();
 273      $tableInfo = $adb->database->MetaColumns($tableName);
 274      foreach ($tableInfo as $column) {
 275          $max_length = $column->max_length;
 276          $scale = $column->scale;
 277  
 278          $tableAndColumnSize[$tableName][$column->name]['max_length'] = $max_length;
 279          $tableAndColumnSize[$tableName][$column->name]['scale'] = $scale;
 280      }
 281      if(!empty($tableAndColumnSize[$tableName][$columnName]['scale'])) {
 282          $decimalsToChange = $currencyField->maxNumberOfDecimals - $tableAndColumnSize[$tableName][$columnName]['scale'];
 283          if($decimalsToChange != 0) {
 284              $maxlength = $tableAndColumnSize[$tableName][$columnName]['max_length'] + $decimalsToChange;
 285              $decimalDigits = $tableAndColumnSize[$tableName][$columnName]['scale'] + $decimalsToChange;
 286  
 287              Migration_Index_View::ExecuteQuery("ALTER TABLE " .$tableName." MODIFY COLUMN ".$columnName." decimal(?,?)", array($maxlength, $decimalDigits));
 288          }
 289      }
 290  }
 291  
 292  $moduleInstance = Vtiger_Module::getInstance('Users');
 293  $currencyBlock = Vtiger_Block::getInstance('LBL_CURRENCY_CONFIGURATION', $moduleInstance);
 294  
 295  $currency_decimals_field = new Vtiger_Field();
 296  $currency_decimals_field->name = 'no_of_currency_decimals';
 297  $currency_decimals_field->label = 'Number Of Currency Decimals';
 298  $currency_decimals_field->table ='vtiger_users';
 299  $currency_decimals_field->column = 'no_of_currency_decimals';
 300  $currency_decimals_field->columntype = 'VARCHAR(2)';
 301  $currency_decimals_field->typeofdata = 'V~O';
 302  $currency_decimals_field->uitype = 16;
 303  $currency_decimals_field->defaultvalue = '2';
 304  $currency_decimals_field->sequence = 6;
 305  $currency_decimals_field->helpinfo = "<b>Currency - Number of Decimal places</b> <br/><br/>".
 306          "Number of decimal places specifies how many number of decimals will be shown after decimal separator.<br/>".
 307          "<b>Eg:</b> 123.00";
 308  $currencyBlock->addField($currency_decimals_field);
 309  $currency_decimals_field->setPicklistValues(array("1","2","3","4","5"));
 310  //Currency Decimal places handling - END

 311  
 312  $inventoryModules = array('Invoice','SalesOrder','PurchaseOrder','Quotes');
 313  $actions = array('Import','Export');
 314  
 315  for($i = 0; $i < count($inventoryModules); $i++) {
 316      $moduleName = $inventoryModules[$i];
 317      $moduleInstance = Vtiger_Module::getInstance($moduleName);
 318  
 319      $blockInstance = new Vtiger_Block();
 320  
 321      $blockInstance->label = 'LBL_ITEM_DETAILS';
 322      $blockInstance->sequence = '5';
 323      $blockInstance->showtitle = '0';
 324  
 325      $moduleInstance->addBlock($blockInstance);
 326  
 327      foreach ($actions as $actionName) {
 328          Vtiger_Access::updateTool($moduleInstance, $actionName, true, '');
 329      }
 330  }
 331  
 332  $itemFieldsName = array('productid','quantity','listprice','comment','discount_amount','discount_percent','tax1','tax2','tax3');
 333  $itemFieldsLabel = array('Item Name','Quantity','List Price','Item Comment','Item Discount Amount','Item Discount Percent','Tax1','Tax2','Tax3');
 334  $itemFieldsTypeOfData = array('V~M','V~M','V~M','V~O','V~O','V~O','V~O','V~O','V~O');
 335  $itemFieldsDisplayType = array('10','7','19','19','7','7','83','83','83');
 336  
 337  for($i=0; $i<count($inventoryModules); $i++) {
 338      $moduleName = $inventoryModules[$i];
 339      $moduleInstance = Vtiger_Module::getInstance($moduleName);
 340      $blockInstance = Vtiger_Block::getInstance('LBL_ITEM_DETAILS',$moduleInstance);
 341  
 342      $relatedmodules = array('Products','Services');
 343  
 344      for($j=0;$j<count($itemFieldsName);$j++) {
 345          $field = new Vtiger_Field();
 346  
 347          $field->name = $itemFieldsName[$j];
 348          $field->label = $itemFieldsLabel[$j];
 349          $field->column = $itemFieldsName[$j];
 350          $field->table = 'vtiger_inventoryproductrel';
 351          $field->uitype = $itemFieldsDisplayType[$j];
 352          $field->typeofdata = $itemFieldsTypeOfData[$j];
 353          $field->readonly = '0';
 354          $field->displaytype = '5';
 355          $field->masseditable = '0';
 356  
 357          $blockInstance->addField($field);
 358  
 359          if($itemFieldsName[$j] == 'productid') {
 360              $field->setRelatedModules($relatedmodules);
 361          }
 362      }
 363  }
 364  
 365  // Register a new actor type for LineItem API

 366  vtws_addActorTypeWebserviceEntityWithoutName('LineItem', 'include/Webservices/LineItem/VtigerLineItemOperation.php', 'VtigerLineItemOperation', array());
 367  
 368  $webserviceObject = VtigerWebserviceObject::fromName($adb,'LineItem');
 369  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_tables(webservice_entity_id,table_name) VALUES (?,?)", array($webserviceObject->getEntityId(), 'vtiger_inventoryproductrel'));
 370  
 371  $fieldTypeId = $adb->getUniqueID("vtiger_ws_entity_fieldtype");
 372  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_fieldtype(fieldtypeid,table_name, field_name,fieldtype) VALUES (?,?,?,?);", array($fieldTypeId, 'vtiger_inventoryproductrel', 'productid',"reference"));
 373  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_referencetype(fieldtypeid,type) VALUES (?,?)",array($fieldTypeId,'Products'));
 374  
 375  $fieldTypeId = $adb->getUniqueID("vtiger_ws_entity_fieldtype");
 376  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_fieldtype(fieldtypeid,table_name, field_name,fieldtype) VALUES (?,?,?,?);", array($fieldTypeId, 'vtiger_inventoryproductrel', 'id',"reference"));
 377  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_referencetype(fieldtypeid,type) VALUES (?,?)",array($fieldTypeId,'Invoice'));
 378  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_referencetype(fieldtypeid,type) VALUES (?,?)",array($fieldTypeId,'SalesOrder'));
 379  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_referencetype(fieldtypeid,type) VALUES (?,?)",array($fieldTypeId,'PurchaseOrder'));
 380  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_referencetype(fieldtypeid,type) VALUES (?,?)",array($fieldTypeId,'Quotes'));
 381  
 382  $fieldTypeId = $adb->getUniqueID("vtiger_ws_entity_fieldtype");
 383  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_fieldtype(fieldtypeid,table_name,field_name,fieldtype) VALUES (?,?,?,?);", array($fieldTypeId,'vtiger_inventoryproductrel', 'incrementondel',"autogenerated"));
 384  
 385  $adb->getUniqueID("vtiger_inventoryproductrel");
 386  Migration_Index_View::ExecuteQuery("UPDATE vtiger_inventoryproductrel_seq SET id=(select max(lineitem_id) from vtiger_inventoryproductrel);",array());
 387  Migration_Index_View::ExecuteQuery("UPDATE vtiger_ws_entity SET handler_path='include/Webservices/LineItem/VtigerInventoryOperation.php',handler_class='VtigerInventoryOperation' where name in ('Invoice','Quotes','PurchaseOrder','SalesOrder');",array());
 388  
 389  $purchaseOrderTabId = getTabid("PurchaseOrder");
 390  
 391  $purchaseOrderAddressInformationBlockId = getBlockId($purchaseOrderTabId, "LBL_ADDRESS_INFORMATION");
 392  
 393  $invoiceTabId = getTabid("Invoice");
 394  $invoiceTabIdAddressInformationBlockId = getBlockId($invoiceTabId, "LBL_ADDRESS_INFORMATION");
 395  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET block=? where tabid=? and block=?;',
 396          array($invoiceTabIdAddressInformationBlockId,$invoiceTabId,$purchaseOrderAddressInformationBlockId));
 397  
 398  vtws_addActorTypeWebserviceEntityWithName('Tax',
 399          'include/Webservices/LineItem/VtigerTaxOperation.php',
 400          'VtigerTaxOperation', array('fieldNames'=>'taxlabel', 'indexField'=>'taxid', 'tableName'=>'vtiger_inventorytaxinfo'), true);
 401  
 402  $webserviceObject = VtigerWebserviceObject::fromName($adb,'Tax');
 403  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_tables(webservice_entity_id,table_name) VALUES (?,?)",array($webserviceObject->getEntityId(),'vtiger_inventorytaxinfo'));
 404  
 405  vtws_addActorTypeWebserviceEntityWithoutName('ProductTaxes',
 406          'include/Webservices/LineItem/VtigerProductTaxesOperation.php',
 407          'VtigerProductTaxesOperation', array());
 408  
 409  $webserviceObject = VtigerWebserviceObject::fromName($adb,'ProductTaxes');
 410  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_tables(webservice_entity_id,table_name) VALUES (?,?)",array($webserviceObject->getEntityId(),'vtiger_producttaxrel'));
 411  
 412  $fieldTypeId = $adb->getUniqueID("vtiger_ws_entity_fieldtype");
 413  
 414  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_fieldtype(fieldtypeid,table_name,field_name,fieldtype) VALUES (?,?,?,?);", array($fieldTypeId,'vtiger_producttaxrel', 'productid',"reference"));
 415  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_referencetype(fieldtypeid,type) VALUES (?,?)",array($fieldTypeId,'Products'));
 416  
 417  $fieldTypeId = $adb->getUniqueID("vtiger_ws_entity_fieldtype");
 418  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_fieldtype(fieldtypeid,table_name,field_name,fieldtype) VALUES (?,?,?,?);", array($fieldTypeId,'vtiger_producttaxrel', 'taxid',"reference"));
 419  Migration_Index_View::ExecuteQuery("INSERT INTO vtiger_ws_entity_referencetype(fieldtypeid,type) VALUES (?,?)",array($fieldTypeId,'Tax'));
 420  
 421  //--

 422  //Changed Columns Display in List view of Leads

 423  $leadsFirstName = 'vtiger_leaddetails:firstname:firstname:Leads_First_Name:V';
 424  $leadsLastName = 'vtiger_leaddetails:lastname:lastname:Leads_Last_Name:V';
 425  Migration_Index_View::ExecuteQuery("UPDATE vtiger_cvcolumnlist SET columnname=? WHERE cvid=? AND columnindex=?", array($leadsFirstName, '1', '1'));
 426  Migration_Index_View::ExecuteQuery("UPDATE vtiger_cvcolumnlist SET columnname=? WHERE cvid=? AND columnindex=?", array($leadsLastName, '1', '2'));
 427  
 428  //Changed the Currency Symbol of Moroccan, Dirham to DH

 429  Migration_Index_View::ExecuteQuery("UPDATE vtiger_currencies SET currency_symbol=? WHERE currency_name=? AND currency_code=?", array('DH', 'Moroccan, Dirham', 'MAD'));
 430  
 431  //Changing picklist values for sales stage of opportunities

 432  Migration_Index_View::ExecuteQuery("UPDATE vtiger_sales_stage SET sales_stage=? WHERE sales_stage=?", array('Proposal or Price Quote', 'Proposal/Price Quote'));
 433  Migration_Index_View::ExecuteQuery("UPDATE vtiger_sales_stage SET sales_stage=? WHERE sales_stage=?", array('Negotiation or Review', 'Negotiation/Review'));
 434  
 435  //Updating the new picklist values of sales stage in opportunities for migration instances

 436  Migration_Index_View::ExecuteQuery("UPDATE vtiger_potential SET sales_stage=? WHERE sales_stage=?", array('Proposal or Price Quote', 'Proposal/Price Quote'));
 437  Migration_Index_View::ExecuteQuery("UPDATE vtiger_potential SET sales_stage=? WHERE sales_stage=?", array('Negotiation or Review', 'Negotiation/Review'));
 438  
 439  //Updating Sales Stage History in opportunities related list for migration instances

 440  Migration_Index_View::ExecuteQuery("UPDATE vtiger_potstagehistory SET stage=? WHERE stage=?", array('Proposal or Price Quote', 'Proposal/Price Quote'));
 441  Migration_Index_View::ExecuteQuery("UPDATE vtiger_potstagehistory SET stage=? WHERE stage=?", array('Negotiation or Review', 'Negotiation/Review'));
 442  
 443  //Updating the sales stage picklist values of opportunities in picklist dependency setup for migration instances

 444  Migration_Index_View::ExecuteQuery("UPDATE vtiger_picklist_dependency SET sourcevalue=? WHERE sourcevalue=?", array('Proposal or Price Quote', 'Proposal/Price Quote'));
 445  Migration_Index_View::ExecuteQuery("UPDATE vtiger_picklist_dependency SET sourcevalue=? WHERE sourcevalue=?", array('Negotiation or Review', 'Negotiation/Review'));
 446  
 447  //Internationalized the description for webforms

 448  Migration_Index_View::ExecuteQuery("UPDATE vtiger_settings_field SET description=? WHERE description=?", array('LBL_WEBFORMS_DESCRIPTION', 'Allows you to manage Webforms'));
 449  
 450  Migration_Index_View::ExecuteQuery('CREATE TABLE IF NOT EXISTS vtiger_crmsetup(userid INT(11) NOT NULL, setup_status INT(2))', array());
 451  if (!defined('INSTALLATION_MODE')) {
 452      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_crmsetup(userid, setup_status) SELECT id, 1 FROM vtiger_users', array());
 453  }
 454  
 455  $discountResult = Migration_Index_View::ExecuteQuery('SELECT * FROM vtiger_selectcolumn WHERE columnname LIKE "vtiger_inventoryproductrel:discount:%" ORDER BY columnindex', array());
 456  $num_rows = $adb->num_rows($discountResult);
 457  
 458  for ($i=0; $i<$num_rows; $i++) {
 459      $columnIndex = $adb->query_result($discountResult, $i, 'columnindex');
 460      $columnName = $adb->query_result($discountResult, $i, 'columnname');
 461      $queryId = $adb->query_result($discountResult, $i, 'queryid');
 462  
 463      $updatedColumnName = str_replace(':discount:', ':discount_amount:', $columnName);
 464      $updateQuery = 'UPDATE vtiger_selectcolumn SET columnname = ? WHERE columnindex = ? and queryid = ?';
 465      $updateParams = array($updatedColumnName, $columnIndex,$queryId);
 466  
 467      Migration_Index_View::ExecuteQuery($updateQuery, $updateParams);
 468  }
 469  
 470  Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_ws_referencetype VALUES (?,?)', array(31,'Campaigns'));
 471  
 472  $moduleInstance = Vtiger_Module::getInstance('Users');
 473  $currencyBlock = Vtiger_Block::getInstance('LBL_CURRENCY_CONFIGURATION', $moduleInstance);
 474  $truncateTrailingZeros = new Vtiger_Field();
 475  
 476  $truncateTrailingZeros->name = 'truncate_trailing_zeros';
 477  $truncateTrailingZeros->label = 'Truncate Trailing Zeros';
 478  $truncateTrailingZeros->table ='vtiger_users';
 479  $truncateTrailingZeros->column = 'truncate_trailing_zeros';
 480  $truncateTrailingZeros->columntype = 'varchar(3)';
 481  $truncateTrailingZeros->typeofdata = 'V~O';
 482  $truncateTrailingZeros->uitype = 56;
 483  $truncateTrailingZeros->sequence = 7;
 484  $truncateTrailingZeros->defaultvalue = 0;
 485  $truncateTrailingZeros->helpinfo = "<b> Truncate Trailing Zeros </b> <br/><br/>".
 486      "It truncated trailing 0s in any of Currency, Decimal and Percentage Field types<br/><br/>".
 487      "<b>Ex:</b><br/>".
 488      "If value is 89.00000 then <br/>".
 489      "decimal and Percentage fields were shows 89<br/>".
 490      "currency field type - shows 89.00<br/>";
 491  $currencyBlock->addField($truncateTrailingZeros);
 492  
 493  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_productcurrencyrel MODIFY COLUMN actual_price decimal(28,8)", array());
 494  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_productcurrencyrel MODIFY COLUMN converted_price decimal(28,8)", array());
 495  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_pricebookproductrel MODIFY COLUMN listprice decimal(27,8)", array());
 496  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_inventoryproductrel MODIFY COLUMN listprice decimal(27,8)", array());
 497  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_inventoryproductrel MODIFY COLUMN discount_amount decimal(27,8)", array());
 498  
 499  $currencyField = new CurrencyField($value);
 500  $result = Migration_Index_View::ExecuteQuery("SELECT tablename,columnname FROM vtiger_field WHERE uitype IN (?,?)",array('71','72'));
 501  $count = $adb->num_rows($result);
 502  for($i=0;$i<$count;$i++) {
 503      $tableName = $adb->query_result($result,$i,'tablename');
 504      $columnName = $adb->query_result($result,$i,'columnname');
 505      Migration_Index_View::ExecuteQuery("ALTER TABLE " .$tableName." MODIFY COLUMN ".$columnName." decimal(?,?)", array(25, 8));
 506  }
 507  
 508  Migration_Index_View::ExecuteQuery('DELETE FROM vtiger_no_of_currency_decimals WHERE no_of_currency_decimalsid=?', array(1));
 509  
 510  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET uitype=?, typeofdata=? WHERE fieldname=?',array(71, 'N~O', 'listprice'));
 511  
 512  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET typeofdata=? WHERE fieldname=?',array('N~O', 'quantity'));
 513  
 514  //--

 515  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET typeofdata=?, uitype =?, fieldlabel=? WHERE fieldname =? and tablename=?', array('N~O', 71, 'Discount', 'discount_amount', 'vtiger_inventoryproductrel'));
 516  
 517  //deleting default workflows

 518  Migration_Index_View::ExecuteQuery("delete from com_vtiger_workflowtasks where task_id=?", array(11));
 519  Migration_Index_View::ExecuteQuery("delete from com_vtiger_workflowtasks where task_id=?", array(12));
 520  
 521  // Creating Default workflows

 522  $workflowManager = new VTWorkflowManager($adb);
 523  $taskManager = new VTTaskManager($adb);
 524  
 525  // Events workflow when Send Notification is checked

 526  $eventsWorkflow = $workflowManager->newWorkFlow("Events");
 527  $eventsWorkflow->test = '[{"fieldname":"sendnotification","operation":"is","value":"true:boolean"}]';
 528  $eventsWorkflow->description = "Workflow for Events when Send Notification is True";
 529  $eventsWorkflow->executionCondition = VTWorkflowManager::$ON_EVERY_SAVE;
 530  $eventsWorkflow->defaultworkflow = 1;
 531  $workflowManager->save($eventsWorkflow);
 532  
 533  $task = $taskManager->createTask('VTEmailTask', $eventsWorkflow->id);
 534  $task->active = true;
 535  $task->summary = 'Send Notification Email to Record Owner';
 536  $task->recepient = "\$(assigned_user_id : (Users) email1)";
 537  $task->subject = "Event :  \$subject";
 538  $task->content = '$(assigned_user_id : (Users) last_name) $(assigned_user_id : (Users) first_name) ,<br/>'
 539          . '<b>Activity Notification Details:</b><br/>'
 540          . 'Subject             : $subject<br/>'
 541          . 'Start date and time : $date_start  $time_start ( $(general : (__VtigerMeta__) dbtimezone) ) <br/>'
 542          . 'End date and time   : $due_date  $time_end ( $(general : (__VtigerMeta__) dbtimezone) ) <br/>'
 543          . 'Status              : $eventstatus <br/>'
 544          . 'Priority            : $taskpriority <br/>'
 545          . 'Related To          : $(parent_id : (Leads) lastname) $(parent_id : (Leads) firstname) $(parent_id : (Accounts) accountname) '
 546                                  . '$(parent_id : (Potentials) potentialname) $(parent_id : (HelpDesk) ticket_title)'
 547                                  . ' $(parent_id : (Campaigns) campaignname) <br/>'
 548          . 'Contacts List       : $(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname) <br/>'
 549          . 'Location            : $location <br/>'
 550          . 'Description         : $description';
 551  $taskManager->saveTask($task);
 552  
 553  // Calendar workflow when Send Notification is checked

 554  $calendarWorkflow = $workflowManager->newWorkFlow("Calendar");
 555  $calendarWorkflow->test = '[{"fieldname":"sendnotification","operation":"is","value":"true:boolean"}]';
 556  $calendarWorkflow->description = "Workflow for Calendar Todos when Send Notification is True";
 557  $calendarWorkflow->executionCondition = VTWorkflowManager::$ON_EVERY_SAVE;
 558  $calendarWorkflow->defaultworkflow = 1;
 559  $workflowManager->save($calendarWorkflow);
 560  
 561  $task = $taskManager->createTask('VTEmailTask', $calendarWorkflow->id);
 562  $task->active = true;
 563  $task->summary = 'Send Notification Email to Record Owner';
 564  $task->recepient = "\$(assigned_user_id : (Users) email1)";
 565  $task->subject = "Task :  \$subject";
 566  $task->content = '$(assigned_user_id : (Users) last_name) $(assigned_user_id : (Users) first_name) ,<br/>'
 567          . '<b>Task Notification Details:</b><br/>'
 568          . 'Subject : $subject<br/>'
 569          . 'Start date and time : $date_start  $time_start ( $(general : (__VtigerMeta__) dbtimezone) ) <br/>'
 570          . 'End date and time   : $due_date ( $(general : (__VtigerMeta__) dbtimezone) ) <br/>'
 571          . 'Status              : $taskstatus <br/>'
 572          . 'Priority            : $taskpriority <br/>'
 573          . 'Related To          : $(parent_id : (Leads) lastname) $(parent_id : (Leads) firstname) $(parent_id : (Accounts) accountname) '
 574                                  . '$(parent_id : (Potentials) potentialname) $(parent_id : (HelpDesk) ticket_title)'
 575                                  . ' $(parent_id : (Campaigns) campaignname) <br/>'
 576          . 'Contacts List       : $(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname) <br/>'
 577          . 'Description         : $description';
 578  $taskManager->saveTask($task);
 579  
 580  global $current_user;
 581  $adb = PearDatabase::getInstance();
 582  $user = new Users();
 583  $current_user = $user->retrieveCurrentUserInfoFromFile(Users::getActiveAdminId());
 584  
 585  $allTabIdResult = Migration_Index_View::ExecuteQuery('SELECT tabid, name FROM vtiger_tab', array());
 586  $noOfTabs = $adb->num_rows($allTabIdResult);
 587  $allTabIds = array();
 588  for($i=0; $i<$noOfTabs; ++$i) {
 589      $tabId = $adb->query_result($allTabIdResult, $i, 'tabid');
 590      $tabName = $adb->query_result($allTabIdResult, $i, 'name');
 591      $allTabIds[$tabName] = $tabId;
 592  }
 593  
 594  //Adding status field for project task

 595  
 596  $moduleInstance = Vtiger_Module::getInstance('ProjectTask');
 597  $blockInstance = Vtiger_Block::getInstance('LBL_PROJECT_TASK_INFORMATION', $moduleInstance);
 598  $fieldInstance = new Vtiger_Field();
 599  $fieldInstance->name = 'projecttaskstatus';
 600  $fieldInstance->label = 'Status';
 601  $fieldInstance->uitype = 15;
 602  $fieldInstance->quickcreate = 0;
 603  $blockInstance->addField($fieldInstance);
 604  
 605  $pickListValues = array('--None--', 'Open', 'In Progress', 'Completed', 'Deferred', 'Canceled ');
 606  
 607  $fieldInstance->setPicklistValues($pickListValues);
 608  
 609  //Dashboard schema changes

 610  Vtiger_Utils::CreateTable('vtiger_module_dashboard_widgets', '(id INT(19) NOT NULL AUTO_INCREMENT, linkid INT(19), userid INT(19), filterid INT(19),
 611                  title VARCHAR(100), data VARCHAR(500) DEFAULT "[]", PRIMARY KEY(id))');
 612  $potentials = Vtiger_Module::getInstance('Potentials');
 613  $potentials->addLink('DASHBOARDWIDGET', 'History', 'index.php?module=Potentials&view=ShowWidget&name=History','', '1');
 614  $potentials->addLink('DASHBOARDWIDGET', 'Upcoming Activities', 'index.php?module=Potentials&view=ShowWidget&name=CalendarActivities','', '2');
 615  $potentials->addLink('DASHBOARDWIDGET', 'Funnel', 'index.php?module=Potentials&view=ShowWidget&name=GroupedBySalesStage','', '3');
 616  $potentials->addLink('DASHBOARDWIDGET', 'Potentials by Stage', 'index.php?module=Potentials&view=ShowWidget&name=GroupedBySalesPerson','', '4');
 617  $potentials->addLink('DASHBOARDWIDGET', 'Pipelined Amount', 'index.php?module=Potentials&view=ShowWidget&name=PipelinedAmountPerSalesPerson','', '5');
 618  $potentials->addLink('DASHBOARDWIDGET', 'Total Revenue', 'index.php?module=Potentials&view=ShowWidget&name=TotalRevenuePerSalesPerson','', '6');
 619  $potentials->addLink('DASHBOARDWIDGET', 'Top Potentials', 'index.php?module=Potentials&view=ShowWidget&name=TopPotentials','', '7');
 620  //$potentials->addLink('DASHBOARDWIDGET', 'Forecast', 'index.php?module=Potentials&view=ShowWidget&name=Forecast','', '8');

 621  $potentials->addLink('DASHBOARDWIDGET', 'Overdue Activities', 'index.php?module=Potentials&view=ShowWidget&name=OverdueActivities','', '9');
 622  
 623  $accounts = Vtiger_Module::getInstance('Accounts');
 624  $accounts->addLink('DASHBOARDWIDGET', 'History', 'index.php?module=Accounts&view=ShowWidget&name=History','', '1');
 625  $accounts->addLink('DASHBOARDWIDGET', 'Upcoming Activities', 'index.php?module=Accounts&view=ShowWidget&name=CalendarActivities','', '2');
 626  $accounts->addLink('DASHBOARDWIDGET', 'Overdue Activities', 'index.php?module=Accounts&view=ShowWidget&name=OverdueActivities','', '3');
 627  
 628  $contacts = Vtiger_Module::getInstance('Contacts');
 629  $contacts->addLink('DASHBOARDWIDGET', 'History', 'index.php?module=Contacts&view=ShowWidget&name=History','', '1');
 630  $contacts->addLink('DASHBOARDWIDGET', 'Upcoming Activities', 'index.php?module=Contacts&view=ShowWidget&name=CalendarActivities','', '2');
 631  $contacts->addLink('DASHBOARDWIDGET', 'Overdue Activities', 'index.php?module=Contacts&view=ShowWidget&name=OverdueActivities','', '3');
 632  
 633  $leads = Vtiger_Module::getInstance('Leads');
 634  $leads->addLink('DASHBOARDWIDGET', 'History', 'index.php?module=Leads&view=ShowWidget&name=History','', '1');
 635  $leads->addLink('DASHBOARDWIDGET', 'Upcoming Activities', 'index.php?module=Leads&view=ShowWidget&name=CalendarActivities','', '2');
 636  //$leads->addLink('DASHBOARDWIDGET', 'Leads Created', 'index.php?module=Leads&view=ShowWidget&name=LeadsCreated','', '3');

 637  $leads->addLink('DASHBOARDWIDGET', 'Leads by Status', 'index.php?module=Leads&view=ShowWidget&name=LeadsByStatus','', '4');
 638  $leads->addLink('DASHBOARDWIDGET', 'Leads by Source', 'index.php?module=Leads&view=ShowWidget&name=LeadsBySource','', '5');
 639  $leads->addLink('DASHBOARDWIDGET', 'Leads by Industry', 'index.php?module=Leads&view=ShowWidget&name=LeadsByIndustry','', '6');
 640  $leads->addLink('DASHBOARDWIDGET', 'Overdue Activities', 'index.php?module=Leads&view=ShowWidget&name=OverdueActivities','', '7');
 641  
 642  $helpDesk = Vtiger_Module::getInstance('HelpDesk');
 643  $helpDesk->addLink('DASHBOARDWIDGET', 'Tickets by Status', 'index.php?module=HelpDesk&view=ShowWidget&name=TicketsByStatus','', '1');
 644  $helpDesk->addLink('DASHBOARDWIDGET', 'Open Tickets', 'index.php?module=HelpDesk&view=ShowWidget&name=OpenTickets','', '2');
 645  
 646  $home = Vtiger_Module::getInstance('Home');
 647  $home->addLink('DASHBOARDWIDGET', 'History', 'index.php?module=Home&view=ShowWidget&name=History','', '1');
 648  $home->addLink('DASHBOARDWIDGET', 'Upcoming Activities', 'index.php?module=Home&view=ShowWidget&name=CalendarActivities','', '2');
 649  $home->addLink('DASHBOARDWIDGET', 'Funnel', 'index.php?module=Potentials&view=ShowWidget&name=GroupedBySalesStage','', '3');
 650  $home->addLink('DASHBOARDWIDGET', 'Potentials by Stage', 'index.php?module=Potentials&view=ShowWidget&name=GroupedBySalesPerson','', '4');
 651  $home->addLink('DASHBOARDWIDGET', 'Pipelined Amount', 'index.php?module=Potentials&view=ShowWidget&name=PipelinedAmountPerSalesPerson','', '5');
 652  $home->addLink('DASHBOARDWIDGET', 'Total Revenue', 'index.php?module=Potentials&view=ShowWidget&name=TotalRevenuePerSalesPerson','', '6');
 653  $home->addLink('DASHBOARDWIDGET', 'Top Potentials', 'index.php?module=Potentials&view=ShowWidget&name=TopPotentials','', '7');
 654  //$home->addLink('DASHBOARDWIDGET', 'Forecast', 'index.php?module=Potentials&view=ShowWidget&name=Forecast','', '8');

 655  
 656  //$home->addLink('DASHBOARDWIDGET', 'Leads Created', 'index.php?module=Leads&view=ShowWidget&name=LeadsCreated','', '9');

 657  $home->addLink('DASHBOARDWIDGET', 'Leads by Status', 'index.php?module=Leads&view=ShowWidget&name=LeadsByStatus','', '10');
 658  $home->addLink('DASHBOARDWIDGET', 'Leads by Source', 'index.php?module=Leads&view=ShowWidget&name=LeadsBySource','', '11');
 659  $home->addLink('DASHBOARDWIDGET', 'Leads by Industry', 'index.php?module=Leads&view=ShowWidget&name=LeadsByIndustry','', '12');
 660  $home->addLink('DASHBOARDWIDGET', 'Overdue Activities', 'index.php?module=Home&view=ShowWidget&name=OverdueActivities','', '13');
 661  
 662  $home->addLink('DASHBOARDWIDGET', 'Tickets by Status', 'index.php?module=HelpDesk&view=ShowWidget&name=TicketsByStatus','', '13');
 663  $home->addLink('DASHBOARDWIDGET', 'Open Tickets', 'index.php?module=HelpDesk&view=ShowWidget&name=OpenTickets','', '14');
 664  
 665  //Calendar and Events module clean up

 666  $calendarTabId = getTabid('Calendar');
 667  $eventTabId = getTabid('Events');
 668  Migration_Index_View::ExecuteQuery('UPDATE vtiger_blocks SET blocklabel ="LBL_DESCRIPTION_INFORMATION" WHERE blockid=20',array());
 669  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET displaytype=1 WHERE fieldname="location" AND tabid = ?', array($calendarTabId));
 670  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET displaytype=1 WHERE fieldname="visibility" AND tabid = ?', array($eventTabId));
 671  
 672  $eventBlockId = getBlockId($eventTabId, 'LBL_EVENT_INFORMATION');
 673  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET block = ? WHERE block = 41', array($eventBlockId));
 674  Migration_Index_View::ExecuteQuery('UPDATE vtiger_blocks SET blocklabel = "LBL_REMINDER_INFORMATION", show_title = 0 WHERE blockid = 40',array());
 675  Migration_Index_View::ExecuteQuery('UPDATE vtiger_blocks SET blocklabel = "LBL_DESCRIPTION_INFORMATION", show_title = 0 WHERE blockid = 41',array());
 676  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET block = 41 WHERE fieldname = "description" AND tabid = ?',array($eventTabId));
 677  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET block = ? WHERE fieldname = "contact_id" AND tabid = ?', array($eventBlockId, $eventTabId));
 678  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET displaytype = 3 WHERE fieldname = ? AND tabid = ?', array('notime', $eventTabId));
 679  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET displaytype = 3 WHERE fieldname = ? AND tabid = ?', array('duration_hours', $eventTabId));
 680  
 681  $projectTabId = getTabid('Project');
 682  $projectTaskTabId = getTabid('ProjectTask');
 683  $projectMilestoneTabId = getTabid('ProjectMilestone');
 684  $contactsTabId = getTabid('Contacts');
 685  $accountsTabId = getTabid('Accounts');
 686  $helpDeskTabId = getTabid('HelpDesk');
 687  
 688  Migration_Index_View::ExecuteQuery('UPDATE vtiger_relatedlists SET actions=? WHERE tabid in(?,?) and related_tabid in (?,?,?)',
 689          array('add', $helpDeskTabId, $projectTabId, $calendarTabId, $projectTaskTabId,  $projectMilestoneTabId));
 690  
 691  Migration_Index_View::ExecuteQuery('UPDATE vtiger_relatedlists SET actions=? WHERE tabid in(?, ?) and related_tabid in (?)',
 692          array('add', $contactsTabId, $accountsTabId, $projectTabId));
 693  
 694  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET presence = 1 WHERE tabid = ? AND fieldname = ?', array($helpDeskTabId, 'comments'));
 695  $faqTabId = getTabid('Faq');
 696  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET presence = 1 WHERE tabid = ? AND fieldname = ?', array($faqTabId, 'comments'));
 697  
 698  Migration_Index_View::ExecuteQuery('UPDATE vtiger_users SET truncate_trailing_zeros = ?', array(1));
 699  
 700  //deleted the id column from the All filter

 701  Migration_Index_View::ExecuteQuery("DELETE FROM vtiger_cvcolumnlist WHERE cvid IN
 702              (SELECT cvid FROM vtiger_customview WHERE viewname='All' AND entitytype NOT IN
 703                  ('Emails','Calendar','ModComments','ProjectMilestone','Project','SMSNotifier','PBXManager','Webmails'))
 704              AND columnindex = 0", array());
 705  
 706  // Added indexes for Modtracker Module to improve performance

 707  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_modtracker_basic ADD INDEX crmidx (crmid)', array());
 708  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_modtracker_basic ADD INDEX idx (id)', array());
 709  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_modtracker_detail ADD INDEX idx (id)', array());
 710  
 711  // Ends

 712  
 713  require_once  'modules/com_vtiger_workflow/VTEntityMethodManager.inc';
 714  $emm = new VTEntityMethodManager($adb);
 715  $emm->addEntityMethod("ModComments","CustomerCommentFromPortal","modules/ModComments/ModCommentsHandler.php","CustomerCommentFromPortal");
 716  $emm->addEntityMethod("ModComments","TicketOwnerComments","modules/ModComments/ModCommentsHandler.php","TicketOwnerComments");
 717  
 718  require_once  'modules/com_vtiger_workflow/VTWorkflowManager.inc';
 719  require_once  'modules/com_vtiger_workflow/VTTaskManager.inc';
 720  $workflowManager = new VTWorkflowManager($adb);
 721  $taskManager = new VTTaskManager($adb);
 722  
 723  $commentsWorkflow = $workflowManager->newWorkFlow("ModComments");
 724  $commentsWorkflow->test = '[{"fieldname":"related_to : (HelpDesk) ticket_title","operation":"is not empty","value":""}]';
 725  $commentsWorkflow->description = "Workflow for comments on Tickets";
 726  $commentsWorkflow->executionCondition = VTWorkflowManager::$ON_FIRST_SAVE;
 727  $commentsWorkflow->defaultworkflow = 1;
 728  $workflowManager->save($commentsWorkflow);
 729  
 730  $task = $taskManager->createTask('VTEntityMethodTask', $commentsWorkflow->id);
 731  $task->active = true;
 732  $task->summary = 'Customer commented from Portal';
 733  $task->methodName = "CustomerCommentFromPortal";
 734  $taskManager->saveTask($task);
 735  
 736  $task1 = $taskManager->createTask('VTEntityMethodTask', $commentsWorkflow->id);
 737  $task1->active = true;
 738  $task1->summary = 'Notify Customer when commenting on a Ticket';
 739  $task1->methodName = "TicketOwnerComments";
 740  $taskManager->saveTask($task1);
 741  // Ends

 742  
 743  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_links MODIFY column linktype VARCHAR(50)', array());
 744  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_links MODIFY column linklabel VARCHAR(50)', array());
 745  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_links MODIFY column handler_class VARCHAR(50)', array());
 746  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_links MODIFY column handler VARCHAR(50)', array());
 747  //--

 748  //Add ModComments to HelpDesk and Faq module

 749  require_once 'modules/ModComments/ModComments.php';
 750  ModComments::addWidgetTo(array("HelpDesk", "Faq"));
 751  global $current_user, $VTIGER_BULK_SAVE_MODE;
 752  $VTIGER_BULK_SAVE_MODE = true;
 753  
 754  $stopLoop = false;
 755  $pageCount = 0;
 756  do {
 757      $ticketComments = Migration_Index_View::ExecuteQuery(sprintf('SELECT * FROM vtiger_ticketcomments ORDER BY commentid ASC LIMIT %s,%s', $pageCount*1000, 1000),  array());
 758      $rows = $adb->num_rows($ticketComments);
 759      if (empty($rows)) {
 760          $stopLoop = true;
 761          break;
 762      }
 763      for($i=0; $i<$rows; $i++) {
 764          $modComments = CRMEntity::getInstance('ModComments');
 765          $modComments->column_fields['commentcontent'] = decode_html($adb->query_result($ticketComments, $i, 'comments'));
 766          $ownerId = $adb->query_result($ticketComments, $i, 'ownerid');
 767          $current_user->id = $ownerId;
 768          $modComments->column_fields['assigned_user_id'] = $modComments->column_fields['creator'] = $ownerId;
 769          $modComments->column_fields['createdtime'] = $adb->query_result($ticketComments, $i, 'createdtime');
 770          $modComments->column_fields['modifiedtime'] = $adb->query_result($ticketComments, $i, 'createdtime');
 771          $modComments->column_fields['related_to'] = $adb->query_result($ticketComments, $i, 'ticketid');
 772          $modComments->save('ModComments');
 773          Migration_Index_View::ExecuteQuery('UPDATE vtiger_crmentity SET modifiedtime = ?, smcreatorid = ?, modifiedby = ? WHERE crmid = ?',
 774              array($modComments->column_fields['createdtime'], $ownerId, $ownerId, $modComments->id));
 775      }
 776      ++$pageCount;
 777  } while (!$stopLoop);
 778  
 779  $stopLoop = false;
 780  $pageCount = 0;
 781  do {
 782      $faqComments = Migration_Index_View::ExecuteQuery(sprintf('SELECT * FROM vtiger_faqcomments ORDER BY commentid ASC LIMIT %s, %s', $pageCount*1000, 1000), array());
 783      $rows = $adb->num_rows($faqComments);
 784      if (empty($rows)) {
 785          $stopLoop = true;
 786          break;
 787      }
 788      for($i=0; $i<$rows; $i++) {
 789          $modComments = CRMEntity::getInstance('ModComments');
 790          $modComments->column_fields['commentcontent'] = decode_html($adb->query_result($faqComments, $i, 'comments'));
 791          $modComments->column_fields['assigned_user_id'] = $modComments->column_fields['creator'] = Users::getActiveAdminId();
 792          $modComments->column_fields['createdtime'] = $adb->query_result($faqComments, $i, 'createdtime');
 793          $modComments->column_fields['modifiedtime'] = $adb->query_result($faqComments, $i, 'createdtime');
 794          $modComments->column_fields['related_to'] = $adb->query_result($faqComments, $i, 'faqid');
 795          $modComments->save('ModComments');
 796          Migration_Index_View::ExecuteQuery('UPDATE vtiger_crmentity SET modifiedtime = ?, smcreatorid = ?, modifiedby = ? WHERE crmid = ?',
 797              array($modComments->column_fields['createdtime'], '6', '6', $modComments->id));
 798      }
 799      ++$pageCount;
 800  } while (!$stopLoop);
 801  
 802  $VTIGER_BULK_SAVE_MODE = false;
 803  
 804  // Added label column in vtiger_crmentity table for easier lookup - Also added Event handler to update the label on save of a record

 805  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_crmentity ADD COLUMN label varchar(255)", array());
 806  
 807  // To avoid infinite-loop if we not able fix label for non-entity/special modules.

 808  $lastMaxCRMId = 0;
 809  do {
 810      $rs = $adb->pquery("SELECT crmid,setype FROM vtiger_crmentity INNER JOIN vtiger_tab ON vtiger_tab.name=vtiger_crmentity.setype WHERE label IS NULL AND crmid > ? LIMIT 500", array($lastMaxCRMId));
 811      if (!$adb->num_rows($rs)) {
 812          break;
 813      }
 814      while ($row = $adb->fetch_array($rs)) {
 815          /**

 816           * TODO: Optimize underlying API to cache re-usable data, for speedy data.

 817           */
 818          $labelInfo = getEntityName($row['setype'], array(intval($row['crmid'])), true);
 819  
 820          if ($labelInfo) {
 821              $label = $labelInfo[$row['crmid']];
 822              Migration_Index_View::ExecuteQuery('UPDATE vtiger_crmentity SET label=? WHERE crmid=? AND setype=?',
 823                          array($label, $row['crmid'], $row['setype']));
 824          }
 825  
 826          if (intval($row['crmid']) > $lastMaxCRMId) {
 827              $lastMaxCRMId = intval($row['crmid']);
 828          }
 829      }
 830      $rs = null;
 831      unset($rs);
 832  } while(true);
 833  
 834  Migration_Index_View::ExecuteQuery('CREATE INDEX vtiger_crmentity_labelidx ON vtiger_crmentity(label)', array());
 835  
 836  $homeModule = Vtiger_Module::getInstance('Home');
 837  Vtiger_Event::register($homeModule, 'vtiger.entity.aftersave', 'Vtiger_RecordLabelUpdater_Handler', 'modules/Vtiger/RecordLabelUpdater.php');
 838  
 839  $moduleInstance = Vtiger_Module::getInstance('ModComments');
 840  $customer = Vtiger_Field::getInstance('customer', $moduleInstance);
 841  if (!$customer) {
 842      $customer = new Vtiger_Field();
 843      $customer->name = 'customer';
 844      $customer->label = 'Customer';
 845      $customer->uitype = '10';
 846      $customer->displaytype = '3';
 847      $blockInstance = Vtiger_Block::getInstance('LBL_MODCOMMENTS_INFORMATION', $moduleInstance);
 848      $blockInstance->addField($customer);
 849      $customer->setRelatedModules(array('Contacts'));
 850  }
 851  
 852  $moduleInstance = Vtiger_Module::getInstance('Potentials');
 853  $filter = Vtiger_Filter::getInstance('All', $moduleInstance);
 854  $fieldInstance = Vtiger_Field::getInstance('amount', $moduleInstance);
 855  $filter->addField($fieldInstance,6);
 856  
 857  
 858  if(file_exists('modules/ModTracker/ModTrackerUtils.php')) {
 859      require_once 'modules/ModTracker/ModTrackerUtils.php';
 860      $modules = $adb->pquery('SELECT * FROM vtiger_tab WHERE isentitytype = 1', array());
 861      $rows = $adb->num_rows($modules);
 862      for($i=0; $i<$rows; $i++) {
 863          $tabid=$adb->query_result($modules, $i, 'tabid');
 864          ModTrackerUtils::modTrac_changeModuleVisibility($tabid, 'module_enable');
 865      }
 866  }
 867  
 868  $operationId = vtws_addWebserviceOperation('retrieve_inventory', 'include/Webservices/LineItem/RetrieveInventory.php', 'vtws_retrieve_inventory', 'GET');
 869  vtws_addWebserviceOperationParam($operationId, 'id', 'String', 1);
 870  
 871  $moduleInstance = Vtiger_Module::getInstance('Events');
 872  $tabId = getTabid('Events');
 873  
 874  // Update/Increment the sequence for the succeeding blocks of Events module, with starting sequence 3

 875  Migration_Index_View::ExecuteQuery('UPDATE vtiger_blocks SET sequence = sequence+1 WHERE tabid=? AND sequence >= 3',
 876                                              array($tabId));
 877  
 878  // Create Recurrence Information block

 879  $recurrenceBlock = new Vtiger_Block();
 880  $recurrenceBlock->label = 'LBL_RECURRENCE_INFORMATION';
 881  $recurrenceBlock->sequence = 3;
 882  $moduleInstance->addBlock($recurrenceBlock);
 883  
 884  $blockId = getBlockId($tabId, 'LBL_RECURRENCE_INFORMATION');
 885  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET block=? WHERE fieldname=? and tabid=?', array($blockId, 'recurringtype', $tabId));
 886  
 887  // Update/Increment the sequence for the succeeding blocks of Users module, with starting sequence 2

 888  $moduleInstance = Vtiger_Module::getInstance('Users');
 889  $tabId = getTabid('Users');
 890  Migration_Index_View::ExecuteQuery('UPDATE vtiger_blocks SET sequence = sequence+1 WHERE tabid=? AND sequence >= 2', array($tabId));
 891  
 892  // Create Calendar Settings block

 893  $calendarSettings = new Vtiger_Block();
 894  $calendarSettings->label = 'LBL_CALENDAR_SETTINGS';
 895  $calendarSettings->sequence = 2;
 896  $moduleInstance->addBlock($calendarSettings);
 897  
 898  $calendarSettings = Vtiger_Block::getInstance('LBL_CALENDAR_SETTINGS', $moduleInstance);
 899  
 900  $dayOfTheWeek = new Vtiger_Field();
 901  $dayOfTheWeek->name = 'dayoftheweek';
 902  $dayOfTheWeek->label = 'Starting Day of the week';
 903  $dayOfTheWeek->table ='vtiger_users';
 904  $dayOfTheWeek->column = 'dayoftheweek';
 905  $dayOfTheWeek->columntype = 'varchar(100)';
 906  $dayOfTheWeek->typeofdata = 'V~O';
 907  $dayOfTheWeek->uitype = 16;
 908  $dayOfTheWeek->sequence = 2;
 909  $dayOfTheWeek->defaultvalue = 'Sunday';
 910  $calendarSettings->addField($dayOfTheWeek);
 911  $dayOfTheWeek->setPicklistValues(array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'));
 912  
 913  $defaultCallDuration = new Vtiger_Field();
 914  $defaultCallDuration->name = 'callduration';
 915  $defaultCallDuration->label = 'Default Call Duration';
 916  $defaultCallDuration->table ='vtiger_users';
 917  $defaultCallDuration->column = 'callduration';
 918  $defaultCallDuration->columntype = 'varchar(100)';
 919  $defaultCallDuration->typeofdata = 'V~O';
 920  $defaultCallDuration->uitype = 16;
 921  $defaultCallDuration->sequence = 3;
 922  $defaultCallDuration->defaultvalue = 5;
 923  $calendarSettings->addField($defaultCallDuration);
 924  $defaultCallDuration->setPicklistValues(array('5','10','30','60','120'));
 925  
 926  $otherEventDuration = new Vtiger_Field();
 927  $otherEventDuration->name = 'othereventduration';
 928  $otherEventDuration->label = 'Other Event Duration';
 929  $otherEventDuration->table ='vtiger_users';
 930  $otherEventDuration->column = 'othereventduration';
 931  $otherEventDuration->columntype = 'varchar(100)';
 932  $otherEventDuration->typeofdata = 'V~O';
 933  $otherEventDuration->uitype = 16;
 934  $otherEventDuration->sequence = 4;
 935  $otherEventDuration->defaultvalue = 5;
 936  $calendarSettings->addField($otherEventDuration);
 937  $otherEventDuration->setPicklistValues(array('5','10','30','60','120'));
 938  
 939  $blockId = getBlockId($tabId, 'LBL_CALENDAR_SETTINGS');
 940  $sql = 'UPDATE vtiger_field SET block = ? , displaytype = ? WHERE tabid = ? AND tablename = ? AND columnname in (?,?,?,?,?,?)';
 941  Migration_Index_View::ExecuteQuery($sql, array($blockId, 1, $tabId, 'vtiger_users', 'time_zone','activity_view','reminder_interval','date_format','start_hour', 'hour_format'));
 942  
 943  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET uitype = ? WHERE tabid = ? AND tablename = ? AND columnname in (?,?)',
 944          array(16, $tabId, 'vtiger_users', 'hour_format', 'start_hour'));
 945  
 946  $fieldid = getFieldid($tabId, 'hour_format');
 947  $hour_format = Vtiger_Field::getInstance($fieldid, $moduleInstance);
 948  $hour_format->setPicklistValues(array(12,24));
 949  
 950  $fieldid = getFieldid($tabId, 'start_hour');
 951  $start_hour = Vtiger_Field::getInstance($fieldid, $moduleInstance);
 952  $start_hour->setPicklistValues(array('00:00','01:00','02:00','03:00','04:00','05:00','06:00','07:00','08:00','09:00','10:00','11:00'
 953                                  ,'12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'));
 954  
 955  //update hour_format value in existing customers

 956  Migration_Index_View::ExecuteQuery('UPDATE vtiger_users SET hour_format = ? WHERE hour_format = ? OR hour_format = ?', array(12, 'am/pm', ''));
 957  
 958  //add user default values

 959  Migration_Index_View::ExecuteQuery('UPDATE vtiger_users SET dayoftheweek = ?, callduration = ?, othereventduration = ?, start_hour = ? ', array('Sunday', 5, 5, '00:00'));
 960  
 961  $moduleInstance = Vtiger_Module::getInstance('Events');
 962  $tabId = getTabid('Events');
 963  
 964  // Update/Increment the sequence for the succeeding blocks of Events module, with starting sequence 4

 965  Migration_Index_View::ExecuteQuery('UPDATE vtiger_blocks SET sequence = sequence+1 WHERE tabid=? AND sequence >= 4', array($tabId));
 966  
 967  // Create Recurrence Information block

 968  $recurrenceBlock = new Vtiger_Block();
 969  $recurrenceBlock->label = 'LBL_RELATED_TO';
 970  $recurrenceBlock->sequence = 4;
 971  $moduleInstance->addBlock($recurrenceBlock);
 972  
 973  $blockId = getBlockId($tabId, 'LBL_RELATED_TO');
 974  
 975  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET block=? WHERE fieldname IN (?,?) and tabid=?', array($blockId, 'contact_id','parent_id', $tabId));
 976  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET displaytype=1 WHERE fieldname=? and tabid=?',array('recurringtype',$tabId));
 977  
 978  // END 2012.12.02

 979  
 980  // //////////////////////////////////////////////

 981  $inventoryModules = array(
 982      'Invoice' => array('LBL_INVOICE_INFORMATION', 'vtiger_invoice', 'invoiceid'),
 983      'SalesOrder' => array('LBL_SO_INFORMATION', 'vtiger_salesorder', 'salesorderid'),
 984      'PurchaseOrder' => array('LBL_PO_INFORMATION', 'vtiger_purchaseorder', 'purchaseorderid'),
 985      'Quotes' => array('LBL_QUOTE_INFORMATION', 'vtiger_quotes', 'quoteid')
 986  );
 987  
 988  foreach ($inventoryModules as $module => $details) {
 989      $tableName = $details[1];
 990      $moduleInstance = Vtiger_Module::getInstance($module);
 991      $block = Vtiger_Block::getInstance($details[0], $moduleInstance);
 992  
 993      $preTaxTotalField = new Vtiger_Field();
 994      $preTaxTotalField->name = 'pre_tax_total';
 995      $preTaxTotalField->label = 'Pre Tax Total';
 996      $preTaxTotalField->table = $tableName;
 997      $preTaxTotalField->column = 'pre_tax_total';
 998      $preTaxTotalField->columntype = 'decimal(25,8)';
 999      $preTaxTotalField->typeofdata = 'N~O';
1000      $preTaxTotalField->uitype = '72';
1001      $preTaxTotalField->masseditable = '1';
1002      $preTaxTotalField->displaytype = '3';
1003      $block->addField($preTaxTotalField);
1004  
1005      $tableId = $details[2];
1006  
1007      $result = $adb->pquery("SELECT $tableId, subtotal, s_h_amount, discount_percent, discount_amount FROM $tableName", array());
1008      $numOfRows = $adb->num_rows($result);
1009  
1010      for ($i = 0; $i < $numOfRows; $i++) {
1011          $id = $adb->query_result($result, $i, $tableId);
1012          $subTotal = (float) $adb->query_result($result, $i, "subtotal");
1013          $shAmount = (float) $adb->query_result($result, $i, "s_h_amount");
1014          $discountAmount = (float) $adb->query_result($result, $i, "discount_amount");
1015          $discountPercent = (float) $adb->query_result($result, $i, "discount_percent");
1016  
1017          if ($discountPercent != '0') {
1018              $discountAmount = ($subTotal * $discountPercent) / 100;
1019          }
1020          $preTaxTotalValue = $subTotal + $shAmount - $discountAmount;
1021  
1022          Migration_Index_View::ExecuteQuery("UPDATE $tableName set pre_tax_total = ? WHERE $tableId = ?", array($preTaxTotalValue, $id));
1023      }
1024  }
1025  
1026  $moduleInstance = Vtiger_Module::getInstance('Users');
1027  
1028  $calendarSettings = Vtiger_Block::getInstance('LBL_CALENDAR_SETTINGS', $moduleInstance);
1029  $calendarsharedtype = new Vtiger_Field();
1030  $calendarsharedtype->name = 'calendarsharedtype';
1031  $calendarsharedtype->label = 'Calendar Shared Type';
1032  $calendarsharedtype->table ='vtiger_users';
1033  $calendarsharedtype->column = 'calendarsharedtype';
1034  $calendarsharedtype->columntype = 'varchar(100)';
1035  $calendarsharedtype->typeofdata = 'V~O';
1036  $calendarsharedtype->uitype = 16;
1037  $calendarsharedtype->sequence = 2;
1038  $calendarsharedtype->displaytype = 3;
1039  $calendarsharedtype->defaultvalue = 'Public';
1040  $calendarSettings->addField($calendarsharedtype);
1041  $calendarsharedtype->setPicklistValues(array('public','private','seletedusers'));
1042  
1043  $allUsers = get_user_array(false);
1044  foreach ($allUsers as $id => $name) {
1045      $query = 'select sharedid from vtiger_sharedcalendar where userid=?';
1046      $result = $adb->pquery($query, array($id));
1047      $count = $adb->num_rows($result);
1048      if($count > 0){
1049          Migration_Index_View::ExecuteQuery('UPDATE vtiger_users SET calendarsharedtype = ? WHERE id = ?', array('selectedusers', $id));
1050      }else{
1051          Migration_Index_View::ExecuteQuery('UPDATE vtiger_users SET calendarsharedtype = ? WHERE id = ? ', array('public', $id));
1052          foreach ($allUsers as $sharedid => $name) {
1053              if($sharedid != $id){
1054                  $sql = "INSERT INTO vtiger_sharedcalendar VALUES (?,?)";
1055                  Migration_Index_View::ExecuteQuery($sql, array($id, $sharedid));
1056              }
1057          }
1058      }
1059  }
1060  
1061  // Add Key Metrics widget.

1062  $homeModule = Vtiger_Module::getInstance('Home');
1063  $homeModule->addLink('DASHBOARDWIDGET', 'Key Metrics', 'index.php?module=Home&view=ShowWidget&name=KeyMetrics');
1064  
1065  $moduleArray = array('Accounts' => 'LBL_ACCOUNT_INFORMATION', 'Contacts' => 'LBL_CONTACT_INFORMATION', 'Potentials' => 'LBL_OPPORTUNITY_INFORMATION');
1066  foreach ($moduleArray as $module => $block) {
1067      $moduleInstance = Vtiger_Module::getInstance($module);
1068      $blockInstance = Vtiger_Block::getInstance($block, $moduleInstance);
1069  
1070      $field = new Vtiger_Field();
1071      $field->name = 'isconvertedfromlead';
1072      $field->label = 'Is Converted From Lead';
1073      $field->uitype = 56;
1074      $field->column = 'isconvertedfromlead';
1075      $field->displaytype = 2;
1076      $field->defaultvalue = 'no';
1077      $field->columntype = 'varchar(3)';
1078      $field->typeofdata = 'C~O';
1079      $blockInstance->addField($field);
1080  }
1081  
1082  $homeModule = Vtiger_Module::getInstance('Home');
1083  $homeModule->addLink('DASHBOARDWIDGET', 'Mini List', 'index.php?module=Home&view=ShowWidget&name=MiniList');
1084  
1085  $moduleInstance = Vtiger_Module::getInstance('Users');
1086  $moreInfoBlock = Vtiger_Block::getInstance('LBL_MORE_INFORMATION', $moduleInstance);
1087  
1088  $viewField = new Vtiger_Field();
1089  $viewField->name = 'default_record_view';
1090  $viewField->label = 'Default Record View';
1091  $viewField->table ='vtiger_users';
1092  $viewField->column = 'default_record_view';
1093  $viewField->columntype = 'VARCHAR(10)';
1094  $viewField->typeofdata = 'V~O';
1095  $viewField->uitype = 16;
1096  $viewField->defaultvalue = 'Summary';
1097  
1098  $moreInfoBlock->addField($viewField);
1099  $viewField->setPicklistValues(array('Summary', 'Detail'));
1100  
1101  Migration_Index_View::ExecuteQuery('UPDATE vtiger_users SET default_record_view = ?', array('Summary'));
1102  
1103  $InvoiceInstance = Vtiger_Module::getInstance('Invoice');
1104  Vtiger_Event::register($InvoiceInstance, 'vtiger.entity.aftersave', 'InvoiceHandler', 'modules/Invoice/InvoiceHandler.php');
1105  
1106  $POInstance = Vtiger_Module::getInstance('PurchaseOrder');
1107  Vtiger_Event::register($POInstance, 'vtiger.entity.aftersave', 'PurchaseOrderHandler', 'modules/PurchaseOrder/PurchaseOrderHandler.php');
1108  
1109  $InvoiceBlockInstance = Vtiger_Block::getInstance('LBL_INVOICE_INFORMATION', $InvoiceInstance);
1110  $field1 = Vtiger_Field::getInstance('received', $InvoiceInstance);
1111  if (!$field1) {
1112      $field1 = new Vtiger_Field();
1113      $field1->name = 'received';
1114      $field1->label = 'Received';
1115      $field1->table = 'vtiger_invoice';
1116      $field1->uitype = 72;
1117      $field1->displaytype = 3;
1118      $field1->typeofdata = 'N~O';
1119      $field1->defaultvalue = 0;
1120      $InvoiceBlockInstance->addField($field1);
1121  }
1122  $field2 = Vtiger_Field::getInstance('balance', $InvoiceInstance);
1123  if (!$field2) {
1124      $field2 = new Vtiger_Field();
1125      $field2->name = 'balance';
1126      $field2->label = 'Balance';
1127      $field1->table = 'vtiger_invoice';
1128      $field2->uitype = 72;
1129      $field2->typeofdata = 'N~O';
1130      $field2->defaultvalue = 0;
1131      $field2->displaytype = 3;
1132      $InvoiceBlockInstance->addField($field2);
1133  }
1134  
1135  $POBlockInstance = Vtiger_Block::getInstance('LBL_PO_INFORMATION', $POInstance);
1136  $field3 = Vtiger_Field::getInstance('paid', $POInstance);
1137  if (!$field3) {
1138      $field3 = new Vtiger_Field();
1139      $field3->name = 'paid';
1140      $field3->label = 'Paid';
1141      $field3->table = 'vtiger_purchaseorder';
1142      $field3->uitype = 72;
1143      $field3->displaytype = 3;
1144      $field3->typeofdata = 'N~O';
1145      $field3->defaultvalue = 0;
1146      $POBlockInstance->addField($field3);
1147  }
1148  $field4 = Vtiger_Field::getInstance('balance', $POInstance);
1149  if (!$field4) {
1150      $field4 = new Vtiger_Field();
1151      $field4->name = 'balance';
1152      $field4->label = 'Balance';
1153      $field4->table = 'vtiger_purchaseorder';
1154      $field4->uitype = 72;
1155      $field4->typeofdata = 'N~O';
1156      $field4->defaultvalue = 0;
1157      $field4->displaytype = 3;
1158      $POBlockInstance->addField($field4);
1159  }
1160  
1161  
1162  $sqltimelogTable = "CREATE TABLE vtiger_sqltimelog ( id integer, type VARCHAR(10),
1163                      data text, started decimal(18,2), ended decimal(18,2), loggedon datetime)";
1164  
1165  Migration_Index_View::ExecuteQuery($sqltimelogTable, array());
1166  
1167  
1168  $moduleName = 'PurchaseOrder';
1169  $emm = new VTEntityMethodManager($adb);
1170  $emm->addEntityMethod($moduleName,"UpdateInventory","include/InventoryHandler.php","handleInventoryProductRel");
1171  
1172  $vtWorkFlow = new VTWorkflowManager($adb);
1173  $poWorkFlow = $vtWorkFlow->newWorkFlow($moduleName);
1174  $poWorkFlow->description = "Update Inventory Products On Every Save";
1175  $poWorkFlow->defaultworkflow = 1;
1176  $poWorkFlow->executionCondition = 3;
1177  $vtWorkFlow->save($poWorkFlow);
1178  
1179  $tm = new VTTaskManager($adb);
1180  $task = $tm->createTask('VTEntityMethodTask', $poWorkFlow->id);
1181  $task->active = true;
1182  $task->summary = "Update Inventory Products";
1183  $task->methodName = "UpdateInventory";
1184  $tm->saveTask($task);
1185  
1186  // Add Tag Cloud widget.

1187  $homeModule = Vtiger_Module::getInstance('Home');
1188  $homeModule->addLink('DASHBOARDWIDGET', 'Tag Cloud', 'index.php?module=Home&view=ShowWidget&name=TagCloud');
1189  
1190  // Schema changed for capturing Dashboard widget positions

1191  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_module_dashboard_widgets ADD COLUMN position VARCHAR(50)',array());
1192  
1193  $moduleInstance = Vtiger_Module::getInstance('Contacts');
1194  if($moduleInstance) {
1195      $moduleInstance->addLink('LISTVIEWSIDEBARWIDGET','Google Contacts',
1196          'module=Google&view=List&sourcemodule=Contacts', '','', '');
1197  }
1198  
1199  $moduleInstance = Vtiger_Module::getInstance('Calendar');
1200  if($moduleInstance) {
1201      $moduleInstance->addLink('LISTVIEWSIDEBARWIDGET','Google Calendar',
1202          'module=Google&view=List&sourcemodule=Calendar', '','', '');
1203  }
1204  
1205  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_cvadvfilter MODIFY comparator VARCHAR(20)', array());
1206  Migration_Index_View::ExecuteQuery('UPDATE vtiger_cvadvfilter SET comparator = ? WHERE comparator = ?', array('next120days', 'next120day'));
1207  Migration_Index_View::ExecuteQuery('UPDATE vtiger_cvadvfilter SET comparator = ? WHERE comparator = ?', array('last120days', 'last120day'));
1208  
1209  Migration_Index_View::ExecuteQuery("UPDATE vtiger_relatedlists SET actions = ? WHERE tabid = ? AND related_tabid IN (?, ?)",
1210      array('ADD', getTabid('Project'), getTabid('ProjectTask'), getTabid('ProjectMilestone')));
1211  
1212  Migration_Index_View::ExecuteQuery("UPDATE vtiger_field SET typeofdata = ? WHERE columnname = ? AND tablename = ?", array("V~O", "company", "vtiger_leaddetails"));
1213  
1214  if(Vtiger_Utils::CheckTable('vtiger_cron_task')) {
1215      Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_cron_task MODIFY COLUMN laststart INT(11) UNSIGNED',Array());
1216      Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_cron_task MODIFY COLUMN lastend INT(11) UNSIGNED',Array());
1217  }
1218  
1219  if(Vtiger_Utils::CheckTable('vtiger_cron_log')) {
1220      Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_cron_log MODIFY COLUMN start INT(11) UNSIGNED',Array());
1221         Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_cron_log MODIFY COLUMN end INT(11) UNSIGNED',Array());
1222  }
1223  
1224  require_once  'vtlib/Vtiger/Cron.php';
1225  Vtiger_Cron::deregister('ScheduleReports');
1226  // END 2013.02.18

1227  
1228  // Start 2013.03.19

1229  // Mail Converter schema changes

1230  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_mailscanner ADD COLUMN timezone VARCHAR(10) default NULL', array());
1231  Migration_Index_View::ExecuteQuery('UPDATE vtiger_mailscanner SET timezone=? WHERE server LIKE ? AND timezone IS NULL', array('-8:00', '%.gmail.com'));
1232  
1233  Migration_Index_View::ExecuteQuery('UPDATE vtiger_report SET state=?', array('CUSTOM'));
1234  
1235  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_relcriteria MODIFY value VARCHAR(512)", array());
1236  Migration_Index_View::ExecuteQuery("ALTER TABLE vtiger_cvadvfilter MODIFY value VARCHAR(512)", array());
1237  // End 2013.03.19

1238  
1239  // Start 2013.04.23

1240  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_sqltimelog MODIFY started DECIMAL(20,6)', array());
1241  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_sqltimelog MODIFY ended DECIMAL(20,6)', array());
1242  
1243  //added Assests tab in contact

1244  $assetsModuleInstance = Vtiger_Module::getInstance('Assets');
1245  $contactModule = Vtiger_Module::getInstance('Contacts');
1246  $contactModule->setRelatedList($assetsModuleInstance, '', false, 'get_dependents_list');
1247  // End 2013.04.23

1248  
1249  // Start 2013.04.30

1250  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_users MODIFY signature TEXT', array());
1251  //Adding column to store the state of short cut settings fields

1252  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_settings_field ADD COLUMN pinned int(1) DEFAULT 0',array());
1253  
1254  $defaultPinnedFields = array('LBL_USERS','LBL_LIST_WORKFLOWS','VTLIB_LBL_MODULE_MANAGER','LBL_PICKLIST_EDITOR');
1255  $defaultPinnedSettingFieldQuery = 'UPDATE vtiger_settings_field SET pinned=1 WHERE name IN ('.generateQuestionMarks($defaultPinnedFields).')';
1256  Migration_Index_View::ExecuteQuery($defaultPinnedSettingFieldQuery,$defaultPinnedFields);
1257  
1258  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_profile ADD COLUMN directly_related_to_role int(1) DEFAULT 0',array());
1259  
1260  $blockId = getSettingsBlockId('LBL_STUDIO');
1261  $result = $adb->pquery('SELECT max(sequence) as maxSequence FROM vtiger_settings_field WHERE blockid=?', array($blockId));
1262  $sequence = 0;
1263  if($adb->num_rows($result) > 0 ) {
1264      $sequence = $adb->query_result($result,0,'maxSequence');
1265  }
1266  
1267  $fieldId = $adb->getUniqueID('vtiger_settings_field');
1268  $query = "INSERT INTO vtiger_settings_field (fieldid, blockid, name, iconpath, description, " .
1269          "linkto, sequence) VALUES (?,?,?,?,?,?,?)";
1270  $layoutEditoLink = 'index.php?module=LayoutEditor&parent=Settings&view=Index';
1271  $params = array($fieldId, $blockId, 'LBL_EDIT_FIELDS', '', 'LBL_LAYOUT_EDITOR_DESCRIPTION', $layoutEditoLink, $sequence);
1272  Migration_Index_View::ExecuteQuery($query, $params);
1273  
1274  Migration_Index_View::ExecuteQuery('UPDATE vtiger_role SET rolename = ? WHERE rolename = ? AND depth = ?', array('Organization', 'Organisation', 0));
1275  
1276  
1277  //Create a new table to support custom fields in Documents module

1278  $adb->query("CREATE TABLE IF NOT EXISTS vtiger_notescf (notesid INT(19), FOREIGN KEY fk_1_vtiger_notescf(notesid) REFERENCES vtiger_notes(notesid) ON DELETE CASCADE);");
1279  
1280  if(!defined('INSTALLATION_MODE')) {
1281      Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_salutationtype ADD COLUMN sortorderid INT(1)', array());
1282  }
1283  
1284  $summaryFields = array(
1285      'Accounts'    => array('assigned_user_id', 'email1', 'phone', 'bill_city', 'bill_country', 'website'),
1286      'Contacts'    => array('assigned_user_id', 'email', 'phone', 'mailingcity', 'mailingcountry'),
1287      'Leads'        => array('assigned_user_id', 'email', 'phone', 'city', 'country', 'leadsource'),
1288      'HelpDesk'    => array('assigned_user_id', 'ticketstatus', 'parent_id', 'ticketseverities', 'description'),
1289      'Potentials'=> array('assigned_user_id', 'amount', 'sales_stage', 'closingdate'),
1290      'Project'    => array('assigned_user_id', 'targetenddate'));
1291  
1292  foreach ($summaryFields as $moduleName => $fieldsList) {
1293      $updateQuery = 'UPDATE vtiger_field SET summaryfield = 1
1294                          WHERE fieldname IN ('.generateQuestionMarks($fieldsList) .') AND tabid = '. getTabid($moduleName);
1295      Migration_Index_View::ExecuteQuery($updateQuery, $fieldsList);
1296  }
1297  
1298  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=? WHERE tablename=? AND fieldname= ?', array('Active', 'vtiger_users', 'status'));
1299  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=? WHERE tablename=? AND fieldname= ?', array('12', 'vtiger_users', 'hour_format'));
1300  
1301  // Adding users field into all the available profiles, this is used in email templates

1302  // when non-admin sends an email with users field in the template

1303  $module = 'Users';
1304  $user = new $module();
1305  $activeAdmin = Users::getActiveAdminId();
1306  $user->retrieve_entity_info($activeAdmin, $module);
1307  $handler = vtws_getModuleHandlerFromName($module, $user);
1308  $meta = $handler->getMeta();
1309  $moduleFields = $meta->getModuleFields();
1310  
1311  $userAccessbleFields = array();
1312  $skipFields = array(98,115,116,31,32);
1313  foreach ($moduleFields as $fieldName => $webserviceField) {
1314      if($webserviceField->getFieldDataType() == 'string' || $webserviceField->getFieldDataType() == 'email' || $webserviceField->getFieldDataType() == 'phone') {
1315          if(!in_array($webserviceField->getUitype(), $skipFields) && $fieldName != 'asterisk_extension'){
1316              $userAccessbleFields[$webserviceField->getFieldId()] .= $fieldName;
1317          }
1318      }
1319  }
1320  
1321  $tabId = getTabid($module);
1322  $query = 'SELECT profileid FROM vtiger_profile';
1323  $result = $adb->pquery($query, array());
1324  
1325  for($i=0; $i<$adb->num_rows($result); $i++) {
1326      $profileId = $adb->query_result($result, $i, 'profileid');
1327      $sql = 'SELECT fieldid FROM vtiger_profile2field WHERE profileid = ? AND tabid = ?';
1328      $fieldsResult = $adb->pquery($sql, array($profileId, $tabId));
1329      $profile2Fields = array();
1330      $rows = $adb->num_rows($fieldsResult);
1331      for($j=0; $j<$rows; $j++) {
1332          array_push($profile2Fields, $adb->query_result($fieldsResult, $j, 'fieldid'));
1333      }
1334      foreach ($userAccessbleFields as $fieldId => $fieldName) {
1335          if(!in_array($fieldId, $profile2Fields)){
1336              $insertQuery = 'INSERT INTO vtiger_profile2field(profileid,tabid,fieldid,visible,readonly) VALUES(?,?,?,?,?)';
1337              Migration_Index_View::ExecuteQuery($insertQuery, array($profileId,$tabId,$fieldId,0,0));
1338          }
1339      }
1340  }
1341  
1342  //Added user field in vtiger_def_org_field table

1343  $sql = 'SELECT fieldid FROM vtiger_def_org_field WHERE tabid = ?';
1344  $result1 = $adb->pquery($sql, array($tabId));
1345  $def_org_fields = array();
1346  $defRows = $adb->num_rows($result1);
1347  for($j=0; $j<$defRows; $j++) {
1348      array_push($def_org_fields, $adb->query_result($result1, $j, 'fieldid'));
1349  }
1350  foreach ($userAccessbleFields as $fieldId => $fieldName) {
1351      if(!in_array($fieldId, $def_org_fields)){
1352          $insertQuery = 'INSERT INTO vtiger_def_org_field(tabid,fieldid,visible,readonly) VALUES(?,?,?,?)';
1353          Migration_Index_View::ExecuteQuery($insertQuery, array($tabId,$fieldId,0,0));
1354      }
1355  }
1356  
1357  //need to recreate user_privileges files as lot of user fields are added in this script and user_priviliges files are not updated

1358  require_once ('modules/Users/CreateUserPrivilegeFile.php');
1359  createUserPrivilegesfile('1');
1360  
1361  //Remove '--None--'/'None' from all the picklist values.

1362  $sql = 'SELECT fieldname FROM vtiger_field WHERE uitype IN(?,?,?,?)';
1363  $result = $adb->pquery($sql, array(15,16,33,55));
1364  $num_rows = $adb->num_rows($result);
1365  for($i=0; $i<$num_rows; $i++){
1366      $fieldName = $adb->query_result($result, $i, 'fieldname');
1367      $checkTable = $adb->pquery('SHOW TABLES LIKE "vtiger_'.$fieldName.'"', array());
1368      if($adb->num_rows($checkTable) > 0) {
1369          $query = "DELETE FROM vtiger_$fieldName WHERE $fieldName = ? OR $fieldName = ?";
1370          Migration_Index_View::ExecuteQuery($query, array('--None--', 'None'));
1371      }
1372  }
1373  
1374  $potentials = Vtiger_Module::getInstance('Potentials');
1375  $potentials->addLink('DASHBOARDWIDGET', 'Funnel Amount', 'index.php?module=Potentials&view=ShowWidget&name=FunnelAmount','', '10');
1376  $home = Vtiger_Module::getInstance('Home');
1377  $home->addLink('DASHBOARDWIDGET', 'Funnel Amount', 'index.php?module=Potentials&view=ShowWidget&name=FunnelAmount','', '10');
1378  
1379  // Enable Sharing-Access for Vendors

1380  $vendorInstance = Vtiger_Module::getInstance('Vendors');
1381  $vendorAssignedToField = Vtiger_Field::getInstance('assigned_user_id', $vendorInstance);
1382  if (!$vendorAssignedToField) {
1383      $vendorBlock = Vtiger_Block::getInstance('LBL_VENDOR_INFORMATION', $vendorInstance);
1384  
1385      $vendorAssignedToField = new Vtiger_Field();
1386      $vendorAssignedToField->name = 'assigned_user_id';
1387      $vendorAssignedToField->label = 'Assigned To';
1388      $vendorAssignedToField->table = 'vtiger_crmentity';
1389      $vendorAssignedToField->column = 'smownerid';
1390      $vendorAssignedToField->uitype = 53;
1391      $vendorAssignedToField->typeofdata = 'V~M';
1392      $vendorBlock->addField($vendorAssignedToField);
1393  
1394      $vendorAllFilter = Vtiger_Filter::getInstance('All', $vendorInstance);
1395      $vendorAllFilter->addField($vendorAssignedToField, 5);
1396  }
1397  
1398  // Allow Sharing access and role-based security for Vendors

1399  Vtiger_Access::deleteSharing($vendorInstance);
1400  Vtiger_Access::initSharing($vendorInstance);
1401  Vtiger_Access::allowSharing($vendorInstance);
1402  Vtiger_Access::setDefaultSharing($vendorInstance);
1403  
1404  Vtiger_Module::syncfile();
1405  
1406  // Add Email Opt-out for Leads

1407  $leadsInstance = Vtiger_Module::getInstance('Leads');
1408  $leadsOptOutField= Vtiger_Field::getInstance('emailoptout', $leadsInstance);
1409  
1410  if (!$leadsOptOutField) {
1411      $leadsOptOutField = new Vtiger_Field();
1412      $leadsOptOutField->name = 'emailoptout';
1413      $leadsOptOutField->label = 'Email Opt Out';
1414      $leadsOptOutField->table = 'vtiger_leaddetails';
1415      $leadsOptOutField->column = $leadsOptOutField->name;
1416      $leadsOptOutField->columntype = 'VARCHAR(3)';
1417      $leadsOptOutField->uitype = 56;
1418      $leadsOptOutField->typeofdata = 'C~O';
1419  
1420      $leadsInformationBlock = Vtiger_Block::getInstance('LBL_LEAD_INFORMATION', $leadsInstance);
1421      $leadsInformationBlock->addField($leadsOptOutField);
1422  
1423      Migration_Index_View::ExecuteQuery('UPDATE vtiger_leaddetails SET emailoptout=0 WHERE emailoptout IS NULL', array());
1424  }
1425  
1426  $module = Vtiger_Module::getInstance('Home');
1427  $module->addLink('DASHBOARDWIDGET', 'Notebook', 'index.php?module=Home&view=ShowWidget&name=Notebook');
1428  
1429  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_module_dashboard_widgets MODIFY data TEXT',array());
1430  
1431  $linkIdResult = $adb->pquery('SELECT linkid FROM vtiger_links WHERE vtiger_links.linklabel="Notebook"', array());
1432  $noteBookLinkId = $adb->query_result($linkIdResult, 0, 'linkid');
1433  
1434  $result = $adb->pquery('SELECT vtiger_homestuff.stufftitle, vtiger_homestuff.userid, vtiger_notebook_contents.contents FROM
1435                          vtiger_homestuff INNER JOIN vtiger_notebook_contents on vtiger_notebook_contents.notebookid = vtiger_homestuff.stuffid
1436                          WHERE vtiger_homestuff.stufftype = ?', array('Notebook'));
1437  
1438  for($i=0; $i<$adb->num_rows($result); $i++) {
1439      $noteBookTitle = $adb->query_result($result, $i, 'stufftitle');
1440      $userId = $adb->query_result($result, $i, 'userid');
1441      $noteBookContent = $adb->query_result($result, $i, 'contents');
1442      $query = 'INSERT INTO vtiger_module_dashboard_widgets(linkid, userid, filterid, title, data) VALUES(?,?,?,?,?)';
1443      $params= array($noteBookLinkId,$userId,0,$noteBookTitle,$noteBookContent);
1444      Migration_Index_View::ExecuteQuery($query, $params);
1445  }
1446  
1447  $moduleInstance = Vtiger_Module::getInstance('ModComments');
1448  $modCommentsUserId = Vtiger_Field::getInstance("userid", $moduleInstance);
1449  $modCommentsReasonToEdit = Vtiger_Field::getInstance("reasontoedit", $moduleInstance);
1450  
1451  if(!$modCommentsUserId){
1452      $blockInstance = Vtiger_Block::getInstance('LBL_MODCOMMENTS_INFORMATION', $moduleInstance);
1453      $userId = new Vtiger_Field();
1454      $userId->name = 'userid';
1455      $userId->label = 'UserId';
1456      $userId->uitype = '10';
1457      $userId->displaytype = '3';
1458      $blockInstance->addField($userId);
1459  }
1460  if(!$modCommentsReasonToEdit){
1461      $blockInstance = Vtiger_Block::getInstance('LBL_MODCOMMENTS_INFORMATION', $moduleInstance);
1462      $reasonToEdit = new Vtiger_Field();
1463      $reasonToEdit->name = 'reasontoedit';
1464      $reasonToEdit->label = 'ReasonToEdit';
1465      $reasonToEdit->uitype = '19';
1466      $reasonToEdit->displaytype = '1';
1467      $blockInstance->addField($reasonToEdit);
1468  }
1469  
1470  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_invoice MODIFY balance decimal(25,8)',array());
1471  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_invoice MODIFY received decimal(25,8)',array());
1472  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_purchaseorder MODIFY balance decimal(25,8)',array());
1473  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_purchaseorder MODIFY paid decimal(25,8)',array());
1474  
1475  $labels = array('LBL_ADD_NOTE', 'Add Note');
1476  $sql = 'UPDATE vtiger_links SET handler = ?, handler_class = ?, handler_path = ? WHERE linklabel IN (?, ?)';
1477  Migration_Index_View::ExecuteQuery($sql, array('isLinkPermitted', 'Documents', 'modules/Documents/Documents.php', $labels));
1478  
1479  $sql = 'UPDATE vtiger_links SET handler = ?, handler_class = ?, handler_path = ? WHERE linklabel = ?';
1480  Migration_Index_View::ExecuteQuery($sql, array('isLinkPermitted', 'ProjectTask', 'modules/ProjectTask/ProjectTask.php', 'Add Project Task'));
1481  
1482  Migration_Index_View::ExecuteQuery('DELETE FROM vtiger_settings_field WHERE name=?', array('EMAILTEMPLATES'));
1483  
1484  $tabIdList = array();
1485  $tabIdList[] = getTabid('Invoice');
1486  $tabIdList[] = getTabid('PurchaseOrder');
1487  
1488  $query = 'SELECT fieldid FROM vtiger_field WHERE (fieldname=? or fieldname=? or fieldname=? ) AND tabid IN ('.generateQuestionMarks($tabIdList).')';
1489  $result = $adb->pquery($query, array('received', 'paid', 'balance',$tabIdList));
1490  $numrows = $adb->num_rows($result);
1491  
1492  for ($i = 0; $i < $numrows; $i++) {
1493      $fieldid = $adb->query_result($result, $i, 'fieldid');
1494      $query = 'Update vtiger_profile2field set readonly = 0 where fieldid=?';
1495      Migration_Index_View::ExecuteQuery($query, array($fieldid));
1496  }
1497  
1498  $actions = array('Import','Export');
1499  $moduleInstance = Vtiger_Module::getInstance('Calendar');
1500  foreach ($actions as $actionName) {
1501      Vtiger_Access::updateTool($moduleInstance, $actionName, true, '');
1502  }
1503  
1504  //Update leads salutation value of none to empty value

1505  Migration_Index_View::ExecuteQuery("UPDATE vtiger_leaddetails SET salutation='' WHERE salutation = ?", array('--None--'));
1506  
1507  //Update contacts salutation value of none to empty value

1508  Migration_Index_View::ExecuteQuery("UPDATE vtiger_contactdetails SET salutation='' WHERE salutation = ?", array('--None--'));
1509  // END 2013-06-25

1510  
1511  // Start 2013-09-24

1512  Migration_Index_View::ExecuteQuery('UPDATE vtiger_eventhandlers SET handler_path = ? WHERE handler_class = ?',
1513                  array('modules/Vtiger/handlers/RecordLabelUpdater.php', 'Vtiger_RecordLabelUpdater_Handler'));
1514  
1515  $inventoryModules = array('Invoice','Quotes','PurchaseOrder','SalesOrder');
1516  foreach ($inventoryModules as $key => $moduleName) {
1517      $moduleInstance = Vtiger_Module::getInstance($moduleName);
1518      $focus = CRMEntity::getInstance($moduleName);
1519      $blockInstance = Vtiger_Block::getInstance('LBL_ITEM_DETAILS',$moduleInstance);
1520  
1521      $field = new Vtiger_Field();
1522      $field->name = 'hdnS_H_Percent';
1523      $field->label = 'S&H Percent';
1524      $field->column = 's_h_percent';
1525      $field->table = $focus->table_name;
1526      $field->uitype = 1;
1527      $field->typeofdata = 'N~O';
1528      $field->readonly = '0';
1529      $field->displaytype = '5';
1530      $field->masseditable = '0';
1531      $field->quickcreate = '0';
1532      $field->columntype = 'INT(11)';
1533      $blockInstance->addField($field);
1534  }
1535  
1536  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_invoice_recurring_info ADD PRIMARY KEY (salesorderid)',array());
1537  
1538  $result = $adb->pquery('SELECT task_id FROM com_vtiger_workflowtasks WHERE workflow_id IN
1539                          (SELECT workflow_id FROM com_vtiger_workflows WHERE module_name IN (?, ?))
1540                          AND summary = ?', array('Calendar', 'Events', 'Send Notification Email to Record Owner'));
1541  $numOfRows = $adb->num_rows($result);
1542  require_once  'modules/com_vtiger_workflow/tasks/VTSendNotificationTask.inc';
1543  for($i=0; $i<$numOfRows; $i++) {
1544      $tm = new VTTaskManager($adb);
1545      $task = $tm->retrieveTask($adb->query_result($result, $i, 'task_id'));
1546  
1547      $sendNotificationTask = new VTSendNotificationTask();
1548      $properties = get_object_vars($task);
1549      foreach ($properties as $propertyName => $propertyValue) {
1550          $sendNotificationTask->$propertyName = str_replace('$(general : (__VtigerMeta__) dbtimezone)', '$(general : (__VtigerMeta__) usertimezone)', $propertyValue);
1551      }
1552      $tm->saveTask($sendNotificationTask);
1553  }
1554  
1555  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET masseditable = ? where fieldname = ? and tabid = ?',
1556              array('1', 'accountname', getTabid('Accounts')));
1557  
1558  $result = $adb->pquery('SELECT taxname FROM vtiger_shippingtaxinfo', array());
1559  $numOfRows = $adb->num_rows($result);
1560  $shippingTaxes = array();
1561  $tabIds = array();
1562  for ($i = 0; $i < $numOfRows; $i++) {
1563      $shippingTaxName = $adb->query_result($result, $i, 'taxname');
1564      array_push($shippingTaxes, $shippingTaxName);
1565  }
1566  
1567  $modules = array('Invoice','Quotes','PurchaseOrder','SalesOrder');
1568  $tabIdQuery = 'SELECT tabid FROM vtiger_tab where name IN ('.generateQuestionMarks($modules).')';
1569  $tabIdRes = $adb->pquery($tabIdQuery,$modules);
1570  $num_rows = $adb->num_rows($tabIdRes);
1571  for ($i = 0; $i < $num_rows; $i++) {
1572      $tabIds[] = $adb->query_result($tabIdRes,0,'tabid');
1573  }
1574  
1575  $query = 'DELETE FROM vtiger_field WHERE tabid IN (' . generateQuestionMarks($tabIds) . ') AND fieldname IN (' . generateQuestionMarks($shippingTaxes) . ')';
1576  Migration_Index_View::ExecuteQuery($query, array_merge($tabIds, $shippingTaxes));
1577  
1578  $entityModules = Vtiger_Module_Model::getEntityModules();
1579  
1580  foreach($entityModules as $moduleModel) {
1581      $crmInstance = CRMEntity::getInstance($moduleModel->getName());
1582      $tabId = $moduleModel->getId();
1583      $defaultRelatedFields = $crmInstance->list_fields_name;
1584      $updateQuery = 'UPDATE vtiger_field SET summaryfield=1  where tabid=? and fieldname IN ('.generateQuestionMarks($defaultRelatedFields).')';
1585      Migration_Index_View::ExecuteQuery($updateQuery,  array_merge(array($tabId), array_values($defaultRelatedFields)));
1586  }
1587  
1588  Migration_Index_View::ExecuteQuery('UPDATE vtiger_currencies SET currency_name = ? where currency_name = ? and currency_code = ?',
1589          array('Hong Kong, Dollars', 'LvHong Kong, Dollars', 'HKD'));
1590  Migration_Index_View::ExecuteQuery('UPDATE vtiger_currency_info SET currency_name = ? where currency_name = ?',
1591          array('Hong Kong, Dollars', 'LvHong Kong, Dollars'));
1592  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=1 WHERE fieldname = ?',array("filestatus"));
1593  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_role ADD allowassignedrecordsto INT(2) NOT NULL DEFAULT 1', array());
1594  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_assets MODIFY datesold date', array());
1595  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_assets MODIFY dateinservice date', array());
1596  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_assets MODIFY serialnumber varchar(200)', array());
1597  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_assets MODIFY account int(19)', array());
1598  Migration_Index_View::ExecuteQuery('ALTER TABLE com_vtiger_workflowtask_queue ADD COLUMN task_contents text', array());
1599  Migration_Index_View::ExecuteQuery('ALTER TABLE com_vtiger_workflowtask_queue DROP INDEX com_vtiger_workflowtask_queue_idx',array());
1600  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_mailscanner_ids modify column messageid varchar(512)' , array());
1601  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_mailscanner_ids add index scanner_message_ids_idx (scannerid, messageid)', array());
1602  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_mailscanner_folders add index folderid_idx (folderid)', array());
1603  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_leaddetails add index email_idx (email)', array());
1604  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_contactdetails add index email_idx (email)', array());
1605  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_account add index email_idx (email1, email2)', array());
1606  
1607  $moduleInstance = Vtiger_Module::getInstance('Users');
1608  $blockInstance = Vtiger_Block::getInstance('LBL_MORE_INFORMATION',$moduleInstance);
1609  
1610  $field = new Vtiger_Field();
1611  $field->name = 'leftpanelhide';
1612  $field->label = 'Left Panel Hide';
1613  $field->column = 'leftpanelhide';
1614  $field->table = 'vtiger_users';
1615  $field->uitype = 56;
1616  $field->typeofdata = 'V~O';
1617  $field->readonly = 1;
1618  $field->displaytype = 1;
1619  $field->masseditable = 1;
1620  $field->quickcreate = 1;
1621  $field->defaultvalue = 0;
1622  $field->columntype = 'VARCHAR(3)';
1623  $blockInstance->addField($field);
1624  
1625  Migration_Index_View::ExecuteQuery('UPDATE vtiger_users SET leftpanelhide = ?', array(0));
1626  $potentialModule = Vtiger_Module::getInstance('Potentials');
1627  $block = Vtiger_Block::getInstance('LBL_OPPORTUNITY_INFORMATION', $potentialModule);
1628  
1629  $relatedToField = Vtiger_Field::getInstance('related_to', $potentialModule);
1630  $relatedToField->unsetRelatedModules(array('Contacts'));
1631  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET typeofdata = ? WHERE fieldid = ?', array('V~O', $relatedToField->id));
1632  
1633  $contactField = Vtiger_Field::getInstance('contact_id', $potentialModule);
1634  if(!$contactField) {
1635      $contactField = new Vtiger_Field();
1636      $contactField->name = 'contact_id';
1637      $contactField->label = 'Contact Name';
1638      $contactField->uitype = '10';
1639      $contactField->column = 'contact_id';
1640      $contactField->table = 'vtiger_potential';
1641      $contactField->columntype = 'INT(19)';
1642      $block->addField($contactField);
1643      $contactField->setRelatedModules(array('Contacts'));
1644      Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET summaryfield=1 WHERE fieldid = ?', array($contactField->id));
1645  }
1646  
1647  $lastPotentialId = 0;
1648  do {
1649      $result = $adb->pquery("SELECT potentialid ,related_to FROM vtiger_potential WHERE potentialid > ? LIMIT 500",
1650              array($lastPotentialId));
1651      if (!$adb->num_rows($result)) break;
1652  
1653      while ($row = $adb->fetch_array($result)) {
1654          $relatedTo = $row['related_to'];
1655          $potentialId = $row['potentialid'];
1656  
1657          $relatedToType = getSalesEntityType($relatedTo);
1658          if($relatedToType != 'Accounts') {
1659              Migration_Index_View::ExecuteQuery('UPDATE vtiger_potential SET contact_id = ?, related_to = null WHERE potentialid = ?',
1660                      array($relatedTo, $potentialId));
1661          }
1662          if (intval($potentialId) > $lastPotentialId) {
1663              $lastPotentialId = intval($row['potentialid']);
1664          }
1665          unset($relatedTo);
1666      }
1667      unset($result);
1668  } while(true);
1669  
1670  $filterResult = $adb->pquery('SELECT * FROM vtiger_cvadvfilter WHERE columnname like ?',
1671          array('vtiger_potential:related_to:related_to:Potentials_Related_%'));
1672  $rows = $adb->num_rows($filterResult);
1673  for($i=0; $i<$rows; $i++) {
1674      $cvid = $adb->query_result($filterResult, $i, 'cvid');
1675      $columnIndex = $adb->query_result($filterResult, $i, 'columnindex');
1676      $comparator = $adb->query_result($filterResult, $i, 'comparator');
1677      $value = $adb->query_result($filterResult, $i, 'value');
1678  
1679      Migration_Index_View::ExecuteQuery('UPDATE vtiger_cvadvfilter SET groupid = 2, column_condition = ? WHERE cvid = ?', array('or', $cvid));
1680      Migration_Index_View::ExecuteQuery('UPDATE vtiger_cvadvfilter_grouping SET groupid = 2 WHERE cvid = ?', array($cvid));
1681  
1682      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_cvadvfilter(cvid,columnindex,columnname,comparator,value,groupid,column_condition)
1683          VALUES(?,?,?,?,?,?,?)', array($cvid, ++$columnIndex,'vtiger_potential:contact_id:contact_id:Potentials_Contact_Name:V',
1684              $comparator, $value, 2, ''));
1685  }
1686  unset($filterResult);
1687  
1688  $filterColumnList = $adb->pquery('SELECT * FROM vtiger_cvcolumnlist WHERE columnname like ?',
1689          array('vtiger_potential:related_to:related_to:Potentials_Related_%'));
1690  $filterColumnRows = $adb->num_rows($filterColumnList);
1691  for($j=0; $j<$filterColumnRows; $j++) {
1692      $cvid = $adb->query_result($filterColumnList, $j, 'cvid');
1693      $filterResult = $adb->pquery('SELECT MAX(columnindex) AS maxcolumn FROM vtiger_cvcolumnlist WHERE cvid = ?', array($cvid));
1694      $maxColumnIndex = $adb->query_result($filterResult, 0, 'maxcolumn');
1695      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_cvcolumnlist(cvid,columnindex,columnname) VALUES (?,?,?)', array($cvid, ++$maxColumnIndex,
1696          'vtiger_potential:contact_id:contact_id:Potentials_Contact_Name:V'));
1697      unset($filterResult);
1698  }
1699  unset($filterColumnList);
1700  
1701  $reportColumnResult = $adb->pquery('SELECT * FROM vtiger_selectcolumn WHERE columnname = ?',
1702          array('vtiger_potential:related_to:Potentials_Related_To:related_to:V'));
1703  $reportColumnRows = $adb->num_rows($reportColumnResult);
1704  
1705  for($k=0; $k<$reportColumnRows; $k++) {
1706      $reportId = $adb->query_result($reportColumnResult, $k, 'queryid');
1707      $filterResult = $adb->pquery('SELECT MAX(columnindex) AS maxcolumn FROM vtiger_selectcolumn WHERE queryid = ?', array($reportId));
1708      $maxColumnIndex = $adb->query_result($filterResult, 0, 'maxcolumn');
1709      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_selectcolumn(queryid,columnindex,columnname) VALUES (?,?,?)', array($reportId,
1710          ++$maxColumnIndex, 'vtiger_potential:contact_id:Potentials_Contact_Name:contact_id:V'));
1711      unset($filterResult);
1712  }
1713  unset($reportColumnResult);
1714  
1715  $filterResult = $adb->pquery('SELECT * FROM vtiger_relcriteria WHERE columnname = ?',
1716                      array('vtiger_potential:related_to:Potentials_Related_To:related_to:V'));
1717  $rows = $adb->num_rows($filterResult);
1718  for($i=0; $i<$rows; $i++) {
1719  
1720      $reportId = $adb->query_result($filterResult, $i, 'queryid');
1721      $columnIndex = $adb->query_result($filterResult, $i, 'columnindex');
1722      $comparator = $adb->query_result($filterResult, $i, 'comparator');
1723      $value = $adb->query_result($filterResult, $i, 'value');
1724  
1725      Migration_Index_View::ExecuteQuery('UPDATE vtiger_relcriteria SET groupid = 2, column_condition = ? WHERE queryid = ?', array('or', $reportId));
1726      Migration_Index_View::ExecuteQuery('UPDATE vtiger_relcriteria_grouping SET groupid = 2 WHERE queryid = ?', array($reportId));
1727  
1728      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_relcriteria(queryid,columnindex,columnname,comparator,value,groupid,column_condition)
1729          VALUES(?,?,?,?,?,?,?)', array($reportId, ++$columnIndex,'vtiger_potential:contact_id:Potentials_Contact_Name:contact_id:V',
1730              $comparator, $value, 2, ''));
1731  }
1732  unset($filterResult);
1733  
1734  $ticketsModule = Vtiger_Module::getInstance('HelpDesk');
1735  $ticketsBlock = Vtiger_Block::getInstance('LBL_TICKET_INFORMATION', $ticketsModule);
1736  
1737  $relatedToField = Vtiger_Field::getInstance('parent_id', $ticketsModule);
1738  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET uitype = 10 WHERE fieldid = ?', array($relatedToField->id));
1739  $relatedToField->setRelatedModules(array('Accounts'));
1740  
1741  $contactField = Vtiger_Field::getInstance('contact_id', $ticketsModule);
1742  if(!$contactField) {
1743      $contactField = new Vtiger_Field();
1744      $contactField->name = 'contact_id';
1745      $contactField->label = 'Contact Name';
1746      $contactField->table = 'vtiger_troubletickets';
1747      $contactField->column = 'contact_id';
1748      $contactField->columntype = 'INT(19)';
1749      $contactField->uitype = '10';
1750      $ticketsBlock->addField($contactField);
1751  
1752      $contactField->setRelatedModules(array('Contacts'));
1753      Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET summaryfield = 1 WHERE fieldid = ?', array($contactField->id));
1754  }
1755  
1756  $lastTicketId = 0;
1757  do {
1758      $ticketsResult = $adb->pquery("SELECT ticketid ,parent_id FROM vtiger_troubletickets WHERE ticketid > ?
1759                          LIMIT 500", array($lastTicketId));
1760      if (!$adb->num_rows($ticketsResult)) break;
1761  
1762      while ($row = $adb->fetch_array($ticketsResult)) {
1763          $parent = $row['parent_id'];
1764          $ticketId = $row['ticketid'];
1765  
1766          $parentType = getSalesEntityType($parent);
1767          if($parentType != 'Accounts') {
1768              Migration_Index_View::ExecuteQuery('UPDATE vtiger_troubletickets SET contact_id = ?, parent_id = null WHERE ticketid = ?',
1769                      array($parent, $ticketId));
1770          }
1771          if (intval($ticketId) > $lastTicketId) {
1772              $lastTicketId = intval($row['ticketid']);
1773          }
1774          unset($parent);
1775      }
1776      unset($ticketsResult);
1777  } while(true);
1778  
1779  $ticketFilterResult = $adb->pquery('SELECT * FROM vtiger_cvadvfilter WHERE columnname like ?',
1780                          array('vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related%'));
1781  $rows = $adb->num_rows($ticketFilterResult);
1782  for($i=0; $i<$rows; $i++) {
1783      $cvid = $adb->query_result($ticketFilterResult, $i, 'cvid');
1784      $columnIndex = $adb->query_result($ticketFilterResult, $i, 'columnindex');
1785      $comparator = $adb->query_result($ticketFilterResult, $i, 'comparator');
1786      $value = $adb->query_result($ticketFilterResult, $i, 'value');
1787  
1788      Migration_Index_View::ExecuteQuery('UPDATE vtiger_cvadvfilter SET groupid = 2, column_condition = ? WHERE cvid = ?', array('or', $cvid));
1789      Migration_Index_View::ExecuteQuery('UPDATE vtiger_cvadvfilter_grouping SET groupid = 2 WHERE cvid = ?', array($cvid));
1790  
1791      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_cvadvfilter(cvid,columnindex,columnname,comparator,value,groupid,column_condition)
1792          VALUES(?,?,?,?,?,?,?)', array($cvid, ++$columnIndex,'vtiger_troubletickets:contact_id:contact_id:HelpDesk_Contact_Name:V',
1793              $comparator, $value, 2, ''));
1794  }
1795  unset($ticketFilterResult);
1796  
1797  $filterColumnList = $adb->pquery('SELECT * FROM vtiger_cvcolumnlist WHERE columnname like ?',
1798          array('vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_%'));
1799  $filterColumnRows = $adb->num_rows($filterColumnList);
1800  for($j=0; $j<$filterColumnRows; $j++) {
1801      $cvid = $adb->query_result($filterColumnList, $j, 'cvid');
1802      $filterResult = $adb->pquery('SELECT MAX(columnindex) AS maxcolumn FROM vtiger_cvcolumnlist WHERE cvid = ?', array($cvid));
1803      $maxColumnIndex = $adb->query_result($filterResult, 0, 'maxcolumn');
1804      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_cvcolumnlist(cvid,columnindex,columnname) VALUES (?,?,?)', array($cvid, ++$maxColumnIndex,
1805          'vtiger_troubletickets:contact_id:contact_id:HelpDesk_Contact_Name:V'));
1806      unset($filterResult);
1807  }
1808  unset($filterColumnList);
1809  
1810  $reportColumnResult = $adb->pquery('SELECT * FROM vtiger_selectcolumn WHERE columnname like ?',
1811          array('vtiger_troubletickets:parent_id:HelpDesk_Related_To:parent_id%'));
1812  $reportColumnRows = $adb->num_rows($reportColumnResult);
1813  for($k=0; $k<$reportColumnRows; $k++) {
1814      $reportId = $adb->query_result($reportColumnResult, $k, 'queryid');
1815      $filterResult = $adb->pquery('SELECT MAX(columnindex) AS maxcolumn FROM vtiger_selectcolumn WHERE queryid = ?', array($reportId));
1816      $maxColumnIndex = $adb->query_result($filterResult, 0, 'maxcolumn');
1817      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_selectcolumn(queryid,columnindex,columnname) VALUES (?,?,?)', array($reportId,
1818          ++$maxColumnIndex, 'vtiger_troubletickets:contact_id:HelpDesk_Contact_Name:contact_id:V'));
1819      unset($filterResult);
1820  }
1821  unset($reportColumnResult);
1822  
1823  $filterResult = $adb->pquery('SELECT * FROM vtiger_relcriteria WHERE columnname like ?',
1824                      array('vtiger_troubletickets:parent_id:HelpDesk_Related_To:parent_id%'));
1825  $rows = $adb->num_rows($filterResult);
1826  for($i=0; $i<$rows; $i++) {
1827      $reportId = $adb->query_result($filterResult, $i, 'queryid');
1828      $columnIndex = $adb->query_result($filterResult, $i, 'columnindex');
1829      $comparator = $adb->query_result($filterResult, $i, 'comparator');
1830      $value = $adb->query_result($filterResult, $i, 'value');
1831  
1832      Migration_Index_View::ExecuteQuery('UPDATE vtiger_relcriteria SET groupid = 2, column_condition = ? WHERE queryid = ?', array('or', $reportId));
1833      Migration_Index_View::ExecuteQuery('UPDATE vtiger_relcriteria_grouping SET groupid = 2 WHERE queryid = ?', array($reportId));
1834  
1835      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_relcriteria(queryid,columnindex,columnname,comparator,value,groupid,column_condition)
1836          VALUES(?,?,?,?,?,?,?)', array($reportId, ++$columnIndex,'vtiger_troubletickets:contact_id:HelpDesk_Contact_Name:contact_id:V',
1837              $comparator, $value, 2, ''));
1838  }
1839  unset($filterResult);
1840  
1841  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=? WHERE tablename=? AND fieldname= ? ', array('Active', 'vtiger_users', 'status'));
1842  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=? WHERE tablename=? AND fieldname= ? ', array('12', 'vtiger_users', 'hour_format'));
1843  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=? WHERE tablename=? AND fieldname= ? ', array('softed', 'vtiger_users', 'theme'));
1844  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET defaultvalue=? WHERE tablename=? AND fieldname= ? ', array('Monday', 'vtiger_users', 'dayoftheweek'));
1845  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_shorturls ADD COLUMN onetime int(5)', array());
1846  
1847  $checkQuery = 'SELECT 1 FROM vtiger_currencies  WHERE currency_name=?';
1848  $checkResult = $adb->pquery($checkQuery,array('Iraqi Dinar'));
1849  if($adb->num_rows($checkResult) <= 0) {
1850      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_currencies VALUES ('.$adb->getUniqueID("vtiger_currencies").',"Iraqi Dinar","IQD","ID")',array());
1851  }
1852  
1853  $potentialModule = Vtiger_Module::getInstance('Potentials');
1854  $potentialTabId = getTabid('Potentials');
1855  
1856  $contactField = Vtiger_Field::getInstance('contact_id', $potentialModule);
1857  $relatedToField = Vtiger_Field::getInstance('related_to', $potentialModule);
1858  
1859  $result = $adb->pquery('SELECT sequence,block FROM vtiger_field WHERE fieldid = ? and tabid = ?', array($relatedToField->id, $potentialTabId));
1860  $relatedToFieldSequence = $adb->query_result($result, 0, 'sequence');
1861  $relatedToFieldBlock = $adb->query_result($result, 0, 'block');
1862  
1863  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET sequence = sequence+1 WHERE sequence > ? and tabid = ? and block = ?', array($relatedToFieldSequence, $potentialTabId, $relatedToFieldBlock));
1864  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET sequence = ? WHERE fieldid = ?', array($relatedToFieldSequence+1, $contactField->id));
1865  
1866  $ticketsModule = Vtiger_Module::getInstance('HelpDesk');
1867  $ticketsTabId = getTabid('HelpDesk');
1868  
1869  $contactField = Vtiger_Field::getInstance('contact_id', $ticketsModule);
1870  $relatedToField = Vtiger_Field::getInstance('parent_id', $ticketsModule);
1871  
1872  $result = $adb->pquery('SELECT sequence,block FROM vtiger_field WHERE fieldid = ? and tabid = ?', array($relatedToField->id, $ticketsTabId));
1873  $relatedToFieldSequence = $adb->query_result($result, 0, 'sequence');
1874  $relatedToFieldBlock = $adb->query_result($result, 0, 'block');
1875  
1876  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET sequence = sequence+1 WHERE sequence > ? and tabid = ? and block = ?', array($relatedToFieldSequence, $ticketsTabId, $relatedToFieldBlock));
1877  Migration_Index_View::ExecuteQuery('UPDATE vtiger_field SET sequence = ? WHERE fieldid = ?', array($relatedToFieldSequence+1, $contactField->id));
1878  
1879  $checkQuery = 'SELECT 1 FROM vtiger_currencies  WHERE currency_name=?';
1880  $checkResult = $adb->pquery($checkQuery,array('Maldivian Ruffiya'));
1881  if($adb->num_rows($checkResult) <= 0) {
1882      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_currencies VALUES ('.$adb->getUniqueID("vtiger_currencies").',"Maldivian Ruffiya","MVR","MVR")',array());
1883  }
1884  
1885  
1886  $result = $adb->pquery('SELECT count(*) AS count FROM vtiger_emailtemplates', array());
1887  Migration_Index_View::ExecuteQuery('UPDATE vtiger_emailtemplates_seq SET id = ?', array(1 + ((int)$adb->query_result($result, 0, 'count'))));
1888  
1889  $usersInstance = Vtiger_Module::getInstance('Users');
1890  $blockInstance = Vtiger_Block::getInstance('LBL_MORE_INFORMATION', $usersInstance);
1891  $usersRowHeightField = Vtiger_Field::getInstance('rowheight', $usersInstance);
1892  if (!$usersRowHeightField) {
1893      $field = new Vtiger_Field();
1894      $field->name = 'rowheight';
1895      $field->label = 'Row Height';
1896      $field->table = 'vtiger_users';
1897      $field->uitype = 16;
1898      $field->typeofdata = 'V~O';
1899      $field->readonly = 1;
1900      $field->displaytype = 1;
1901      $field->masseditable = 1;
1902      $field->quickcreate = 1;
1903      $field->columntype = 'VARCHAR(10)';
1904      $field->defaultvalue = 'medium';
1905      $blockInstance->addField($field);
1906  
1907      $field->setPicklistValues(array('wide', 'medium', 'narrow'));
1908  }
1909  
1910  $moduleInstance = Vtiger_Module::getInstance('HelpDesk');
1911  $block = Vtiger_Block::getInstance('LBL_TICKET_INFORMATION', $moduleInstance);
1912  $fromPortal = Vtiger_Field_Model::getInstance('from_portal', $moduleInstance);
1913  
1914  if(!$fromPortal){
1915      $field = new Vtiger_Field();
1916      $field->name = 'from_portal';
1917      $field->label = 'From Portal';
1918      $field->table ='vtiger_ticketcf';
1919      $field->column = 'from_portal';
1920      $field->columntype = 'varchar(3)';
1921      $field->typeofdata = 'C~O';
1922      $field->uitype = 56;
1923      $field->displaytype = 3;
1924      $field->presence = 0;
1925      $block->addField($field);
1926  }
1927  
1928  //Start: Customer - Feature #10254 Configuring all Email notifications including Ticket notifications

1929  $moduleName = 'HelpDesk';
1930  //Start: Moving Entity methods of Comments to Workflows

1931  $result = $adb->pquery('SELECT DISTINCT workflow_id FROM com_vtiger_workflowtasks WHERE workflow_id IN
1932                  (SELECT workflow_id FROM com_vtiger_workflows WHERE module_name IN (?) AND defaultworkflow = ?)
1933                  AND task LIKE ?', array('ModComments', 1, '%VTEntityMethodTask%'));
1934  $numOfRows = $adb->num_rows($result);
1935  
1936  for ($i = 0; $i < $numOfRows; $i++) {
1937      $wfs = new VTWorkflowManager($adb);
1938      $workflowModel = $wfs->retrieve($adb->query_result($result, $i, 'workflow_id'));
1939      $workflowModel->filtersavedinnew = 6;
1940      $workflowModel->executionCondition = 3;
1941      $workflowModel->moduleName = $moduleName;
1942  
1943      $newWorkflowModel = $wfs->newWorkflow($moduleName);
1944      $workflowProperties = get_object_vars($workflowModel);
1945      foreach ($workflowProperties as $workflowPropertyName => $workflowPropertyValue) {
1946          $newWorkflowModel->$workflowPropertyName = $workflowPropertyValue;
1947      }
1948  
1949      $newConditions = array(
1950          array('fieldname' => '_VT_add_comment',
1951              'operation' => 'is added',
1952              'value' => '',
1953              'valuetype' => 'rawtext',
1954              'joincondition' => '',
1955              'groupjoin' => 'and',
1956              'groupid' => '0')
1957      );
1958  
1959      $tm = new VTTaskManager($adb);
1960      $tasks = $tm->getTasksForWorkflow($workflowModel->id);
1961      foreach ($tasks as $task) {
1962          $properties = get_object_vars($task);
1963  
1964          $emailTask = new VTEmailTask();
1965          $emailTask->executeImmediately = 0;
1966          $emailTask->summary = $properties['summary'];
1967          $emailTask->active = $properties['active'];
1968  
1969          switch ($properties['methodName']) {
1970              case 'CustomerCommentFromPortal' :
1971                  $tm->deleteTask($task->id);
1972  
1973                  $newWorkflowConditions = $newConditions;
1974                  $newWorkflowConditions[] = array(
1975                      'fieldname' => 'from_portal',
1976                      'operation' => 'is',
1977                      'value' => '1',
1978                      'valuetype' => 'rawtext',
1979                      'joincondition' => '',
1980                      'groupjoin' => 'and',
1981                      'groupid' => '0'
1982                  );
1983  
1984                  unset($newWorkflowModel->id);
1985                  $newWorkflowModel->test = Zend_Json::encode($newWorkflowConditions);
1986                  $newWorkflowModel->description = 'Comment Added From Portal : Send Email to Record Owner';
1987                  $wfs->save($newWorkflowModel);
1988  
1989                  $emailTask->id = '';
1990                  $emailTask->workflowId = $newWorkflowModel->id;
1991                  $emailTask->summary = 'Comment Added From Portal : Send Email to Record Owner';
1992                  $emailTask->fromEmail = '$(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname)&lt;$(contact_id : (Contacts) email)&gt;';
1993                  $emailTask->recepient = ',$(assigned_user_id : (Users) email1)';
1994                  $emailTask->subject = 'Respond to Ticket ID## $(general : (__VtigerMeta__) recordId) ## in Customer Portal - URGENT';
1995                  $emailTask->content = 'Dear $(assigned_user_id : (Users) last_name) $(assigned_user_id : (Users) first_name),<br><br>
1996                                  Customer has provided the following additional information to your reply:<br><br>
1997                                  <b>$lastComment</b><br><br>
1998                                  Kindly respond to above ticket at the earliest.<br><br>
1999                                  Regards<br>Support Administrator';
2000                  $tm->saveTask($emailTask);
2001                  break;
2002  
2003  
2004              case 'TicketOwnerComments' :
2005                  $tm->deleteTask($task->id);
2006  
2007                  $newConditions[] = array(
2008                      'fieldname' => 'from_portal',
2009                      'operation' => 'is',
2010                      'value' => '0',
2011                      'valuetype' => 'rawtext',
2012                      'joincondition' => '',
2013                      'groupjoin' => 'and',
2014                      'groupid' => '0'
2015                  );
2016  
2017                  $newWorkflowConditions = $newConditions;
2018                  $newWorkflowConditions[] = array(
2019                      'fieldname' => '(contact_id : (Contacts) emailoptout)',
2020                      'operation' => 'is',
2021                      'value' => '0',
2022                      'valuetype' => 'rawtext',
2023                      'joincondition' => 'and',
2024                      'groupjoin' => 'and',
2025                      'groupid' => '0'
2026                  );
2027  
2028                  $portalCondition = array(
2029                      array('fieldname' => '(contact_id : (Contacts) portal)',
2030                          'operation' => 'is',
2031                          'value' => '0',
2032                          'valuetype' => 'rawtext',
2033                          'joincondition' => 'and',
2034                          'groupjoin' => 'and',
2035                          'groupid' => '0')
2036                  );
2037  
2038                  unset($newWorkflowModel->id);
2039                  $newWorkflowModel->test = Zend_Json::encode(array_merge($portalCondition, $newWorkflowConditions));
2040                  $newWorkflowModel->description = 'Comment Added From CRM : Send Email to Contact, where Contact is not a Portal User';
2041                  $wfs->save($newWorkflowModel);
2042  
2043                  $emailTask->id = '';
2044                  $emailTask->workflowId = $newWorkflowModel->id;
2045                  $emailTask->summary = 'Comment Added From CRM : Send Email to Contact, where Contact is not a Portal User';
2046                  $emailTask->fromEmail = '$(general : (__VtigerMeta__) supportName)&lt;$(general : (__VtigerMeta__) supportEmailId)&gt;';
2047                  $emailTask->recepient = ',$(contact_id : (Contacts) email)';
2048                  $emailTask->subject = '$ticket_no [ Ticket Id : $(general : (__VtigerMeta__) recordId) ] $ticket_title';
2049                  $emailTask->content = 'Dear $(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname),<br><br>
2050                              The Ticket is replied the details are :<br><br>
2051                              Ticket No : $ticket_no<br>
2052                              Status : $ticketstatus<br>
2053                              Category : $ticketcategories<br>
2054                              Severity : $ticketseverities<br>
2055                              Priority : $ticketpriorities<br><br>
2056                              Description : <br>$description<br><br>
2057                              Solution : <br>$solution<br>
2058                              The comments are : <br>
2059                              $allComments<br><br>
2060                              Regards<br>Support Administrator';
2061                  $tm->saveTask($emailTask);
2062  
2063                  $portalCondition = array(
2064                      array('fieldname' => '(contact_id : (Contacts) portal)',
2065                          'operation' => 'is',
2066                          'value' => '1',
2067                          'valuetype' => 'rawtext',
2068                          'joincondition' => 'and',
2069                          'groupjoin' => 'and',
2070                          'groupid' => '0')
2071                  );
2072  
2073                  unset($newWorkflowModel->id);
2074                  $newWorkflowModel->test = Zend_Json::encode(array_merge($portalCondition, $newWorkflowConditions));
2075                  $newWorkflowModel->description = 'Comment Added From CRM : Send Email to Contact, where Contact is Portal User';
2076                  $wfs->save($newWorkflowModel);
2077  
2078                  $emailTask->id = '';
2079                  $emailTask->workflowId = $newWorkflowModel->id;
2080                  $emailTask->summary = 'Comment Added From CRM : Send Email to Contact, where Contact is Portal User';
2081                  $emailTask->content = 'Ticket No : $ticket_no<br>
2082                                          Ticket Id : $(general : (__VtigerMeta__) recordId)<br>
2083                                          Subject : $ticket_title<br><br>
2084                                          Dear $(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname),<br><br>
2085                                          There is a reply to <b>$ticket_title</b> in the "Customer Portal" at VTiger.
2086                                          You can use the following link to view the replies made:<br>
2087                                          <a href="$(general : (__VtigerMeta__) portaldetailviewurl)">Ticket Details</a><br><br>
2088                                          Thanks<br>$(general : (__VtigerMeta__) supportName)';
2089                  $tm->saveTask($emailTask);
2090  
2091                  $newConditions[] = array(
2092                      'fieldname' => '(parent_id : (Accounts) emailoptout)',
2093                      'operation' => 'is',
2094                      'value' => '0',
2095                      'valuetype' => 'rawtext',
2096                      'joincondition' => 'and',
2097                      'groupjoin' => 'and',
2098                      'groupid' => '0'
2099                  );
2100  
2101                  $workflowModel->test = Zend_Json::encode($newConditions);
2102                  $workflowModel->description = 'Comment Added From CRM : Send Email to Organization';
2103                  $wfs->save($workflowModel);
2104  
2105                  $emailTask->id = '';
2106                  $emailTask->workflowId = $workflowModel->id;
2107                  $emailTask->summary = 'Comment Added From CRM : Send Email to Organization';
2108                  $emailTask->recepient = ',$(parent_id : (Accounts) email1),';
2109                  $emailTask->content = 'Ticket ID : $(general : (__VtigerMeta__) recordId)<br>Ticket Title : $ticket_title<br><br>
2110                                  Dear $(parent_id : (Accounts) accountname),<br><br>
2111                                  The Ticket is replied the details are :<br><br>
2112                                  Ticket No : $ticket_no<br>
2113                                  Status : $ticketstatus<br>
2114                                  Category : $ticketcategories<br>
2115                                  Severity : $ticketseverities<br>
2116                                  Priority : $ticketpriorities<br><br>
2117                                  Description : <br>$description<br><br>
2118                                  Solution : <br>$solution<br>
2119                                  The comments are : <br>
2120                                  $allComments<br><br>
2121                                  Regards<br>Support Administrator';
2122                  $tm->saveTask($emailTask);
2123  
2124                  break;
2125          }
2126      }
2127  }
2128  //End: Moved Entity methods of Comments to Workflows

2129  //Start: Moving Entity methods of Tickets to Workflows

2130  $result = $adb->pquery('SELECT DISTINCT workflow_id FROM com_vtiger_workflowtasks WHERE workflow_id IN
2131                  (SELECT workflow_id FROM com_vtiger_workflows WHERE module_name IN (?) AND defaultworkflow = ?)
2132                  AND task LIKE ?', array($moduleName, 1, '%VTEntityMethodTask%'));
2133  $numOfRows = $adb->num_rows($result);
2134  
2135  for ($i = 0; $i < $numOfRows; $i++) {
2136      $wfs = new VTWorkflowManager($adb);
2137      $workflowModel = $wfs->retrieve($adb->query_result($result, $i, 'workflow_id'));
2138      $workflowModel->filtersavedinnew = 6;
2139  
2140      $tm = new VTTaskManager($adb);
2141      $tasks = $tm->getTasksForWorkflow($workflowModel->id);
2142      foreach ($tasks as $task) {
2143          $properties = get_object_vars($task);
2144  
2145          $emailTask = new VTEmailTask();
2146          $emailTask->executeImmediately = 0;
2147          $emailTask->summary = $properties['summary'];
2148          $emailTask->active = $properties['active'];
2149          switch ($properties['methodName']) {
2150              case 'NotifyOnPortalTicketCreation' :
2151                  $oldCondtions = Migration_Index_View::transformAdvanceFilterToWorkFlowFilter(Zend_Json::decode($workflowModel->test));
2152                  $newConditions = array(
2153                      array('fieldname' => 'from_portal',
2154                          'operation' => 'is',
2155                          'value' => '1',
2156                          'valuetype' => 'rawtext',
2157                          'joincondition' => '',
2158                          'groupjoin' => 'and',
2159                          'groupid' => '0')
2160                  );
2161                  $newConditions = array_merge($oldCondtions, $newConditions);
2162  
2163                  $workflowModel->test = Zend_Json::encode($newConditions);
2164                  $workflowModel->description = 'Ticket Creation From Portal : Send Email to Record Owner and Contact';
2165                  $wfs->save($workflowModel);
2166  
2167                  $emailTask->id = '';
2168                  $emailTask->workflowId = $properties['workflowId'];
2169                  $emailTask->summary = 'Notify Record Owner when Ticket is created from Portal';
2170                  $emailTask->fromEmail = '$(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname)&lt;$(general : (__VtigerMeta__) supportEmailId)&gt;';
2171                  $emailTask->recepient = ',$(assigned_user_id : (Users) email1)';
2172                  $emailTask->subject = '[From Portal] $ticket_no [ Ticket Id : $(general : (__VtigerMeta__) recordId) ] $ticket_title';
2173                  $emailTask->content = 'Ticket No : $ticket_no<br>
2174                                Ticket ID : $(general : (__VtigerMeta__) recordId)<br>
2175                                Ticket Title : $ticket_title<br><br>
2176                                $description';
2177                  $tm->saveTask($emailTask);
2178  
2179                  $emailTask->id = $properties['id'];
2180                  $emailTask->summary = 'Notify Related Contact when Ticket is created from Portal';
2181                  $emailTask->fromEmail = '$(general : (__VtigerMeta__) supportName)&lt;$(general : (__VtigerMeta__) supportEmailId)&gt;';
2182                  $emailTask->recepient = ',$(contact_id : (Contacts) email)';
2183  
2184                  $tm->saveTask($emailTask);
2185                  break;
2186  
2187  
2188              case 'NotifyOnPortalTicketComment' :
2189                  $tm->deleteTask($properties['id']);
2190                  Migration_Index_View::ExecuteQuery('DELETE FROM com_vtiger_workflows WHERE workflow_id = ?', array($workflowModel->id));
2191                  break;
2192  
2193  
2194              case 'NotifyParentOnTicketChange' :
2195                  $newWorkflowModel = $wfs->newWorkflow($workflowModel->moduleName);
2196                  $workflowProperties = get_object_vars($workflowModel);
2197                  foreach ($workflowProperties as $workflowPropertyName => $workflowPropertyValue) {
2198                      $newWorkflowModel->$workflowPropertyName = $workflowPropertyValue;
2199                  }
2200  
2201                  $oldCondtions = Migration_Index_View::transformAdvanceFilterToWorkFlowFilter(Zend_Json::decode($newWorkflowModel->test));
2202                  $newConditions = array(
2203                      array('fieldname' => 'ticketstatus',
2204                          'operation' => 'has changed to',
2205                          'value' => 'Closed',
2206                          'valuetype' => 'rawtext',
2207                          'joincondition' => 'or',
2208                          'groupjoin' => 'and',
2209                          'groupid' => '1'),
2210                      array('fieldname' => 'solution',
2211                          'operation' => 'has changed',
2212                          'value' => '',
2213                          'valuetype' => '',
2214                          'joincondition' => 'or',
2215                          'groupjoin' => 'and',
2216                          'groupid' => '1'),
2217                      array('fieldname' => 'description',
2218                          'operation' => 'has changed',
2219                          'value' => '',
2220                          'valuetype' => '',
2221                          'joincondition' => 'or',
2222                          'groupjoin' => 'and',
2223                          'groupid' => '1')
2224                  );
2225                  $newConditions = array_merge($oldCondtions, $newConditions);
2226  
2227                  $newAccountCondition = array(
2228                      array('fieldname' => '(parent_id : (Accounts) emailoptout)',
2229                          'operation' => 'is',
2230                          'value' => '0',
2231                          'valuetype' => 'rawtext',
2232                          'joincondition' => 'and',
2233                          'groupjoin' => 'and',
2234                          'groupid' => '0')
2235                  );
2236                  $newWorkflowConditions = array_merge($newAccountCondition, $newConditions);
2237  
2238                  unset($newWorkflowModel->id);
2239                  $newWorkflowModel->test = Zend_Json::encode($newWorkflowConditions);
2240                  $newWorkflowModel->description = 'Send Email to Organization on Ticket Update';
2241                  $wfs->save($newWorkflowModel);
2242  
2243                  $emailTask->id = '';
2244                  $emailTask->summary = 'Send Email to Organization on Ticket Update';
2245                  $emailTask->fromEmail = '$(general : (__VtigerMeta__) supportName)&lt;$(general : (__VtigerMeta__) supportEmailId)&gt;';
2246                  $emailTask->recepient = ',$(parent_id : (Accounts) email1)';
2247                  $emailTask->subject = '$ticket_no [ Ticket Id : $(general : (__VtigerMeta__) recordId) ] $ticket_title';
2248                  $emailTask->content = 'Ticket ID : $(general : (__VtigerMeta__) recordId)<br>Ticket Title : $ticket_title<br><br>
2249                                  Dear $(parent_id : (Accounts) accountname),<br><br>
2250                                  The Ticket is replied the details are :<br><br>
2251                                  Ticket No : $ticket_no<br>
2252                                  Status : $ticketstatus<br>
2253                                  Category : $ticketcategories<br>
2254                                  Severity : $ticketseverities<br>
2255                                  Priority : $ticketpriorities<br><br>
2256                                  Description : <br>$description<br><br>
2257                                  Solution : <br>$solution<br>
2258                                  The comments are : <br>
2259                                  $allComments<br><br>
2260                                  Regards<br>Support Administrator';
2261  
2262                  $emailTask->workflowId = $newWorkflowModel->id;
2263                  $tm->saveTask($emailTask);
2264  
2265                  $portalCondition = array(
2266                      array('fieldname' => 'from_portal',
2267                          'operation' => 'is',
2268                          'value' => '0',
2269                          'valuetype' => 'rawtext',
2270                          'joincondition' => '',
2271                          'groupjoin' => 'and',
2272                          'groupid' => '0')
2273                  );
2274  
2275                  unset($newWorkflowModel->id);
2276                  $newWorkflowModel->executionCondition = 1;
2277                  $newWorkflowModel->test = Zend_Json::encode(array_merge($newAccountCondition, $portalCondition));
2278                  $newWorkflowModel->description = 'Ticket Creation From CRM : Send Email to Organization';
2279                  $wfs->save($newWorkflowModel);
2280  
2281                  $emailTask->id = '';
2282                  $emailTask->workflowId = $newWorkflowModel->id;
2283                  $emailTask->summary = 'Ticket Creation From CRM : Send Email to Organization';
2284                  $tm->saveTask($emailTask);
2285  
2286                  $newContactCondition = array(
2287                      array('fieldname' => '(contact_id : (Contacts) emailoptout)',
2288                          'operation' => 'is',
2289                          'value' => '0',
2290                          'valuetype' => 'rawtext',
2291                          'joincondition' => 'and',
2292                          'groupjoin' => 'and',
2293                          'groupid' => '0')
2294                  );
2295                  $newConditions = array_merge($newContactCondition, $newConditions);
2296  
2297                  $workflowModel->test = Zend_Json::encode($newConditions);
2298                  $workflowModel->description = 'Send Email to Contact on Ticket Update';
2299                  $wfs->save($workflowModel);
2300  
2301                  $emailTask->id = $properties['id'];
2302                  $emailTask->workflowId = $properties['workflowId'];
2303                  $emailTask->summary = 'Send Email to Contact on Ticket Update';
2304                  $emailTask->recepient = ',$(contact_id : (Contacts) email)';
2305                  $emailTask->content = 'Ticket ID : $(general : (__VtigerMeta__) recordId)<br>Ticket Title : $ticket_title<br><br>
2306                                  Dear $(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname),<br><br>
2307                                  The Ticket is replied the details are :<br><br>
2308                                  Ticket No : $ticket_no<br>
2309                                  Status : $ticketstatus<br>
2310                                  Category : $ticketcategories<br>
2311                                  Severity : $ticketseverities<br>
2312                                  Priority : $ticketpriorities<br><br>
2313                                  Description : <br>$description<br><br>
2314                                  Solution : <br>$solution<br>
2315                                  The comments are : <br>
2316                                  $allComments<br><br>
2317                                  Regards<br>Support Administrator';
2318  
2319                  $tm->saveTask($emailTask);
2320  
2321                  unset($newWorkflowModel->id);
2322                  $newWorkflowModel->executionCondition = 1;
2323                  $newWorkflowModel->test = Zend_Json::encode(array_merge($newContactCondition, $portalCondition));
2324                  $newWorkflowModel->description = 'Ticket Creation From CRM : Send Email to Contact';
2325                  $wfs->save($newWorkflowModel);
2326  
2327                  $emailTask->id = '';
2328                  $emailTask->workflowId = $newWorkflowModel->id;
2329                  $emailTask->summary = 'Ticket Creation From CRM : Send Email to Contact';
2330                  $tm->saveTask($emailTask);
2331                  break;
2332  
2333  
2334              case 'NotifyOwnerOnTicketChange' :
2335                  $tm->deleteTask($task->id);
2336  
2337                  $newWorkflowModel = $wfs->newWorkflow($workflowModel->moduleName);
2338                  $workflowProperties = get_object_vars($workflowModel);
2339                  foreach ($workflowProperties as $workflowPropertyName => $workflowPropertyValue) {
2340                      $newWorkflowModel->$workflowPropertyName = $workflowPropertyValue;
2341                  }
2342  
2343                  $oldCondtions = Migration_Index_View::transformAdvanceFilterToWorkFlowFilter(Zend_Json::decode($newWorkflowModel->test));
2344                  $newConditions = array(
2345                      array('fieldname' => 'ticketstatus',
2346                          'operation' => 'has changed to',
2347                          'value' => 'Closed',
2348                          'valuetype' => 'rawtext',
2349                          'joincondition' => 'or',
2350                          'groupjoin' => 'and',
2351                          'groupid' => '1'),
2352                      array('fieldname' => 'solution',
2353                          'operation' => 'has changed',
2354                          'value' => '',
2355                          'valuetype' => '',
2356                          'joincondition' => 'or',
2357                          'groupjoin' => 'and',
2358                          'groupid' => '1'),
2359                      array('fieldname' => 'assigned_user_id',
2360                          'operation' => 'has changed',
2361                          'value' => '',
2362                          'valuetype' => '',
2363                          'joincondition' => 'or',
2364                          'groupjoin' => 'and',
2365                          'groupid' => '1'),
2366                      array('fieldname' => 'description',
2367                          'operation' => 'has changed',
2368                          'value' => '',
2369                          'valuetype' => '',
2370                          'joincondition' => 'or',
2371                          'groupjoin' => 'and',
2372                          'groupid' => '1')
2373                  );
2374                  $newConditions = array_merge($oldCondtions, $newConditions);
2375  
2376                  unset($newWorkflowModel->id);
2377                  $newWorkflowModel->test = Zend_Json::encode($newConditions);
2378                  $newWorkflowModel->description = 'Send Email to Record Owner on Ticket Update';
2379                  $wfs->save($newWorkflowModel);
2380  
2381                  $emailTask->id = '';
2382                  $emailTask->workflowId = $newWorkflowModel->id;
2383                  $emailTask->summary = 'Send Email to Record Owner on Ticket Update';
2384                  $emailTask->fromEmail = '$(general : (__VtigerMeta__) supportName)&lt;$(general : (__VtigerMeta__) supportEmailId)&gt;';
2385                  $emailTask->recepient = ',$(assigned_user_id : (Users) email1)';
2386                  $emailTask->subject = 'Ticket Number : $ticket_no $ticket_title';
2387                  $emailTask->content = 'Ticket ID : $(general : (__VtigerMeta__) recordId)<br>Ticket Title : $ticket_title<br><br>
2388                                  Dear $(assigned_user_id : (Users) last_name) $(assigned_user_id : (Users) first_name),<br><br>
2389                                  The Ticket is replied the details are :<br><br>
2390                                  Ticket No : $ticket_no<br>
2391                                  Status : $ticketstatus<br>
2392                                  Category : $ticketcategories<br>
2393                                  Severity : $ticketseverities<br>
2394                                  Priority : $ticketpriorities<br><br>
2395                                  Description : <br>$description<br><br>
2396                                  Solution : <br>$solution
2397                                  $allComments<br><br>
2398                                  Regards<br>Support Administrator';
2399                  $emailTask->id = '';
2400                  $tm->saveTask($emailTask);
2401  
2402                  $portalCondition = array(
2403                      array('fieldname' => 'from_portal',
2404                          'operation' => 'is',
2405                          'value' => '0',
2406                          'valuetype' => 'rawtext',
2407                          'joincondition' => '',
2408                          'groupjoin' => 'and',
2409                          'groupid' => '0')
2410                  );
2411  
2412                  unset($newWorkflowModel->id);
2413                  $newWorkflowModel->executionCondition = 1;
2414                  $newWorkflowModel->test = Zend_Json::encode($portalCondition);
2415                  $newWorkflowModel->description = 'Ticket Creation From CRM : Send Email to Record Owner';
2416                  $wfs->save($newWorkflowModel);
2417  
2418                  $emailTask->id = '';
2419                  $emailTask->workflowId = $newWorkflowModel->id;
2420                  $emailTask->summary = 'Ticket Creation From CRM : Send Email to Record Owner';
2421                  $tm->saveTask($emailTask);
2422                  break;
2423          }
2424      }
2425  }
2426  $em = new VTEventsManager($adb);
2427  $em->registerHandler('vtiger.entity.aftersave', 'modules/ModComments/ModCommentsHandler.php', 'ModCommentsHandler');
2428  $result = $adb->pquery('SELECT blockid FROM vtiger_blocks where tabid = ? AND (blocklabel is NULL OR blocklabel = "")', array(getTabid('Emails')));
2429  $numOfRows = $adb->num_rows($result);
2430  
2431  $query = 'UPDATE vtiger_blocks SET blocklabel = CASE blockid ';
2432  for ($i = 0; $i < $numOfRows; $i++) {
2433      $blockId = $adb->query_result($result, $i, 'blockid');
2434      $blockLabel = 'Emails_Block' . ($i + 1);
2435      $query .= "WHEN $blockId THEN '$blockLabel' ";
2436  }
2437  $query .= 'ELSE blocklabel END';
2438  Migration_Index_View::ExecuteQuery($query, array());
2439  
2440  $result = $adb->pquery('SELECT task_id FROM com_vtiger_workflowtasks WHERE workflow_id IN
2441                                                                      (SELECT workflow_id FROM com_vtiger_workflows WHERE module_name IN (?, ?))
2442                                                                      AND task LIKE ?', array('Calendar', 'Events', '%$(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname)%'));
2443  $numOfRows = $adb->num_rows($result);
2444  
2445  for ($i = 0; $i < $numOfRows; $i++) {
2446      $tm = new VTTaskManager($adb);
2447      $task = $tm->retrieveTask($adb->query_result($result, $i, 'task_id'));
2448  
2449      $emailTask = new VTEmailTask();
2450      $properties = get_object_vars($task);
2451      foreach ($properties as $propertyName => $propertyValue) {
2452          $propertyValue = str_replace('$date_start  $time_start ( $(general : (__VtigerMeta__) usertimezone) ) ', '$date_start', $propertyValue);
2453          $propertyValue = str_replace('$due_date  $time_end ( $(general : (__VtigerMeta__) usertimezone) )', '$due_date', $propertyValue);
2454          $propertyValue = str_replace('$due_date ( $(general : (__VtigerMeta__) usertimezone) )', '$due_date', $propertyValue);
2455          $propertyValue = str_replace('$(contact_id : (Contacts) lastname) $(contact_id : (Contacts) firstname)', '$contact_id', $propertyValue);
2456          $emailTask->$propertyName = $propertyValue;
2457      }
2458  
2459      $tm->saveTask($emailTask);
2460  }
2461  
2462  $result = $adb->pquery('SELECT 1 FROM vtiger_currencies WHERE currency_name = ?', array('Ugandan Shilling'));
2463  if(!$adb->num_rows($result)) {
2464      Migration_Index_View::ExecuteQuery('INSERT INTO vtiger_currencies (currencyid, currency_name, currency_code, currency_symbol) VALUES(?, ?, ?, ?)',
2465              array($adb->getUniqueID('vtiger_currencies'), 'Ugandan Shilling', 'UGX', 'Sh'));
2466  }
2467  $em = new VTEventsManager($adb);
2468  $em->registerHandler('vtiger.picklist.afterrename', 'modules/Settings/Picklist/handlers/PickListHandler.php', 'PickListHandler');
2469  $em->registerHandler('vtiger.picklist.afterdelete', 'modules/Settings/Picklist/handlers/PickListHandler.php', 'PickListHandler');
2470  
2471  Migration_Index_View::ExecuteQuery('ALTER TABLE vtiger_inventoryproductrel MODIFY comment varchar(500)', array());
2472  
2473  $module = Vtiger_Module::getInstance('Accounts');
2474  $module->addLink('DETAILVIEWSIDEBARWIDGET', 'Google Map', 'module=Google&view=Map&mode=showMap&viewtype=detail', '', '', '');
2475  
2476  // Changes as on 2013.11.29

2477  
2478  Migration_Index_View::ExecuteQuery('DELETE FROM vtiger_settings_field WHERE name=?', array('LBL_BACKUP_SERVER_SETTINGS'));
2479  
2480  // Changes ends as on 2013.11.29

2481  Migration_Index_View::ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_faqcf ( 
2482                                  faqid int(19), 
2483                                  PRIMARY KEY (faqid), 
2484                                  CONSTRAINT fk_1_vtiger_faqcf FOREIGN KEY (faqid) REFERENCES vtiger_faq(id) ON DELETE CASCADE 
2485                  ) ENGINE=InnoDB DEFAULT CHARSET=utf8", array()); 


Generated: Fri Nov 28 20:08:37 2014 Cross-referenced by PHPXref 0.7.1