/*
|---------------------------------------------------------------------------------------------------
| Dirname PHP 7 update
|---------------------------------------------------------------------------------------------------
505585
public static function dirname_r( $path, $count = 1 ){
    if ( $count > 1 ){
      return dirname(self::dirname_r( $path, --$count) );
    } else {
      return dirname( $path );
    }
	}
159329
public function actionUpdate()
    {
        $module = \jacmoe\mdpages\Module::getInstance();

        if(!is_dir(Yii::getAlias($module->pages_directory))) {
            $this->stderr("Execution terminated: the repository to update does not exist - please run init first.\n", Console::FG_RED);
            return self::EXIT_CODE_ERROR;
        }

        if (!$this->acquireMutex()) {
            $this->stderr("Execution terminated: command is already running.\n", Console::FG_RED);
            return self::EXIT_CODE_ERROR;
        }

        $git = Yii::createObject('jacmoe\mdpages\components\yii2tech\Git');

        $log = '';
        if($git->hasRemoteChanges(Yii::getAlias($module->pages_directory), $log)) {
            //echo $log;

            $placeholders = [
                '{binPath}' => 'git',
                '{projectRoot}' => Yii::getAlias($module->pages_directory),
                '{remote}' => 'origin',
                '{branch}' => 'master',
            ];
            $result = Shell::execute('(cd {projectRoot}; {binPath} diff --name-only HEAD {remote}/{branch})', $placeholders);
            $raw_files = $result->toString();

            $git->applyRemoteChanges(Yii::getAlias($module->pages_directory), $log);
            //echo $log;

            $files = explode("\n", $raw_files);
            array_shift($files); // the first entry is the command
            array_pop($files); // the last entry is the exit code

            $to_update = array();
            foreach($files as $file) {
                $to_update[] = Yii::getAlias('@pages') . '/' . $file;
            }

            $this->updateDB($to_update);

            $this->createImageSymlink();

        } else {
            $this->stdout("No changes detected\n\n", Console::FG_GREEN);
        }

        $this->releaseMutex();
        return self::EXIT_CODE_NORMAL;

    }
1248684
function update_cdn_container($container_name, $ttl=86400, $cdn_log_retention=False,
                                  $cdn_acl_user_agent="", $cdn_acl_referrer)
    {
        if ($container_name == "")
            throw new SyntaxException("Container name not set.");

        if ($container_name != "0" and !isset($container_name))
            throw new SyntaxException("Container name not set.");

        $url_path = $this->_make_path("CDN", $container_name);
        $hdrs = array(
            CDN_ENABLED => "True",
            CDN_TTL => $ttl,
            CDN_LOG_RETENTION => $cdn_log_retention ?  "True" : "False",
            CDN_ACL_USER_AGENT => $cdn_acl_user_agent,
            CDN_ACL_REFERRER => $cdn_acl_referrer,
            );
        $return_code = $this->_send_request("DEL_POST",$url_path,$hdrs,"POST");
        if ($return_code == 401) {
            $this->error_str = "Unauthorized";
            return array($return_code, $this->error_str, NULL);
        }
        if ($return_code == 404) {
            $this->error_str = "Container not found.";
            return array($return_code, $this->error_str, NULL);
        }
        if ($return_code != 202) {
            $this->error_str="Unexpected HTTP response: ".$this->response_reason;
            return array($return_code, $this->error_str, NULL);
        }
        return array($return_code, "Accepted", $this->_cdn_uri);

    }
277346
static function renameDir( $dir )
    {
        // just rename. Actual removing will be performed by cronjob.

        // This directory renaming is only performed on the local filesystem
        // to ensure purging of really old data. If the DB file handler is in
        // use it will check the modified_subnode field of the tree structure
        // to determin expiry when the cache-block entry is accessed.
        if ( file_exists( $dir ) )
        {
            if ( is_dir( $dir ) )
            {
                $uniqid = md5( uniqid( 'ezpsubtreecache'. getmypid(), true ) );
                $expiryCacheDir = eZSys::cacheDirectory() . '/template-block-expiry/' . $uniqid[0] . '/' . $uniqid[1] . '/' . $uniqid[2] . '/' . $uniqid;

                if ( !file_exists( $expiryCacheDir ) )
                {
                    eZDir::mkdir( $expiryCacheDir, false, true );
                }
                eZFile::rename( $dir, $expiryCacheDir, false, eZFile::APPEND_DEBUG_ON_FAILURE );
            }
            else
            {
                eZDebug::writeWarning( "$dir should be a directory. Template-block caches for 'subtree_expiry' are not removed.", __METHOD__ );
            }
        }
    }
187785
public function update_8009003() {
    $composer_json = $this->updater->getComposerJson();

    $composer_json['extra']['installer-types'][] = 'bower-asset';
    $composer_json['extra']['installer-types'][] = 'npm-asset';
    $composer_json['extra']['installer-paths']['docroot/libraries/{$name}'][] = 'type:bower-asset';
    $composer_json['extra']['installer-paths']['docroot/libraries/{$name}'][] = 'type:npm-asset';

    // Add the Asset Packagist repository if it does not already exist.
    if (isset($composer_json['repositories'])) {
      $repository_key = NULL;
      foreach ($composer_json['repositories'] as $key => $repository) {
        if ($repository['type'] == 'composer' && strpos($repository['url'], 'https://asset-packagist.org') === 0) {
          $repository_key = $key;
          break;
        }
      }
      if (is_null($repository_key)) {
        $composer_json['repositories']['asset-packagist'] = [
          'type' => 'composer',
          'url' => 'https://asset-packagist.org',
        ];
      }
    }

    $projectAcsfHooks = $this->updater->getRepoRoot() . '/factory-hooks';
    $acsf_inited = file_exists($projectAcsfHooks);
    if ($acsf_inited) {
      $composer_json['config']['platform']['php'] = '5.6';
    }

    $this->updater->writeComposerJson($composer_json);

    $messages = [
      "Your composer.json file has been modified to be compatible with Lightning 2.1.8+.",
      "You must execute `composer update` to update your lock file.",
    ];
    $formattedBlock = $this->updater->getFormatter()->formatBlock($messages, 'ice');
    $this->updater->getOutput()->writeln("");
    $this->updater->getOutput()->writeln($formattedBlock);
    $this->updater->getOutput()->writeln("");
  }
1133508
function cleanupUpdates() {
        Object.keys(_idsToUpdate).forEach(function (id) {
            var installResult = _idsToUpdate[id],
                keepFile = installResult.keepFile,
                filename = installResult.localPath;

            if (filename && !keepFile) {
                FileSystem.getFileForPath(filename).unlink();
            }
        });
        _idsToUpdate = {};
    }
961132
public function update()
    {
        /** @var \Bolt\Filesystem\Handler\JsonFile $jsonFile */
        $jsonFile = $this->app['filesystem']->get('extensions://composer.json', new JsonFile());

        if (!$jsonFile->exists()) {
            try {
                $this->init('extensions://composer.json');
            } catch (IOException $e) {
                $this->messages[] = Trans::__('page.extend.error-composer-json-not-readable');

                $this->app['extend.writeable'] = false;
                $this->app['extend.online'] = false;

                return null;
            }
        }

        $json = $jsonOrig = $jsonFile->parse();

        // Workaround Bolt 2.0 installs with "require": []
        if (isset($json['require']) && empty($json['require'])) {
            unset($json['require']);
        }

        $json = $this->setJsonDefaults($json);

        // Write out the file, but only if it's actually changed, and if it's writable.
        if ($json != $jsonOrig) {
            try {
                $jsonFile->dump($json);
            } catch (IOException $e) {
                $this->messages[] = Trans::__('page.extend.error-composer-json-not-writable');
            }
        }

        return $json;
    }
200143
function updateSite () {
    start('Adding new version of the docs site...');
    const options = { cwd: './code.material.angularjs.org' };
    writeDocsJson();

    // build files for bower
    exec([
        'rm -rf dist',
        'gulp docs'
    ]);
    replaceFilePaths();

    // copy files over to site repo
    exec([
        `cp -Rf ../dist/docs ${newVersion}`,
        'rm -rf latest && cp -Rf ../dist/docs latest',
        'git add -A',
        `git commit -m "release: version ${newVersion}"`,
        'rm -rf ../dist'
    ], options);
    replaceBaseHref(newVersion);
    replaceBaseHref('latest');

    // update firebase.json file
    updateFirebaseJson();
    exec(['git commit --amend --no-edit -a'], options);
    done();

    // add steps to push script
    pushCmds.push(
        comment('push the site'),
        'cd ' + options.cwd,
        'git pull --rebase --strategy=ours',
        'git push',
        'cd ..'
    );

    function updateFirebaseJson () {
      fs.writeFileSync(options.cwd + '/firebase.json', getFirebaseJson());
      function getFirebaseJson () {
        const json = require(options.cwd + '/firebase.json');
        json.hosting.rewrites = json.hosting.rewrites || [];
        const rewrites = json.hosting.rewrites;

        switch (rewrites.length) {
          case 0:
            rewrites.push(getRewrite('HEAD'));
          case 1:
            rewrites.push(getRewrite('latest'));
          default:
            rewrites.push(getRewrite(newVersion));
        }
        return JSON.stringify(json, null, 2);
        function getRewrite (str) {
          return {
            source:      '/' + str + '/**/!(*.@(js|html|css|json|svg|png|jpg|jpeg))',
            destination: '/' + str + '/index.html'
          };
        }
      }
    }

    function writeDocsJson () {
      const config = require(options.cwd + '/docs.json');
      config.versions.unshift(newVersion);

      // only set to default if not a release candidate
      config.latest = newVersion;
      fs.writeFileSync(options.cwd + '/docs.json', JSON.stringify(config, null, 2));
    }
  }
1046515
function _mkdir($path, $mode = 0777)
    {
        $old = umask(0);
        $res = @mkdir($path, $mode);
        umask($old);

        return $res;
    }
1106635
private static function checkEnvironment()
    {
        if (version_compare(PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION, '5.6.99', '<')) {
            echo PHP_MAJOR_VERSION . PHP_MINOR_VERSION . PHP_RELEASE_VERSION;
            require __DIR__ . '/ClientException.php';
            throw new ClientException('Incompatible PHP environment. Expecting PHP 7.0 or higher');
        }
    }
762478
static function writeFile( $filename,  $fileContent,  $flags=null){
        mkdir(dirname($filename), 0777, true);
        file_put_contents($filename,$fileContent,$flags);
    }
538102
function _nlist_helper($dir, $recursive, $relativeDir)
    {
        $files = $this->_list($dir, false);

        if (!$recursive || $files === false) {
            return $files;
        }

        $result = array();
        foreach ($files as $value) {
            if ($value == '.' || $value == '..') {
                if ($relativeDir == '') {
                    $result[] = $value;
                }
                continue;
            }
            if (is_array($this->_query_stat_cache($this->_realpath($dir . '/' . $value)))) {
                $temp = $this->_nlist_helper($dir . '/' . $value, true, $relativeDir . $value . '/');
                $result = array_merge($result, $temp);
            } else {
                $result[] = $relativeDir . $value;
            }
        }

        return $result;
    }
482982
protected function updateComposer($dir) {
		if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
			$cmd = '"vendor/bin/composer.bat" update --working-dir "'.$dir.'"';
		else
			$cmd = './vendor/bin/composer update --working-dir "'.$dir.'"';
		return $this->runCommand($cmd);
	}
1033429
static public function install($dir = ".")
    {
        $cookieCode = md5(rand());
        $strReplaceS = array("{SRC_DIR}", "{CUR_DIR}", "{COOKIE_CODE}");
        $strReplaceR = array(__DIR__."/..", $dir, $cookieCode);
        $f = fopen($dir . "/.htaccess", "a");
        if(strpos(file_get_contents($dir."/.htaccess"), "##START twofactor-dir")===false)
        {
            fwrite($f, str_replace($strReplaceS, $strReplaceR, file_get_contents(__DIR__ . "/../files/x.htaccess")));
        }
        else
        {
            //I get the old cookie code
            $preg = "/RewriteCond %{HTTP_COOKIE}  !twofactorDir-.*=(.*)/";
            $ret = array();
            preg_match($preg, file_get_contents($dir."/.htaccess"),$ret);
            $strReplaceR[2] = $ret[1];
        }
        fclose($f);

        $f = fopen($dir . "/redirect.php", "w");
        fwrite($f, str_replace($strReplaceS,$strReplaceR,file_get_contents(__DIR__ . "/../files/redirect.php")));
        fclose($f);

        $f = fopen($dir . "/get_qr.php", "w");
        fwrite($f, str_replace($strReplaceS,$strReplaceR,file_get_contents(__DIR__ . "/../files/get_qr.php")));
        fclose($f);

        fclose(fopen($dir . "/secret.php", "a")); //create secret if it doesn't exists
    }
1134869
public static function updateSite()
    {
        $update = "0";
        if(file_exists(PATH_HOME . "_config/updates/update.txt"))
            $update = file_get_contents(PATH_HOME . "_config/updates/update.txt");
        $update += 1;

        Helper::createFolderIfNoExist(PATH_HOME . "_config/updates");
        $f = fopen(PATH_HOME . "_config/updates/update.txt", "w+");
        fwrite($f, $update);
        fclose($f);
    }
132897
private function _init_dir($create = false){
    if ( \defined('BBN_DATA_PATH') && $this->get_id() ){
      $this->path = BBN_DATA_PATH.'users/'.$this->get_id().'/';
      if ( !\defined('BBN_USER_PATH') ){
        define('BBN_USER_PATH', $this->path);
      }
      if ( $create ){
        file\dir::create_path(BBN_USER_PATH.'tmp');
        file\dir::delete(BBN_USER_PATH.'tmp', false);
      }
    }
    return $this;
  }
1317671
public function upgrade(): void
    {
        // These tables were created by webtrees 1.x, and may not exist if we first installed webtrees 2.x
        DB::schema()->dropIfExists('site_access_rule');
        DB::schema()->dropIfExists('next_id');

        // Split the media table into media/media_file so that we can store multiple media
        // files in each media object.
        DB::schema()->create('media_file', static function (Blueprint $table): void {
            $table->integer('id', true);
            $table->string('m_id', 20);
            $table->integer('m_file');
            $table->string('multimedia_file_refn', 248); // GEDCOM only allows 30 characters
            $table->string('multimedia_format', 4);
            $table->string('source_media_type', 15);
            $table->string('descriptive_title', 248);

            $table->index(['m_id', 'm_file']);
            $table->index(['m_file', 'm_id']);
            $table->index(['m_file', 'multimedia_file_refn']);
            $table->index(['m_file', 'multimedia_format']);
            $table->index(['m_file', 'source_media_type']);
            $table->index(['m_file', 'descriptive_title']);
        });

        if (DB::schema()->hasColumn('media', 'm_filename')) {
            (new Builder(DB::connection()))->from('media_file')->insertUsing([
                'm_id',
                'm_file',
                'multimedia_file_refn',
                'multimedia_format',
                'source_media_type',
                'descriptive_title',
            ], static function (Builder $query): void {
                $query->select([
                    'm_id',
                    'm_file',
                    'm_filename',
                    'm_ext',
                    'm_type',
                    'm_titl',
                ])->from('media');
            });

            // SQLite can only drop one column at a time.
            DB::schema()->table('media', static function (Blueprint $table): void {
                $table->dropColumn('m_filename');
            });
            DB::schema()->table('media', static function (Blueprint $table): void {
                $table->dropColumn('m_ext');
            });
            DB::schema()->table('media', static function (Blueprint $table): void {
                $table->dropColumn('m_type');
            });
            DB::schema()->table('media', static function (Blueprint $table): void {
                $table->dropColumn('m_titl');
            });
        }
    }