Upgrade from SimpleMap (3.3.x)

@throws \Throwable
@throws \craft\errors\ElementNotFoundException
@throws \yii\base\Exception
428028
private function _upgrade3 ()
    {
	    $craft    = \Craft::$app;
	    $elements = $craft->elements;

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

	    $rows = (new Query())
		    ->select([
		    	'ownerId',
			    'ownerSiteId',
			    'fieldId',
			    'lat',
			    'lng',
			    'zoom',
			    'address',
			    'parts',
		    ])
		    ->from(Map::TableName)
		    ->all();

	    // 2. Re-create the table
	    $this->dropTable(Map::TableName);
	    (new Install())->safeUp();

	    // 3. Store the old data as new
	    foreach ($rows as $row)
	    {
		    echo '    > Upgrade map value ' . $row['address'] . PHP_EOL;

		    $map = new MapElement($row);

		    if (!$map->zoom)
		    	$map->zoom = 15;

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

	    // 4. Update field settings
	    echo '    > Upgrade map field type upgrade' . PHP_EOL;

	    $rows = (new Query())
		    ->select(['id', 'settings', 'handle'])
		    ->from(Table::FIELDS)
		    ->where(['type' => MapField::class])
		    ->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']),
			    'hideMap' => $oldSettings['hideMap'],
		    ];

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

	    $this->updatePluginSettings();
    }
376212
public function compile()
    {
        // check for the bare minimum
        if ($this->table === false || $this->type === false) {
            throw (new \Exception('Query compilation failure: missing table or type'));
        }
        switch ($this->type) {
            case 'UPDATE':
                return $this->generateUPDATEStatement();
            case 'INSERT':
                return $this->generateINSERTStatement();
            case 'DELETE':
                return $this->generateDELETEStatement();
            default:
                return $this->generateSELECTStatement();
        }
    }
393798
protected static function fe()
    {
        if( ! empty(ZN::upgrade()) )
        {
            $status = self::$lang['upgradeSuccess'];
        }
        else
        {
            $status = self::$lang['alreadyVersion'];

            if( $upgradeError = ZN::upgradeError() )
            {
                $status = $upgradeError;
            }         
        }

        return $status;
    }
876273
public function refresh()
    {
        // Use passed in constructor xml metadata
        // or get it from Xmlable object instance.
        $data = $this->xml;
        if (is_null($data)) {
            $data = $this->object->xml();
        }

        // Accept plain xml root element as string or object
        // (skip xml validation for string format).
        if (is_string($data) || $data instanceof XmlElement) {
            $this->xml = $data;
            return;
        }

        // Throw exception if data is neither string, XmlElement nor array.
        // Array must contain one element (root) with sub-elements (nodes).
        if (!is_array($data) || count($data) != 1) {
            $ns = get_class($this->object);
            throw new InvalidXmlFormatException("Method \\$ns::xml() must return string, XmlElement or array. More information at https://github.com/mleczek/xml#xml-body.");
        }

        // Build XML from array metadata
        $root = new XmlElement('XmlConverter');
        $this->xml = $this->build($root, $data)->innerXml();
    }
456122
private function loadInstallationMap()
	{
		if (file_exists($this->mapFile)) {
			if (!is_readable($this->mapFile) || is_dir($this->mapFile)) {
				throw new \Exception(sprintf(
					'Cannot read map file at %s', $this->mapFile
				));
			}

			$this->installationMap = json_decode(file_get_contents($this->mapFile), TRUE);

			if ($this->installationMap === NULL) {
				throw new \Exception(sprintf(
					'Broken map file at %s', $this->mapFile
				));
			}
		}
	}
586974
protected function updateSelector()
    {
        $buffer = implode('', $this->getBuffer());
        $qtiClassMap = ($this->isWebComponentFriendly()) ? array_merge(self::$qtiClassMapping, self::$wcFriendlyQtiClassMapping) : self::$qtiClassMapping;

        if (strpos($buffer, ',') === false) {

            // Do not rescope if already scoped!
            if (strpos($buffer, '#' . $this->getId()) === false) {
                $buffer = ($this->doesMapQtiClasses() === true) ? CssUtils::mapSelector($buffer, $qtiClassMap) : $buffer;
                $buffer = ($this->doesMapQtiPseudoClasses() === true) ? CssUtils::mapPseudoClasses($buffer, self::getQtiPseudoClassMapping()) : $buffer;
                $this->output('#' . $this->getId() . ' ' . $buffer . '{');
            } else {
                $buffer = ($this->doesMapQtiPseudoClasses() === true) ? CssUtils::mapPseudoClasses($buffer, self::getQtiPseudoClassMapping()) : $buffer;
                $this->output($buffer . '{');
            }
        } else {
            $classes = explode(',', $buffer);
            $newClasses = array();

            foreach ($classes as $c) {

                // Same as above, do not rescope if already scoped...
                if (strpos($c, '#' . $this->getId()) === false) {
                    $c = ($this->doesMapQtiClasses() === true) ? CssUtils::mapSelector($c, $qtiClassMap) : $c;
                    $newC =  '#' . $this->getId() . ' ' . trim($c);
                    $newC = str_replace(trim($c), $newC, $c);
                } else {
                    $newC = $c;
                }

                $newClasses[] = $newC;
            }

            $buffer = implode(',', $newClasses);
            $buffer = ($this->doesMapQtiPseudoClasses() === true) ? CssUtils::mapPseudoClasses($buffer, self::getQtiPseudoClassMapping()) : $buffer;
            $this->output($buffer . '{');
        }
    }
290841
public function addOrUpdate()
    {
        $this->request->allowMethod(['post']);
        if (!$this->request->is('ajax')) {
            throw new \RuntimeException('Wrong type of request!');
        }
        $params = is_array($this->request->getData()) ? $this->request->getData() : [];
        /**
         * @var \Cake\Datasource\EntityInterface $translation
         */
        $translation = $this->Translations->getTranslations(
            $params['object_model'],
            $params['object_foreign_key'],
            [
                'language' => $params['language_id'],
                'toEntity' => true,
                'field' => $params['object_field'],
            ]
        );
        if (empty($translation)) {
            /**
             * @var \Cake\Datasource\EntityInterface $translation
             */
            $translation = $this->Translations->newEntity();
        }

        $translation = $this->Translations->patchEntity($translation, $params);
        $result = $this->Translations->save($translation);
        $body = (string)json_encode(!empty($result) ? true : false);
        $this->response = $this->response->withType('application/json')->withStringBody($body);
        $this->autoRender = false;
    }
346784
public function upgrade(): void
    {
        // This table was previously created by the favorites module in 1.7.9.
        // These migrations are now part of the core code.

        if (!DB::schema()->hasTable('news')) {
            DB::schema()->create('news', static function (Blueprint $table): void {
                $table->integer('news_id', true);
                $table->integer('user_id')->nullable();
                $table->integer('gedcom_id')->nullable();
                $table->string('subject', 255);
                $table->text('body');
                $table->timestamp('updated')->useCurrent();
                
                $table->index(['user_id', 'updated']);
                $table->index(['gedcom_id', 'updated']);

                $table->foreign('user_id')->references('user_id')->on('user')->onDelete('cascade');
                $table->foreign('gedcom_id')->references('gedcom_id')->on('gedcom')->onDelete('cascade');
            });
        }
    }
752723
public function updateModel(): bool
    {
        $this->getFromForm();
        if (!$this->save()) {
            throw new Exception(\Yii::t('app', 'Ошибка при обновлении в БД'));
        }
        return true;
    }
387514
public function mergeStructure()
	{
		$tables = $this->db->getTableList();

		if ($this->from instanceof \SimpleXMLElement)
		{
			$xml = $this->from;
		}
		else
		{
			$xml = new \SimpleXMLElement($this->from);
		}

		// Get all the table definitions.
		$xmlTables = $xml->xpath('database/table_structure');

		foreach ($xmlTables as $table)
		{
			// Convert the magic prefix into the real table name.
			$tableName = $this->getRealTableName((string) $table['name']);

			if (\in_array($tableName, $tables, true))
			{
				// The table already exists. Now check if there is any difference.
				if ($queries = $this->getAlterTableql($xml->database->table_structure))
				{
					// Run the queries to upgrade the data structure.
					foreach ($queries as $query)
					{
						$this->db->setQuery((string) $query);

						try
						{
							$this->db->execute();
						}
						catch (\RuntimeException $e)
						{
							$this->db->log(LogLevel::DEBUG, 'Fail: ' . $this->db->getQuery());

							throw $e;
						}

						$this->db->log(LogLevel::DEBUG, 'Pass: ' . $this->db->getQuery());
					}
				}
			}
			else
			{
				// This is a new table.
				$sql = $this->xmlToCreate($table);

				$this->db->setQuery((string) $sql);

				try
				{
					$this->db->execute();
				}
				catch (\RuntimeException $e)
				{
					$this->db->log(LogLevel::DEBUG, 'Fail: ' . $this->db->getQuery());

					throw $e;
				}

				$this->db->log(LogLevel::DEBUG, 'Pass: ' . $this->db->getQuery());
			}
		}
	}
644157
public function build()
    {
        if ($this->classMetadata->hasField($this->fieldName)) {
            throw new InvalidMappingException(
                "Locale field [{$this->fieldName}] should not be mapped as column property in entity - {$this->classMetadata->name}, since it makes no sense"
            );
        }

        $this->classMetadata->appendExtension($this->getExtensionName(), [
            'locale' => $this->fieldName,
        ]);
    }
712840
public function actionLinkToModel()
    {
        $rr = new RequestResponse();

        if ($rr->isRequestAjaxPost()) {
            try {
                if (!\Yii::$app->request->post('file_id') || !\Yii::$app->request->post('modelId') || !\Yii::$app->request->post('modelClassName') || !\Yii::$app->request->post('modelAttribute')) {
                    throw new \yii\base\Exception("�� ���������� ������� ������");
                }

                $file = CmsStorageFile::findOne(\Yii::$app->request->post('file_id'));
                if (!$file) {
                    throw new \yii\base\Exception("�������� ���� ��� ������ ��� �� ����������");
                }

                if (!is_subclass_of(\Yii::$app->request->post('modelClassName'), ActiveRecord::className())) {
                    throw new \yii\base\Exception("���������� ��������� ���� � ���� ������");
                }

                $className = \Yii::$app->request->post('modelClassName');
                /**
                 * @var $model ActiveRecord
                 */
                $model = $className::findOne(\Yii::$app->request->post('modelId'));
                if (!$model) {
                    throw new \yii\base\Exception("������ � ������� ���������� ��������� ���� �� �������");
                }

                if (!$model->hasAttribute(\Yii::$app->request->post('modelAttribute'))) {
                    throw new \yii\base\Exception("� ������ �� ������ ������� �������� �����: " . \Yii::$app->request->post('modelAttribute'));
                }

                //�������� ������� �����
                if ($oldFileId = $model->{\Yii::$app->request->post('modelAttribute')}) {
                    /**
                     * @var $oldFile CmsStorageFile
                     * @var $file CmsStorageFile
                     */
                    $oldFile = CmsStorageFile::findOne($oldFileId);
                    $oldFile->delete();
                }

                $model->{\Yii::$app->request->post('modelAttribute')} = $file->id;
                if (!$model->save(false)) {
                    throw new \yii\base\Exception("�� ������� ��������� ������");
                }

                $file->name = $model->name;
                $file->save(false);

                $rr->success = true;
                $rr->message = "";

            } catch (\Exception $e) {
                $rr->success = false;
                $rr->message = $e->getMessage();
            }

        }

        return $rr;
    }
1082507
@SuppressWarnings("deprecation")
    public boolean upgrade() throws Exception {
        // We need to start a client so we can send requests to elasticsearch
        try {
            esClient.start();
        } catch (Exception t) {
            logger.fatal("We can not start Elasticsearch Client. Exiting.", t);
            return false;
        }

        // The upgrade script is for now a bit dumb. It assumes that you had an old version of FSCrawler (< 2.3) and it will
        // simply move data from index/folder to index_folder
        String index = settings.getElasticsearch().getIndex();

        // Check that the old index actually exists
        if (esClient.isExistingIndex(index)) {
            // We check that the new indices don't exist yet or are empty
            String indexFolder = settings.getElasticsearch().getIndexFolder();
            boolean indexExists = esClient.isExistingIndex(indexFolder);
            long numberOfDocs = 0;
            if (indexExists) {
                ESSearchResponse responseFolder = esClient.search(new ESSearchRequest().withIndex(indexFolder));
                numberOfDocs = responseFolder.getTotalHits();
            }
            if (numberOfDocs > 0) {
                logger.warn("[{}] already exists and is not empty. No upgrade needed.", indexFolder);
            } else {
                logger.debug("[{}] can be upgraded.", index);

                // Create the new indices with the right mappings (well, we don't read existing user configuration)
                if (!indexExists) {
                    esClient.createIndices();
                    logger.info("[{}] has been created.", indexFolder);
                }

                // Run reindex task for folders
                logger.info("Starting reindex folders...");
                int folders = esClient.reindex(index, INDEX_TYPE_FOLDER, indexFolder);
                logger.info("Done reindexing [{}] folders...", folders);

                // Run delete by query task for folders
                logger.info("Starting removing folders from [{}]...", index);
                esClient.deleteByQuery(index, INDEX_TYPE_FOLDER);
                logger.info("Done removing folders from [{}]", index);

                logger.info("You can now upgrade your elasticsearch cluster to >=6.0.0!");
                return true;
            }
        } else {
            logger.info("[{}] does not exist. No upgrade needed.", index);
        }

        return false;
    }
838414
public static function putMapping()
    {
        $instance = new static;
        $mapping = $instance->basicElasticParams();
        $params = array(
            '_source'       => array('enabled' => true),
            'properties'    => $instance->getMappingProperties()
        );

        $mapping['body'][$instance->getTypeName()] = $params;

        return $instance->getElasticClient()->indices()->putMapping($mapping);
    }
602942
public function createElementVersion(Element $element, ElementStructure $elementStructure = null, $triggerLanguage, $userId, $comment = null)
    {
        $oldElementVersion = $this->findLatestElementVersion($element);

        $elementSource = $this->findElementSource($element->getElementtypeId());

        $elementVersion = new ElementVersion();
        $elementVersion
            ->setId(null)
            ->setElement($element)
            ->setElementSource($elementSource)
            ->setVersion($oldElementVersion->getVersion() + 1)
            ->setCreateUserId($userId)
            ->setCreatedAt(new \DateTime())
            ->setComment($comment)
            ->setTriggerLanguage($triggerLanguage);

        $element->setLatestVersion($elementVersion->getVersion());

        $this->elementManager->updateElement($element, false);

        if ($elementStructure) {
            $this->fixElementVersion($elementStructure, $elementVersion);
            $this->elementStructureManager->updateElementStructure($elementStructure, false);
        }

        $this->fieldMapper->apply($elementVersion, $elementStructure, $elementStructure->getLanguages());

        $this->elementVersionManager->updateElementVersion($elementVersion, true);

        $this->elementHistoryManager->insert(
            ElementHistoryManagerInterface::ACTION_CREATE_ELEMENT_VERSION,
            $element->getEid(),
            $userId,
            null,
            null,
            $elementVersion->getVersion(),
            $triggerLanguage
        );

        return $elementVersion;
    }
460251
public function actionUpdate()
	{
		$post=$this->loadPost();
		if(Yii::app()->request->isPostRequest)
		{
			if(isset($_POST['Post']))
				$post->setAttributes($_POST['Post']);
			if($post->save())
				$this->redirect(array('show','id'=>$post->id));
		}
		$this->render('update',array('post'=>$post));
	}
769857
function installMapsSupport() {
  require('source-map-support').install({
    environment: 'node',
    handleUncaughtExceptions: false,
    retrieveSourceMap: (source) => {
      return sourceMapsCache.has(source) ?
             {map: sourceMapsCache.get(source), url: source} :
             null;
    },
  });
}