Ejemplo n.º 1
0
Archivo: Main.php Proyecto: kingsj/core
 /**
  * Execute certain hook handle
  *
  * @return void
  */
 public function executeHookHandler()
 {
     foreach (\Includes\Decorator\Plugin\Doctrine\Utils\FixturesManager::getFixtures() as $fixture) {
         \XLite\Core\Database::getInstance()->loadFixturesFromYaml($fixture);
     }
     \Includes\Decorator\Plugin\Doctrine\Utils\FixturesManager::removeFixtures();
 }
Ejemplo n.º 2
0
 /**
  * Execute certain hook handle
  *
  * @return void
  */
 public function executeHookHandler()
 {
     $list = \Includes\Decorator\Plugin\Doctrine\Utils\FixturesManager::getFixtures();
     if ($list) {
         \Includes\Utils\Operator::showMessage('', true, false);
         foreach ($list as $fixture) {
             $message = '...Load ' . substr($fixture, strlen(LC_DIR_ROOT));
             \Includes\Utils\Operator::showMessage($message, true, true);
             \Includes\Decorator\Utils\CacheManager::logMessage(PHP_EOL);
             \Includes\Decorator\Utils\CacheManager::logMessage($message);
             if (static::isYAML($fixture)) {
                 // Load YAML fixture
                 \XLite\Core\Database::getInstance()->loadFixturesFromYaml($fixture);
             } else {
                 // Load SQL queries
                 \Includes\Utils\Database::uploadSQLFromFile($fixture);
             }
             \Includes\Decorator\Plugin\Doctrine\Utils\FixturesManager::removeFixtureFromList($fixture);
             if (\Includes\Decorator\Utils\CacheManager::isTimeExceeds(static::STEP_TTL)) {
                 break;
             }
         }
     }
     \Includes\Decorator\Utils\CacheManager::logMessage(PHP_EOL);
     \XLite\Core\Database::getEM()->clear();
 }
Ejemplo n.º 3
0
 /**
  * doActionBackupWriteToFile
  *
  * @return void
  */
 protected function doActionBackupWriteToFile()
 {
     $destFile = $this->sqldumpFile;
     $this->startDump();
     // Make database backup and store it in $this->sqldumpFile file
     \XLite\Core\Database::getInstance()->exportSQLToFile($destFile, true);
     \XLite\Core\TopMessage::addInfo('Database backup created successfully');
     $this->setReturnURL($this->buildURL('db_backup'));
     $this->doRedirect();
 }
Ejemplo n.º 4
0
/**
 * X-Cart
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the software license agreement
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.x-cart.com/license-agreement.html
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to licensing@x-cart.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not modify this file if you wish to upgrade X-Cart to newer versions
 * in the future. If you wish to customize X-Cart for your needs please
 * refer to http://www.x-cart.com/ for more information.
 *
 * @category  X-Cart 5
 * @author    Qualiteam software Ltd <*****@*****.**>
 * @copyright Copyright (c) 2011-2015 Qualiteam software Ltd <*****@*****.**>. All rights reserved
 * @license   http://www.x-cart.com/license-agreement.html X-Cart 5 License Agreement
 * @link      http://www.x-cart.com/
 */
function createRegionsForUK()
{
    $gbRegionsFile = __DIR__ . LC_DS . 'gb_regions.yaml';
    if (!\Includes\Utils\FileManager::isFileReadable($gbRegionsFile)) {
        return false;
    }
    \XLite\Core\Database::getInstance()->loadFixturesFromYaml($gbRegionsFile);
    \XLite\Core\Database::getEM()->flush();
    return true;
}
Ejemplo n.º 5
0
 /**
  * Execute certain hook handle
  *
  * @return void
  */
 public function executeHookHandler()
 {
     $schema = \Includes\Decorator\Plugin\Doctrine\Utils\DBSchemaManager::getDBSchema();
     if ($schema) {
         do {
             $queries = array();
             foreach ($schema as $k => $query) {
                 $queries[] = $query;
                 unset($schema[$k]);
             }
             if ($queries) {
                 \XLite\Core\Database::getInstance()->executeQueries($queries);
             }
         } while ($schema && !\Includes\Decorator\Utils\CacheManager::isTimeExceeds(static::STEP_TTL));
         \Includes\Decorator\Plugin\Doctrine\Utils\DBSchemaManager::updateDBSchema($schema);
     }
 }
Ejemplo n.º 6
0
 /**
  * Perform upgrade
  *
  * @param boolean    $isTestMode       Flag OPTIONAL
  * @param array|null $filesToOverwrite List of custom files to overwrite OPTIONAL
  *
  * @return void
  */
 public function upgrade($isTestMode = true, $filesToOverwrite = null)
 {
     parent::upgrade($isTestMode, $filesToOverwrite);
     if (!$isTestMode) {
         list($author, $name) = explode('\\', $this->getActualName());
         if (!$this->isValid()) {
             \Includes\SafeMode::markModuleAsUnsafe($author, $name);
         }
         // Load fixtures
         if (!$this->isInstalled()) {
             $yaml = \Includes\Utils\ModulesManager::getModuleYAMLFile($author, $name);
             if (\Includes\Utils\FileManager::isFileReadable($yaml)) {
                 \XLite\Core\Database::getInstance()->loadFixturesFromYaml($yaml);
             }
         }
         $this->updateDBRecords();
     }
 }
Ejemplo n.º 7
0
 /**
  * doActionBackup
  *
  * @return void
  */
 protected function doActionBackup()
 {
     $verbose = false;
     $destfile = null;
     // write to 'stdout' by default
     if (\XLite\Core\Request::getInstance()->write_to_file) {
         $destFile = $this->sqldumpFile;
         $verbose = true;
         $this->startDump();
     } else {
         $destFile = LC_DIR_BACKUP . sprintf('sqldump.backup.%d.sql', time());
         $this->startDownload('db_backup.sql');
     }
     // Make database backup and store it in $this->sqldumpFile file
     $result = \XLite\Core\Database::getInstance()->exportSQLToFile($destFile, $verbose);
     if (\XLite\Core\Request::getInstance()->write_to_file) {
         echo '<br /><b>' . static::t('Database backup created successfully') . '</b><br />';
     } else {
         readfile($destFile);
         unlink($destFile);
         exit;
     }
 }
Ejemplo n.º 8
0
 /**
  * Common restore database method used by actions
  *
  * @param mixed $sqlFile File with SQL data for loading into database
  *
  * @return boolean
  */
 protected function restoreDatabase($sqlFile)
 {
     $result = false;
     // File to create temporary backup to be able rollback database
     $backupSQLFile = LC_DIR_BACKUP . sprintf('sqldump.backup.%d.sql', time());
     // Make the process of restoring database verbose
     $verbose = true;
     // Start
     $this->startDump();
     // Making the temporary backup file
     echo static::t('Making backup of the current database state...');
     $result = \XLite\Core\Database::getInstance()->exportSQLToFile($backupSQLFile, $verbose);
     // Loading specified SQL-file to the database
     echo '<br /><br />' . static::t('Loading the database from file...');
     $result = \Includes\Utils\Database::uploadSQLFromFile($sqlFile, $verbose);
     if ($result) {
         // If file has been loaded into database successfully
         $message = static::t('Database restored successfully!');
         // Prepare the cache rebuilding
         \XLite::setCleanUpCacheFlag(true);
     } else {
         // If an error occured while loading file into database
         $message = static::t('The database has not been restored because of the errors');
         // Restore database from temporary backup
         echo '<br /><br />' . static::t('Restoring database from the backup...');
         \Includes\Utils\Database::uploadSQLFromFile($backupSQLFile, $verbose);
     }
     // Display the result message
     echo '<br /><br />' . $message . '<br />';
     // Display Javascript to cancel scrolling page to bottom
     func_refresh_end();
     // Display the bottom HTML part
     $this->displayPageFooter();
     // Remove temporary backup file
     unlink($backupSQLFile);
     return $result;
 }
Ejemplo n.º 9
0
 /**
  * Lifecycle callback
  *
  * @return void
  *
  * @PreUpdate
  */
 public function prepareBeforeUpdate()
 {
     $changeSet = \XLite\Core\Database::getEM()->getUnitOfWork()->getEntityChangeSet($this);
     if (!empty($changeSet['enabled'])) {
         \XLite\Core\Database::getInstance()->setDisabledStructures($this->getActualName(), $this->getEnabled() ? array() : \Includes\Utils\ModulesManager::getModuleProtectedStructures($this->getAuthor(), $this->getName()));
         $this->switchLinkedModels($this->getEnabled());
     }
 }
Ejemplo n.º 10
0
 /**
  * Process DB schema
  *
  * @param array  $schema Schema
  * @param string $type   Schema type
  *
  * @return array
  */
 public function processSchema(array $schema, $type)
 {
     if (\XLite\Core\Database::SCHEMA_UPDATE == $type || \XLite\Core\Database::SCHEMA_CREATE == $type) {
         foreach ($this->getDetailedForeignKeys() as $cell) {
             if (is_array($cell) && !empty($cell['fields']) && !empty($cell['referenceRepo'])) {
                 if (!isset($cell['referenceFields']) || !is_array($cell['referenceFields'])) {
                     $cell['referenceFields'] = $cell['fields'];
                 }
                 $pattern = '/(' . $this->_class->getTableName() . '`' . ' ADD CONSTRAINT \\w+ FOREIGN KEY \\(`' . implode('`,`', $cell['fields']) . '`\\)' . ' REFERENCES `' . $this->_em->getClassMetadata($cell['referenceRepo'])->getTableName() . '`' . ' \\(`' . implode('`,`', $cell['referenceFields']) . '`\\))\\s*(?:.+)?$/Ss';
                 $replace = '$1 ON DELETE ' . (isset($cell['delete']) ? strtoupper($cell['delete']) : 'CASCADE');
                 if (isset($cell['update'])) {
                     $replace .= ' ON UPDATE ' . strtoupper($cell['update']);
                 } elseif (!isset($cell['delete']) || 'CASCADE' == strtoupper($cell['delete'])) {
                     $replace .= ' ON UPDATE CASCADE';
                 }
                 $schema = preg_replace($pattern, $replace, $schema);
             }
         }
         // Do not remove TABLES AND FOREIGN KEYS
         list($disabledTables, $disabledColumns) = \XLite\Core\Database::getInstance()->getDisabledStructuresToStore();
         // Do not remove TABLES
         list($enabledTables, $enabledColumns) = \XLite\Core\Database::getInstance()->getEnabledStructuresToStore();
         // Do not drop disabled tables and foreign keys
         foreach ($disabledTables as $i => $t) {
             $disabledTables[$i] = preg_quote($t, '/');
         }
         foreach ($enabledTables as $i => $t) {
             $enabledTables[$i] = preg_quote($t, '/');
         }
         $tablePrefix = preg_quote(\XLite\Core\Database::getInstance()->getTablePrefix(), '/');
         if ($disabledTables) {
             $schema = preg_grep('/ALTER TABLE `' . $tablePrefix . '(?:' . implode('|', $disabledTables) . ')` DROP FOREIGN KEY /Ss', $schema, PREG_GREP_INVERT);
             $schema = preg_grep('/ALTER TABLE `' . $tablePrefix . '(?:' . implode('|', $disabledTables) . ')` ADD CONSTRAINT [a-zA-Z0-9-_]+ FOREIGN KEY /Ss', $schema, PREG_GREP_INVERT);
             $schema = preg_grep('/DROP TABLE IF EXISTS `' . $tablePrefix . '(?:' . implode('|', $disabledTables + $enabledTables) . ')`/Ss', $schema, PREG_GREP_INVERT);
         }
         // Do not drop disabled columns
         foreach ($disabledColumns as $t => $fields) {
             $t = preg_quote($t, '/');
             foreach ($fields as $f => $change) {
                 $f = preg_quote($f, '/');
                 if (preg_match('/NOT NULL/Ss', $change) || !preg_match('/^\\S+\\s+\\S+\\s+NULL/Ss', $change)) {
                     // Change NOT NULL to NULL
                     $change = preg_replace('/^([^`]\\S*[^`])\\s/', '`\\1` ', $change);
                     if (preg_match('/NOT NULL/Ss', $change)) {
                         $change = preg_replace('/\\s+NOT NULL/Ss', ' NULL', $change);
                     } else {
                         $change = preg_replace('/^(\\S+\\s+\\S+)\\s+/Ss', '\\1 NULL ', $change);
                     }
                     $schema = preg_replace('/(ALTER TABLE `' . $tablePrefix . $t . '`.*) DROP `' . $f . '`(, |$)/Ss', '\\1 MODIFY ' . $change . '\\2', $schema);
                 } else {
                     $schema = preg_replace('/(ALTER TABLE `' . $tablePrefix . $t . '`.*) DROP `' . $f . '`(, |$)/Ss', '\\1 ', $schema);
                 }
             }
         }
         // Assign columns' character sets
         foreach ($this->columnsCharSets as $column => $charset) {
             $schema = preg_replace('/(`' . $this->_class->getTableName() . '`.+`' . $column . '`\\s+' . '(?:char|varchar|tinytext|text|mediumtext|longtext)(?:\\(\\d+\\))?)/Ssi', '$1 CHARACTER SET ' . $charset, $schema);
         }
         // Clear empty ALTER TABLE
         $schema = preg_replace('/ALTER TABLE `' . $tablePrefix . '[^`]+`\\s*$/Ss', '', $schema);
     }
     return $schema;
 }
Ejemplo n.º 11
0
 /**
  * Update shipping methods with data received from the marketplace
  *
  * @param array $data List of payment methods received from marketplace
  *
  * @return void
  */
 public function updateShippingMethods($data)
 {
     if (!empty($data) && is_array($data)) {
         $tmpMethods = $this->createQueryBuilder('m')->select('m')->getQuery()->getArrayResult();
         if ($tmpMethods) {
             $methods = array();
             // Prepare associative array of existing methods with 'processor' as a key
             foreach ($tmpMethods as $m) {
                 if ('offline' !== $m['processor'] && '' === $m['carrier']) {
                     $methods[$m['processor']] = $m;
                 }
             }
             foreach ($data as $i => $extMethod) {
                 if (!empty($extMethod['processor'])) {
                     $extMethod['fromMarketplace'] = 1;
                     $data[$i] = $extMethod;
                     if (isset($methods[$extMethod['processor']])) {
                         // Method already exists in the database
                         if (!$methods[$extMethod['processor']]['fromMarketplace']) {
                             // Method is not from marketplace, do not update
                             unset($data[$i]);
                         }
                     }
                 } else {
                     // Wrong data row, ignore this
                     unset($data[$i]);
                 }
             }
             // Save data as temporary yaml file
             $yaml = \Symfony\Component\Yaml\Yaml::dump(array('XLite\\Model\\Shipping\\Method' => $data));
             $yamlFile = LC_DIR_TMP . 'pm.yaml';
             \Includes\Utils\FileManager::write(LC_DIR_TMP . 'pm.yaml', $yaml);
             // Update database from yaml file
             \XLite\Core\Database::getInstance()->loadFixturesFromYaml($yamlFile);
         }
     }
 }
Ejemplo n.º 12
0
 /**
  * Update payment methods with data received from the marketplace
  *
  * @param array List of payment methods received from marketplace
  *
  * @return void
  */
 public function updatePaymentMethods($data)
 {
     if (!empty($data) && is_array($data)) {
         $tmpMethods = $this->createQueryBuilder('m')->select('m')->getQuery()->getArrayResult();
         if ($tmpMethods) {
             $methods = array();
             // Prepare associative array of existing methods with 'service_name' as a key
             foreach ($tmpMethods as $m) {
                 $methods[$m['service_name']] = $m;
             }
             foreach ($data as $i => $extMethod) {
                 if (!empty($extMethod['service_name'])) {
                     $extMethod['fromMarketplace'] = 1;
                     $extMethod['moduleEnabled'] = 0;
                     $data[$i] = $extMethod;
                     if (isset($methods[$extMethod['service_name']])) {
                         // Method already exists in the database
                         if (!$methods[$extMethod['service_name']]['fromMarketplace']) {
                             $data[$i] = array('service_name' => $extMethod['service_name'], 'countries' => !empty($extMethod['countries']) ? $extMethod['countries'] : array(), 'exCountries' => !empty($extMethod['exCountries']) ? $extMethod['exCountries'] : array(), 'orderby' => !empty($extMethod['orderby']) ? $extMethod['orderby'] : 0);
                         }
                     }
                 } else {
                     // Wrong data row, ignore this
                     unset($data[$i]);
                 }
             }
             // Save data as temporary yaml file
             $yaml = \Symfony\Component\Yaml\Yaml::dump(array('XLite\\Model\\Payment\\Method' => $data));
             $yamlFile = LC_DIR_TMP . 'pm.yaml';
             \Includes\Utils\FileManager::write(LC_DIR_TMP . 'pm.yaml', $yaml);
             // Update database from yaml file
             \XLite\Core\Database::getInstance()->loadFixturesFromYaml($yamlFile);
         }
     }
 }
Ejemplo n.º 13
0
 /**
  * Uninstall module
  *
  * @param \XLite\Model\Module $module    Module object
  * @param array               &$messages Messages list
  *
  * @return boolean
  */
 public function uninstallModule(\XLite\Model\Module $module, &$messages)
 {
     $result = false;
     // Get module pack
     $pack = new \XLite\Core\Pack\Module($module);
     $dirs = $pack->getDirs();
     $nonWritableDirs = array();
     // Check module directories permissions
     foreach ($dirs as $dir) {
         if (\Includes\Utils\FileManager::isExists($dir) && !\Includes\Utils\FileManager::isDirWriteable($dir)) {
             $nonWritableDirs[] = \Includes\Utils\FileManager::getRelativePath($dir, LC_DIR_ROOT);
         }
     }
     $params = array('name' => sprintf('%s v%s (%s)', $module->getModuleName(), $module->getVersion(), $module->getAuthorName()));
     if (empty($nonWritableDirs)) {
         $yamlData = array();
         $yamlFiles = \Includes\Utils\ModulesManager::getModuleYAMLFiles($module->getAuthor(), $module->getName());
         foreach ($yamlFiles as $yamlFile) {
             $yamlData[] = \Includes\Utils\FileManager::read($yamlFile);
         }
         if (!$module->checkModuleMainClass()) {
             $classFile = LC_DIR_CLASSES . \Includes\Utils\Converter::getClassFile($module->getMainClass());
             if (\Includes\Utils\FileManager::isFileReadable($classFile)) {
                 require_once $classFile;
             }
         }
         // Call uninstall event method
         $r = $module->callModuleMethod('callUninstallEvent', 111);
         if (111 == $r) {
             \XLite\Logger::getInstance()->log($module->getActualName() . ': Method callUninstallEvent() was not called');
         }
         // Remove from FS
         foreach ($dirs as $dir) {
             \Includes\Utils\FileManager::unlinkRecursive($dir);
         }
         \Includes\Utils\ModulesManager::disableModule($module->getActualName());
         \Includes\Utils\ModulesManager::removeModuleFromDisabledStructure($module->getActualName());
         // Remove module from DB
         try {
             // Refresh module entity as it was changed by disableModule() method above
             $module = $this->find($module->getModuleID());
             $this->delete($module);
         } catch (\Exception $e) {
             $messages[] = $e->getMessage();
         }
         if ($module->getModuleID()) {
             $messages[] = \XLite\Core\Translation::getInstance()->translate('A DB error occured while uninstalling the module X', $params);
         } else {
             if (!empty($yamlData)) {
                 foreach ($yamlData as $yaml) {
                     \XLite\Core\Database::getInstance()->unloadFixturesFromYaml($yaml);
                 }
             }
             $messages[] = \XLite\Core\Translation::getInstance()->translate('The module X has been uninstalled successfully', $params);
             $result = true;
         }
     } else {
         $messages[] = \XLite\Core\Translation::getInstance()->translate('Unable to delete module X files: some dirs have no writable permissions: Y', $params + array('dirs' => implode(', ', $nonWritableDirs)));
     }
     return $result;
 }
Ejemplo n.º 14
0
 /**
  * Prepare DB schema
  *
  * @return void
  */
 public static function prepareDBSchema()
 {
     static::$schema = \XLite\Core\Database::getInstance()->getDBSchema(\XLite\Core\Database::getInstance()->getDBSchemaMode());
     static::saveFile();
 }
Ejemplo n.º 15
0
 /**
  * Uninstall module
  *
  * @return void
  */
 protected function doActionUninstall()
 {
     $module = $this->getModule();
     if ($module) {
         $pack = new \XLite\Core\Pack\Module($module);
         $dirs = $pack->getDirs();
         $nonWritableDirs = array();
         // Check permissions
         foreach ($dirs as $dir) {
             if (!\Includes\Utils\FileManager::isDirWriteable($dir)) {
                 $nonWritableDirs[] = \Includes\Utils\FileManager::getRelativePath($dir, LC_DIR_ROOT);
             }
         }
         $params = array('name' => $module->getActualName());
         if (empty($nonWritableDirs)) {
             $yaml = \Includes\Utils\FileManager::read(\Includes\Utils\ModulesManager::getModuleYAMLFile($module->getAuthor(), $module->getName()));
             // Remove from FS
             foreach ($dirs as $dir) {
                 \Includes\Utils\FileManager::unlinkRecursive($dir);
             }
             // Disable this and depended modules
             \Includes\Utils\ModulesManager::disableModule($module->getActualName());
             \Includes\Utils\ModulesManager::removeModuleFromDisabledStructure($module->getActualName());
             // Remove from DB
             \XLite\Core\Database::getRepo('\\XLite\\Model\\Module')->delete($module);
             if ($module->getModuleID()) {
                 $message = 'A DB error occured while uninstalling the module "{{name}}"';
                 $this->showError(__FUNCTION__, $message, $params);
             } else {
                 if (!empty($yaml)) {
                     \XLite\Core\Database::getInstance()->unloadFixturesFromYaml($yaml);
                 }
                 $message = 'The module "{{name}}" has been uninstalled successfully';
                 $this->showInfo(__FUNCTION__, $message, $params);
             }
             // To restore previous state
             \XLite\Core\Marketplace::getInstance()->saveAddonsList(0);
             // Flag to rebuild cache
             \XLite::setCleanUpCacheFlag(true);
         } else {
             $message = 'Unable to delete module "{{name}}" files: some dirs have no writable permissions: {{dirs}}';
             $this->showError(__FUNCTION__, $message, $params + array('dirs' => implode(', ', $nonWritableDirs)));
         }
     }
 }
Ejemplo n.º 16
0
Archivo: Db.php Proyecto: kingsj/core
 /**
  * Truncate all data
  *
  * @return void
  */
 protected function doActionTruncate()
 {
     $type = \XLite\Core\Request::getInstance()->type;
     $type = $type ? strtolower($type) : 'all';
     $lines = 0;
     $types = array_map('trim', explode(',', $type));
     foreach ($types as $type) {
         switch ($type) {
             case \XLite\Model\Repo\ARepo::TYPE_STORE:
             case \XLite\Model\Repo\ARepo::TYPE_SECONDARY:
             case \XLite\Model\Repo\ARepo::TYPE_SERVICE:
                 $lines += \XLite\Core\Database::getInstance()->truncateByType($type);
                 break;
             default:
                 $lines += \XLite\Core\Database::getInstance()->truncate($list);
         }
     }
     $this->printContent('Truncated tables: ' . $lines);
 }
Ejemplo n.º 17
0
 /**
  * Add all enabled modules to ENABLED registry
  *
  * @return void
  */
 public function addEnabledModulesToRegistry()
 {
     foreach ($this->findBy(array('enabled' => true)) as $module) {
         \XLite\Core\Database::getInstance()->registerModuleToEnabledRegistry($module->getActualName(), \Includes\Utils\ModulesManager::getModuleProtectedStructures($module->getAuthor(), $module->getName()));
     }
 }
Ejemplo n.º 18
0
 /**
  * Process DB schema
  *
  * @param array  $schema Schema
  * @param string $type   Schema type
  *
  * TODO: Refactor it, divide et impera
  * @return array
  */
 public function processSchema(array $schema, $type)
 {
     if (\XLite\Core\Database::SCHEMA_UPDATE === $type || \XLite\Core\Database::SCHEMA_CREATE === $type) {
         // Do not remove TABLES AND FOREIGN KEYS
         list($disabledTables, $disabledColumns) = \XLite\Core\Database::getInstance()->getDisabledStructuresToStore();
         // Do not drop disabled tables and foreign keys
         foreach ($disabledTables as $i => $t) {
             $disabledTables[$i] = preg_quote($t, '/');
         }
         $tablePrefix = preg_quote(\XLite\Core\Database::getInstance()->getTablePrefix(), '/');
         if ($disabledTables) {
             // Do not remove TABLES
             list($enabledTables, ) = \XLite\Core\Database::getInstance()->getEnabledStructuresToStore();
             foreach ($enabledTables as $i => $t) {
                 $enabledTables[$i] = preg_quote($t, '/');
             }
             $schema = preg_grep('/ALTER TABLE `?' . $tablePrefix . '(?:' . implode('|', $disabledTables) . ')`? DROP FOREIGN KEY /Ss', $schema, PREG_GREP_INVERT);
             $schema = preg_grep('/ALTER TABLE `?' . $tablePrefix . '(?:' . implode('|', $disabledTables) . ')`? ADD CONSTRAINT [a-zA-Z0-9-_]+ FOREIGN KEY /Ss', $schema, PREG_GREP_INVERT);
             $schema = preg_grep('/DROP TABLE IF EXISTS `?' . $tablePrefix . '(?:' . implode('|', $disabledTables + $enabledTables) . ')`?/Ss', $schema, PREG_GREP_INVERT);
             // Do not drop foreign keys referenced to the disabled tables
             preg_match_all('/ALTER TABLE `?([a-zA-Z0-9-_]+)`? DROP FOREIGN KEY `?([a-zA-Z0-9-_]+)`?/S', implode(';', $schema), $droppedKeys);
             if (!empty($droppedKeys[0]) && is_array($droppedKeys[0])) {
                 $filterOnDropKeys = array();
                 $len = strlen($tablePrefix);
                 for ($i = 0; $i < count($droppedKeys[0]); $i++) {
                     $foreignKeys = \XLite\Core\Database::getEM()->getConnection()->getSchemaManager()->listTableForeignKeys($droppedKeys[1][$i]);
                     if (!empty($foreignKeys)) {
                         foreach ($foreignKeys as $fkey) {
                             if (in_array(substr($fkey->getForeignTableName(), $len), $disabledTables, true)) {
                                 $filterOnDropKeys[] = substr($fkey->getName(), 3);
                                 // Cut off 'FK_' from key name
                             }
                         }
                     }
                 }
                 if ($filterOnDropKeys) {
                     $filterOnDropKeys = array_unique($filterOnDropKeys);
                     $schema = preg_grep('/ALTER TABLE `?[a-zA-Z0-9-_]+`? DROP FOREIGN KEY `?FK_(?:' . implode('|', $filterOnDropKeys) . ')`?/Ss', $schema, PREG_GREP_INVERT);
                     $indexNames = preg_filter('/DROP INDEX `?IDX_(.*?)`? ON `?[a-zA-Z0-9-_]+`?/Ss', '\\1', $schema);
                     // Hack for different names of indexes (IDX_*) and foreign keys (FK_*) in Windows
                     // See BUG-1963
                     $filterOnDropKeysForIndexes = array_filter($indexNames, function ($idxName) use($filterOnDropKeys) {
                         return array_reduce($filterOnDropKeys, function ($carry, $fkName) use($idxName) {
                             return $carry ?: false !== strpos($fkName, $idxName);
                         }, false);
                     });
                     $schema = preg_grep('/DROP INDEX `?IDX_(?:' . implode('|', $filterOnDropKeysForIndexes) . ')`? ON `?[a-zA-Z0-9-_]+`?/Ss', $schema, PREG_GREP_INVERT);
                 }
             }
         }
         // Do not drop disabled columns
         foreach ($disabledColumns as $t => $fields) {
             $t = preg_quote($t, '/');
             foreach ($fields as $f => $change) {
                 $f = preg_quote($f, '/');
                 if (preg_match('/NOT NULL/S', $change) || !preg_match('/^.+NULL/Ss', $change)) {
                     // Change NOT NULL to NULL
                     $change = preg_replace('/^([^`]\\S*[^`])\\s/', '`\\1` ', $change);
                     if (preg_match('/NOT NULL/S', $change)) {
                         $change = preg_replace('/\\s+NOT NULL/S', ' NULL', $change);
                     } else {
                         $change = preg_replace('/^(.+)/Ss', '\\1 NULL ', $change);
                     }
                     $schema = preg_replace('/^(ALTER TABLE `?' . $tablePrefix . $t . '`?.*) DROP `?' . $f . '`?(,|$)/Ss', '\\1 MODIFY ' . $change . '\\2', $schema);
                 } else {
                     $schema = preg_replace('/(ALTER TABLE `?' . $tablePrefix . $t . '`?.*?)DROP `?' . $f . '`?(, | *$)/Ss', '\\1 ', $schema);
                 }
                 $schema = preg_replace('/[, \\t\\n\\r\\0\\x0B]*?$/S', '', $schema);
             }
         }
         // Do not drop index if it is not exist in database
         $notExistedIndexes = $this->getNotExistedIndexes($schema);
         $schema = preg_grep('/DROP INDEX `?IDX_(?:' . implode('|', $notExistedIndexes) . ')`? ON `?[a-zA-Z0-9-_]+`?/Ss', $schema, PREG_GREP_INVERT);
         // Assign columns' character sets
         foreach ($this->columnsCharSets as $column => $charset) {
             $schema = preg_replace('/(' . $this->_class->getTableName() . '.+' . $column . '\\s+' . '(?:char|varchar|tinytext|text|mediumtext|longtext)(?:\\(\\d+\\))?)/Ssi', '$1 CHARACTER SET ' . $charset, $schema);
         }
         // Clear empty ALTER TABLE
         $schema = preg_replace('/ALTER TABLE `' . $tablePrefix . '[^`]+`\\s*$/Ss', '', $schema);
     }
     return $schema;
 }
Ejemplo n.º 19
0
// vim: set ts=4 sw=4 sts=4 et:
/**
 * LiteCommerce
 * 
 * NOTICE OF LICENSE
 * 
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to licensing@litecommerce.com so we can send you a copy immediately.
 * 
 * PHP version 5.3.0
 * 
 * @category  LiteCommerce
 * @author    Creative Development LLC <*****@*****.**> 
 * @copyright Copyright (c) 2011 Creative Development LLC <*****@*****.**>. All rights reserved
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      http://www.litecommerce.com/
 */
return function () {
    // Update tables structure to avoid categories and products images loss
    $prefix = \XLite\Core\Database::getInstance()->getTablePrefix();
    $queries = array("ALTER TABLE `{$prefix}category_images` DROP FOREIGN KEY `{$prefix}category_images_ibfk_1`;", "ALTER TABLE `{$prefix}category_images` CHANGE `id` `category_id` int(10) unsigned DEFAULT NULL;", "ALTER TABLE `{$prefix}category_images` CHANGE `image_id` `id` int(10) unsigned NOT NULL AUTO_INCREMENT;", "ALTER TABLE `{$prefix}product_images` DROP FOREIGN KEY `{$prefix}product_images_ibfk_1`;", "ALTER TABLE `{$prefix}product_images` CHANGE `id` `product_id` int(10) unsigned DEFAULT NULL;", "ALTER TABLE `{$prefix}product_images` CHANGE `image_id` `id` int(10) unsigned NOT NULL AUTO_INCREMENT;");
    foreach ($queries as $query) {
        \Includes\Utils\Database::execute($query);
    }
};
Ejemplo n.º 20
0
 /**
  * Get entity manager
  *
  * @return \Doctrine\ORM\EntityManager
  */
 public static function getEM()
 {
     // FIXME
     if (!isset(static::$em)) {
         \XLite\Core\Database::getInstance();
     }
     return static::$em;
 }
Ejemplo n.º 21
0
Archivo: Main.php Proyecto: kingsj/core
 /**
  * Execute certain hook handle
  *
  * @return void
  */
 public function executeHookHandler()
 {
     \XLite\Core\Database::getInstance()->updateDBSchema();
 }
Ejemplo n.º 22
0
 /**
  * Sets up the fixture, for example, open a network connection.
  * This method is called before a test is executed.
  *
  * @return void
  * @see    ____func_see____
  * @since  1.0.0
  */
 protected function setUp()
 {
     set_time_limit(0);
     $request = $this->getRequest();
     // This data will be parsed by Reqest/Router transports
     $GLOBALS['_SERVER']['REQUEST_METHOD'] = $request['method'];
     if (!empty($request['data'])) {
         $GLOBALS['_' . $request['method']] = $request['data'];
     }
     if (!empty($request['cookies'])) {
         $GLOBALS['_COOKIE'] = $request['cookies'];
     }
     // Instantiate singltons
     if ($this->needAppInit($request)) {
         $this->app = \XLite::getInstance()->run($request['controller']);
     }
     // Set customer skin
     \XLite\Core\Layout::getInstance()->setCustomerSkin();
     // Clear and restart (if need) entity manager
     \XLite\Core\Database::getEM()->clear();
     $this->query('SET autocommit = 1');
     try {
         \XLite\Core\Database::getEM()->flush();
     } catch (\Doctrine\ORM\ORMException $e) {
         if ('The EntityManager is closed.' == $e->getMessage()) {
             \XLite\Core\Database::getInstance()->startEntityManager();
         } else {
             throw $e;
         }
     }
     \XLite\Core\Session::getInstance()->restart();
     // Memory usage
     $this->start['memory'] = memory_get_usage();
     $this->end['memory'] = 0;
     // Timing
     $this->start['time'] = microtime(true);
 }
Ejemplo n.º 23
0
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.x-cart.com/license-agreement.html
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to licensing@x-cart.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not modify this file if you wish to upgrade X-Cart to newer versions
 * in the future. If you wish to customize X-Cart for your needs please
 * refer to http://www.x-cart.com/ for more information.
 *
 * @category  X-Cart 5
 * @author    Qualiteam software Ltd <*****@*****.**>
 * @copyright Copyright (c) 2011-2015 Qualiteam software Ltd <*****@*****.**>. All rights reserved
 * @license   http://www.x-cart.com/license-agreement.html X-Cart 5 License Agreement
 * @link      http://www.x-cart.com/
 */
return function () {
    $tables = \XLite\Core\Database::getEM()->getConnection()->getSchemaManager()->listTableNames();
    $prefix = \XLite\Core\Database::getInstance()->getTablePrefix();
    $queries = array('SET UNIQUE_CHECKS=0, FOREIGN_KEY_CHECKS=0');
    foreach ($tables as $k => $v) {
        if ($v != $prefix . 'view_lists') {
            $queries[] = 'ALTER TABLE`' . $v . '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;';
        }
    }
    $queries[] = 'SET UNIQUE_CHECKS=1, FOREIGN_KEY_CHECKS=1';
    \XLite\Core\Database::getInstance()->executeQueries($queries);
};
Ejemplo n.º 24
0
 * @author    Qualiteam software Ltd <*****@*****.**>
 * @copyright Copyright (c) 2011-2015 Qualiteam software Ltd <*****@*****.**>. All rights reserved
 * @license   http://www.x-cart.com/license-agreement.html X-Cart 5 License Agreement
 * @link      http://www.x-cart.com/
 */
return function () {
    $config = \XLite\Core\Config::getInstance()->CDev->AustraliaPost;
    $fields = array('test_mode', 'api_key', 'package_type', 'package_box_type', 'service_option', 'extra_cover', 'extra_cover_value', 'currency_rate', 'enable_new_methods', 'debug_enabled', 'max_weight');
    $booleanFields = array('test_mode', 'extra_cover', 'enable_new_methods', 'debug_enabled');
    $values = array();
    foreach ($fields as $fieldName) {
        $values[$fieldName] = isset($booleanFields[$fieldName]) ? 'Y' === $config->{$fieldName} || 1 === (int) $config->{$fieldName} : $config->{$fieldName};
    }
    $values['dimensions'] = serialize(array($config->length, $config->width, $config->height));
    $yamlFile = __DIR__ . LC_DS . 'post_rebuild.yaml';
    \XLite\Core\Database::getInstance()->loadFixturesFromYaml($yamlFile);
    /** @var \XLite\Model\Repo\Config $repo */
    $repo = \XLite\Core\Database::getRepo('XLite\\Model\\Config');
    $category = 'CDev\\AustraliaPost';
    foreach ($values as $name => $value) {
        $repo->createOption(array('category' => $category, 'name' => $name, 'value' => $value));
    }
    foreach (array('length', 'width', 'height') as $name) {
        $option = $repo->findOneBy(array('name' => $name, 'category' => $category));
        if ($option) {
            \XLite\Core\Database::getEM()->remove($option);
        }
    }
    \XLite\Core\Database::getEM()->flush();
    \XLite\Core\Config::updateInstance();
    /** @var \XLite\Model\Repo\Shipping\Method $repo */
Ejemplo n.º 25
0
 /**
  * Get entity manager
  *
  * @return \Doctrine\ORM\EntityManager
  */
 public static function getEM()
 {
     // FIXME: add __constructStatic
     if (null === static::$em) {
         \XLite\Core\Database::getInstance();
     }
     return static::$em;
 }