Upgrade Ecommerce metadata - from version 0 (closed source) to version 1 (first open source version, february 2013)

@deprecated
184127
public function upgradeEcommerce() {

		$options = get_option( 'ecomm-url' );
		$compare = $this->getDeprecatedComparisonTable( 'ecommerce' );
		$new_options = [];

		if ( $options ) {
			foreach ( $options as $meta_key => $meta_value ) {
				$new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false;
				if ( $new_meta_key ) {
					$new_options[ $new_meta_key ] = $meta_value;
				}
			}
		}

		update_option( 'pressbooks_ecommerce_links', $new_options );
		delete_option( 'ecomm-url' );
	}
482340
public function upgradeDatabase()
    {
        $config = $this->getConfig();

        // In case public registrations have been enabled with manual approval,
        // the user needs to setup workflows manually to apply the same
        // functionality after the upgrade. It is safer to disable public
        // registrations for as long as it takes to setup the workflows.
        if ($config->get('concrete.user.registration.enabled') &&
            $config->get('concrete.user.registration.approval')
        ) {
            $config->save('concrete.user.registration.enabled', false);
            $config->save('concrete.user.registration.approval', null);
            $config->save('concrete.user.registration.type', 'disabled');
        }
    }
801733
public function upgradeDatabase()
    {
        $service = \Core::make('site');
        $site = $service->getDefault();
        $siteConfig = $site->getConfigRepository();
        $url = $siteConfig->get('seo.canonical_ssl_url');
        if ($url) {
            if ($siteConfig->get('seo.canonical_url')) {
                $siteConfig->save('seo.canonical_url_alternative', $url);
            } else {
                $siteConfig->save('seo.canonical_url', $url);
            }
            $siteConfig->save('seo.canonical_ssl_url', null);
        }
    }
1170607
private function updateVersionNumber()
    {
        $dados = json_decode(file_get_contents(PATH_HOME . "_config/config.json"), true);
        $dados['version'] += 0.01;
        Config::createConfig($dados);

        Helper::createFolderIfNoExist(PATH_HOME . "_config/updates");
        $f = fopen(PATH_HOME . "_config/updates/version.txt", "w+");
        fwrite($f, file_get_contents(PATH_HOME . "composer.lock"));
        fclose($f);
    }
52511
public function upgradeDatabase()
    {
        \Concrete\Core\Database\Schema\Schema::refreshCoreXMLSchema([
            'ConversationPermissionAddMessageAccessList',
            'ConversationSubscriptions',
            'Conversations',
        ]);

        // Subscribe admin to conversations by default, if we have no subscriptions
        $users = \Conversation::getDefaultSubscribedUsers();
        if (count($users) == 0) {
            $admin = \UserInfo::getByID(USER_SUPER_ID);
            if (is_object($admin)) {
                $users = [$admin];
                \Conversation::setDefaultSubscribedUsers($users);
            }
        }

        $db = \Database::get();
        $db->Execute('DROP TABLE IF EXISTS PageStatistics');

        $this->refreshBlockType('page_list');

        $this->refreshBlockType('page_title');

        $this->refreshBlockType('form');

        $c = \Page::getByPath('/dashboard/system/seo/urls');
        if (is_object($c) && !$c->isError()) {
            $c->update(['cName' => 'URLs and Redirection']);
        }

        $this->createSinglePage('/dashboard/system/environment/entities', 'Database Entities', ['meta_keywords' => 'database, entities, doctrine, orm']);

        $pkx = Category::getByHandle('multilingual_section');
        if (!is_object($pkx)) {
            $pkx = Category::add('multilingual_section');
        }
        $pkx->associateAccessEntityType(Type::getByHandle('group'));
        $pkx->associateAccessEntityType(Type::getByHandle('user'));
        $pkx->associateAccessEntityType(Type::getByHandle('group_combination'));

        $db->Execute('alter table QueueMessages modify column body longtext not null');

        $this->updatePermissionDurationObjects();

        $key = Key::getByHandle('add_conversation_message');
        if (is_object($key) && !$key->permissionKeyHasCustomClass()) {
            $key->setPermissionKeyHasCustomClass(true);
        }

        $this->installMaintenanceModePermission();

        $db = \Database::get();
        if ($this->updateSectionPlurals) {
            $rs = $db->Execute('select cID, msLanguage, msCountry from MultilingualSections');
            while ($row = $rs->FetchRow()) {
                $locale = $row['msLanguage'];
                if ($row['msCountry']) {
                    $locale .= '_' . $row['msCountry'];
                }
                $localeInfo = \Gettext\Languages\Language::getById($locale);
                if ($localeInfo) {
                    $pluralCases = [];
                    foreach ($localeInfo->categories as $category) {
                        $pluralCases[] = $category->id . '@' . $category->examples;
                    }
                    $db->update(
                        'MultilingualSections',
                        [
                            'msNumPlurals' => count($localeInfo->categories),
                            'msPluralRule' => $localeInfo->formula,
                            'msPluralCases' => implode("\n", $pluralCases),
                        ],
                        ['cID' => $row['cID']]
                        );
                }
            }
        }
        if ($this->updateMultilingualTranslations) {
            $db->Execute("UPDATE MultilingualTranslations SET comments = REPLACE(comments, ':', '\\n') WHERE comments IS NOT NULL");
        }
    }
1245731
def update_metadata(ctx, archive_name):
    '''
    
    '''

    _generate_api(ctx)
    args, kwargs = _parse_args_and_kwargs(ctx.args)
    assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args)

    var = ctx.obj.api.get_archive(archive_name)

    var.update_metadata(metadata=kwargs)
923666
private function _upgrade2 ()
    {
    	$craft = \Craft::$app;
    	$elements = $craft->elements;

    	// Delete the old plugin row
	    $this->delete(Table::PLUGINS, ['handle' => 'simple-map']);

	    // Update the old data
	    echo '    > Start map data upgrade' . PHP_EOL;

	    $rows = (new Query())
		    ->select('*')
		    ->from('{{%simplemap_maps}}')
		    ->all();

	    foreach ($rows as $row)
	    {
		    echo '    > Upgrade map value ' . $row['address'] . PHP_EOL;

	    	$site = $this->getSiteByLocale($row['ownerLocale']);

	    	$map = new MapElement([
			    'ownerId'     => $row['ownerId'],
			    'ownerSiteId' => $site->id,
			    'fieldId'     => $row['fieldId'],
			    'lat'         => $row['lat'],
			    'lng'         => $row['lng'],
			    'zoom'        => $row['zoom'] ?? 15,
			    'address'     => $row['address'],
			    'parts'       => Json::decodeIfJson($row['parts']),
		    ]);

		    $elements->saveElement($map, false);
	    }

	    $this->dropTable('{{%simplemap_maps}}');

	    // Update old field types
	    echo '    > Upgrade map field type upgrade' . PHP_EOL;

	    $rows = (new Query())
		    ->select(['id', 'settings', 'handle'])
		    ->from(Table::FIELDS)
		    ->where(['type' => 'SimpleMap_Map'])
		    ->all();

	    foreach ($rows as $row)
	    {
		    echo '    > Upgrade map field ' . $row['handle'] . PHP_EOL;

	    	$id = $row['id'];
	    	$oldSettings = Json::decodeIfJson($row['settings']);

	    	$newSettings = [
			    'lat'     => $oldSettings['lat'],
			    'lng'     => $oldSettings['lng'],
			    'zoom'    => $oldSettings['zoom'] ?? 15,
			    'country' => strtoupper($oldSettings['countryRestriction'] ?? '') ?: null,
			    'hideMap' => $oldSettings['hideMap'],
		    ];

		    $this->db->createCommand()
			    ->update(
			    	Table::FIELDS,
				    [
				    	'type' => MapField::class,
					    'settings' => Json::encode($newSettings),
				    ],
				    compact('id')
			    )
			    ->execute();
	    }

	    // Update the plugin settings
	    $this->updatePluginSettings();
    }
80982
public function upgradeDatabase()
    {
        $factory = $this->app->make(TypeFactory::class);

        // check if an attribute with the 'user_selector' handle exists
        $userSelectorAttribute = $factory->getByHandle('user_selector');
        if (is_object($userSelectorAttribute)) {

            // unlink the attribute type from any package and change its name
            $userSelectorAttribute->setPackage(null);
            $userSelectorAttribute->setAttributeTypeName(t('User Selector'));
            $em = $this->app->make(EntityManager::class);
            $em->persist($userSelectorAttribute);
            $em->flush();
        } else {

            // add the 'user_selector' attribute
            $type = $factory->add('user_selector', t('User Selector'));

            // associate the 'user_selector' attribute to collection category
            $category = Category::getByHandle('collection')->getController();
            $category->associateAttributeKeyType($type);

            // associate the 'user_selector' attribute to site category
            $category = Category::getByHandle('site')->getController();
            $category->associateAttributeKeyType($type);

            // associate the 'user_selector' attribute to user category
            $category = Category::getByHandle('user')->getController();
            $category->associateAttributeKeyType($type);

            // associate the 'user_selector' attribute to file category
            $category = Category::getByHandle('file')->getController();
            $category->associateAttributeKeyType($type);

            // associate the 'user_selector' attribute to file category
            $category = Category::getByHandle('event')->getController();
            $category->associateAttributeKeyType($type);
        }

        $db = $this->connection;
        if ($db->tableExists('atUserSelector')) {
            // This is the name of the user selector attribute table in some implementations of the user selector attribute
            // We need to take this data and place it into atNumber.
            $db->query(<<<EOT
insert into atNumber (avID, value)
    select
        atUserSelector.avID, atUserSelector.value
    from
        atUserSelector
    inner join
        AttributeValues on atUserSelector.avID = AttributeValues.avID
    left join
        atNumber on atUserSelector.avID = atNumber.avID
    where
        atNumber.avID is null
EOT
            );
        }
    }
412842
public function upgradeDatabase()
    {
        $db = $this->connection;
        $db->executeQuery("UPDATE FileImageThumbnailPaths SET thumbnailFormat = ? WHERE thumbnailFormat = '' AND (path LIKE '%.jpg' OR path LIKE '%.jpeg' OR path LIKE '%.pjpg' OR path LIKE '%.pjpeg')", [BitmapFormat::FORMAT_JPEG]);
        $db->executeQuery("UPDATE FileImageThumbnailPaths SET thumbnailFormat = ? WHERE thumbnailFormat = ''", [BitmapFormat::FORMAT_PNG]);
    }
1293648
function mergeNewAndOldMeta(old, updated) {
  const merged = {
    firstPublishTime: old.firstPublishTime || updated.publishTime
  };

  if (!Object.keys(old).length) {
    return updated;
  }

  if (old.history && updated.history) {
    merged.history = old.history.concat(updated.history);
  }

  return Object.assign(old, updated, merged);
}
508725
private void updateRequestMetadata() {
        // Take event level metadata, merge with top level metadata
        // event level metadata takes precedence
        try {
            JSONObject metadata = new JSONObject();
            Iterator<String> i = prefHelper_.getRequestMetadata().keys();
            while (i.hasNext()) {
                String k = i.next();
                metadata.put(k, prefHelper_.getRequestMetadata().get(k));
            }
            JSONObject originalMetadata = params_.optJSONObject(Defines.Jsonkey.Metadata.getKey());
            if (originalMetadata != null) {
                Iterator<String> postIter = originalMetadata.keys();
                while (postIter.hasNext()) {
                    String key = postIter.next();
                    // override keys from above
                    metadata.put(key, originalMetadata.get(key));
                }
            }
            // Install metadata need to be send only with Install request
            if ((this instanceof ServerRequestRegisterInstall) && prefHelper_.getInstallMetadata().length() > 0) {
                params_.putOpt(Defines.Jsonkey.InstallMetadata.getKey(), prefHelper_.getInstallMetadata());
            }
            params_.put(Defines.Jsonkey.Metadata.getKey(), metadata);
        } catch (JSONException e) {
           PrefHelper.Debug("Could not merge metadata, ignoring user metadata.");
        }
    }
179830
def upgrade():
    """"""
    op.execute('COMMIT')  # See https://bitbucket.org/zzzeek/alembic/issue/123
    ctx = op.get_context()
    metadata = ctx.opts['target_metadata']
    metadata.naming_convention = NAMING_CONVENTION
    metadata.bind = ctx.connection.engine
    insp = Inspector.from_engine(ctx.connection.engine)

    for table_name in insp.get_table_names():
        if table_name not in metadata.tables:
            continue

        table = metadata.tables[table_name]

        ixs = {}
        uqs = {}
        fks = {}

        for ix in insp.get_indexes(table_name):
            ixs[tuple(ix['column_names'])] = ix
        for uq in insp.get_unique_constraints(table_name):
            uqs[tuple(uq['column_names'])] = uq
        for fk in insp.get_foreign_keys(table_name):
            fks[(tuple(fk['constrained_columns']), fk['referred_table'])] = fk

        with op.batch_alter_table(
                table_name, naming_convention=NAMING_CONVENTION) as batch_op:
            for c in list(table.constraints) + list(table.indexes):
                key = None
                if isinstance(c, sa.schema.ForeignKeyConstraint):
                    key = (tuple(c.column_keys), c.referred_table.name)
                    fk = fks.get(key)
                    if fk and c.name != fk['name']:
                        batch_op.drop_constraint(
                            fk['name'], type_='foreignkey')
                        batch_op.create_foreign_key(
                            op.f(c.name), fk['referred_table'],
                            fk['constrained_columns'],
                            fk['referred_columns'],
                            **fk['options']
                        )
                elif isinstance(c, sa.schema.UniqueConstraint):
                    key = tuple(c.columns.keys())
                    uq = uqs.get(key)
                    if uq and c.name != uq['name']:
                        batch_op.drop_constraint(uq['name'], type_='unique')
                        batch_op.create_unique_constraint(
                            op.f(c.name), uq['column_names'])
                elif isinstance(c, sa.schema.CheckConstraint):
                    util.warn('Update {0.table.name} CHECK {0.name} '
                              'manually'.format(c))
                elif isinstance(c, sa.schema.Index):
                    key = tuple(c.columns.keys())
                    ix = ixs.get(key)
                    if ix and c.name != ix['name']:
                        batch_op.drop_index(ix['name'])
                        batch_op.create_index(
                            op.f(c.name), ix['column_names'],
                            unique=ix['unique'],
                        )
                elif isinstance(c, sa.schema.PrimaryKeyConstraint) or \
                        c.name == '_unnamed_':
                    # NOTE we don't care about primary keys since they have
                    # specific syntax.
                    pass
                else:
                    raise RuntimeError('Missing {0!r}'.format(c))
557917
public function upgradeDatabase()
    {
        $type = Type::getByHandle('select');
        $em = $this->connection->getEntityManager();
        if ($type) {
            /*
             * @var $type \Concrete\Core\Entity\Attribute\Type
             */
            $type->setAttributeTypeName('Option List');
            $em->persist($type);
            $em->flush();
        }

        $this->refreshEntities([
            'Concrete\Core\Entity\Attribute\Key\Settings\SelectSettings',
        ]);
    }
546745
def upgrade():
    """"""
    op.drop_constraint('fk_oauth2server_client_user_id_accounts_user',
                       'oauth2server_client', type_='foreignkey')
    op.create_foreign_key(op.f('fk_oauth2server_client_user_id_accounts_user'),
                          'oauth2server_client', 'accounts_user', ['user_id'],
                          ['id'], ondelete='CASCADE')
    op.create_index(op.f('ix_oauth2server_client_user_id'),
                    'oauth2server_client', ['user_id'], unique=False)
    op.drop_constraint('fk_oauth2server_token_user_id_accounts_user',
                       'oauth2server_token', type_='foreignkey')
    op.create_foreign_key(op.f('fk_oauth2server_token_user_id_accounts_user'),
                          'oauth2server_token', 'accounts_user', ['user_id'],
                          ['id'], ondelete='CASCADE')
    op.create_index(op.f('ix_oauth2server_token_user_id'),
                    'oauth2server_token', ['user_id'], unique=False)
    op.drop_constraint('fk_oauth2server_token_client_id_oauth2server_client',
                       'oauth2server_token', type_='foreignkey')
    op.create_foreign_key(
        op.f('fk_oauth2server_token_client_id_oauth2server_client'),
        'oauth2server_token', 'oauth2server_client', ['client_id'],
        ['client_id'], ondelete='CASCADE')
    op.create_index(op.f('ix_oauth2server_token_client_id'),
                    'oauth2server_token', ['client_id'], unique=False)
1104972
public function upgradeBookInformation() {

		// Metadata

		$meta_post = $this->getMetaPost();
		if ( ! $meta_post ) {
			return; // Do nothing
		}

		$metadata = $this->getMetaPostMetadata();
		$compare = $this->getDeprecatedComparisonTable( 'metadata' );

		foreach ( $metadata as $meta_key => $meta_value ) {
			$new_meta_key = ( isset( $compare[ $meta_key ] ) ) ? $compare[ $meta_key ] : false;
			if ( $new_meta_key ) {
				$meta_id = $this->getMidByKey( $meta_post->ID, $meta_key );
				if ( $meta_id ) {
					if ( isset( $this->upgradeCheckboxes[ $meta_key ] ) ) {
						$meta_value = 'on';
					} elseif ( is_array( $meta_value ) ) {
						$meta_value = array_values( $meta_value );
						$meta_value = array_pop( $meta_value );
					}

					// Overrides
					if ( 'pb_language' === $new_meta_key ) {
						$meta_value = substr( strtolower( $meta_value ), 0, 2 );
					}
					if ( 'pb_publication_date' === $new_meta_key ) {
						$meta_value = strtotime( $meta_value );
					}

					// Update the original $meta_key to the $new_meta_key
					update_metadata_by_mid( 'post', $meta_id, $meta_value, $new_meta_key );
				}
			}
		}
		// Force title change
		update_metadata( 'post', $meta_post->ID, 'pb_title', get_bloginfo( 'name' ) );
	}
110994
public function upgradeDatabase()
    {
        /* add permissions lines for edit_block_name and edit_block_cache_settings */
        $ebk = Key::getByHandle('edit_block_name');
        if (!is_object($ebk)) {
            Key::add('block', 'edit_block_name', 'Edit Name', "Controls whether users can change the block's name (rarely used.).", false, false);
        }
        $ebk = Key::getByHandle('edit_block_cache_settings');
        if (!is_object($ebk)) {
            Key::add('block', 'edit_block_cache_settings', 'Edit Cache Settings', 'Controls whether users can change the block cache settings for this block instance.', false, false);
        }

        /* Add marketplace single pages */
        $this->createSinglePage('/dashboard/extend/connect', 'Connect to the Community', ['meta_keywords' => 'concrete5.org, my account, marketplace']);
        $this->createSinglePage('/dashboard/extend/themes', 'Get More Themes', ['meta_keywords' => 'buy theme, new theme, marketplace, template']);
        $this->createSinglePage('/dashboard/extend/addons', 'Get More Add-Ons', ['meta_keywords' => 'buy addon, buy add on, buy add-on, purchase addon, purchase add on, purchase add-on, find addon, new addon, marketplace']);

        /* Add auth types ("handle|name") "twitter|Twitter" and "community|concrete5.org" */
        try {
            $community = AuthenticationType::getByHandle('community');
        } catch (Exception $e) {
            $community = AuthenticationType::add('community', 'concrete5.org');
            if (is_object($community)) {
                $community->disable();
            }
        }

        try {
            $twitter = AuthenticationType::getByHandle('twitter');
        } catch (Exception $e) {
            $twitter = AuthenticationType::add('twitter', 'Twitter');
            if (is_object($twitter)) {
                $twitter->disable();
            }
        }

        /* delete customize page themes dashboard single page */
        $customize = Page::getByPath('/dashboard/pages/themes/customize');
        if (is_object($customize) && !$customize->isError()) {
            $customize->delete();
        }

        /* exclude nav from flat view in dashboard */
        $flat = Page::getByPath('/dashboard/sitemap/explore');
        if (is_object($customize) && !$customize->isError() && $this->isAttributeHandleValid(PageCategory::class, 'exclude_nav')) {
            $flat->setAttribute('exclude_nav', false);
        }
    }
917785
public function upgradeDatabase()
    {
        $this->refreshEntities([
            AddressSettings::class,
        ]);
        $this->migrateDrafts();
        $app = Application::getFacadeApplication();
        // I think this has to be in postUp because it's a completely new table that's not in Schema at all? Bleh.
        $this->refreshEntities([
            Geolocator::class,
        ]);

        $glService = $app->make(GeolocatorService::class);
        /* @var GeolocatorService $glService */
        if ($glService->getByHandle('geoplugin') === null) {
            $geolocator = Geolocator::create(
                'geoplugin',
                'geoPlugin'
            );
            $geolocator
                ->setGeolocatorConfiguration([
                    'url' => 'http://www.geoplugin.net/json.gp?ip=[[IP]]',
                ])
            ;
            $glService->setCurrent($geolocator);
            $em = $glService->getEntityManager();
            $em->persist($geolocator);
            $em->flush($geolocator);
        }

        $this->createSinglePage('/dashboard/system/environment/geolocation', 'Geolocation', ['meta_keywords' => 'geolocation, ip, address, country, nation, place, locate']);
    }