repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_harbormaster.php | scripts/setup/manage_harbormaster.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage Harbormaster'));
$args->setSynopsis(<<<EOSYNOPSIS
**harbormaster** __command__ [__options__]
Manage and debug Harbormaster.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('HarbormasterManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_nuance.php | scripts/setup/manage_nuance.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage Nuance'));
$args->setSynopsis(<<<EOSYNOPSIS
**nuance** __command__ [__options__]
Manage and debug Nuance.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('NuanceManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_config.php | scripts/setup/manage_config.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/init/init-setup.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage configuration'));
$args->setSynopsis(<<<EOSYNOPSIS
**config** __command__ [__options__]
Manage Phabricator configuration.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorConfigManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_webhook.php | scripts/setup/manage_webhook.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/init/init-script.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage webhooks'));
$args->setSynopsis(<<<EOSYNOPSIS
**webhook** __command__ [__options__]
Manage webhooks.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('HeraldWebhookManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_auth.php | scripts/setup/manage_auth.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage authentication'));
$args->setSynopsis(<<<EOSYNOPSIS
**auth** __command__ [__options__]
Manage Phabricator authentication configuration.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorAuthManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_i18n.php | scripts/setup/manage_i18n.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage internationalization'));
$args->setSynopsis(<<<EOSYNOPSIS
**i18n** __command__ [__options__]
Manage translations and internationalization.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorInternationalizationManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_user.php | scripts/setup/manage_user.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setSynopsis(<<<EOSYNOPSIS
**user** __command__ [__options__]
Modify user accounts to regain access to an install.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorPeopleManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_garbage.php | scripts/setup/manage_garbage.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage garbage collectors'));
$args->setSynopsis(<<<EOSYNOPSIS
**garbage** __command__ [__options__]
Manage garbage collectors.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorGarbageCollectorManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_herald.php | scripts/setup/manage_herald.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/init/init-script.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage Herald'));
$args->setSynopsis(<<<EOSYNOPSIS
**herald** __command__ [__options__]
Manage and debug Herald.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('HeraldManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_lock.php | scripts/setup/manage_lock.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/init/init-script.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage locks'));
$args->setSynopsis(<<<EOSYNOPSIS
**lock** __command__ [__options__]
Manage locks.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorLockManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_audit.php | scripts/setup/manage_audit.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage audits'));
$args->setSynopsis(<<<EOSYNOPSIS
**audit** __command__ [__options__]
Manage Phabricator audits.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorAuditManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_differential.php | scripts/setup/manage_differential.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage hunks'));
$args->setSynopsis(<<<EOSYNOPSIS
**differential** __command__ [__options__]
Manage Differential.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorDifferentialManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_worker.php | scripts/setup/manage_worker.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage task queue'));
$args->setSynopsis(<<<EOSYNOPSIS
**worker** __command__ [__options__]
Manage the task queue.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorWorkerManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_policy.php | scripts/setup/manage_policy.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage policies'));
$args->setSynopsis(<<<EOSYNOPSIS
**policy** __command__ [__options__]
Administrative tool for reviewing and editing policies.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorPolicyManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_conduit.php | scripts/setup/manage_conduit.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/init/init-script.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage Conduit'));
$args->setSynopsis(<<<EOSYNOPSIS
**conduit** __command__ [__options__]
Manage Conduit.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorConduitManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_trigger.php | scripts/setup/manage_trigger.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage triggers'));
$args->setSynopsis(<<<EOSYNOPSIS
**trigger** __command__ [__options__]
Manage event triggers.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorWorkerTriggerManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_phortune.php | scripts/setup/manage_phortune.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage billing'));
$args->setSynopsis(<<<EOSYNOPSIS
**phortune** __command__ [__options__]
Manage billing.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorPhortuneManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_remove.php | scripts/setup/manage_remove.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('remove objects'));
$args->setSynopsis(<<<EOSYNOPSIS
**remove** __command__ [__options__]
Administrative tool for destroying objects permanently.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorSystemRemoveWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/setup/manage_feed.php | scripts/setup/manage_feed.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage feed'));
$args->setSynopsis(<<<EOSYNOPSIS
**feed** __command__ [__options__]
Test and debug feed events.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorFeedManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/search/manage_search.php | scripts/search/manage_search.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage search'));
$args->setSynopsis(<<<EOSYNOPSIS
**search** __command__ [__options__]
Manage Phabricator search index.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorSearchManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/symbols/import_repository_symbols.php | scripts/symbols/import_repository_symbols.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setSynopsis(<<<EOSYNOPSIS
**import_repository_symbols.php** [__options__] __repository__ < symbols
Import repository symbols (symbols are read from stdin).
EOSYNOPSIS
);
$args->parseStandardArguments();
$args->parse(
array(
array(
'name' => 'no-purge',
'help' => pht(
'Do not clear all symbols for this repository before '.
'uploading new symbols. Useful for incremental updating.'),
),
array(
'name' => 'ignore-errors',
'help' => pht(
"If a line can't be parsed, ignore that line and ".
"continue instead of exiting."),
),
array(
'name' => 'max-transaction',
'param' => 'num-syms',
'default' => '100000',
'help' => pht(
'Maximum number of symbols that should '.
'be part of a single transaction.'),
),
array(
'name' => 'repository',
'wildcard' => true,
),
));
$identifiers = $args->getArg('repository');
if (count($identifiers) !== 1) {
$args->printHelpAndExit();
}
$identifier = head($identifiers);
$repository = id(new PhabricatorRepositoryQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withIdentifiers($identifiers)
->executeOne();
if (!$repository) {
echo tsprintf(
"%s\n",
pht('Repository "%s" does not exist.', $identifier));
exit(1);
}
if (!function_exists('posix_isatty') || posix_isatty(STDIN)) {
echo pht('Parsing input from stdin...'), "\n";
}
$input = file_get_contents('php://stdin');
$input = trim($input);
$input = explode("\n", $input);
function commit_symbols(
array $symbols,
PhabricatorRepository $repository,
$no_purge) {
echo pht('Looking up path IDs...'), "\n";
$path_map =
PhabricatorRepositoryCommitChangeParserWorker::lookupOrCreatePaths(
ipull($symbols, 'path'));
$symbol = new PhabricatorRepositorySymbol();
$conn_w = $symbol->establishConnection('w');
echo pht('Preparing queries...'), "\n";
$sql = array();
foreach ($symbols as $dict) {
$sql[] = qsprintf(
$conn_w,
'(%s, %s, %s, %s, %s, %d, %d)',
$repository->getPHID(),
$dict['ctxt'],
$dict['name'],
$dict['type'],
$dict['lang'],
$dict['line'],
$path_map[$dict['path']]);
}
if (!$no_purge) {
echo pht('Purging old symbols...'), "\n";
queryfx(
$conn_w,
'DELETE FROM %T WHERE repositoryPHID = %s',
$symbol->getTableName(),
$repository->getPHID());
}
echo pht('Loading %s symbols...', phutil_count($sql)), "\n";
foreach (array_chunk($sql, 128) as $chunk) {
queryfx(
$conn_w,
'INSERT INTO %T
(repositoryPHID, symbolContext, symbolName, symbolType,
symbolLanguage, lineNumber, pathID) VALUES %LQ',
$symbol->getTableName(),
$chunk);
}
}
function check_string_value($value, $field_name, $line_no, $max_length) {
if (strlen($value) > $max_length) {
throw new Exception(
pht(
"%s '%s' defined on line #%d is too long, ".
"maximum %s length is %d characters.",
$field_name,
$value,
$line_no,
$field_name,
$max_length));
}
if (!phutil_is_utf8_with_only_bmp_characters($value)) {
throw new Exception(
pht(
"%s '%s' defined on line #%d is not a valid ".
"UTF-8 string, it should contain only UTF-8 characters.",
$field_name,
$value,
$line_no));
}
}
$no_purge = $args->getArg('no-purge');
$symbols = array();
foreach ($input as $key => $line) {
try {
$line_no = $key + 1;
$matches = null;
$ok = preg_match(
'/^((?P<context>[^ ]+)? )?(?P<name>[^ ]+) (?P<type>[^ ]+) '.
'(?P<lang>[^ ]+) (?P<line>\d+) (?P<path>.*)$/',
$line,
$matches);
if (!$ok) {
throw new Exception(
pht(
"Line #%d of input is invalid. Expected five or six space-delimited ".
"fields: maybe symbol context, symbol name, symbol type, symbol ".
"language, line number, path. For example:\n\n%s\n\n".
"Actual line was:\n\n%s",
$line_no,
'idx function php 13 /path/to/some/file.php',
$line));
}
if (empty($matches['context'])) {
$matches['context'] = '';
}
$context = $matches['context'];
$name = $matches['name'];
$type = $matches['type'];
$lang = $matches['lang'];
$line_number = $matches['line'];
$path = $matches['path'];
check_string_value($context, pht('Symbol context'), $line_no, 128);
check_string_value($name, pht('Symbol name'), $line_no, 128);
check_string_value($type, pht('Symbol type'), $line_no, 12);
check_string_value($lang, pht('Symbol language'), $line_no, 32);
check_string_value($path, pht('Path'), $line_no, 512);
if (!strlen($path) || $path[0] != '/') {
throw new Exception(
pht(
"Path '%s' defined on line #%d is invalid. Paths should begin with ".
"'%s' and specify a path from the root of the project, like '%s'.",
$path,
$line_no,
'/',
'/src/utils/utils.php'));
}
$symbols[] = array(
'ctxt' => $context,
'name' => $name,
'type' => $type,
'lang' => $lang,
'line' => $line_number,
'path' => $path,
);
} catch (Exception $e) {
if ($args->getArg('ignore-errors')) {
continue;
} else {
throw $e;
}
}
if (count($symbols) >= $args->getArg('max-transaction')) {
try {
echo pht(
"Committing %s symbols...\n",
new PhutilNumber($args->getArg('max-transaction')));
commit_symbols($symbols, $repository, $no_purge);
$no_purge = true;
unset($symbols);
$symbols = array();
} catch (Exception $e) {
if ($args->getArg('ignore-errors')) {
continue;
} else {
throw $e;
}
}
}
}
if (count($symbols)) {
commit_symbols($symbols, $repository, $no_purge);
}
echo pht('Done.')."\n";
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/symbols/generate_ctags_symbols.php | scripts/symbols/generate_ctags_symbols.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setSynopsis(<<<EOSYNOPSIS
**generate_ctags_symbols.php** [__options__]
Generate repository symbols using Exuberant Ctags. Paths are read from stdin.
EOSYNOPSIS
);
$args->parseStandardArguments();
if (ctags_check_executable() == false) {
echo phutil_console_format(
"%s\n\n%s\n",
pht(
'Could not find Exuberant Ctags. Make sure it is installed and '.
'available in executable path.'),
pht(
'Exuberant Ctags project page: %s',
'http://ctags.sourceforge.net/'));
exit(1);
}
if (posix_isatty(STDIN)) {
echo phutil_console_format(
"%s\n",
pht(
'Usage: %s',
"find . -type f -name '*.py' | ./generate_ctags_symbols.php"));
exit(1);
}
$input = file_get_contents('php://stdin');
$data = array();
$futures = array();
foreach (explode("\n", trim($input)) as $file) {
if (!strlen($file)) {
continue;
}
$file = Filesystem::readablePath($file);
$futures[$file] = ctags_get_parser_future($file);
}
$futures = new FutureIterator($futures);
foreach ($futures->limit(8) as $file => $future) {
$tags = $future->resolve();
$tags = explode("\n", $tags[1]);
foreach ($tags as $tag) {
$parts = explode(';', $tag);
// Skip lines that we can not parse.
if (count($parts) < 2) {
continue;
}
// Split ctags information.
$tag_info = explode("\t", $parts[0]);
// Split exuberant ctags "extension fields" (additional information).
$parts[1] = trim($parts[1], "\t \"");
$extension_fields = explode("\t", $parts[1]);
// Skip lines that we can not parse.
if (count($tag_info) < 3 || count($extension_fields) < 2) {
continue;
}
// Default context to empty.
$extension_fields[] = '';
list($token, $file_path, $line_num) = $tag_info;
list($type, $language, $context) = $extension_fields;
// Skip lines with tokens containing a space.
if (strpos($token, ' ') !== false) {
continue;
}
// Strip "language:"
$language = substr($language, 9);
// To keep consistent with "Separate with commas, for example: php, py"
// in Arcanist Project edit form.
$language = str_ireplace('python', 'py', $language);
// Also, "normalize" C++ and C#.
$language = str_ireplace('c++', 'cpp', $language);
$language = str_ireplace('c#', 'cs', $language);
// Ruby has "singleton method", for example.
$type = substr(str_replace(' ', '_', $type), 0, 12);
// class:foo, struct:foo, union:foo, enum:foo, ...
$context = last(explode(':', $context, 2));
$ignore = array(
'variable' => true,
);
if (empty($ignore[$type])) {
print_symbol($file_path, $line_num, $type, $token, $context, $language);
}
}
}
function ctags_get_parser_future($path) {
$future = new ExecFuture('ctags -n --fields=Kls -o - %s', $path);
return $future;
}
function ctags_check_executable() {
$result = exec_manual('ctags --version');
return !empty($result[1]);
}
function print_symbol($file, $line_num, $type, $token, $context, $language) {
// Get rid of relative path.
$file = explode('/', $file);
if ($file[0] == '.' || $file[0] == '..') {
array_shift($file);
}
$file = '/'.implode('/', $file);
$parts = array(
$context,
$token,
$type,
strtolower($language),
$line_num,
$file,
);
echo implode(' ', $parts)."\n";
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/symbols/generate_php_symbols.php | scripts/symbols/generate_php_symbols.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setSynopsis(<<<EOSYNOPSIS
**generate_php_symbols.php** [__options__]
Generate repository symbols using XHPAST. Paths are read from stdin.
EOSYNOPSIS
);
$args->parseStandardArguments();
if (posix_isatty(STDIN)) {
echo phutil_console_format(
"%s\n",
pht(
'Usage: %s',
"find . -type f -name '*.php' | ./generate_php_symbols.php"));
exit(1);
}
$input = file_get_contents('php://stdin');
$data = array();
$futures = array();
foreach (explode("\n", trim($input)) as $file) {
if (!strlen($file)) {
continue;
}
$file = Filesystem::readablePath($file);
$data[$file] = Filesystem::readFile($file);
$futures[$file] = PhutilXHPASTBinary::getParserFuture($data[$file]);
}
$futures = new FutureIterator($futures);
foreach ($futures->limit(8) as $file => $future) {
$tree = XHPASTTree::newFromDataAndResolvedExecFuture(
$data[$file],
$future->resolve());
$root = $tree->getRootNode();
$scopes = array();
$functions = $root->selectDescendantsOfType('n_FUNCTION_DECLARATION');
foreach ($functions as $function) {
$name = $function->getChildByIndex(2);
// Skip anonymous functions.
if (!$name->getConcreteString()) {
continue;
}
print_symbol($file, 'function', $name);
}
$classes = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
foreach ($classes as $class) {
$class_name = $class->getChildByIndex(1);
print_symbol($file, 'class', $class_name);
$scopes[] = array($class, $class_name);
}
$interfaces = $root->selectDescendantsOfType('n_INTERFACE_DECLARATION');
foreach ($interfaces as $interface) {
$interface_name = $interface->getChildByIndex(1);
// We don't differentiate classes and interfaces in highlighters.
print_symbol($file, 'class', $interface_name);
$scopes[] = array($interface, $interface_name);
}
$constants = $root->selectDescendantsOfType('n_CONSTANT_DECLARATION_LIST');
foreach ($constants as $constant_list) {
foreach ($constant_list->getChildren() as $constant) {
$constant_name = $constant->getChildByIndex(0);
print_symbol($file, 'constant', $constant_name);
}
}
foreach ($scopes as $scope) {
// This prints duplicate symbols in the case of nested classes.
// Luckily, PHP doesn't allow those.
list($class, $class_name) = $scope;
$consts = $class->selectDescendantsOfType(
'n_CLASS_CONSTANT_DECLARATION_LIST');
foreach ($consts as $const_list) {
foreach ($const_list->getChildren() as $const) {
$const_name = $const->getChildByIndex(0);
print_symbol($file, 'class_const', $const_name, $class_name);
}
}
$members = $class->selectDescendantsOfType(
'n_CLASS_MEMBER_DECLARATION_LIST');
foreach ($members as $member_list) {
foreach ($member_list->getChildren() as $member) {
if ($member->getTypeName() == 'n_CLASS_MEMBER_MODIFIER_LIST') {
continue;
}
$member_name = $member->getChildByIndex(0);
print_symbol($file, 'member', $member_name, $class_name);
}
}
$methods = $class->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$method_name = $method->getChildByIndex(2);
print_symbol($file, 'method', $method_name, $class_name);
}
}
}
function print_symbol($file, $type, XHPASTNode $node, $context = null) {
$parts = array(
$context ? $context->getConcreteString() : '',
// Variable tokens are `$name`, not just `name`, so strip the "$"" off of
// class field names
ltrim($node->getConcreteString(), '$'),
$type,
'php',
$node->getLineNumber(),
'/'.ltrim($file, './'),
);
echo implode(' ', $parts)."\n";
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/symbols/clear_repository_symbols.php | scripts/symbols/clear_repository_symbols.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setSynopsis(<<<EOSYNOPSIS
**clear_repository_symbols.php** [__options__] __repository__
Clear repository symbols.
EOSYNOPSIS
);
$args->parseStandardArguments();
$args->parse(
array(
array(
'name' => 'repository',
'wildcard' => true,
),
));
$identifiers = $args->getArg('repository');
if (count($identifiers) !== 1) {
$args->printHelpAndExit();
}
$identifier = head($identifiers);
$repository = id(new PhabricatorRepositoryQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withIdentifiers($identifiers)
->executeOne();
if (!$repository) {
echo tsprintf(
"%s\n",
pht('Repository "%s" does not exist.', $identifier));
exit(1);
}
$input = file_get_contents('php://stdin');
$normalized = array();
foreach (explode("\n", trim($input)) as $path) {
// Emulate the behavior of the symbol generation scripts.
$normalized[] = '/'.ltrim($path, './');
}
$paths = PhabricatorRepositoryCommitChangeParserWorker::lookupOrCreatePaths(
$normalized);
$symbol = new PhabricatorRepositorySymbol();
$conn_w = $symbol->establishConnection('w');
foreach (array_chunk(array_values($paths), 128) as $chunk) {
queryfx(
$conn_w,
'DELETE FROM %T WHERE repositoryPHID = %s AND pathID IN (%Ld)',
$symbol->getTableName(),
$repository->getPHID(),
$chunk);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/daemon/launch_daemon.php | scripts/daemon/launch_daemon.php | #!/usr/bin/env php
<?php
// NOTE: This is substantially the same as the libphutil/ "launch_daemon.php"
// script, except it loads the Phabricator environment and adds some Phabricator
// specific flags.
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
} else {
declare(ticks = 1);
}
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
$overseer = new PhutilDaemonOverseer($argv);
$bootloader = PhutilBootloader::getInstance();
foreach ($bootloader->getAllLibraries() as $library) {
$overseer->addLibrary(phutil_get_library_root($library));
}
$overseer->run();
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/daemon/manage_daemons.php | scripts/daemon/manage_daemons.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';
PhabricatorDaemonManagementWorkflow::requireExtensions();
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage daemons'));
$args->setSynopsis(<<<EOSYNOPSIS
**phd** __command__ [__options__]
Manage Phabricator daemons.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorDaemonManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/daemon/exec/exec_daemon.php | scripts/daemon/exec/exec_daemon.php | #!/usr/bin/env php
<?php
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
} else {
declare(ticks = 1);
}
require_once dirname(__FILE__).'/../../__init_script__.php';
if (!posix_isatty(STDOUT)) {
$sid = posix_setsid();
if ($sid <= 0) {
throw new Exception(pht('Failed to create new process session!'));
}
}
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('daemon executor'));
$args->setSynopsis(<<<EOHELP
**exec_daemon.php** [__options__] __daemon__ ...
Run an instance of __daemon__.
EOHELP
);
$args->parse(
array(
array(
'name' => 'trace',
'help' => pht('Enable debug tracing.'),
),
array(
'name' => 'trace-memory',
'help' => pht('Enable debug memory tracing.'),
),
array(
'name' => 'verbose',
'help' => pht('Enable verbose activity logging.'),
),
array(
'name' => 'label',
'short' => 'l',
'param' => 'label',
'help' => pht(
'Optional process label. Makes "%s" nicer, no behavioral effects.',
'ps'),
),
array(
'name' => 'daemon',
'wildcard' => true,
),
));
$trace_memory = $args->getArg('trace-memory');
$trace_mode = $args->getArg('trace') || $trace_memory;
$verbose = $args->getArg('verbose');
if (function_exists('posix_isatty') && posix_isatty(STDIN)) {
fprintf(STDERR, pht('Reading daemon configuration from stdin...')."\n");
}
$config = @file_get_contents('php://stdin');
$config = id(new PhutilJSONParser())->parse($config);
PhutilTypeSpec::checkMap(
$config,
array(
'log' => 'optional string|null',
'argv' => 'optional list<wild>',
'load' => 'optional list<string>',
'down' => 'optional int',
));
$log = idx($config, 'log');
if ($log) {
ini_set('error_log', $log);
PhutilErrorHandler::setErrorListener(array('PhutilDaemon', 'errorListener'));
}
$load = idx($config, 'load', array());
foreach ($load as $library) {
$library = Filesystem::resolvePath($library);
phutil_load_library($library);
}
PhutilErrorHandler::initialize();
$daemon = $args->getArg('daemon');
if (!$daemon) {
throw new PhutilArgumentUsageException(
pht('Specify which class of daemon to start.'));
} else if (count($daemon) > 1) {
throw new PhutilArgumentUsageException(
pht('Specify exactly one daemon to start.'));
} else {
$daemon = head($daemon);
if (!class_exists($daemon)) {
throw new PhutilArgumentUsageException(
pht(
'No class "%s" exists in any known library.',
$daemon));
} else if (!is_subclass_of($daemon, 'PhutilDaemon')) {
throw new PhutilArgumentUsageException(
pht(
'Class "%s" is not a subclass of "%s".',
$daemon,
'PhutilDaemon'));
}
}
$argv = idx($config, 'argv', array());
$daemon = newv($daemon, array($argv));
if ($trace_mode) {
$daemon->setTraceMode();
}
if ($trace_memory) {
$daemon->setTraceMemory();
}
if ($verbose) {
$daemon->setVerbose(true);
}
$down_duration = idx($config, 'down');
if ($down_duration) {
$daemon->setScaledownDuration($down_duration);
}
$daemon->execute();
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/init/init-script.php | scripts/init/init-script.php | <?php
// Initialize a standard script.
require_once dirname(__FILE__).'/lib.php';
init_phabricator_script(
array(
'config.optional' => false,
));
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/init/lib.php | scripts/init/lib.php | <?php
function init_phabricator_script(array $options) {
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
$include_path = ini_get('include_path');
ini_set(
'include_path',
$include_path.PATH_SEPARATOR.dirname(__FILE__).'/../../../');
$ok = @include_once 'arcanist/support/init/init-script.php';
if (!$ok) {
echo
'FATAL ERROR: Unable to load the "Arcanist" library. '.
'Put "arcanist/" next to "phabricator/" on disk.';
echo "\n";
exit(1);
}
phutil_load_library('arcanist/src');
phutil_load_library(dirname(__FILE__).'/../../src/');
$config_optional = $options['config.optional'];
PhabricatorEnv::initializeScriptEnvironment($config_optional);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/init/init-aphlict.php | scripts/init/init-aphlict.php | <?php
require_once dirname(__FILE__).'/lib.php';
init_phabricator_script(
array(
// NOTE: We allow aphlict to start with no database, because it's
// reasonable to isolate the notification server from other hosts.
'config.optional' => true,
));
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/init/init-script-with-signals.php | scripts/init/init-script-with-signals.php | <?php
// Initialize a script that will handle signals.
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
} else {
declare(ticks = 1);
}
require_once dirname(__FILE__).'/init-script.php';
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/init/init-setup.php | scripts/init/init-setup.php | <?php
// Initialize a setup script which may run before database connections have
// been configured. Scripts initialized in this way ignore database errors
// while building database configuration and continue.
require_once dirname(__FILE__).'/lib.php';
init_phabricator_script(
array(
'config.optional' => true,
));
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/celerity/generate_emoji.php | scripts/celerity/generate_emoji.php | #!/usr/bin/env php
<?php
require_once dirname(dirname(__FILE__)).'/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('regenerate Emoji data sheets'));
$args->setSynopsis(<<<EOHELP
**emoji**
Rebuild Emoji data sheets.
EOHELP
);
$args->parseStandardArguments();
$args->parse(
array(
array(
'name' => 'force',
'help' => pht('Force regeneration even if sources have not changed.'),
),
));
$root = dirname(phutil_get_library_root('phabricator'));
// move this to an argument?
$path = $root.'/emoji_strategy.json';
$export_path = $root.'/resources/emoji/manifest.json';
if (Filesystem::pathExists($path)) {
$json = Filesystem::readFile($path);
$emojis = phutil_json_decode($json);
$data = array();
foreach ($emojis as $shortname => $emoji) {
$unicode = $emoji['unicode'];
$codes = explode('-', $unicode);
$hex = '';
foreach ($codes as $code) {
$hex .= phutil_utf8_encode_codepoint(hexdec($code));
}
$data[$shortname] = $hex;
}
ksort($data);
$json = new PhutilJSON();
$data = $json->encodeFormatted($data);
Filesystem::writeFile($export_path, $data);
echo pht('Done.')."\n";
} else {
echo pht('Path %s not exist.', $path)."\n";
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/celerity/generate_sprites.php | scripts/celerity/generate_sprites.php | #!/usr/bin/env php
<?php
require_once dirname(dirname(__FILE__)).'/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('regenerate CSS sprite sheets'));
$args->setSynopsis(<<<EOHELP
**sprites**
Rebuild CSS sprite sheets.
EOHELP
);
$args->parseStandardArguments();
$args->parse(
array(
array(
'name' => 'force',
'help' => pht('Force regeneration even if sources have not changed.'),
),
));
$root = dirname(phutil_get_library_root('phabricator'));
$webroot = $root.'/webroot/rsrc';
$webroot = Filesystem::readablePath($webroot);
$generator = new CeleritySpriteGenerator();
$sheets = array(
'tokens' => $generator->buildTokenSheet(),
'login' => $generator->buildLoginSheet(),
);
list($err) = exec_manual('optipng');
if ($err) {
$have_optipng = false;
echo phutil_console_format(
"<bg:red> %s </bg> %s\n%s\n",
pht('WARNING'),
pht('`%s` not found in PATH.', 'optipng'),
pht('Sprites will not be optimized! Install `%s`!', 'optipng'));
} else {
$have_optipng = true;
}
foreach ($sheets as $name => $sheet) {
$sheet->setBasePath($root);
$manifest_path = $root.'/resources/sprite/manifest/'.$name.'.json';
if (!$args->getArg('force')) {
if (Filesystem::pathExists($manifest_path)) {
$data = Filesystem::readFile($manifest_path);
$data = phutil_json_decode($data);
if (!$sheet->needsRegeneration($data)) {
continue;
}
}
}
$sheet
->generateCSS($webroot."/css/sprite-{$name}.css")
->generateManifest($root."/resources/sprite/manifest/{$name}.json");
foreach ($sheet->getScales() as $scale) {
if ($scale == 1) {
$sheet_name = "sprite-{$name}.png";
} else {
$sheet_name = "sprite-{$name}-X{$scale}.png";
}
$full_path = "{$webroot}/image/{$sheet_name}";
$sheet->generateImage($full_path, $scale);
if ($have_optipng) {
echo pht('Optimizing...')."\n";
phutil_passthru('optipng -o7 -clobber %s', $full_path);
}
}
}
echo pht('Done.')."\n";
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/scripts/sql/manage_storage.php | scripts/sql/manage_storage.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/init/init-setup.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage storage and schemata'));
$args->setSynopsis(<<<EOHELP
**storage** __workflow__ [__options__]
Manage database storage and schema versioning.
**storage** upgrade
Initialize or upgrade storage.
**storage** upgrade --user __root__ --password __hunter2__
Use administrative credentials for schema changes.
EOHELP
);
$args->parseStandardArguments();
$default_namespace = PhabricatorLiskDAO::getDefaultStorageNamespace();
try {
$args->parsePartial(
array(
array(
'name' => 'force',
'short' => 'f',
'help' => pht(
'Do not prompt before performing dangerous operations.'),
),
array(
'name' => 'host',
'param' => 'hostname',
'help' => pht(
'Operate on the database server identified by __hostname__.'),
),
array(
'name' => 'ref',
'param' => 'ref',
'help' => pht(
'Operate on the database identified by __ref__.'),
),
array(
'name' => 'user',
'short' => 'u',
'param' => 'username',
'help' => pht(
'Connect with __username__ instead of the configured default.'),
),
array(
'name' => 'password',
'short' => 'p',
'param' => 'password',
'help' => pht('Use __password__ instead of the configured default.'),
),
array(
'name' => 'namespace',
'param' => 'name',
'default' => $default_namespace,
'help' => pht(
"Use namespace __namespace__ instead of the configured ".
"default ('%s'). This is an advanced feature used by unit tests; ".
"you should not normally use this flag.",
$default_namespace),
),
array(
'name' => 'dryrun',
'help' => pht(
'Do not actually change anything, just show what would be changed.'),
),
array(
'name' => 'disable-utf8mb4',
'help' => pht(
'Disable %s, even if the database supports it. This is an '.
'advanced feature used for testing internal changes; you '.
'should not normally use this flag.',
'utf8mb4'),
),
));
} catch (PhutilArgumentUsageException $ex) {
$args->printUsageException($ex);
exit(77);
}
// First, test that the Phabricator configuration is set up correctly. After
// we know this works we'll test any administrative credentials specifically.
$refs = PhabricatorDatabaseRef::getActiveDatabaseRefs();
if (!$refs) {
throw new PhutilArgumentUsageException(
pht('No databases are configured.'));
}
$host = $args->getArg('host');
$ref_key = $args->getArg('ref');
if (($host !== null) || ($ref_key !== null)) {
if ($host && $ref_key) {
throw new PhutilArgumentUsageException(
pht(
'Use "--host" or "--ref" to select a database, but not both.'));
}
$refs = PhabricatorDatabaseRef::getActiveDatabaseRefs();
$possible_refs = array();
foreach ($refs as $possible_ref) {
if ($host && ($possible_ref->getHost() == $host)) {
$possible_refs[] = $possible_ref;
break;
}
if ($ref_key && ($possible_ref->getRefKey() == $ref_key)) {
$possible_refs[] = $possible_ref;
break;
}
}
if (!$possible_refs) {
if ($host) {
throw new PhutilArgumentUsageException(
pht(
'There is no configured database on host "%s". This command can '.
'only interact with configured databases.',
$host));
} else {
throw new PhutilArgumentUsageException(
pht(
'There is no configured database with ref "%s". This command can '.
'only interact with configured databases.',
$ref_key));
}
}
if (count($possible_refs) > 1) {
throw new PhutilArgumentUsageException(
pht(
'Host "%s" identifies more than one database. Use "--ref" to select '.
'a specific database.',
$host));
}
$refs = $possible_refs;
}
$apis = array();
foreach ($refs as $ref) {
$default_user = $ref->getUser();
$default_host = $ref->getHost();
$default_port = $ref->getPort();
$test_api = id(new PhabricatorStorageManagementAPI())
->setUser($default_user)
->setHost($default_host)
->setPort($default_port)
->setPassword($ref->getPass())
->setNamespace($args->getArg('namespace'));
try {
queryfx(
$test_api->getConn(null),
'SELECT 1');
} catch (AphrontQueryException $ex) {
$message = phutil_console_format(
"**%s**\n\n%s\n\n%s\n\n%s\n\n**%s**: %s\n",
pht('MySQL Credentials Not Configured'),
pht(
'Unable to connect to MySQL using the configured credentials. '.
'You must configure standard credentials before you can upgrade '.
'storage. Run these commands to set up credentials:'),
" $ ./bin/config set mysql.host __host__\n".
" $ ./bin/config set mysql.user __username__\n".
" $ ./bin/config set mysql.pass __password__",
pht(
'These standard credentials are separate from any administrative '.
'credentials provided to this command with __%s__ or '.
'__%s__, and must be configured correctly before you can proceed.',
'--user',
'--password'),
pht('Raw MySQL Error'),
$ex->getMessage());
echo phutil_console_wrap($message);
exit(1);
}
if ($args->getArg('password') === null) {
// This is already a PhutilOpaqueEnvelope.
$password = $ref->getPass();
} else {
// Put this in a PhutilOpaqueEnvelope.
$password = new PhutilOpaqueEnvelope($args->getArg('password'));
PhabricatorEnv::overrideConfig('mysql.pass', $args->getArg('password'));
}
$selected_user = $args->getArg('user');
if ($selected_user === null) {
$selected_user = $default_user;
}
$api = id(new PhabricatorStorageManagementAPI())
->setUser($selected_user)
->setHost($default_host)
->setPort($default_port)
->setPassword($password)
->setNamespace($args->getArg('namespace'))
->setDisableUTF8MB4($args->getArg('disable-utf8mb4'));
PhabricatorEnv::overrideConfig('mysql.user', $api->getUser());
$ref->setUser($selected_user);
$ref->setPass($password);
try {
queryfx(
$api->getConn(null),
'SELECT 1');
} catch (AphrontQueryException $ex) {
$message = phutil_console_format(
"**%s**\n\n%s\n\n**%s**: %s\n",
pht('Bad Administrative Credentials'),
pht(
'Unable to connect to MySQL using the administrative credentials '.
'provided with the __%s__ and __%s__ flags. Check that '.
'you have entered them correctly.',
'--user',
'--password'),
pht('Raw MySQL Error'),
$ex->getMessage());
echo phutil_console_wrap($message);
exit(1);
}
$api->setRef($ref);
$apis[] = $api;
}
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorStorageManagementWorkflow')
->execute();
$patches = PhabricatorSQLPatchList::buildAllPatches();
foreach ($workflows as $workflow) {
$workflow->setAPIs($apis);
$workflow->setPatches($patches);
}
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/support/aphlict/server/aphlict_launcher.php | support/aphlict/server/aphlict_launcher.php | #!/usr/bin/env php
<?php
$root = dirname(dirname(dirname(dirname(__FILE__))));
require_once $root.'/scripts/init/init-aphlict.php';
PhabricatorAphlictManagementWorkflow::requireExtensions();
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage Aphlict notification server'));
$args->setSynopsis(<<<EOSYNOPSIS
**aphlict** __command__ [__options__]
Manage the Aphlict server.
EOSYNOPSIS
);
$args->parseStandardArguments();
$workflows = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorAphlictManagementWorkflow')
->execute();
$workflows[] = new PhutilHelpArgumentWorkflow();
$args->parseWorkflows($workflows);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/support/phame/libskin.php | support/phame/libskin.php | <?php
function _e($text) {
return phutil_escape_html($text);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/support/startup/PhabricatorClientConnectionLimit.php | support/startup/PhabricatorClientConnectionLimit.php | <?php
final class PhabricatorClientConnectionLimit
extends PhabricatorClientLimit {
protected function getBucketDuration() {
return 60;
}
protected function getBucketCount() {
return 15;
}
protected function shouldRejectConnection($score) {
// Reject connections if the cumulative score across all buckets exceeds
// the limit.
return ($score > $this->getLimit());
}
protected function getConnectScore() {
return 1;
}
protected function getPenaltyScore() {
return 0;
}
protected function getDisconnectScore(array $request_state) {
return -1;
}
protected function getRateLimitReason($score) {
$client_key = $this->getClientKey();
// NOTE: This happens before we load libraries, so we can not use pht()
// here.
return
"TOO MANY CONCURRENT CONNECTIONS\n".
"You (\"{$client_key}\") have too many concurrent ".
"connections.\n";
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/support/startup/PhabricatorClientLimit.php | support/startup/PhabricatorClientLimit.php | <?php
abstract class PhabricatorClientLimit {
private $limitKey;
private $clientKey;
private $limit;
final public function setLimitKey($limit_key) {
$this->limitKey = $limit_key;
return $this;
}
final public function getLimitKey() {
return $this->limitKey;
}
final public function setClientKey($client_key) {
$this->clientKey = $client_key;
return $this;
}
final public function getClientKey() {
return $this->clientKey;
}
final public function setLimit($limit) {
$this->limit = $limit;
return $this;
}
final public function getLimit() {
return $this->limit;
}
final public function didConnect() {
// NOTE: We can not use pht() here because this runs before libraries
// load.
if (!function_exists('apc_fetch') && !function_exists('apcu_fetch')) {
throw new Exception(
'You can not configure connection rate limits unless APC/APCu are '.
'available. Rate limits rely on APC/APCu to track clients and '.
'connections.');
}
if ($this->getClientKey() === null) {
throw new Exception(
'You must configure a client key when defining a rate limit.');
}
if ($this->getLimitKey() === null) {
throw new Exception(
'You must configure a limit key when defining a rate limit.');
}
if ($this->getLimit() === null) {
throw new Exception(
'You must configure a limit when defining a rate limit.');
}
$points = $this->getConnectScore();
if ($points) {
$this->addScore($points);
}
$score = $this->getScore();
if (!$this->shouldRejectConnection($score)) {
// Client has not hit the limit, so continue processing the request.
return null;
}
$penalty = $this->getPenaltyScore();
if ($penalty) {
$this->addScore($penalty);
$score += $penalty;
}
return $this->getRateLimitReason($score);
}
final public function didDisconnect(array $request_state) {
$score = $this->getDisconnectScore($request_state);
if ($score) {
$this->addScore($score);
}
}
/**
* Get the number of seconds for each rate bucket.
*
* For example, a value of 60 will create one-minute buckets.
*
* @return int Number of seconds per bucket.
*/
abstract protected function getBucketDuration();
/**
* Get the total number of rate limit buckets to retain.
*
* @return int Total number of rate limit buckets to retain.
*/
abstract protected function getBucketCount();
/**
* Get the score to add when a client connects.
*
* @return double Connection score.
*/
abstract protected function getConnectScore();
/**
* Get the number of penalty points to add when a client hits a rate limit.
*
* @return double Penalty score.
*/
abstract protected function getPenaltyScore();
/**
* Get the score to add when a client disconnects.
*
* @return double Connection score.
*/
abstract protected function getDisconnectScore(array $request_state);
/**
* Get a human-readable explanation of why the client is being rejected.
*
* @return string Brief rejection message.
*/
abstract protected function getRateLimitReason($score);
/**
* Determine whether to reject a connection.
*
* @return bool True to reject the connection.
*/
abstract protected function shouldRejectConnection($score);
/**
* Get the APC key for the smallest stored bucket.
*
* @return string APC key for the smallest stored bucket.
* @task ratelimit
*/
private function getMinimumBucketCacheKey() {
$limit_key = $this->getLimitKey();
return "limit:min:{$limit_key}";
}
/**
* Get the current bucket ID for storing rate limit scores.
*
* @return int The current bucket ID.
*/
private function getCurrentBucketID() {
return (int)(time() / $this->getBucketDuration());
}
/**
* Get the APC key for a given bucket.
*
* @param int Bucket to get the key for.
* @return string APC key for the bucket.
*/
private function getBucketCacheKey($bucket_id) {
$limit_key = $this->getLimitKey();
return "limit:bucket:{$limit_key}:{$bucket_id}";
}
/**
* Add points to the rate limit score for some client.
*
* @param string Some key which identifies the client making the request.
* @param float The cost for this request; more points pushes them toward
* the limit faster.
* @return this
*/
private function addScore($score) {
$is_apcu = (bool)function_exists('apcu_fetch');
$current = $this->getCurrentBucketID();
$bucket_key = $this->getBucketCacheKey($current);
// There's a bit of a race here, if a second process reads the bucket
// before this one writes it, but it's fine if we occasionally fail to
// record a client's score. If they're making requests fast enough to hit
// rate limiting, we'll get them soon enough.
if ($is_apcu) {
$bucket = apcu_fetch($bucket_key);
} else {
$bucket = apc_fetch($bucket_key);
}
if (!is_array($bucket)) {
$bucket = array();
}
$client_key = $this->getClientKey();
if (empty($bucket[$client_key])) {
$bucket[$client_key] = 0;
}
$bucket[$client_key] += $score;
if ($is_apcu) {
@apcu_store($bucket_key, $bucket);
} else {
@apc_store($bucket_key, $bucket);
}
return $this;
}
/**
* Get the current rate limit score for a given client.
*
* @return float The client's current score.
* @task ratelimit
*/
private function getScore() {
$is_apcu = (bool)function_exists('apcu_fetch');
// Identify the oldest bucket stored in APC.
$min_key = $this->getMinimumBucketCacheKey();
if ($is_apcu) {
$min = apcu_fetch($min_key);
} else {
$min = apc_fetch($min_key);
}
// If we don't have any buckets stored yet, store the current bucket as
// the oldest bucket.
$cur = $this->getCurrentBucketID();
if (!$min) {
if ($is_apcu) {
@apcu_store($min_key, $cur);
} else {
@apc_store($min_key, $cur);
}
$min = $cur;
}
// Destroy any buckets that are older than the minimum bucket we're keeping
// track of. Under load this normally shouldn't do anything, but will clean
// up an old bucket once per minute.
$count = $this->getBucketCount();
for ($cursor = $min; $cursor < ($cur - $count); $cursor++) {
$bucket_key = $this->getBucketCacheKey($cursor);
if ($is_apcu) {
apcu_delete($bucket_key);
@apcu_store($min_key, $cursor + 1);
} else {
apc_delete($bucket_key);
@apc_store($min_key, $cursor + 1);
}
}
$client_key = $this->getClientKey();
// Now, sum up the client's scores in all of the active buckets.
$score = 0;
for (; $cursor <= $cur; $cursor++) {
$bucket_key = $this->getBucketCacheKey($cursor);
if ($is_apcu) {
$bucket = apcu_fetch($bucket_key);
} else {
$bucket = apc_fetch($bucket_key);
}
if (isset($bucket[$client_key])) {
$score += $bucket[$client_key];
}
}
return $score;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/support/startup/PhabricatorStartup.php | support/startup/PhabricatorStartup.php | <?php
/**
* Handle request startup, before loading the environment or libraries. This
* class bootstraps the request state up to the point where we can enter
* Phabricator code.
*
* NOTE: This class MUST NOT have any dependencies. It runs before libraries
* load.
*
* Rate Limiting
* =============
*
* Phabricator limits the rate at which clients can request pages, and issues
* HTTP 429 "Too Many Requests" responses if clients request too many pages too
* quickly. Although this is not a complete defense against high-volume attacks,
* it can protect an install against aggressive crawlers, security scanners,
* and some types of malicious activity.
*
* To perform rate limiting, each page increments a score counter for the
* requesting user's IP. The page can give the IP more points for an expensive
* request, or fewer for an authetnicated request.
*
* Score counters are kept in buckets, and writes move to a new bucket every
* minute. After a few minutes (defined by @{method:getRateLimitBucketCount}),
* the oldest bucket is discarded. This provides a simple mechanism for keeping
* track of scores without needing to store, access, or read very much data.
*
* Users are allowed to accumulate up to 1000 points per minute, averaged across
* all of the tracked buckets.
*
* @task info Accessing Request Information
* @task hook Startup Hooks
* @task apocalypse In Case Of Apocalypse
* @task validation Validation
* @task ratelimit Rate Limiting
* @task phases Startup Phase Timers
* @task request-path Request Path
*/
final class PhabricatorStartup {
private static $startTime;
private static $debugTimeLimit;
private static $accessLog;
private static $capturingOutput;
private static $rawInput;
private static $oldMemoryLimit;
private static $phases;
private static $limits = array();
private static $requestPath;
/* -( Accessing Request Information )-------------------------------------- */
/**
* @task info
*/
public static function getStartTime() {
return self::$startTime;
}
/**
* @task info
*/
public static function getMicrosecondsSinceStart() {
// This is the same as "phutil_microseconds_since()", but we may not have
// loaded libraries yet.
return (int)(1000000 * (microtime(true) - self::getStartTime()));
}
/**
* @task info
*/
public static function setAccessLog($access_log) {
self::$accessLog = $access_log;
}
/**
* @task info
*/
public static function getRawInput() {
if (self::$rawInput === null) {
$stream = new AphrontRequestStream();
if (isset($_SERVER['HTTP_CONTENT_ENCODING'])) {
$encoding = trim($_SERVER['HTTP_CONTENT_ENCODING']);
$stream->setEncoding($encoding);
}
$input = '';
do {
$bytes = $stream->readData();
if ($bytes === null) {
break;
}
$input .= $bytes;
} while (true);
self::$rawInput = $input;
}
return self::$rawInput;
}
/* -( Startup Hooks )------------------------------------------------------ */
/**
* @param float Request start time, from `microtime(true)`.
* @task hook
*/
public static function didStartup($start_time) {
self::$startTime = $start_time;
self::$phases = array();
self::$accessLog = null;
self::$requestPath = null;
static $registered;
if (!$registered) {
// NOTE: This protects us against multiple calls to didStartup() in the
// same request, but also against repeated requests to the same
// interpreter state, which we may implement in the future.
register_shutdown_function(array(__CLASS__, 'didShutdown'));
$registered = true;
}
self::setupPHP();
self::verifyPHP();
// If we've made it this far, the environment isn't completely broken so
// we can switch over to relying on our own exception recovery mechanisms.
ini_set('display_errors', 0);
self::connectRateLimits();
self::normalizeInput();
self::readRequestPath();
self::beginOutputCapture();
}
/**
* @task hook
*/
public static function didShutdown() {
// Disconnect any active rate limits before we shut down. If we don't do
// this, requests which exit early will lock a slot in any active
// connection limits, and won't count for rate limits.
self::disconnectRateLimits(array());
$event = error_get_last();
if (!$event) {
return;
}
switch ($event['type']) {
case E_ERROR:
case E_PARSE:
case E_COMPILE_ERROR:
break;
default:
return;
}
$msg = ">>> UNRECOVERABLE FATAL ERROR <<<\n\n";
if ($event) {
// Even though we should be emitting this as text-plain, escape things
// just to be sure since we can't really be sure what the program state
// is when we get here.
$msg .= htmlspecialchars(
$event['message']."\n\n".$event['file'].':'.$event['line'],
ENT_QUOTES,
'UTF-8');
}
// flip dem tables
$msg .= "\n\n\n";
$msg .= "\xe2\x94\xbb\xe2\x94\x81\xe2\x94\xbb\x20\xef\xb8\xb5\x20\xc2\xaf".
"\x5c\x5f\x28\xe3\x83\x84\x29\x5f\x2f\xc2\xaf\x20\xef\xb8\xb5\x20".
"\xe2\x94\xbb\xe2\x94\x81\xe2\x94\xbb";
self::didFatal($msg);
}
public static function loadCoreLibraries() {
$phabricator_root = dirname(dirname(dirname(__FILE__)));
$libraries_root = dirname($phabricator_root);
$root = null;
if (!empty($_SERVER['PHUTIL_LIBRARY_ROOT'])) {
$root = $_SERVER['PHUTIL_LIBRARY_ROOT'];
}
ini_set(
'include_path',
$libraries_root.PATH_SEPARATOR.ini_get('include_path'));
$ok = @include_once $root.'arcanist/src/init/init-library.php';
if (!$ok) {
self::didFatal(
'Unable to load the "Arcanist" library. Put "arcanist/" next to '.
'"phabricator/" on disk.');
}
// Load Phabricator itself using the absolute path, so we never end up doing
// anything surprising (loading index.php and libraries from different
// directories).
phutil_load_library($phabricator_root.'/src');
}
/* -( Output Capture )----------------------------------------------------- */
public static function beginOutputCapture() {
if (self::$capturingOutput) {
self::didFatal('Already capturing output!');
}
self::$capturingOutput = true;
ob_start();
}
public static function endOutputCapture() {
if (!self::$capturingOutput) {
return null;
}
self::$capturingOutput = false;
return ob_get_clean();
}
/* -( Debug Time Limit )--------------------------------------------------- */
/**
* Set a time limit (in seconds) for the current script. After time expires,
* the script fatals.
*
* This works like `max_execution_time`, but prints out a useful stack trace
* when the time limit expires. This is primarily intended to make it easier
* to debug pages which hang by allowing extraction of a stack trace: set a
* short debug limit, then use the trace to figure out what's happening.
*
* The limit is implemented with a tick function, so enabling it implies
* some accounting overhead.
*
* @param int Time limit in seconds.
* @return void
*/
public static function setDebugTimeLimit($limit) {
self::$debugTimeLimit = $limit;
static $initialized;
if (!$initialized) {
declare(ticks=1);
register_tick_function(array(__CLASS__, 'onDebugTick'));
}
}
/**
* Callback tick function used by @{method:setDebugTimeLimit}.
*
* Fatals with a useful stack trace after the time limit expires.
*
* @return void
*/
public static function onDebugTick() {
$limit = self::$debugTimeLimit;
if (!$limit) {
return;
}
$elapsed = (microtime(true) - self::getStartTime());
if ($elapsed > $limit) {
$frames = array();
foreach (debug_backtrace() as $frame) {
$file = isset($frame['file']) ? $frame['file'] : '-';
$file = basename($file);
$line = isset($frame['line']) ? $frame['line'] : '-';
$class = isset($frame['class']) ? $frame['class'].'->' : null;
$func = isset($frame['function']) ? $frame['function'].'()' : '?';
$frames[] = "{$file}:{$line} {$class}{$func}";
}
self::didFatal(
"Request aborted by debug time limit after {$limit} seconds.\n\n".
"STACK TRACE\n".
implode("\n", $frames));
}
}
/* -( In Case of Apocalypse )---------------------------------------------- */
/**
* Fatal the request completely in response to an exception, sending a plain
* text message to the client. Calls @{method:didFatal} internally.
*
* @param string Brief description of the exception context, like
* `"Rendering Exception"`.
* @param Throwable The exception itself.
* @param bool True if it's okay to show the exception's stack trace
* to the user. The trace will always be logged.
* @return exit This method **does not return**.
*
* @task apocalypse
*/
public static function didEncounterFatalException(
$note,
$ex,
$show_trace) {
$message = '['.$note.'/'.get_class($ex).'] '.$ex->getMessage();
$full_message = $message;
$full_message .= "\n\n";
$full_message .= $ex->getTraceAsString();
if ($show_trace) {
$message = $full_message;
}
self::didFatal($message, $full_message);
}
/**
* Fatal the request completely, sending a plain text message to the client.
*
* @param string Plain text message to send to the client.
* @param string Plain text message to send to the error log. If not
* provided, the client message is used. You can pass a more
* detailed message here (e.g., with stack traces) to avoid
* showing it to users.
* @return exit This method **does not return**.
*
* @task apocalypse
*/
public static function didFatal($message, $log_message = null) {
if ($log_message === null) {
$log_message = $message;
}
self::endOutputCapture();
$access_log = self::$accessLog;
if ($access_log) {
// We may end up here before the access log is initialized, e.g. from
// verifyPHP().
$access_log->setData(
array(
'c' => 500,
));
$access_log->write();
}
header(
'Content-Type: text/plain; charset=utf-8',
$replace = true,
$http_error = 500);
error_log($log_message);
echo $message."\n";
exit(1);
}
/* -( Validation )--------------------------------------------------------- */
/**
* @task validation
*/
private static function setupPHP() {
error_reporting(E_ALL | E_STRICT);
self::$oldMemoryLimit = ini_get('memory_limit');
ini_set('memory_limit', -1);
// If we have libxml, disable the incredibly dangerous entity loader.
// PHP 8 deprecates this function and disables this by default; remove once
// PHP 7 is no longer supported or a future version has removed the function
// entirely.
if (function_exists('libxml_disable_entity_loader')) {
@libxml_disable_entity_loader(true);
}
// See T13060. If the locale for this process (the parent process) is not
// a UTF-8 locale we can encounter problems when launching subprocesses
// which receive UTF-8 parameters in their command line argument list.
@setlocale(LC_ALL, 'en_US.UTF-8');
$config_map = array(
// See PHI1894. Keep "args" in exception backtraces.
'zend.exception_ignore_args' => 0,
// See T13100. We'd like the regex engine to fail, rather than segfault,
// if handed a pathological regular expression.
'pcre.backtrack_limit' => 10000,
'pcre.recusion_limit' => 10000,
// NOTE: Arcanist applies a similar set of startup options for CLI
// environments in "init-script.php". Changes here may also be
// appropriate to apply there.
);
foreach ($config_map as $config_key => $config_value) {
ini_set($config_key, $config_value);
}
}
/**
* @task validation
*/
public static function getOldMemoryLimit() {
return self::$oldMemoryLimit;
}
/**
* @task validation
*/
private static function normalizeInput() {
// Replace superglobals with unfiltered versions, disrespect php.ini (we
// filter ourselves).
// NOTE: We don't filter INPUT_SERVER because we don't want to overwrite
// changes made in "preamble.php".
// NOTE: WE don't filter INPUT_POST because we may be constructing it
// lazily if "enable_post_data_reading" is disabled.
$filter = array(
INPUT_GET,
INPUT_ENV,
INPUT_COOKIE,
);
foreach ($filter as $type) {
$filtered = filter_input_array($type, FILTER_UNSAFE_RAW);
if (!is_array($filtered)) {
continue;
}
switch ($type) {
case INPUT_GET:
$_GET = array_merge($_GET, $filtered);
break;
case INPUT_COOKIE:
$_COOKIE = array_merge($_COOKIE, $filtered);
break;
case INPUT_ENV;
$env = array_merge($_ENV, $filtered);
$_ENV = self::filterEnvSuperglobal($env);
break;
}
}
self::rebuildRequest();
}
/**
* @task validation
*/
public static function rebuildRequest() {
// Rebuild $_REQUEST, respecting order declared in ".ini" files.
$order = ini_get('request_order');
if (!$order) {
$order = ini_get('variables_order');
}
if (!$order) {
// $_REQUEST will be empty, so leave it alone.
return;
}
$_REQUEST = array();
for ($ii = 0; $ii < strlen($order); $ii++) {
switch ($order[$ii]) {
case 'G':
$_REQUEST = array_merge($_REQUEST, $_GET);
break;
case 'P':
$_REQUEST = array_merge($_REQUEST, $_POST);
break;
case 'C':
$_REQUEST = array_merge($_REQUEST, $_COOKIE);
break;
default:
// $_ENV and $_SERVER never go into $_REQUEST.
break;
}
}
}
/**
* Adjust `$_ENV` before execution.
*
* Adjustments here primarily impact the environment as seen by subprocesses.
* The environment is forwarded explicitly by @{class:ExecFuture}.
*
* @param map<string, wild> Input `$_ENV`.
* @return map<string, string> Suitable `$_ENV`.
* @task validation
*/
private static function filterEnvSuperglobal(array $env) {
// In some configurations, we may get "argc" and "argv" set in $_ENV.
// These are not real environmental variables, and "argv" may have an array
// value which can not be forwarded to subprocesses. Remove these from the
// environment if they are present.
unset($env['argc']);
unset($env['argv']);
return $env;
}
/**
* @task validation
*/
private static function verifyPHP() {
$required_version = '5.2.3';
if (version_compare(PHP_VERSION, $required_version) < 0) {
self::didFatal(
"You are running PHP version '".PHP_VERSION."', which is older than ".
"the minimum version, '{$required_version}'. Update to at least ".
"'{$required_version}'.");
}
if (function_exists('get_magic_quotes_gpc')) {
if (@get_magic_quotes_gpc()) {
self::didFatal(
'Your server is configured with the PHP language feature '.
'"magic_quotes_gpc" enabled.'.
"\n\n".
'This feature is "highly discouraged" by PHP\'s developers, and '.
'has been removed entirely in PHP8.'.
"\n\n".
'You must disable "magic_quotes_gpc" to run Phabricator. Consult '.
'the PHP manual for instructions.');
}
}
if (extension_loaded('apc')) {
$apc_version = phpversion('apc');
$known_bad = array(
'3.1.14' => true,
'3.1.15' => true,
'3.1.15-dev' => true,
);
if (isset($known_bad[$apc_version])) {
self::didFatal(
"You have APC {$apc_version} installed. This version of APC is ".
"known to be bad, and does not work with Phabricator (it will ".
"cause Phabricator to fatal unrecoverably with nonsense errors). ".
"Downgrade to version 3.1.13.");
}
}
if (isset($_SERVER['HTTP_PROXY'])) {
self::didFatal(
'This HTTP request included a "Proxy:" header, poisoning the '.
'environment (CVE-2016-5385 / httpoxy). Declining to process this '.
'request. For details, see: https://phurl.io/u/httpoxy');
}
}
/**
* @task request-path
*/
private static function readRequestPath() {
// See T13575. The request path may be provided in:
//
// - the "$_GET" parameter "__path__" (normal for Apache and nginx); or
// - the "$_SERVER" parameter "REQUEST_URI" (normal for the PHP builtin
// webserver).
//
// Locate it wherever it is, and store it for later use. Note that writing
// to "$_REQUEST" here won't always work, because later code may rebuild
// "$_REQUEST" from other sources.
if (isset($_REQUEST['__path__']) && strlen($_REQUEST['__path__'])) {
self::setRequestPath($_REQUEST['__path__']);
return;
}
// Compatibility with PHP 5.4+ built-in web server.
if (php_sapi_name() == 'cli-server') {
$path = parse_url($_SERVER['REQUEST_URI']);
self::setRequestPath($path['path']);
return;
}
if (!isset($_REQUEST['__path__'])) {
self::didFatal(
"Request parameter '__path__' is not set. Your rewrite rules ".
"are not configured correctly.");
}
if (!strlen($_REQUEST['__path__'])) {
self::didFatal(
"Request parameter '__path__' is set, but empty. Your rewrite rules ".
"are not configured correctly. The '__path__' should always ".
"begin with a '/'.");
}
}
/**
* @task request-path
*/
public static function getRequestPath() {
$path = self::$requestPath;
if ($path === null) {
self::didFatal(
'Request attempted to access request path, but no request path is '.
'available for this request. You may be calling web request code '.
'from a non-request context, or your webserver may not be passing '.
'a request path to Phabricator in a format that it understands.');
}
return $path;
}
/**
* @task request-path
*/
public static function setRequestPath($path) {
self::$requestPath = $path;
}
/* -( Rate Limiting )------------------------------------------------------ */
/**
* Add a new client limits.
*
* @param PhabricatorClientLimit New limit.
* @return PhabricatorClientLimit The limit.
*/
public static function addRateLimit(PhabricatorClientLimit $limit) {
self::$limits[] = $limit;
return $limit;
}
/**
* Apply configured rate limits.
*
* If any limit is exceeded, this method terminates the request.
*
* @return void
* @task ratelimit
*/
private static function connectRateLimits() {
$limits = self::$limits;
$reason = null;
$connected = array();
foreach ($limits as $limit) {
$reason = $limit->didConnect();
$connected[] = $limit;
if ($reason !== null) {
break;
}
}
// If we're killing the request here, disconnect any limits that we
// connected to try to keep the accounting straight.
if ($reason !== null) {
foreach ($connected as $limit) {
$limit->didDisconnect(array());
}
self::didRateLimit($reason);
}
}
/**
* Tear down rate limiting and allow limits to score the request.
*
* @param map<string, wild> Additional, freeform request state.
* @return void
* @task ratelimit
*/
public static function disconnectRateLimits(array $request_state) {
$limits = self::$limits;
// Remove all limits before disconnecting them so this works properly if
// it runs twice. (We run this automatically as a shutdown handler.)
self::$limits = array();
foreach ($limits as $limit) {
$limit->didDisconnect($request_state);
}
}
/**
* Emit an HTTP 429 "Too Many Requests" response (indicating that the user
* has exceeded application rate limits) and exit.
*
* @return exit This method **does not return**.
* @task ratelimit
*/
private static function didRateLimit($reason) {
header(
'Content-Type: text/plain; charset=utf-8',
$replace = true,
$http_error = 429);
echo $reason;
exit(1);
}
/* -( Startup Timers )----------------------------------------------------- */
/**
* Record the beginning of a new startup phase.
*
* For phases which occur before @{class:PhabricatorStartup} loads, save the
* time and record it with @{method:recordStartupPhase} after the class is
* available.
*
* @param string Phase name.
* @task phases
*/
public static function beginStartupPhase($phase) {
self::recordStartupPhase($phase, microtime(true));
}
/**
* Record the start time of a previously executed startup phase.
*
* For startup phases which occur after @{class:PhabricatorStartup} loads,
* use @{method:beginStartupPhase} instead. This method can be used to
* record a time before the class loads, then hand it over once the class
* becomes available.
*
* @param string Phase name.
* @param float Phase start time, from `microtime(true)`.
* @task phases
*/
public static function recordStartupPhase($phase, $time) {
self::$phases[$phase] = $time;
}
/**
* Get information about startup phase timings.
*
* Sometimes, performance problems can occur before we start the profiler.
* Since the profiler can't examine these phases, it isn't useful in
* understanding their performance costs.
*
* Instead, the startup process marks when it enters various phases using
* @{method:beginStartupPhase}. A later call to this method can retrieve this
* information, which can be examined to gain greater insight into where
* time was spent. The output is still crude, but better than nothing.
*
* @task phases
*/
public static function getPhases() {
return self::$phases;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/support/startup/PhabricatorClientRateLimit.php | support/startup/PhabricatorClientRateLimit.php | <?php
final class PhabricatorClientRateLimit
extends PhabricatorClientLimit {
protected function getBucketDuration() {
return 60;
}
protected function getBucketCount() {
return 5;
}
protected function shouldRejectConnection($score) {
$limit = $this->getLimit();
// Reject connections if the average score across all buckets exceeds the
// limit.
$average_score = $score / $this->getBucketCount();
return ($average_score > $limit);
}
protected function getConnectScore() {
return 0;
}
protected function getPenaltyScore() {
return 1;
}
protected function getDisconnectScore(array $request_state) {
$score = 1;
// If the user was logged in, let them make more requests.
if (isset($request_state['viewer'])) {
$viewer = $request_state['viewer'];
if ($viewer->isOmnipotent()) {
// If the viewer was omnipotent, this was an intracluster request or
// some other kind of special request, so don't give it any points
// toward rate limiting.
$score = 0;
} else if ($viewer->isLoggedIn()) {
// If the viewer was logged in, give them fewer points than if they
// were logged out, since this traffic is much more likely to be
// legitimate.
$score = 0.25;
}
}
return $score;
}
protected function getRateLimitReason($score) {
$client_key = $this->getClientKey();
// NOTE: This happens before we load libraries, so we can not use pht()
// here.
return
"TOO MANY REQUESTS\n".
"You (\"{$client_key}\") are issuing too many requests ".
"too quickly.\n";
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/support/startup/preamble-utils.php | support/startup/preamble-utils.php | <?php
/**
* Parse the "X_FORWARDED_FOR" HTTP header to determine the original client
* address.
*
* @param int Number of devices to trust.
* @return void
*/
function preamble_trust_x_forwarded_for_header($layers = 1) {
if (!is_int($layers) || ($layers < 1)) {
echo
'preamble_trust_x_forwarded_for_header(<layers>): '.
'"layers" parameter must an integer larger than 0.'."\n";
echo "\n";
exit(1);
}
if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return;
}
$forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'];
if ($forwarded_for === null || !strlen($forwarded_for)) {
return;
}
$address = preamble_get_x_forwarded_for_address($forwarded_for, $layers);
$_SERVER['REMOTE_ADDR'] = $address;
}
function preamble_get_x_forwarded_for_address($raw_header, $layers) {
// The raw header may be a list of IPs, like "1.2.3.4, 4.5.6.7", if the
// request the load balancer received also had this header. In particular,
// this happens routinely with requests received through a CDN, but can also
// happen illegitimately if the client just makes up an "X-Forwarded-For"
// header full of lies.
// We can only trust the N elements at the end of the list which correspond
// to network-adjacent devices we control. Usually, we're behind a single
// load balancer and "N" is 1, so we want to take the last element in the
// list.
// In some cases, "N" may be more than 1, if the network is configured so
// that that requests are routed through multiple layers of load balancers
// and proxies. In this case, we want to take the Nth-to-last element of
// the list.
$addresses = explode(',', $raw_header);
// If we have more than one trustworthy device on the network path, discard
// corresponding elements from the list. For example, if we have 7 devices,
// we want to discard the last 6 elements of the list.
// The final device address does not appear in the list, since devices do
// not append their own addresses to "X-Forwarded-For".
$discard_addresses = ($layers - 1);
// However, we don't want to throw away all of the addresses. Some requests
// may originate from within the network, and may thus not have as many
// addresses as we expect. If we have fewer addresses than trustworthy
// devices, discard all but one address.
$max_discard = (count($addresses) - 1);
$discard_count = min($discard_addresses, $max_discard);
if ($discard_count) {
$addresses = array_slice($addresses, 0, -$discard_count);
}
$original_address = end($addresses);
$original_address = trim($original_address);
return $original_address;
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/webroot/index.php | webroot/index.php | <?php
phabricator_startup();
$fatal_exception = null;
try {
PhabricatorStartup::beginStartupPhase('libraries');
PhabricatorStartup::loadCoreLibraries();
PhabricatorStartup::beginStartupPhase('purge');
PhabricatorCaches::destroyRequestCache();
PhabricatorStartup::beginStartupPhase('sink');
$sink = new AphrontPHPHTTPSink();
// PHP introduced a "Throwable" interface in PHP 7 and began making more
// runtime errors throw as "Throwable" errors. This is generally good, but
// makes top-level exception handling that is compatible with both PHP 5
// and PHP 7 a bit tricky.
// In PHP 5, "Throwable" does not exist, so "catch (Throwable $ex)" catches
// nothing.
// In PHP 7, various runtime conditions raise an Error which is a Throwable
// but NOT an Exception, so "catch (Exception $ex)" will not catch them.
// To cover both cases, we "catch (Exception $ex)" to catch everything in
// PHP 5, and most things in PHP 7. Then, we "catch (Throwable $ex)" to catch
// everything else in PHP 7. For the most part, we only need to do this at
// the top level.
$main_exception = null;
try {
PhabricatorStartup::beginStartupPhase('run');
AphrontApplicationConfiguration::runHTTPRequest($sink);
} catch (Exception $ex) {
$main_exception = $ex;
} catch (Throwable $ex) {
$main_exception = $ex;
}
if ($main_exception) {
$response_exception = null;
try {
$response = new AphrontUnhandledExceptionResponse();
$response->setException($main_exception);
$response->setShowStackTraces($sink->getShowStackTraces());
PhabricatorStartup::endOutputCapture();
$sink->writeResponse($response);
} catch (Exception $ex) {
$response_exception = $ex;
} catch (Throwable $ex) {
$response_exception = $ex;
}
// If we hit a rendering exception, ignore it and throw the original
// exception. It is generally more interesting and more likely to be
// the root cause.
if ($response_exception) {
throw $main_exception;
}
}
} catch (Exception $ex) {
$fatal_exception = $ex;
} catch (Throwable $ex) {
$fatal_exception = $ex;
}
if ($fatal_exception) {
PhabricatorStartup::didEncounterFatalException(
'Core Exception',
$fatal_exception,
false);
}
function phabricator_startup() {
// Load the PhabricatorStartup class itself.
$t_startup = microtime(true);
$root = dirname(dirname(__FILE__));
require_once $root.'/support/startup/PhabricatorStartup.php';
// Load client limit classes so the preamble can configure limits.
require_once $root.'/support/startup/PhabricatorClientLimit.php';
require_once $root.'/support/startup/PhabricatorClientRateLimit.php';
require_once $root.'/support/startup/PhabricatorClientConnectionLimit.php';
require_once $root.'/support/startup/preamble-utils.php';
// If the preamble script exists, load it.
$t_preamble = microtime(true);
$preamble_path = $root.'/support/preamble.php';
if (file_exists($preamble_path)) {
require_once $preamble_path;
}
$t_hook = microtime(true);
PhabricatorStartup::didStartup($t_startup);
PhabricatorStartup::recordStartupPhase('startup.init', $t_startup);
PhabricatorStartup::recordStartupPhase('preamble', $t_preamble);
PhabricatorStartup::recordStartupPhase('hook', $t_hook);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/__phutil_library_map__.php | src/__phutil_library_map__.php | <?php
/**
* This file is automatically generated. Use 'arc liberate' to rebuild it.
*
* @generated
* @phutil-library-version 2
*/
phutil_register_library_map(array(
'__library_version__' => 2,
'class' => array(
'AlmanacAddress' => 'applications/almanac/util/AlmanacAddress.php',
'AlmanacBinding' => 'applications/almanac/storage/AlmanacBinding.php',
'AlmanacBindingDeletePropertyTransaction' => 'applications/almanac/xaction/AlmanacBindingDeletePropertyTransaction.php',
'AlmanacBindingDisableController' => 'applications/almanac/controller/AlmanacBindingDisableController.php',
'AlmanacBindingDisableTransaction' => 'applications/almanac/xaction/AlmanacBindingDisableTransaction.php',
'AlmanacBindingEditConduitAPIMethod' => 'applications/almanac/conduit/AlmanacBindingEditConduitAPIMethod.php',
'AlmanacBindingEditController' => 'applications/almanac/controller/AlmanacBindingEditController.php',
'AlmanacBindingEditEngine' => 'applications/almanac/editor/AlmanacBindingEditEngine.php',
'AlmanacBindingEditor' => 'applications/almanac/editor/AlmanacBindingEditor.php',
'AlmanacBindingInterfaceTransaction' => 'applications/almanac/xaction/AlmanacBindingInterfaceTransaction.php',
'AlmanacBindingPHIDType' => 'applications/almanac/phid/AlmanacBindingPHIDType.php',
'AlmanacBindingPropertyEditEngine' => 'applications/almanac/editor/AlmanacBindingPropertyEditEngine.php',
'AlmanacBindingQuery' => 'applications/almanac/query/AlmanacBindingQuery.php',
'AlmanacBindingSearchConduitAPIMethod' => 'applications/almanac/conduit/AlmanacBindingSearchConduitAPIMethod.php',
'AlmanacBindingSearchEngine' => 'applications/almanac/query/AlmanacBindingSearchEngine.php',
'AlmanacBindingServiceTransaction' => 'applications/almanac/xaction/AlmanacBindingServiceTransaction.php',
'AlmanacBindingSetPropertyTransaction' => 'applications/almanac/xaction/AlmanacBindingSetPropertyTransaction.php',
'AlmanacBindingTableView' => 'applications/almanac/view/AlmanacBindingTableView.php',
'AlmanacBindingTransaction' => 'applications/almanac/storage/AlmanacBindingTransaction.php',
'AlmanacBindingTransactionQuery' => 'applications/almanac/query/AlmanacBindingTransactionQuery.php',
'AlmanacBindingTransactionType' => 'applications/almanac/xaction/AlmanacBindingTransactionType.php',
'AlmanacBindingViewController' => 'applications/almanac/controller/AlmanacBindingViewController.php',
'AlmanacBindingsSearchEngineAttachment' => 'applications/almanac/engineextension/AlmanacBindingsSearchEngineAttachment.php',
'AlmanacCacheEngineExtension' => 'applications/almanac/engineextension/AlmanacCacheEngineExtension.php',
'AlmanacClusterDatabaseServiceType' => 'applications/almanac/servicetype/AlmanacClusterDatabaseServiceType.php',
'AlmanacClusterRepositoryServiceType' => 'applications/almanac/servicetype/AlmanacClusterRepositoryServiceType.php',
'AlmanacClusterServiceType' => 'applications/almanac/servicetype/AlmanacClusterServiceType.php',
'AlmanacConsoleController' => 'applications/almanac/controller/AlmanacConsoleController.php',
'AlmanacController' => 'applications/almanac/controller/AlmanacController.php',
'AlmanacCreateDevicesCapability' => 'applications/almanac/capability/AlmanacCreateDevicesCapability.php',
'AlmanacCreateNamespacesCapability' => 'applications/almanac/capability/AlmanacCreateNamespacesCapability.php',
'AlmanacCreateNetworksCapability' => 'applications/almanac/capability/AlmanacCreateNetworksCapability.php',
'AlmanacCreateServicesCapability' => 'applications/almanac/capability/AlmanacCreateServicesCapability.php',
'AlmanacCustomServiceType' => 'applications/almanac/servicetype/AlmanacCustomServiceType.php',
'AlmanacDAO' => 'applications/almanac/storage/AlmanacDAO.php',
'AlmanacDeletePropertyEditField' => 'applications/almanac/engineextension/AlmanacDeletePropertyEditField.php',
'AlmanacDeletePropertyEditType' => 'applications/almanac/engineextension/AlmanacDeletePropertyEditType.php',
'AlmanacDevice' => 'applications/almanac/storage/AlmanacDevice.php',
'AlmanacDeviceController' => 'applications/almanac/controller/AlmanacDeviceController.php',
'AlmanacDeviceDeletePropertyTransaction' => 'applications/almanac/xaction/AlmanacDeviceDeletePropertyTransaction.php',
'AlmanacDeviceEditConduitAPIMethod' => 'applications/almanac/conduit/AlmanacDeviceEditConduitAPIMethod.php',
'AlmanacDeviceEditController' => 'applications/almanac/controller/AlmanacDeviceEditController.php',
'AlmanacDeviceEditEngine' => 'applications/almanac/editor/AlmanacDeviceEditEngine.php',
'AlmanacDeviceEditor' => 'applications/almanac/editor/AlmanacDeviceEditor.php',
'AlmanacDeviceListController' => 'applications/almanac/controller/AlmanacDeviceListController.php',
'AlmanacDeviceNameNgrams' => 'applications/almanac/storage/AlmanacDeviceNameNgrams.php',
'AlmanacDeviceNameTransaction' => 'applications/almanac/xaction/AlmanacDeviceNameTransaction.php',
'AlmanacDevicePHIDType' => 'applications/almanac/phid/AlmanacDevicePHIDType.php',
'AlmanacDevicePropertyEditEngine' => 'applications/almanac/editor/AlmanacDevicePropertyEditEngine.php',
'AlmanacDeviceQuery' => 'applications/almanac/query/AlmanacDeviceQuery.php',
'AlmanacDeviceSearchConduitAPIMethod' => 'applications/almanac/conduit/AlmanacDeviceSearchConduitAPIMethod.php',
'AlmanacDeviceSearchEngine' => 'applications/almanac/query/AlmanacDeviceSearchEngine.php',
'AlmanacDeviceSetPropertyTransaction' => 'applications/almanac/xaction/AlmanacDeviceSetPropertyTransaction.php',
'AlmanacDeviceStatus' => 'applications/almanac/constants/AlmanacDeviceStatus.php',
'AlmanacDeviceStatusTransaction' => 'applications/almanac/xaction/AlmanacDeviceStatusTransaction.php',
'AlmanacDeviceTransaction' => 'applications/almanac/storage/AlmanacDeviceTransaction.php',
'AlmanacDeviceTransactionQuery' => 'applications/almanac/query/AlmanacDeviceTransactionQuery.php',
'AlmanacDeviceTransactionType' => 'applications/almanac/xaction/AlmanacDeviceTransactionType.php',
'AlmanacDeviceViewController' => 'applications/almanac/controller/AlmanacDeviceViewController.php',
'AlmanacDrydockPoolServiceType' => 'applications/almanac/servicetype/AlmanacDrydockPoolServiceType.php',
'AlmanacEditor' => 'applications/almanac/editor/AlmanacEditor.php',
'AlmanacInterface' => 'applications/almanac/storage/AlmanacInterface.php',
'AlmanacInterfaceAddressTransaction' => 'applications/almanac/xaction/AlmanacInterfaceAddressTransaction.php',
'AlmanacInterfaceDatasource' => 'applications/almanac/typeahead/AlmanacInterfaceDatasource.php',
'AlmanacInterfaceDeleteController' => 'applications/almanac/controller/AlmanacInterfaceDeleteController.php',
'AlmanacInterfaceDestroyTransaction' => 'applications/almanac/xaction/AlmanacInterfaceDestroyTransaction.php',
'AlmanacInterfaceDeviceTransaction' => 'applications/almanac/xaction/AlmanacInterfaceDeviceTransaction.php',
'AlmanacInterfaceEditConduitAPIMethod' => 'applications/almanac/conduit/AlmanacInterfaceEditConduitAPIMethod.php',
'AlmanacInterfaceEditController' => 'applications/almanac/controller/AlmanacInterfaceEditController.php',
'AlmanacInterfaceEditEngine' => 'applications/almanac/editor/AlmanacInterfaceEditEngine.php',
'AlmanacInterfaceEditor' => 'applications/almanac/editor/AlmanacInterfaceEditor.php',
'AlmanacInterfaceNetworkTransaction' => 'applications/almanac/xaction/AlmanacInterfaceNetworkTransaction.php',
'AlmanacInterfacePHIDType' => 'applications/almanac/phid/AlmanacInterfacePHIDType.php',
'AlmanacInterfacePortTransaction' => 'applications/almanac/xaction/AlmanacInterfacePortTransaction.php',
'AlmanacInterfaceQuery' => 'applications/almanac/query/AlmanacInterfaceQuery.php',
'AlmanacInterfaceSearchConduitAPIMethod' => 'applications/almanac/conduit/AlmanacInterfaceSearchConduitAPIMethod.php',
'AlmanacInterfaceSearchEngine' => 'applications/almanac/query/AlmanacInterfaceSearchEngine.php',
'AlmanacInterfaceTableView' => 'applications/almanac/view/AlmanacInterfaceTableView.php',
'AlmanacInterfaceTransaction' => 'applications/almanac/storage/AlmanacInterfaceTransaction.php',
'AlmanacInterfaceTransactionQuery' => 'applications/almanac/query/AlmanacInterfaceTransactionQuery.php',
'AlmanacInterfaceTransactionType' => 'applications/almanac/xaction/AlmanacInterfaceTransactionType.php',
'AlmanacKeys' => 'applications/almanac/util/AlmanacKeys.php',
'AlmanacManageClusterServicesCapability' => 'applications/almanac/capability/AlmanacManageClusterServicesCapability.php',
'AlmanacManagementRegisterWorkflow' => 'applications/almanac/management/AlmanacManagementRegisterWorkflow.php',
'AlmanacManagementTrustKeyWorkflow' => 'applications/almanac/management/AlmanacManagementTrustKeyWorkflow.php',
'AlmanacManagementUntrustKeyWorkflow' => 'applications/almanac/management/AlmanacManagementUntrustKeyWorkflow.php',
'AlmanacManagementWorkflow' => 'applications/almanac/management/AlmanacManagementWorkflow.php',
'AlmanacModularTransaction' => 'applications/almanac/storage/AlmanacModularTransaction.php',
'AlmanacNames' => 'applications/almanac/util/AlmanacNames.php',
'AlmanacNamesTestCase' => 'applications/almanac/util/__tests__/AlmanacNamesTestCase.php',
'AlmanacNamespace' => 'applications/almanac/storage/AlmanacNamespace.php',
'AlmanacNamespaceController' => 'applications/almanac/controller/AlmanacNamespaceController.php',
'AlmanacNamespaceEditConduitAPIMethod' => 'applications/almanac/conduit/AlmanacNamespaceEditConduitAPIMethod.php',
'AlmanacNamespaceEditController' => 'applications/almanac/controller/AlmanacNamespaceEditController.php',
'AlmanacNamespaceEditEngine' => 'applications/almanac/editor/AlmanacNamespaceEditEngine.php',
'AlmanacNamespaceEditor' => 'applications/almanac/editor/AlmanacNamespaceEditor.php',
'AlmanacNamespaceListController' => 'applications/almanac/controller/AlmanacNamespaceListController.php',
'AlmanacNamespaceNameNgrams' => 'applications/almanac/storage/AlmanacNamespaceNameNgrams.php',
'AlmanacNamespaceNameTransaction' => 'applications/almanac/xaction/AlmanacNamespaceNameTransaction.php',
'AlmanacNamespacePHIDType' => 'applications/almanac/phid/AlmanacNamespacePHIDType.php',
'AlmanacNamespaceQuery' => 'applications/almanac/query/AlmanacNamespaceQuery.php',
'AlmanacNamespaceSearchConduitAPIMethod' => 'applications/almanac/conduit/AlmanacNamespaceSearchConduitAPIMethod.php',
'AlmanacNamespaceSearchEngine' => 'applications/almanac/query/AlmanacNamespaceSearchEngine.php',
'AlmanacNamespaceTransaction' => 'applications/almanac/storage/AlmanacNamespaceTransaction.php',
'AlmanacNamespaceTransactionQuery' => 'applications/almanac/query/AlmanacNamespaceTransactionQuery.php',
'AlmanacNamespaceTransactionType' => 'applications/almanac/xaction/AlmanacNamespaceTransactionType.php',
'AlmanacNamespaceViewController' => 'applications/almanac/controller/AlmanacNamespaceViewController.php',
'AlmanacNetwork' => 'applications/almanac/storage/AlmanacNetwork.php',
'AlmanacNetworkController' => 'applications/almanac/controller/AlmanacNetworkController.php',
'AlmanacNetworkEditConduitAPIMethod' => 'applications/almanac/conduit/AlmanacNetworkEditConduitAPIMethod.php',
'AlmanacNetworkEditController' => 'applications/almanac/controller/AlmanacNetworkEditController.php',
'AlmanacNetworkEditEngine' => 'applications/almanac/editor/AlmanacNetworkEditEngine.php',
'AlmanacNetworkEditor' => 'applications/almanac/editor/AlmanacNetworkEditor.php',
'AlmanacNetworkListController' => 'applications/almanac/controller/AlmanacNetworkListController.php',
'AlmanacNetworkNameNgrams' => 'applications/almanac/storage/AlmanacNetworkNameNgrams.php',
'AlmanacNetworkNameTransaction' => 'applications/almanac/xaction/AlmanacNetworkNameTransaction.php',
'AlmanacNetworkPHIDType' => 'applications/almanac/phid/AlmanacNetworkPHIDType.php',
'AlmanacNetworkQuery' => 'applications/almanac/query/AlmanacNetworkQuery.php',
'AlmanacNetworkSearchConduitAPIMethod' => 'applications/almanac/conduit/AlmanacNetworkSearchConduitAPIMethod.php',
'AlmanacNetworkSearchEngine' => 'applications/almanac/query/AlmanacNetworkSearchEngine.php',
'AlmanacNetworkTransaction' => 'applications/almanac/storage/AlmanacNetworkTransaction.php',
'AlmanacNetworkTransactionQuery' => 'applications/almanac/query/AlmanacNetworkTransactionQuery.php',
'AlmanacNetworkTransactionType' => 'applications/almanac/xaction/AlmanacNetworkTransactionType.php',
'AlmanacNetworkViewController' => 'applications/almanac/controller/AlmanacNetworkViewController.php',
'AlmanacPropertiesDestructionEngineExtension' => 'applications/almanac/engineextension/AlmanacPropertiesDestructionEngineExtension.php',
'AlmanacPropertiesEditEngineExtension' => 'applications/almanac/engineextension/AlmanacPropertiesEditEngineExtension.php',
'AlmanacPropertiesSearchEngineAttachment' => 'applications/almanac/engineextension/AlmanacPropertiesSearchEngineAttachment.php',
'AlmanacProperty' => 'applications/almanac/storage/AlmanacProperty.php',
'AlmanacPropertyController' => 'applications/almanac/controller/AlmanacPropertyController.php',
'AlmanacPropertyDeleteController' => 'applications/almanac/controller/AlmanacPropertyDeleteController.php',
'AlmanacPropertyEditController' => 'applications/almanac/controller/AlmanacPropertyEditController.php',
'AlmanacPropertyEditEngine' => 'applications/almanac/editor/AlmanacPropertyEditEngine.php',
'AlmanacPropertyInterface' => 'applications/almanac/property/AlmanacPropertyInterface.php',
'AlmanacPropertyQuery' => 'applications/almanac/query/AlmanacPropertyQuery.php',
'AlmanacQuery' => 'applications/almanac/query/AlmanacQuery.php',
'AlmanacSchemaSpec' => 'applications/almanac/storage/AlmanacSchemaSpec.php',
'AlmanacSearchEngineAttachment' => 'applications/almanac/engineextension/AlmanacSearchEngineAttachment.php',
'AlmanacService' => 'applications/almanac/storage/AlmanacService.php',
'AlmanacServiceController' => 'applications/almanac/controller/AlmanacServiceController.php',
'AlmanacServiceDatasource' => 'applications/almanac/typeahead/AlmanacServiceDatasource.php',
'AlmanacServiceDeletePropertyTransaction' => 'applications/almanac/xaction/AlmanacServiceDeletePropertyTransaction.php',
'AlmanacServiceEditConduitAPIMethod' => 'applications/almanac/conduit/AlmanacServiceEditConduitAPIMethod.php',
'AlmanacServiceEditController' => 'applications/almanac/controller/AlmanacServiceEditController.php',
'AlmanacServiceEditEngine' => 'applications/almanac/editor/AlmanacServiceEditEngine.php',
'AlmanacServiceEditor' => 'applications/almanac/editor/AlmanacServiceEditor.php',
'AlmanacServiceListController' => 'applications/almanac/controller/AlmanacServiceListController.php',
'AlmanacServiceNameNgrams' => 'applications/almanac/storage/AlmanacServiceNameNgrams.php',
'AlmanacServiceNameTransaction' => 'applications/almanac/xaction/AlmanacServiceNameTransaction.php',
'AlmanacServicePHIDType' => 'applications/almanac/phid/AlmanacServicePHIDType.php',
'AlmanacServicePropertyEditEngine' => 'applications/almanac/editor/AlmanacServicePropertyEditEngine.php',
'AlmanacServiceQuery' => 'applications/almanac/query/AlmanacServiceQuery.php',
'AlmanacServiceSearchConduitAPIMethod' => 'applications/almanac/conduit/AlmanacServiceSearchConduitAPIMethod.php',
'AlmanacServiceSearchEngine' => 'applications/almanac/query/AlmanacServiceSearchEngine.php',
'AlmanacServiceSetPropertyTransaction' => 'applications/almanac/xaction/AlmanacServiceSetPropertyTransaction.php',
'AlmanacServiceTransaction' => 'applications/almanac/storage/AlmanacServiceTransaction.php',
'AlmanacServiceTransactionQuery' => 'applications/almanac/query/AlmanacServiceTransactionQuery.php',
'AlmanacServiceTransactionType' => 'applications/almanac/xaction/AlmanacServiceTransactionType.php',
'AlmanacServiceType' => 'applications/almanac/servicetype/AlmanacServiceType.php',
'AlmanacServiceTypeDatasource' => 'applications/almanac/typeahead/AlmanacServiceTypeDatasource.php',
'AlmanacServiceTypeTestCase' => 'applications/almanac/servicetype/__tests__/AlmanacServiceTypeTestCase.php',
'AlmanacServiceTypeTransaction' => 'applications/almanac/xaction/AlmanacServiceTypeTransaction.php',
'AlmanacServiceViewController' => 'applications/almanac/controller/AlmanacServiceViewController.php',
'AlmanacSetPropertyEditField' => 'applications/almanac/engineextension/AlmanacSetPropertyEditField.php',
'AlmanacSetPropertyEditType' => 'applications/almanac/engineextension/AlmanacSetPropertyEditType.php',
'AlmanacTransactionType' => 'applications/almanac/xaction/AlmanacTransactionType.php',
'AphlictDropdownDataQuery' => 'applications/aphlict/query/AphlictDropdownDataQuery.php',
'Aphront304Response' => 'aphront/response/Aphront304Response.php',
'Aphront400Response' => 'aphront/response/Aphront400Response.php',
'Aphront403Response' => 'aphront/response/Aphront403Response.php',
'Aphront404Response' => 'aphront/response/Aphront404Response.php',
'AphrontAccessDeniedQueryException' => 'infrastructure/storage/exception/AphrontAccessDeniedQueryException.php',
'AphrontAjaxResponse' => 'aphront/response/AphrontAjaxResponse.php',
'AphrontApplicationConfiguration' => 'aphront/configuration/AphrontApplicationConfiguration.php',
'AphrontAutoIDView' => 'view/AphrontAutoIDView.php',
'AphrontBarView' => 'view/widget/bars/AphrontBarView.php',
'AphrontBaseMySQLDatabaseConnection' => 'infrastructure/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php',
'AphrontBoolHTTPParameterType' => 'aphront/httpparametertype/AphrontBoolHTTPParameterType.php',
'AphrontCalendarEventView' => 'applications/calendar/view/AphrontCalendarEventView.php',
'AphrontCharacterSetQueryException' => 'infrastructure/storage/exception/AphrontCharacterSetQueryException.php',
'AphrontConnectionLostQueryException' => 'infrastructure/storage/exception/AphrontConnectionLostQueryException.php',
'AphrontConnectionQueryException' => 'infrastructure/storage/exception/AphrontConnectionQueryException.php',
'AphrontController' => 'aphront/AphrontController.php',
'AphrontCountQueryException' => 'infrastructure/storage/exception/AphrontCountQueryException.php',
'AphrontCursorPagerView' => 'view/control/AphrontCursorPagerView.php',
'AphrontDatabaseConnection' => 'infrastructure/storage/connection/AphrontDatabaseConnection.php',
'AphrontDatabaseTableRef' => 'infrastructure/storage/xsprintf/AphrontDatabaseTableRef.php',
'AphrontDatabaseTableRefInterface' => 'infrastructure/storage/xsprintf/AphrontDatabaseTableRefInterface.php',
'AphrontDatabaseTransactionState' => 'infrastructure/storage/connection/AphrontDatabaseTransactionState.php',
'AphrontDeadlockQueryException' => 'infrastructure/storage/exception/AphrontDeadlockQueryException.php',
'AphrontDialogResponse' => 'aphront/response/AphrontDialogResponse.php',
'AphrontDialogView' => 'view/AphrontDialogView.php',
'AphrontDuplicateKeyQueryException' => 'infrastructure/storage/exception/AphrontDuplicateKeyQueryException.php',
'AphrontEpochHTTPParameterType' => 'aphront/httpparametertype/AphrontEpochHTTPParameterType.php',
'AphrontException' => 'aphront/exception/AphrontException.php',
'AphrontFileHTTPParameterType' => 'aphront/httpparametertype/AphrontFileHTTPParameterType.php',
'AphrontFileResponse' => 'aphront/response/AphrontFileResponse.php',
'AphrontFormCheckboxControl' => 'view/form/control/AphrontFormCheckboxControl.php',
'AphrontFormControl' => 'view/form/control/AphrontFormControl.php',
'AphrontFormDateControl' => 'view/form/control/AphrontFormDateControl.php',
'AphrontFormDateControlValue' => 'view/form/control/AphrontFormDateControlValue.php',
'AphrontFormDividerControl' => 'view/form/control/AphrontFormDividerControl.php',
'AphrontFormFileControl' => 'view/form/control/AphrontFormFileControl.php',
'AphrontFormHandlesControl' => 'view/form/control/AphrontFormHandlesControl.php',
'AphrontFormMarkupControl' => 'view/form/control/AphrontFormMarkupControl.php',
'AphrontFormPasswordControl' => 'view/form/control/AphrontFormPasswordControl.php',
'AphrontFormPolicyControl' => 'view/form/control/AphrontFormPolicyControl.php',
'AphrontFormRadioButtonControl' => 'view/form/control/AphrontFormRadioButtonControl.php',
'AphrontFormRecaptchaControl' => 'view/form/control/AphrontFormRecaptchaControl.php',
'AphrontFormSelectControl' => 'view/form/control/AphrontFormSelectControl.php',
'AphrontFormStaticControl' => 'view/form/control/AphrontFormStaticControl.php',
'AphrontFormSubmitControl' => 'view/form/control/AphrontFormSubmitControl.php',
'AphrontFormTextAreaControl' => 'view/form/control/AphrontFormTextAreaControl.php',
'AphrontFormTextControl' => 'view/form/control/AphrontFormTextControl.php',
'AphrontFormTextWithSubmitControl' => 'view/form/control/AphrontFormTextWithSubmitControl.php',
'AphrontFormTokenizerControl' => 'view/form/control/AphrontFormTokenizerControl.php',
'AphrontFormTypeaheadControl' => 'view/form/control/AphrontFormTypeaheadControl.php',
'AphrontFormView' => 'view/form/AphrontFormView.php',
'AphrontGlyphBarView' => 'view/widget/bars/AphrontGlyphBarView.php',
'AphrontHTMLResponse' => 'aphront/response/AphrontHTMLResponse.php',
'AphrontHTTPHeaderParser' => 'aphront/headerparser/AphrontHTTPHeaderParser.php',
'AphrontHTTPHeaderParserTestCase' => 'aphront/headerparser/__tests__/AphrontHTTPHeaderParserTestCase.php',
'AphrontHTTPParameterType' => 'aphront/httpparametertype/AphrontHTTPParameterType.php',
'AphrontHTTPProxyResponse' => 'aphront/response/AphrontHTTPProxyResponse.php',
'AphrontHTTPSink' => 'aphront/sink/AphrontHTTPSink.php',
'AphrontHTTPSinkTestCase' => 'aphront/sink/__tests__/AphrontHTTPSinkTestCase.php',
'AphrontIntHTTPParameterType' => 'aphront/httpparametertype/AphrontIntHTTPParameterType.php',
'AphrontInvalidCredentialsQueryException' => 'infrastructure/storage/exception/AphrontInvalidCredentialsQueryException.php',
'AphrontIsolatedDatabaseConnection' => 'infrastructure/storage/connection/AphrontIsolatedDatabaseConnection.php',
'AphrontIsolatedDatabaseConnectionTestCase' => 'infrastructure/storage/__tests__/AphrontIsolatedDatabaseConnectionTestCase.php',
'AphrontIsolatedHTTPSink' => 'aphront/sink/AphrontIsolatedHTTPSink.php',
'AphrontJSONHTTPParameterType' => 'aphront/httpparametertype/AphrontJSONHTTPParameterType.php',
'AphrontJSONResponse' => 'aphront/response/AphrontJSONResponse.php',
'AphrontJavelinView' => 'view/AphrontJavelinView.php',
'AphrontKeyboardShortcutsAvailableView' => 'view/widget/AphrontKeyboardShortcutsAvailableView.php',
'AphrontListFilterView' => 'view/layout/AphrontListFilterView.php',
'AphrontListHTTPParameterType' => 'aphront/httpparametertype/AphrontListHTTPParameterType.php',
'AphrontLockTimeoutQueryException' => 'infrastructure/storage/exception/AphrontLockTimeoutQueryException.php',
'AphrontMalformedRequestException' => 'aphront/exception/AphrontMalformedRequestException.php',
'AphrontMoreView' => 'view/layout/AphrontMoreView.php',
'AphrontMultiColumnView' => 'view/layout/AphrontMultiColumnView.php',
'AphrontMultipartParser' => 'aphront/multipartparser/AphrontMultipartParser.php',
'AphrontMultipartParserTestCase' => 'aphront/multipartparser/__tests__/AphrontMultipartParserTestCase.php',
'AphrontMultipartPart' => 'aphront/multipartparser/AphrontMultipartPart.php',
'AphrontMySQLDatabaseConnection' => 'infrastructure/storage/connection/mysql/AphrontMySQLDatabaseConnection.php',
'AphrontMySQLDatabaseConnectionTestCase' => 'infrastructure/storage/__tests__/AphrontMySQLDatabaseConnectionTestCase.php',
'AphrontMySQLiDatabaseConnection' => 'infrastructure/storage/connection/mysql/AphrontMySQLiDatabaseConnection.php',
'AphrontNotSupportedQueryException' => 'infrastructure/storage/exception/AphrontNotSupportedQueryException.php',
'AphrontNullView' => 'view/AphrontNullView.php',
'AphrontObjectMissingQueryException' => 'infrastructure/storage/exception/AphrontObjectMissingQueryException.php',
'AphrontPHIDHTTPParameterType' => 'aphront/httpparametertype/AphrontPHIDHTTPParameterType.php',
'AphrontPHIDListHTTPParameterType' => 'aphront/httpparametertype/AphrontPHIDListHTTPParameterType.php',
'AphrontPHPHTTPSink' => 'aphront/sink/AphrontPHPHTTPSink.php',
'AphrontPageView' => 'view/page/AphrontPageView.php',
'AphrontParameterQueryException' => 'infrastructure/storage/exception/AphrontParameterQueryException.php',
'AphrontPlainTextResponse' => 'aphront/response/AphrontPlainTextResponse.php',
'AphrontProgressBarView' => 'view/widget/bars/AphrontProgressBarView.php',
'AphrontProjectListHTTPParameterType' => 'aphront/httpparametertype/AphrontProjectListHTTPParameterType.php',
'AphrontProxyResponse' => 'aphront/response/AphrontProxyResponse.php',
'AphrontQueryException' => 'infrastructure/storage/exception/AphrontQueryException.php',
'AphrontQueryTimeoutQueryException' => 'infrastructure/storage/exception/AphrontQueryTimeoutQueryException.php',
'AphrontRecoverableQueryException' => 'infrastructure/storage/exception/AphrontRecoverableQueryException.php',
'AphrontRedirectResponse' => 'aphront/response/AphrontRedirectResponse.php',
'AphrontRedirectResponseTestCase' => 'aphront/response/__tests__/AphrontRedirectResponseTestCase.php',
'AphrontReloadResponse' => 'aphront/response/AphrontReloadResponse.php',
'AphrontRemarkupHTTPParameterType' => 'aphront/httpparametertype/AphrontRemarkupHTTPParameterType.php',
'AphrontRequest' => 'aphront/AphrontRequest.php',
'AphrontRequestExceptionHandler' => 'aphront/handler/AphrontRequestExceptionHandler.php',
'AphrontRequestStream' => 'aphront/requeststream/AphrontRequestStream.php',
'AphrontRequestTestCase' => 'aphront/__tests__/AphrontRequestTestCase.php',
'AphrontResponse' => 'aphront/response/AphrontResponse.php',
'AphrontResponseProducerInterface' => 'aphront/interface/AphrontResponseProducerInterface.php',
'AphrontRoutingMap' => 'aphront/site/AphrontRoutingMap.php',
'AphrontRoutingMapTestCase' => 'aphront/__tests__/AphrontRoutingMapTestCase.php',
'AphrontRoutingResult' => 'aphront/site/AphrontRoutingResult.php',
'AphrontSchemaQueryException' => 'infrastructure/storage/exception/AphrontSchemaQueryException.php',
'AphrontScopedUnguardedWriteCapability' => 'aphront/writeguard/AphrontScopedUnguardedWriteCapability.php',
'AphrontSelectHTTPParameterType' => 'aphront/httpparametertype/AphrontSelectHTTPParameterType.php',
'AphrontSideNavFilterView' => 'view/layout/AphrontSideNavFilterView.php',
'AphrontSite' => 'aphront/site/AphrontSite.php',
'AphrontStackTraceView' => 'view/widget/AphrontStackTraceView.php',
'AphrontStandaloneHTMLResponse' => 'aphront/response/AphrontStandaloneHTMLResponse.php',
'AphrontStringHTTPParameterType' => 'aphront/httpparametertype/AphrontStringHTTPParameterType.php',
'AphrontStringListHTTPParameterType' => 'aphront/httpparametertype/AphrontStringListHTTPParameterType.php',
'AphrontTableView' => 'view/control/AphrontTableView.php',
'AphrontTagView' => 'view/AphrontTagView.php',
'AphrontTokenizerTemplateView' => 'view/control/AphrontTokenizerTemplateView.php',
'AphrontTypeaheadTemplateView' => 'view/control/AphrontTypeaheadTemplateView.php',
'AphrontUnhandledExceptionResponse' => 'aphront/response/AphrontUnhandledExceptionResponse.php',
'AphrontUserListHTTPParameterType' => 'aphront/httpparametertype/AphrontUserListHTTPParameterType.php',
'AphrontView' => 'view/AphrontView.php',
'AphrontWebpageResponse' => 'aphront/response/AphrontWebpageResponse.php',
'AphrontWriteGuard' => 'aphront/writeguard/AphrontWriteGuard.php',
'ArcanistConduitAPIMethod' => 'applications/arcanist/conduit/ArcanistConduitAPIMethod.php',
'AuditConduitAPIMethod' => 'applications/audit/conduit/AuditConduitAPIMethod.php',
'AuditQueryConduitAPIMethod' => 'applications/audit/conduit/AuditQueryConduitAPIMethod.php',
'AuthManageProvidersCapability' => 'applications/auth/capability/AuthManageProvidersCapability.php',
'BulkParameterType' => 'applications/transactions/bulk/type/BulkParameterType.php',
'BulkPointsParameterType' => 'applications/transactions/bulk/type/BulkPointsParameterType.php',
'BulkRemarkupParameterType' => 'applications/transactions/bulk/type/BulkRemarkupParameterType.php',
'BulkSelectParameterType' => 'applications/transactions/bulk/type/BulkSelectParameterType.php',
'BulkStringParameterType' => 'applications/transactions/bulk/type/BulkStringParameterType.php',
'BulkTokenizerParameterType' => 'applications/transactions/bulk/type/BulkTokenizerParameterType.php',
'CalendarTimeUtil' => 'applications/calendar/util/CalendarTimeUtil.php',
'CalendarTimeUtilTestCase' => 'applications/calendar/__tests__/CalendarTimeUtilTestCase.php',
'CelerityAPI' => 'applications/celerity/CelerityAPI.php',
'CelerityDarkModePostprocessor' => 'applications/celerity/postprocessor/CelerityDarkModePostprocessor.php',
'CelerityDefaultPostprocessor' => 'applications/celerity/postprocessor/CelerityDefaultPostprocessor.php',
'CelerityHighContrastPostprocessor' => 'applications/celerity/postprocessor/CelerityHighContrastPostprocessor.php',
'CelerityLargeFontPostprocessor' => 'applications/celerity/postprocessor/CelerityLargeFontPostprocessor.php',
'CelerityManagementMapWorkflow' => 'applications/celerity/management/CelerityManagementMapWorkflow.php',
'CelerityManagementSyntaxWorkflow' => 'applications/celerity/management/CelerityManagementSyntaxWorkflow.php',
'CelerityManagementWorkflow' => 'applications/celerity/management/CelerityManagementWorkflow.php',
'CelerityPhabricatorResourceController' => 'applications/celerity/controller/CelerityPhabricatorResourceController.php',
'CelerityPhabricatorResources' => 'applications/celerity/resources/CelerityPhabricatorResources.php',
'CelerityPhysicalResources' => 'applications/celerity/resources/CelerityPhysicalResources.php',
'CelerityPhysicalResourcesTestCase' => 'applications/celerity/resources/__tests__/CelerityPhysicalResourcesTestCase.php',
'CelerityPostprocessor' => 'applications/celerity/postprocessor/CelerityPostprocessor.php',
'CelerityPostprocessorTestCase' => 'applications/celerity/__tests__/CelerityPostprocessorTestCase.php',
'CelerityRedGreenPostprocessor' => 'applications/celerity/postprocessor/CelerityRedGreenPostprocessor.php',
'CelerityResourceController' => 'applications/celerity/controller/CelerityResourceController.php',
'CelerityResourceGraph' => 'applications/celerity/CelerityResourceGraph.php',
'CelerityResourceMap' => 'applications/celerity/CelerityResourceMap.php',
'CelerityResourceMapGenerator' => 'applications/celerity/CelerityResourceMapGenerator.php',
'CelerityResourceTransformer' => 'applications/celerity/CelerityResourceTransformer.php',
'CelerityResourceTransformerTestCase' => 'applications/celerity/__tests__/CelerityResourceTransformerTestCase.php',
'CelerityResources' => 'applications/celerity/resources/CelerityResources.php',
'CelerityResourcesOnDisk' => 'applications/celerity/resources/CelerityResourcesOnDisk.php',
'CeleritySpriteGenerator' => 'applications/celerity/CeleritySpriteGenerator.php',
'CelerityStaticResourceResponse' => 'applications/celerity/CelerityStaticResourceResponse.php',
'ChatLogConduitAPIMethod' => 'applications/chatlog/conduit/ChatLogConduitAPIMethod.php',
'ChatLogQueryConduitAPIMethod' => 'applications/chatlog/conduit/ChatLogQueryConduitAPIMethod.php',
'ChatLogRecordConduitAPIMethod' => 'applications/chatlog/conduit/ChatLogRecordConduitAPIMethod.php',
'ConduitAPIDocumentationPage' => 'applications/conduit/data/ConduitAPIDocumentationPage.php',
'ConduitAPIMethod' => 'applications/conduit/method/ConduitAPIMethod.php',
'ConduitAPIMethodTestCase' => 'applications/conduit/method/__tests__/ConduitAPIMethodTestCase.php',
'ConduitAPIRequest' => 'applications/conduit/protocol/ConduitAPIRequest.php',
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/__phutil_library_init__.php | src/__phutil_library_init__.php | <?php
phutil_register_library('phabricator', __FILE__);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/PhabricatorEditor.php | src/infrastructure/PhabricatorEditor.php | <?php
abstract class PhabricatorEditor extends Phobject {
private $actor;
private $excludeMailRecipientPHIDs = array();
final public function setActor(PhabricatorUser $actor) {
$this->actor = $actor;
return $this;
}
final public function getActor() {
return $this->actor;
}
final public function requireActor() {
$actor = $this->getActor();
if (!$actor) {
throw new PhutilInvalidStateException('setActor');
}
return $actor;
}
final public function setExcludeMailRecipientPHIDs($phids) {
$this->excludeMailRecipientPHIDs = $phids;
return $this;
}
final protected function getExcludeMailRecipientPHIDs() {
return $this->excludeMailRecipientPHIDs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/PhabricatorStorageManagementAPI.php | src/infrastructure/storage/management/PhabricatorStorageManagementAPI.php | <?php
final class PhabricatorStorageManagementAPI extends Phobject {
private $ref;
private $host;
private $user;
private $port;
private $password;
private $namespace;
private $conns = array();
private $disableUTF8MB4;
const CHARSET_DEFAULT = 'CHARSET';
const CHARSET_SORT = 'CHARSET_SORT';
const CHARSET_FULLTEXT = 'CHARSET_FULLTEXT';
const COLLATE_TEXT = 'COLLATE_TEXT';
const COLLATE_SORT = 'COLLATE_SORT';
const COLLATE_FULLTEXT = 'COLLATE_FULLTEXT';
const TABLE_STATUS = 'patch_status';
const TABLE_HOSTSTATE = 'hoststate';
public function setDisableUTF8MB4($disable_utf8_mb4) {
$this->disableUTF8MB4 = $disable_utf8_mb4;
return $this;
}
public function getDisableUTF8MB4() {
return $this->disableUTF8MB4;
}
public function setNamespace($namespace) {
$this->namespace = $namespace;
PhabricatorLiskDAO::pushStorageNamespace($namespace);
return $this;
}
public function getNamespace() {
return $this->namespace;
}
public function setUser($user) {
$this->user = $user;
return $this;
}
public function getUser() {
return $this->user;
}
public function setPassword($password) {
$this->password = $password;
return $this;
}
public function getPassword() {
return $this->password;
}
public function setHost($host) {
$this->host = $host;
return $this;
}
public function getHost() {
return $this->host;
}
public function setPort($port) {
$this->port = $port;
return $this;
}
public function getPort() {
return $this->port;
}
public function setRef(PhabricatorDatabaseRef $ref) {
$this->ref = $ref;
return $this;
}
public function getRef() {
return $this->ref;
}
public function getDatabaseName($fragment) {
return $this->namespace.'_'.$fragment;
}
public function getInternalDatabaseName($name) {
$namespace = $this->getNamespace();
$prefix = $namespace.'_';
if (strncmp($name, $prefix, strlen($prefix))) {
return null;
}
return substr($name, strlen($prefix));
}
public function getDisplayName() {
return $this->getRef()->getDisplayName();
}
public function getDatabaseList(array $patches, $only_living = false) {
assert_instances_of($patches, 'PhabricatorStoragePatch');
$list = array();
foreach ($patches as $patch) {
if ($patch->getType() == 'db') {
if ($only_living && $patch->isDead()) {
continue;
}
$list[] = $this->getDatabaseName($patch->getName());
}
}
return $list;
}
public function getConn($fragment) {
$database = $this->getDatabaseName($fragment);
$return = &$this->conns[$this->host][$this->user][$database];
if (!$return) {
$return = PhabricatorDatabaseRef::newRawConnection(
array(
'user' => $this->user,
'pass' => $this->password,
'host' => $this->host,
'port' => $this->port,
'database' => $fragment
? $database
: null,
));
}
return $return;
}
public function getAppliedPatches() {
try {
$applied = queryfx_all(
$this->getConn('meta_data'),
'SELECT patch FROM %T',
self::TABLE_STATUS);
return ipull($applied, 'patch');
} catch (AphrontAccessDeniedQueryException $ex) {
throw new PhutilProxyException(
pht(
'Failed while trying to read schema status: the database "%s" '.
'exists, but the current user ("%s") does not have permission to '.
'access it. GRANT the current user more permissions, or use a '.
'different user.',
$this->getDatabaseName('meta_data'),
$this->getUser()),
$ex);
} catch (AphrontQueryException $ex) {
return null;
}
}
public function getPatchDurations() {
try {
$rows = queryfx_all(
$this->getConn('meta_data'),
'SELECT patch, duration FROM %T WHERE duration IS NOT NULL',
self::TABLE_STATUS);
return ipull($rows, 'duration', 'patch');
} catch (AphrontQueryException $ex) {
return array();
}
}
public function createDatabase($fragment) {
$info = $this->getCharsetInfo();
queryfx(
$this->getConn(null),
'CREATE DATABASE IF NOT EXISTS %T COLLATE %T',
$this->getDatabaseName($fragment),
$info[self::COLLATE_TEXT]);
}
public function createTable($fragment, $table, array $cols) {
queryfx(
$this->getConn($fragment),
'CREATE TABLE IF NOT EXISTS %T.%T (%Q) '.
'ENGINE=InnoDB, COLLATE utf8_general_ci',
$this->getDatabaseName($fragment),
$table,
implode(', ', $cols));
}
public function getLegacyPatches(array $patches) {
assert_instances_of($patches, 'PhabricatorStoragePatch');
try {
$row = queryfx_one(
$this->getConn('meta_data'),
'SELECT version FROM %T',
'schema_version');
$version = $row['version'];
} catch (AphrontQueryException $ex) {
return array();
}
$legacy = array();
foreach ($patches as $key => $patch) {
if ($patch->getLegacy() !== false && $patch->getLegacy() <= $version) {
$legacy[] = $key;
}
}
return $legacy;
}
public function markPatchApplied($patch, $duration = null) {
$conn = $this->getConn('meta_data');
queryfx(
$conn,
'INSERT INTO %T (patch, applied) VALUES (%s, %d)',
self::TABLE_STATUS,
$patch,
time());
// We didn't add this column for a long time, so it may not exist yet.
if ($duration !== null) {
try {
queryfx(
$conn,
'UPDATE %T SET duration = %d WHERE patch = %s',
self::TABLE_STATUS,
(int)floor($duration * 1000000),
$patch);
} catch (AphrontQueryException $ex) {
// Just ignore this, as it almost certainly indicates that we just
// don't have the column yet.
}
}
}
public function applyPatch(PhabricatorStoragePatch $patch) {
$type = $patch->getType();
$name = $patch->getName();
switch ($type) {
case 'db':
$this->createDatabase($name);
break;
case 'sql':
$this->applyPatchSQL($name);
break;
case 'php':
$this->applyPatchPHP($name);
break;
default:
throw new Exception(pht("Unable to apply patch of type '%s'.", $type));
}
}
public function applyPatchSQL($sql) {
$sql = Filesystem::readFile($sql);
$queries = preg_split('/;\s+/', $sql);
$queries = array_filter($queries);
$conn = $this->getConn(null);
$charset_info = $this->getCharsetInfo();
foreach ($charset_info as $key => $value) {
$charset_info[$key] = qsprintf($conn, '%T', $value);
}
foreach ($queries as $query) {
$query = str_replace('{$NAMESPACE}', $this->namespace, $query);
foreach ($charset_info as $key => $value) {
$query = str_replace('{$'.$key.'}', $value, $query);
}
try {
// NOTE: We're using the unsafe "%Z" conversion here. There's no
// avoiding it since we're executing raw text files full of SQL.
queryfx($conn, '%Z', $query);
} catch (AphrontAccessDeniedQueryException $ex) {
throw new PhutilProxyException(
pht(
'Unable to access a required database or table. This almost '.
'always means that the user you are connecting with ("%s") does '.
'not have sufficient permissions granted in MySQL. You can '.
'use `bin/storage databases` to get a list of all databases '.
'permission is required on.',
$this->getUser()),
$ex);
}
}
}
public function applyPatchPHP($script) {
$schema_conn = $this->getConn(null);
require_once $script;
}
public function isCharacterSetAvailable($character_set) {
if ($character_set == 'utf8mb4') {
if ($this->getDisableUTF8MB4()) {
return false;
}
}
$conn = $this->getConn(null);
return self::isCharacterSetAvailableOnConnection($character_set, $conn);
}
public function getClientCharset() {
if ($this->isCharacterSetAvailable('utf8mb4')) {
return 'utf8mb4';
} else {
return 'utf8';
}
}
public static function isCharacterSetAvailableOnConnection(
$character_set,
AphrontDatabaseConnection $conn) {
$result = queryfx_one(
$conn,
'SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.CHARACTER_SETS
WHERE CHARACTER_SET_NAME = %s',
$character_set);
return (bool)$result;
}
public function getCharsetInfo() {
if ($this->isCharacterSetAvailable('utf8mb4')) {
// If utf8mb4 is available, we use it with the utf8mb4_unicode_ci
// collation. This is most correct, and will sort properly.
$charset = 'utf8mb4';
$charset_sort = 'utf8mb4';
$charset_full = 'utf8mb4';
$collate_text = 'utf8mb4_bin';
$collate_sort = 'utf8mb4_unicode_ci';
$collate_full = 'utf8mb4_unicode_ci';
} else {
// If utf8mb4 is not available, we use binary for most data. This allows
// us to store 4-byte unicode characters.
//
// It's possible that strings will be truncated in the middle of a
// character on insert. We encourage users to set STRICT_ALL_TABLES
// to prevent this.
//
// For "fulltext" and "sort" columns, we don't use binary.
//
// With "fulltext", we can not use binary because MySQL won't let us.
// We use 3-byte utf8 instead and accept being unable to index 4-byte
// characters.
//
// With "sort", if we use binary we lose case insensitivity (for
// example, "ALincoln@logcabin.com" and "alincoln@logcabin.com" would no
// longer be identified as the same email address). This can be very
// confusing and is far worse overall than not supporting 4-byte unicode
// characters, so we use 3-byte utf8 and accept limited 4-byte support as
// a tradeoff to get sensible collation behavior. Many columns where
// collation is important rarely contain 4-byte characters anyway, so we
// are not giving up too much.
$charset = 'binary';
$charset_sort = 'utf8';
$charset_full = 'utf8';
$collate_text = 'binary';
$collate_sort = 'utf8_general_ci';
$collate_full = 'utf8_general_ci';
}
return array(
self::CHARSET_DEFAULT => $charset,
self::CHARSET_SORT => $charset_sort,
self::CHARSET_FULLTEXT => $charset_full,
self::COLLATE_TEXT => $collate_text,
self::COLLATE_SORT => $collate_sort,
self::COLLATE_FULLTEXT => $collate_full,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/PhabricatorStoragePatch.php | src/infrastructure/storage/management/PhabricatorStoragePatch.php | <?php
final class PhabricatorStoragePatch extends Phobject {
private $key;
private $fullKey;
private $name;
private $type;
private $after;
private $legacy;
private $dead;
private $phase;
const PHASE_DEFAULT = 'default';
const PHASE_WORKER = 'worker';
public function __construct(array $dict) {
$this->key = $dict['key'];
$this->type = $dict['type'];
$this->fullKey = $dict['fullKey'];
$this->legacy = $dict['legacy'];
$this->name = $dict['name'];
$this->after = $dict['after'];
$this->dead = $dict['dead'];
$this->phase = $dict['phase'];
}
public function getLegacy() {
return $this->legacy;
}
public function getAfter() {
return $this->after;
}
public function getType() {
return $this->type;
}
public function getName() {
return $this->name;
}
public function getFullKey() {
return $this->fullKey;
}
public function getKey() {
return $this->key;
}
public function getPhase() {
return $this->phase;
}
public function isDead() {
return $this->dead;
}
public function getIsGlobalPatch() {
return ($this->getType() == 'php');
}
public static function getPhaseList() {
return array_keys(self::getPhaseMap());
}
public static function getDefaultPhase() {
return self::PHASE_DEFAULT;
}
private static function getPhaseMap() {
return array(
self::PHASE_DEFAULT => array(
'order' => 0,
),
self::PHASE_WORKER => array(
'order' => 1,
),
);
}
public function newSortVector() {
$map = self::getPhaseMap();
$phase = $this->getPhase();
return id(new PhutilSortVector())
->addInt($map[$phase]['order']);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementQuickstartWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementQuickstartWorkflow.php | <?php
final class PhabricatorStorageManagementQuickstartWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('quickstart')
->setExamples('**quickstart** [__options__]')
->setSynopsis(
pht(
'Generate a new quickstart database dump. This command is mostly '.
'useful for internal development.'))
->setArguments(
array(
array(
'name' => 'output',
'param' => 'file',
'help' => pht('Specify output file to write.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
parent::execute($args);
$output = $args->getArg('output');
if (!$output) {
throw new PhutilArgumentUsageException(
pht(
'Specify a file to write with `%s`.',
'--output'));
}
$namespace = 'phabricator_quickstart_'.Filesystem::readRandomCharacters(8);
$bin = dirname(phutil_get_library_root('phabricator')).'/bin/storage';
// We don't care which database we're using to generate a quickstart file,
// since all of the schemata should be identical.
$api = $this->getAnyAPI();
$ref = $api->getRef();
$ref_key = $ref->getRefKey();
if (!$api->isCharacterSetAvailable('utf8mb4')) {
throw new PhutilArgumentUsageException(
pht(
'You can only generate a new quickstart file if MySQL supports '.
'the %s character set (available in MySQL 5.5 and newer). The '.
'configured server does not support %s.',
'utf8mb4',
'utf8mb4'));
}
$err = phutil_passthru(
'%s upgrade --force --no-quickstart --namespace %s --ref %s',
$bin,
$namespace,
$ref_key);
if ($err) {
return $err;
}
$err = phutil_passthru(
'%s adjust --force --namespace %s --ref %s',
$bin,
$namespace,
$ref_key);
if ($err) {
return $err;
}
$tmp = new TempFile();
$err = phutil_passthru(
'%s dump --namespace %s --ref %s > %s',
$bin,
$namespace,
$ref_key,
$tmp);
if ($err) {
return $err;
}
$err = phutil_passthru(
'%s destroy --force --namespace %s --ref %s',
$bin,
$namespace,
$ref_key);
if ($err) {
return $err;
}
$dump = Filesystem::readFile($tmp);
$dump = str_replace(
$namespace,
'{$NAMESPACE}',
$dump);
// NOTE: This is a hack. We can not use `binary` for these columns, because
// they are a part of a fulltext index. This regex is avoiding matching a
// possible NOT NULL at the end of the line.
$old = $dump;
$dump = preg_replace(
'/`corpus` longtext CHARACTER SET .*? COLLATE [^\s,]+/mi',
'`corpus` longtext CHARACTER SET {$CHARSET_FULLTEXT} '.
'COLLATE {$COLLATE_FULLTEXT}',
$dump);
if ($dump == $old) {
// If we didn't make any changes, yell about it. We'll produce an invalid
// dump otherwise.
throw new PhutilArgumentUsageException(
pht(
'Failed to apply hack to adjust %s search column!',
'FULLTEXT'));
}
$dump = str_replace(
'utf8mb4_bin',
'{$COLLATE_TEXT}',
$dump);
$dump = str_replace(
'utf8mb4_unicode_ci',
'{$COLLATE_SORT}',
$dump);
$dump = str_replace(
'utf8mb4',
'{$CHARSET}',
$dump);
$old = $dump;
$dump = preg_replace(
'/CHARACTER SET {\$CHARSET} COLLATE {\$COLLATE_SORT}/mi',
'CHARACTER SET {$CHARSET_SORT} COLLATE {$COLLATE_SORT}',
$dump);
if ($dump == $old) {
throw new PhutilArgumentUsageException(
pht('Failed to adjust SORT columns!'));
}
// Strip out a bunch of unnecessary commands which make the dump harder
// to handle and slower to import.
// Remove character set adjustments and key disables.
$dump = preg_replace(
'(^/\*.*\*/;$)m',
'',
$dump);
// Remove comments.
$dump = preg_replace('/^--.*$/m', '', $dump);
// Remove table drops, locks, and unlocks. These are never relevant when
// performing a quickstart.
$dump = preg_replace(
'/^(DROP TABLE|LOCK TABLES|UNLOCK TABLES).*$/m',
'',
$dump);
// Collapse adjacent newlines.
$dump = preg_replace('/\n\s*\n/', "\n", $dump);
$dump = str_replace(';', ";\n", $dump);
$dump = trim($dump)."\n";
Filesystem::writeFile($output, $dump);
$console = PhutilConsole::getConsole();
$console->writeOut(
"**<bg:green> %s </bg>** %s\n",
pht('SUCCESS'),
pht('Wrote fresh quickstart SQL.'));
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementWorkflow.php | <?php
abstract class PhabricatorStorageManagementWorkflow
extends PhabricatorManagementWorkflow {
private $apis = array();
private $dryRun;
private $force;
private $patches;
private $didInitialize;
final public function setAPIs(array $apis) {
$this->apis = $apis;
return $this;
}
final public function getAnyAPI() {
return head($this->getAPIs());
}
final public function getMasterAPIs() {
$apis = $this->getAPIs();
$results = array();
foreach ($apis as $api) {
if ($api->getRef()->getIsMaster()) {
$results[] = $api;
}
}
if (!$results) {
throw new PhutilArgumentUsageException(
pht(
'This command only operates on database masters, but the selected '.
'database hosts do not include any masters.'));
}
return $results;
}
final public function getSingleAPI() {
$apis = $this->getAPIs();
if (count($apis) == 1) {
return head($apis);
}
throw new PhutilArgumentUsageException(
pht(
'This server is configured in cluster mode, with multiple database '.
'hosts. Use "--host" to specify which host you want to operate on.'));
}
final public function getAPIs() {
return $this->apis;
}
final protected function isDryRun() {
return $this->dryRun;
}
final protected function setDryRun($dry_run) {
$this->dryRun = $dry_run;
return $this;
}
final protected function isForce() {
return $this->force;
}
final protected function setForce($force) {
$this->force = $force;
return $this;
}
public function getPatches() {
return $this->patches;
}
public function setPatches(array $patches) {
assert_instances_of($patches, 'PhabricatorStoragePatch');
$this->patches = $patches;
return $this;
}
protected function isReadOnlyWorkflow() {
return false;
}
public function execute(PhutilArgumentParser $args) {
$this->setDryRun($args->getArg('dryrun'));
$this->setForce($args->getArg('force'));
if (!$this->isReadOnlyWorkflow()) {
if (PhabricatorEnv::isReadOnly()) {
if ($this->isForce()) {
PhabricatorEnv::setReadOnly(false, null);
} else {
throw new PhutilArgumentUsageException(
pht(
'This server is currently in read-only mode. Use --force to '.
'override this mode.'));
}
}
}
return $this->didExecute($args);
}
public function didExecute(PhutilArgumentParser $args) {}
private function loadSchemata(PhabricatorStorageManagementAPI $api) {
$query = id(new PhabricatorConfigSchemaQuery());
$ref = $api->getRef();
$ref_key = $ref->getRefKey();
$query->setAPIs(array($api));
$query->setRefs(array($ref));
$actual = $query->loadActualSchemata();
$expect = $query->loadExpectedSchemata();
$comp = $query->buildComparisonSchemata($expect, $actual);
return array(
$comp[$ref_key],
$expect[$ref_key],
$actual[$ref_key],
);
}
final protected function adjustSchemata(
PhabricatorStorageManagementAPI $api,
$unsafe) {
$lock = $this->lock($api);
try {
$err = $this->doAdjustSchemata($api, $unsafe);
// Analyze tables if we're not doing a dry run and adjustments are either
// all clear or have minor errors like surplus tables.
if (!$this->dryRun) {
$should_analyze = (($err == 0) || ($err == 2));
if ($should_analyze) {
$this->analyzeTables($api);
}
}
} catch (Exception $ex) {
$lock->unlock();
throw $ex;
}
$lock->unlock();
return $err;
}
private function doAdjustSchemata(
PhabricatorStorageManagementAPI $api,
$unsafe) {
$console = PhutilConsole::getConsole();
$console->writeOut(
"%s\n",
pht(
'Verifying database schemata on "%s"...',
$api->getRef()->getRefKey()));
list($adjustments, $errors) = $this->findAdjustments($api);
if (!$adjustments) {
$console->writeOut(
"%s\n",
pht('Found no adjustments for schemata.'));
return $this->printErrors($errors, 0);
}
if (!$this->force && !$api->isCharacterSetAvailable('utf8mb4')) {
$message = pht(
"You have an old version of MySQL (older than 5.5) which does not ".
"support the utf8mb4 character set. We strongly recommend upgrading ".
"to 5.5 or newer.\n\n".
"If you apply adjustments now and later update MySQL to 5.5 or newer, ".
"you'll need to apply adjustments again (and they will take a long ".
"time).\n\n".
"You can exit this workflow, update MySQL now, and then run this ".
"workflow again. This is recommended, but may cause a lot of downtime ".
"right now.\n\n".
"You can exit this workflow, continue using this software without ".
"applying adjustments, update MySQL at a later date, and then run ".
"this workflow again. This is also a good approach, and will let you ".
"delay downtime until later.\n\n".
"You can proceed with this workflow, and then optionally update ".
"MySQL at a later date. After you do, you'll need to apply ".
"adjustments again.\n\n".
"For more information, see \"Managing Storage Adjustments\" in ".
"the documentation.");
$console->writeOut(
"\n**<bg:yellow> %s </bg>**\n\n%s\n",
pht('OLD MySQL VERSION'),
phutil_console_wrap($message));
$prompt = pht('Continue with old MySQL version?');
if (!phutil_console_confirm($prompt, $default_no = true)) {
return;
}
}
$table = id(new PhutilConsoleTable())
->addColumn('database', array('title' => pht('Database')))
->addColumn('table', array('title' => pht('Table')))
->addColumn('name', array('title' => pht('Name')))
->addColumn('info', array('title' => pht('Issues')));
foreach ($adjustments as $adjust) {
$info = array();
foreach ($adjust['issues'] as $issue) {
$info[] = PhabricatorConfigStorageSchema::getIssueName($issue);
}
$table->addRow(array(
'database' => $adjust['database'],
'table' => idx($adjust, 'table'),
'name' => idx($adjust, 'name'),
'info' => implode(', ', $info),
));
}
$console->writeOut("\n\n");
$table->draw();
if ($this->dryRun) {
$console->writeOut(
"%s\n",
pht('DRYRUN: Would apply adjustments.'));
return 0;
} else if ($this->didInitialize) {
// If we just initialized the database, continue without prompting. This
// is nicer for first-time setup and there's no reasonable reason any
// user would ever answer "no" to the prompt against an empty schema.
} else if (!$this->force) {
$console->writeOut(
"\n%s\n",
pht(
"Found %s adjustment(s) to apply, detailed above.\n\n".
"You can review adjustments in more detail from the web interface, ".
"in Config > Database Status. To better understand the adjustment ".
"workflow, see \"Managing Storage Adjustments\" in the ".
"documentation.\n\n".
"MySQL needs to copy table data to make some adjustments, so these ".
"migrations may take some time.",
phutil_count($adjustments)));
$prompt = pht('Apply these schema adjustments?');
if (!phutil_console_confirm($prompt, $default_no = true)) {
return 1;
}
}
$console->writeOut(
"%s\n",
pht('Applying schema adjustments...'));
$conn = $api->getConn(null);
if ($unsafe) {
queryfx($conn, 'SET SESSION sql_mode = %s', '');
} else {
queryfx($conn, 'SET SESSION sql_mode = %s', 'STRICT_ALL_TABLES');
}
$failed = array();
// We make changes in several phases.
$phases = array(
// Drop surplus autoincrements. This allows us to drop primary keys on
// autoincrement columns.
'drop_auto',
// Drop all keys we're going to adjust. This prevents them from
// interfering with column changes.
'drop_keys',
// Apply all database, table, and column changes.
'main',
// Restore adjusted keys.
'add_keys',
// Add missing autoincrements.
'add_auto',
);
$bar = id(new PhutilConsoleProgressBar())
->setTotal(count($adjustments) * count($phases));
foreach ($phases as $phase) {
foreach ($adjustments as $adjust) {
try {
switch ($adjust['kind']) {
case 'database':
if ($phase == 'main') {
queryfx(
$conn,
'ALTER DATABASE %T CHARACTER SET = %s COLLATE = %s',
$adjust['database'],
$adjust['charset'],
$adjust['collation']);
}
break;
case 'table':
if ($phase == 'main') {
queryfx(
$conn,
'ALTER TABLE %T.%T COLLATE = %s, ENGINE = %s',
$adjust['database'],
$adjust['table'],
$adjust['collation'],
$adjust['engine']);
}
break;
case 'column':
$apply = false;
$auto = false;
$new_auto = idx($adjust, 'auto');
if ($phase == 'drop_auto') {
if ($new_auto === false) {
$apply = true;
$auto = false;
}
} else if ($phase == 'main') {
$apply = true;
if ($new_auto === false) {
$auto = false;
} else {
$auto = $adjust['is_auto'];
}
} else if ($phase == 'add_auto') {
if ($new_auto === true) {
$apply = true;
$auto = true;
}
}
if ($apply) {
$parts = array();
if ($auto) {
$parts[] = qsprintf(
$conn,
'AUTO_INCREMENT');
}
if ($adjust['charset']) {
switch ($adjust['charset']) {
case 'binary':
$charset_value = qsprintf($conn, 'binary');
break;
case 'utf8':
$charset_value = qsprintf($conn, 'utf8');
break;
case 'utf8mb4':
$charset_value = qsprintf($conn, 'utf8mb4');
break;
default:
throw new Exception(
pht(
'Unsupported character set "%s".',
$adjust['charset']));
}
switch ($adjust['collation']) {
case 'binary':
$collation_value = qsprintf($conn, 'binary');
break;
case 'utf8_general_ci':
$collation_value = qsprintf($conn, 'utf8_general_ci');
break;
case 'utf8mb4_bin':
$collation_value = qsprintf($conn, 'utf8mb4_bin');
break;
case 'utf8mb4_unicode_ci':
$collation_value = qsprintf($conn, 'utf8mb4_unicode_ci');
break;
default:
throw new Exception(
pht(
'Unsupported collation set "%s".',
$adjust['collation']));
}
$parts[] = qsprintf(
$conn,
'CHARACTER SET %Q COLLATE %Q',
$charset_value,
$collation_value);
}
if ($parts) {
$parts = qsprintf($conn, '%LJ', $parts);
} else {
$parts = qsprintf($conn, '');
}
if ($adjust['nullable']) {
$nullable = qsprintf($conn, 'NULL');
} else {
$nullable = qsprintf($conn, 'NOT NULL');
}
// TODO: We're using "%Z" here for the column type, which is
// technically unsafe. It would be nice to be able to use "%Q"
// instead, but this requires a fair amount of legwork to
// enumerate all column types.
queryfx(
$conn,
'ALTER TABLE %T.%T MODIFY %T %Z %Q %Q',
$adjust['database'],
$adjust['table'],
$adjust['name'],
$adjust['type'],
$parts,
$nullable);
}
break;
case 'key':
if (($phase == 'drop_keys') && $adjust['exists']) {
if ($adjust['name'] == 'PRIMARY') {
$key_name = qsprintf($conn, 'PRIMARY KEY');
} else {
$key_name = qsprintf($conn, 'KEY %T', $adjust['name']);
}
queryfx(
$conn,
'ALTER TABLE %T.%T DROP %Q',
$adjust['database'],
$adjust['table'],
$key_name);
}
if (($phase == 'add_keys') && $adjust['keep']) {
// Different keys need different creation syntax. Notable
// special cases are primary keys and fulltext keys.
if ($adjust['name'] == 'PRIMARY') {
$key_name = qsprintf($conn, 'PRIMARY KEY');
} else if ($adjust['indexType'] == 'FULLTEXT') {
$key_name = qsprintf($conn, 'FULLTEXT %T', $adjust['name']);
} else {
if ($adjust['unique']) {
$key_name = qsprintf(
$conn,
'UNIQUE KEY %T',
$adjust['name']);
} else {
$key_name = qsprintf(
$conn,
'/* NONUNIQUE */ KEY %T',
$adjust['name']);
}
}
queryfx(
$conn,
'ALTER TABLE %T.%T ADD %Q (%LK)',
$adjust['database'],
$adjust['table'],
$key_name,
$adjust['columns']);
}
break;
default:
throw new Exception(
pht('Unknown schema adjustment kind "%s"!', $adjust['kind']));
}
} catch (AphrontQueryException $ex) {
$failed[] = array($adjust, $ex);
}
$bar->update(1);
}
}
$bar->done();
if (!$failed) {
$console->writeOut(
"%s\n",
pht('Completed applying all schema adjustments.'));
$err = 0;
} else {
$table = id(new PhutilConsoleTable())
->addColumn('target', array('title' => pht('Target')))
->addColumn('error', array('title' => pht('Error')));
foreach ($failed as $failure) {
list($adjust, $ex) = $failure;
$pieces = array_select_keys(
$adjust,
array('database', 'table', 'name'));
$pieces = array_filter($pieces);
$target = implode('.', $pieces);
$table->addRow(
array(
'target' => $target,
'error' => $ex->getMessage(),
));
}
$console->writeOut("\n");
$table->draw();
$console->writeOut(
"\n%s\n",
pht('Failed to make some schema adjustments, detailed above.'));
$console->writeOut(
"%s\n",
pht(
'For help troubleshooting adjustments, see "Managing Storage '.
'Adjustments" in the documentation.'));
$err = 1;
}
return $this->printErrors($errors, $err);
}
private function findAdjustments(
PhabricatorStorageManagementAPI $api) {
list($comp, $expect, $actual) = $this->loadSchemata($api);
$issue_charset = PhabricatorConfigStorageSchema::ISSUE_CHARSET;
$issue_collation = PhabricatorConfigStorageSchema::ISSUE_COLLATION;
$issue_columntype = PhabricatorConfigStorageSchema::ISSUE_COLUMNTYPE;
$issue_surpluskey = PhabricatorConfigStorageSchema::ISSUE_SURPLUSKEY;
$issue_missingkey = PhabricatorConfigStorageSchema::ISSUE_MISSINGKEY;
$issue_columns = PhabricatorConfigStorageSchema::ISSUE_KEYCOLUMNS;
$issue_unique = PhabricatorConfigStorageSchema::ISSUE_UNIQUE;
$issue_longkey = PhabricatorConfigStorageSchema::ISSUE_LONGKEY;
$issue_auto = PhabricatorConfigStorageSchema::ISSUE_AUTOINCREMENT;
$issue_engine = PhabricatorConfigStorageSchema::ISSUE_ENGINE;
$adjustments = array();
$errors = array();
foreach ($comp->getDatabases() as $database_name => $database) {
foreach ($this->findErrors($database) as $issue) {
$errors[] = array(
'database' => $database_name,
'issue' => $issue,
);
}
$expect_database = $expect->getDatabase($database_name);
$actual_database = $actual->getDatabase($database_name);
if (!$expect_database || !$actual_database) {
// If there's a real issue here, skip this stuff.
continue;
}
if ($actual_database->getAccessDenied()) {
// If we can't access the database, we can't access the tables either.
continue;
}
$issues = array();
if ($database->hasIssue($issue_charset)) {
$issues[] = $issue_charset;
}
if ($database->hasIssue($issue_collation)) {
$issues[] = $issue_collation;
}
if ($issues) {
$adjustments[] = array(
'kind' => 'database',
'database' => $database_name,
'issues' => $issues,
'charset' => $expect_database->getCharacterSet(),
'collation' => $expect_database->getCollation(),
);
}
foreach ($database->getTables() as $table_name => $table) {
foreach ($this->findErrors($table) as $issue) {
$errors[] = array(
'database' => $database_name,
'table' => $table_name,
'issue' => $issue,
);
}
$expect_table = $expect_database->getTable($table_name);
$actual_table = $actual_database->getTable($table_name);
if (!$expect_table || !$actual_table) {
continue;
}
$issues = array();
if ($table->hasIssue($issue_collation)) {
$issues[] = $issue_collation;
}
if ($table->hasIssue($issue_engine)) {
$issues[] = $issue_engine;
}
if ($issues) {
$adjustments[] = array(
'kind' => 'table',
'database' => $database_name,
'table' => $table_name,
'issues' => $issues,
'collation' => $expect_table->getCollation(),
'engine' => $expect_table->getEngine(),
);
}
foreach ($table->getColumns() as $column_name => $column) {
foreach ($this->findErrors($column) as $issue) {
$errors[] = array(
'database' => $database_name,
'table' => $table_name,
'name' => $column_name,
'issue' => $issue,
);
}
$expect_column = $expect_table->getColumn($column_name);
$actual_column = $actual_table->getColumn($column_name);
if (!$expect_column || !$actual_column) {
continue;
}
$issues = array();
if ($column->hasIssue($issue_collation)) {
$issues[] = $issue_collation;
}
if ($column->hasIssue($issue_charset)) {
$issues[] = $issue_charset;
}
if ($column->hasIssue($issue_columntype)) {
$issues[] = $issue_columntype;
}
if ($column->hasIssue($issue_auto)) {
$issues[] = $issue_auto;
}
if ($issues) {
if ($expect_column->getCharacterSet() === null) {
// For non-text columns, we won't be specifying a collation or
// character set.
$charset = null;
$collation = null;
} else {
$charset = $expect_column->getCharacterSet();
$collation = $expect_column->getCollation();
}
$adjustment = array(
'kind' => 'column',
'database' => $database_name,
'table' => $table_name,
'name' => $column_name,
'issues' => $issues,
'collation' => $collation,
'charset' => $charset,
'type' => $expect_column->getColumnType(),
// NOTE: We don't adjust column nullability because it is
// dangerous, so always use the current nullability.
'nullable' => $actual_column->getNullable(),
// NOTE: This always stores the current value, because we have
// to make these updates separately.
'is_auto' => $actual_column->getAutoIncrement(),
);
if ($column->hasIssue($issue_auto)) {
$adjustment['auto'] = $expect_column->getAutoIncrement();
}
$adjustments[] = $adjustment;
}
}
foreach ($table->getKeys() as $key_name => $key) {
foreach ($this->findErrors($key) as $issue) {
$errors[] = array(
'database' => $database_name,
'table' => $table_name,
'name' => $key_name,
'issue' => $issue,
);
}
$expect_key = $expect_table->getKey($key_name);
$actual_key = $actual_table->getKey($key_name);
$issues = array();
$keep_key = true;
if ($key->hasIssue($issue_surpluskey)) {
$issues[] = $issue_surpluskey;
$keep_key = false;
}
if ($key->hasIssue($issue_missingkey)) {
$issues[] = $issue_missingkey;
}
if ($key->hasIssue($issue_columns)) {
$issues[] = $issue_columns;
}
if ($key->hasIssue($issue_unique)) {
$issues[] = $issue_unique;
}
// NOTE: We can't really fix this, per se, but we may need to remove
// the key to change the column type. In the best case, the new
// column type won't be overlong and recreating the key really will
// fix the issue. In the worst case, we get the right column type and
// lose the key, which is still better than retaining the key having
// the wrong column type.
if ($key->hasIssue($issue_longkey)) {
$issues[] = $issue_longkey;
}
if ($issues) {
$adjustment = array(
'kind' => 'key',
'database' => $database_name,
'table' => $table_name,
'name' => $key_name,
'issues' => $issues,
'exists' => (bool)$actual_key,
'keep' => $keep_key,
);
if ($keep_key) {
$adjustment += array(
'columns' => $expect_key->getColumnNames(),
'unique' => $expect_key->getUnique(),
'indexType' => $expect_key->getIndexType(),
);
}
$adjustments[] = $adjustment;
}
}
}
}
return array($adjustments, $errors);
}
private function findErrors(PhabricatorConfigStorageSchema $schema) {
$result = array();
foreach ($schema->getLocalIssues() as $issue) {
$status = PhabricatorConfigStorageSchema::getIssueStatus($issue);
if ($status == PhabricatorConfigStorageSchema::STATUS_FAIL) {
$result[] = $issue;
}
}
return $result;
}
private function printErrors(array $errors, $default_return) {
if (!$errors) {
return $default_return;
}
$console = PhutilConsole::getConsole();
$table = id(new PhutilConsoleTable())
->addColumn('target', array('title' => pht('Target')))
->addColumn('error', array('title' => pht('Error')));
$any_surplus = false;
$all_surplus = true;
$any_access = false;
$all_access = true;
foreach ($errors as $error) {
$pieces = array_select_keys(
$error,
array('database', 'table', 'name'));
$pieces = array_filter($pieces);
$target = implode('.', $pieces);
$name = PhabricatorConfigStorageSchema::getIssueName($error['issue']);
$issue = $error['issue'];
if ($issue === PhabricatorConfigStorageSchema::ISSUE_SURPLUS) {
$any_surplus = true;
} else {
$all_surplus = false;
}
if ($issue === PhabricatorConfigStorageSchema::ISSUE_ACCESSDENIED) {
$any_access = true;
} else {
$all_access = false;
}
$table->addRow(
array(
'target' => $target,
'error' => $name,
));
}
$console->writeOut("\n");
$table->draw();
$console->writeOut("\n");
$message = array();
if ($all_surplus) {
$message[] = pht(
'You have surplus schemata (extra tables or columns which this '.
'software does not expect). For information on resolving these '.
'issues, see the "Surplus Schemata" section in the "Managing Storage '.
'Adjustments" article in the documentation.');
} else if ($all_access) {
$message[] = pht(
'The user you are connecting to MySQL with does not have the correct '.
'permissions, and can not access some databases or tables that it '.
'needs to be able to access. GRANT the user additional permissions.');
} else {
$message[] = pht(
'The schemata have errors (detailed above) which the adjustment '.
'workflow can not fix.');
if ($any_access) {
$message[] = pht(
'Some of these errors are caused by access control problems. '.
'The user you are connecting with does not have permission to see '.
'all of the database or tables that this software uses. You need to '.
'GRANT the user more permission, or use a different user.');
}
if ($any_surplus) {
$message[] = pht(
'Some of these errors are caused by surplus schemata (extra '.
'tables or columns which this software does not expect). These are '.
'not serious. For information on resolving these issues, see the '.
'"Surplus Schemata" section in the "Managing Storage Adjustments" '.
'article in the documentation.');
}
$message[] = pht(
'If you are not developing %s itself, report this issue to '.
'the upstream.',
PlatformSymbols::getPlatformServerName());
$message[] = pht(
'If you are developing %s, these errors usually indicate '.
'that your schema specifications do not agree with the schemata your '.
'code actually builds.',
PlatformSymbols::getPlatformServerName());
}
$message = implode("\n\n", $message);
if ($all_surplus) {
$console->writeOut(
"**<bg:yellow> %s </bg>**\n\n%s\n",
pht('SURPLUS SCHEMATA'),
phutil_console_wrap($message));
} else if ($all_access) {
$console->writeOut(
"**<bg:yellow> %s </bg>**\n\n%s\n",
pht('ACCESS DENIED'),
phutil_console_wrap($message));
} else {
$console->writeOut(
"**<bg:red> %s </bg>**\n\n%s\n",
pht('SCHEMATA ERRORS'),
phutil_console_wrap($message));
}
return 2;
}
final protected function upgradeSchemata(
array $apis,
$apply_only = null,
$no_quickstart = false,
$init_only = false) {
$locks = array();
foreach ($apis as $api) {
$locks[] = $this->lock($api);
}
try {
$this->doUpgradeSchemata($apis, $apply_only, $no_quickstart, $init_only);
} catch (Exception $ex) {
foreach ($locks as $lock) {
$lock->unlock();
}
throw $ex;
}
foreach ($locks as $lock) {
$lock->unlock();
}
}
private function doUpgradeSchemata(
array $apis,
$apply_only,
$no_quickstart,
$init_only) {
$patches = $this->patches;
$is_dryrun = $this->dryRun;
// We expect that patches should already be sorted properly. However,
// phase behavior will be wrong if they aren't, so make sure.
$patches = msortv($patches, 'newSortVector');
$api_map = array();
foreach ($apis as $api) {
$api_map[$api->getRef()->getRefKey()] = $api;
}
foreach ($api_map as $ref_key => $api) {
$applied = $api->getAppliedPatches();
$needs_init = ($applied === null);
if (!$needs_init) {
continue;
}
if ($is_dryrun) {
echo tsprintf(
"%s\n",
pht(
'DRYRUN: Storage on host "%s" does not exist yet, so it '.
'would be created.',
$ref_key));
continue;
}
if ($apply_only) {
throw new PhutilArgumentUsageException(
pht(
'Storage on host "%s" has not been initialized yet. You must '.
'initialize storage before selectively applying patches.',
$ref_key));
}
// If we're initializing storage for the first time on any host, track
// it so that we can give the user a nicer experience during the
// subsequent adjustment phase.
$this->didInitialize = true;
$legacy = $api->getLegacyPatches($patches);
if ($legacy || $no_quickstart || $init_only) {
// If we have legacy patches, we can't quickstart.
$api->createDatabase('meta_data');
$api->createTable(
'meta_data',
'patch_status',
array(
'patch VARCHAR(255) NOT NULL PRIMARY KEY COLLATE utf8_general_ci',
'applied INT UNSIGNED NOT NULL',
));
foreach ($legacy as $patch) {
$api->markPatchApplied($patch);
}
} else {
echo tsprintf(
"%s\n",
pht(
'Loading quickstart template onto "%s"...',
$ref_key));
$root = dirname(phutil_get_library_root('phabricator'));
$sql = $root.'/resources/sql/quickstart.sql';
$api->applyPatchSQL($sql);
}
}
if ($init_only) {
echo pht('Storage initialized.')."\n";
return 0;
}
$applied_map = array();
$state_map = array();
foreach ($api_map as $ref_key => $api) {
$applied = $api->getAppliedPatches();
// If we still have nothing applied, this is a dry run and we didn't
// actually initialize storage. Here, just do nothing.
if ($applied === null) {
if ($is_dryrun) {
continue;
} else {
throw new Exception(
pht(
'Database initialization on host "%s" applied no patches!',
$ref_key));
}
}
$applied = array_fuse($applied);
$state_map[$ref_key] = $applied;
if ($apply_only) {
if (isset($applied[$apply_only])) {
if (!$this->force && !$is_dryrun) {
echo phutil_console_wrap(
pht(
'Patch "%s" has already been applied on host "%s". Are you '.
'sure you want to apply it again? This may put your storage '.
'in a state that the upgrade scripts can not automatically '.
'manage.',
$apply_only,
$ref_key));
if (!phutil_console_confirm(pht('Apply patch again?'))) {
echo pht('Cancelled.')."\n";
return 1;
}
}
// Mark this patch as not yet applied on this host.
unset($applied[$apply_only]);
}
}
$applied_map[$ref_key] = $applied;
}
// If we're applying only a specific patch, select just that patch.
if ($apply_only) {
$patches = array_select_keys($patches, array($apply_only));
}
// Apply each patch to each database. We apply patches patch-by-patch,
// not database-by-database: for each patch we apply it to every database,
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementStatusWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementStatusWorkflow.php | <?php
final class PhabricatorStorageManagementStatusWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('status')
->setExamples('**status** [__options__]')
->setSynopsis(pht('Show patch application status.'));
}
protected function isReadOnlyWorkflow() {
return true;
}
public function didExecute(PhutilArgumentParser $args) {
foreach ($this->getAPIs() as $api) {
$patches = $this->getPatches();
$applied = $api->getAppliedPatches();
if ($applied === null) {
echo phutil_console_format(
"**%s**: %s\n",
pht('Database Not Initialized'),
pht('Run **%s** to initialize.', './bin/storage upgrade'));
return 1;
}
$ref = $api->getRef();
$table = id(new PhutilConsoleTable())
->setShowHeader(false)
->addColumn('id', array('title' => pht('ID')))
->addColumn('phase', array('title' => pht('Phase')))
->addColumn('host', array('title' => pht('Host')))
->addColumn('status', array('title' => pht('Status')))
->addColumn('duration', array('title' => pht('Duration')))
->addColumn('type', array('title' => pht('Type')))
->addColumn('name', array('title' => pht('Name')));
$durations = $api->getPatchDurations();
foreach ($patches as $patch) {
$duration = idx($durations, $patch->getFullKey());
if ($duration === null) {
$duration = '-';
} else {
$duration = pht('%s us', new PhutilNumber($duration));
}
if (in_array($patch->getFullKey(), $applied)) {
$status = pht('Applied');
} else {
$status = pht('Not Applied');
}
$table->addRow(
array(
'id' => $patch->getFullKey(),
'phase' => $patch->getPhase(),
'host' => $ref->getRefKey(),
'status' => $status,
'duration' => $duration,
'type' => $patch->getType(),
'name' => $patch->getName(),
));
}
$table->draw();
}
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementAdjustWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementAdjustWorkflow.php | <?php
final class PhabricatorStorageManagementAdjustWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('adjust')
->setExamples('**adjust** [__options__]')
->setSynopsis(
pht(
'Make schemata adjustments to correct issues with characters sets, '.
'collations, and keys.'))
->setArguments(
array(
array(
'name' => 'unsafe',
'help' => pht(
'Permit adjustments which truncate data. This option may '.
'destroy some data, but the lost data is usually not '.
'important (most commonly, the ends of very long object '.
'titles).'),
),
));
}
public function didExecute(PhutilArgumentParser $args) {
$unsafe = $args->getArg('unsafe');
foreach ($this->getMasterAPIs() as $api) {
$this->requireAllPatchesApplied($api);
$err = $this->adjustSchemata($api, $unsafe);
if ($err) {
return $err;
}
}
return 0;
}
private function requireAllPatchesApplied(
PhabricatorStorageManagementAPI $api) {
$applied = $api->getAppliedPatches();
if ($applied === null) {
throw new PhutilArgumentUsageException(
pht(
'You have not initialized the database yet. You must initialize '.
'the database before you can adjust schemata. Run `%s` '.
'to initialize the database.',
'storage upgrade'));
}
$applied = array_fuse($applied);
$patches = $this->getPatches();
$patches = mpull($patches, null, 'getFullKey');
$missing = array_diff_key($patches, $applied);
if ($missing) {
throw new PhutilArgumentUsageException(
pht(
'You have not applied all available storage patches yet. You must '.
'apply all available patches before you can adjust schemata. '.
'Run `%s` to show patch status, and `%s` to apply missing patches.',
'storage status',
'storage upgrade'));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementOptimizeWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementOptimizeWorkflow.php | <?php
final class PhabricatorStorageManagementOptimizeWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('optimize')
->setExamples('**optimize**')
->setSynopsis(pht('Run "OPTIMIZE TABLE" on tables to reclaim space.'));
}
public function didExecute(PhutilArgumentParser $args) {
$api = $this->getSingleAPI();
$conn = $api->getConn(null);
$patches = $this->getPatches();
$databases = $api->getDatabaseList($patches, true);
$total_bytes = 0;
foreach ($databases as $database) {
queryfx($conn, 'USE %C', $database);
$tables = queryfx_all($conn, 'SHOW TABLE STATUS');
foreach ($tables as $table) {
$table_name = $table['Name'];
$old_bytes =
$table['Data_length'] +
$table['Index_length'] +
$table['Data_free'];
$this->logInfo(
pht('OPTIMIZE'),
pht(
'Optimizing table "%s"."%s"...',
$database,
$table_name));
$t_start = microtime(true);
queryfx(
$conn,
'OPTIMIZE TABLE %T',
$table_name);
$t_end = microtime(true);
$status = queryfx_one(
$conn,
'SHOW TABLE STATUS LIKE %s',
$table_name);
$new_bytes =
$status['Data_length'] +
$status['Index_length'] +
$status['Data_free'];
$duration_ms = (int)(1000 * ($t_end - $t_start));
if ($old_bytes > $new_bytes) {
$this->logOkay(
pht('DONE'),
pht(
'Compacted table by %s in %sms.',
phutil_format_bytes($old_bytes - $new_bytes),
new PhutilNumber($duration_ms)));
} else {
$this->logInfo(
pht('DONE'),
pht(
'Optimized table (in %sms) but it had little effect.',
new PhutilNumber($duration_ms)));
}
$total_bytes += ($old_bytes - $new_bytes);
}
}
$this->logOkay(
pht('OPTIMIZED'),
pht(
'Completed optimizations, reclaimed %s of disk space.',
phutil_format_bytes($total_bytes)));
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementAnalyzeWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementAnalyzeWorkflow.php | <?php
final class PhabricatorStorageManagementAnalyzeWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('analyze')
->setExamples('**analyze**')
->setSynopsis(
pht('Run "ANALYZE TABLE" on tables to improve performance.'));
}
public function didExecute(PhutilArgumentParser $args) {
$api = $this->getSingleAPI();
$this->analyzeTables($api);
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementShellWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementShellWorkflow.php | <?php
final class PhabricatorStorageManagementShellWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('shell')
->setExamples('**shell** [__options__]')
->setSynopsis(pht('Launch an interactive shell.'));
}
protected function isReadOnlyWorkflow() {
return true;
}
public function execute(PhutilArgumentParser $args) {
$api = $this->getSingleAPI();
list($host, $port) = $this->getBareHostAndPort($api->getHost());
$flag_port = $port
? csprintf('--port %d', $port)
: '';
$flag_password = '';
$password = $api->getPassword();
if ($password) {
if (strlen($password->openEnvelope())) {
$flag_password = csprintf('--password=%P', $password);
}
}
return phutil_passthru(
'mysql --protocol=TCP --default-character-set %R -u %s %C -h %s %C',
$api->getClientCharset(),
$api->getUser(),
$flag_password,
$host,
$flag_port);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementProbeWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementProbeWorkflow.php | <?php
final class PhabricatorStorageManagementProbeWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('probe')
->setExamples('**probe**')
->setSynopsis(pht('Show approximate table sizes.'));
}
protected function isReadOnlyWorkflow() {
return true;
}
public function didExecute(PhutilArgumentParser $args) {
$api = $this->getSingleAPI();
$console = PhutilConsole::getConsole();
$console->writeErr(
"%s\n",
pht('Analyzing table sizes (this may take a moment)...'));
$patches = $this->getPatches();
$databases = $api->getDatabaseList($patches, true);
$conn_r = $api->getConn(null);
$data = array();
foreach ($databases as $database) {
queryfx($conn_r, 'USE %C', $database);
$tables = queryfx_all(
$conn_r,
'SHOW TABLE STATUS');
$tables = ipull($tables, null, 'Name');
$data[$database] = $tables;
}
$totals = array_fill_keys(array_keys($data), 0);
$overall = 0;
foreach ($data as $db => $tables) {
foreach ($tables as $table => $info) {
$table_size = $info['Data_length'] + $info['Index_length'];
$data[$db][$table]['_totalSize'] = $table_size;
$totals[$db] += $table_size;
$overall += $table_size;
}
}
asort($totals);
$table = id(new PhutilConsoleTable())
->setShowHeader(false)
->setPadding(2)
->addColumn('name', array('title' => pht('Database / Table')))
->addColumn(
'size',
array(
'title' => pht('Size'),
'align' => PhutilConsoleTable::ALIGN_RIGHT,
))
->addColumn(
'percentage',
array(
'title' => pht('Percentage'),
'align' => PhutilConsoleTable::ALIGN_RIGHT,
));
foreach ($totals as $db => $size) {
list($database_size, $database_percentage) = $this->formatSize(
$totals[$db],
$overall);
$table->addRow(array(
'name' => tsprintf('**%s**', $db),
'size' => tsprintf('**%s**', $database_size),
'percentage' => tsprintf('**%s**', $database_percentage),
));
$data[$db] = isort($data[$db], '_totalSize');
foreach ($data[$db] as $table_name => $info) {
list($table_size, $table_percentage) = $this->formatSize(
$info['_totalSize'],
$overall);
$table->addRow(array(
'name' => ' '.$table_name,
'size' => $table_size,
'percentage' => $table_percentage,
));
}
}
list($overall_size, $overall_percentage) = $this->formatSize(
$overall,
$overall);
$table->addRow(array(
'name' => tsprintf('**%s**', pht('TOTAL')),
'size' => tsprintf('**%s**', $overall_size),
'percentage' => tsprintf('**%s**', $overall_percentage),
));
$table->draw();
return 0;
}
private function formatSize($n, $o) {
return array(
pht('%s MB', new PhutilNumber($n / (1024 * 1024), 1)),
sprintf('%3.1f%%', 100 * ($n / $o)),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementRenamespaceWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementRenamespaceWorkflow.php | <?php
final class PhabricatorStorageManagementRenamespaceWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('renamespace')
->setExamples(
'**renamespace** [__options__] '.
'--input __dump.sql__ --from __old__ --to __new__ > __out.sql__')
->setSynopsis(pht('Change the database namespace of a .sql dump file.'))
->setArguments(
array(
array(
'name' => 'input',
'param' => 'file',
'help' => pht('SQL dumpfile to process.'),
),
array(
'name' => 'live',
'help' => pht(
'Generate a live dump instead of processing a file on disk.'),
),
array(
'name' => 'from',
'param' => 'namespace',
'help' => pht('Current database namespace used by dumpfile.'),
),
array(
'name' => 'to',
'param' => 'namespace',
'help' => pht('Desired database namespace for output.'),
),
array(
'name' => 'output',
'param' => 'file',
'help' => pht('Write output directly to a file on disk.'),
),
array(
'name' => 'compress',
'help' => pht('Emit gzipped output instead of plain text.'),
),
array(
'name' => 'overwrite',
'help' => pht(
'With __--output__, write to disk even if the file already '.
'exists.'),
),
));
}
protected function isReadOnlyWorkflow() {
return true;
}
public function didExecute(PhutilArgumentParser $args) {
$console = PhutilConsole::getConsole();
$input = $args->getArg('input');
$is_live = $args->getArg('live');
if (!strlen($input) && !$is_live) {
throw new PhutilArgumentUsageException(
pht(
'Specify the dumpfile to read with "--input", or use "--live" to '.
'generate one automatically.'));
}
$from = $args->getArg('from');
if (!strlen($from)) {
throw new PhutilArgumentUsageException(
pht(
'Specify namespace to rename from with %s.',
'--from'));
}
$to = $args->getArg('to');
if (!strlen($to)) {
throw new PhutilArgumentUsageException(
pht(
'Specify namespace to rename to with %s.',
'--to'));
}
$output_file = $args->getArg('output');
$is_overwrite = $args->getArg('overwrite');
$is_compress = $args->getArg('compress');
if ($is_overwrite) {
if ($output_file === null) {
throw new PhutilArgumentUsageException(
pht(
'The "--overwrite" flag can only be used alongside "--output".'));
}
}
if ($output_file !== null) {
if (Filesystem::pathExists($output_file)) {
if (!$is_overwrite) {
throw new PhutilArgumentUsageException(
pht(
'Output file "%s" already exists. Use "--overwrite" '.
'to overwrite.',
$output_file));
}
}
}
if ($is_live) {
$api = $this->getSingleAPI();
$ref_key = $api->getRef()->getRefKey();
$root = dirname(phutil_get_library_root('phabricator'));
$future = new ExecFuture(
'%R dump --ref %s',
$root.'/bin/storage',
$ref_key);
$lines = new LinesOfALargeExecFuture($future);
} else {
$lines = new LinesOfALargeFile($input);
}
if ($output_file === null) {
$file = fopen('php://stdout', 'wb');
$output_name = pht('stdout');
} else {
if ($is_compress) {
$file = gzopen($output_file, 'wb');
} else {
$file = fopen($output_file, 'wb');
}
$output_name = $output_file;
}
if (!$file) {
throw new Exception(
pht(
'Failed to open output file "%s" for writing.',
$output_name));
}
$name_pattern = preg_quote($from, '@');
$patterns = array(
'use' => '@^(USE `)('.$name_pattern.')(_.*)$@',
'create' => '@^(CREATE DATABASE /\*.*?\*/ `)('.$name_pattern.')(_.*)$@',
);
$found = array_fill_keys(array_keys($patterns), 0);
try {
$matches = null;
foreach ($lines as $line) {
foreach ($patterns as $key => $pattern) {
if (preg_match($pattern, $line, $matches)) {
$line = $matches[1].$to.$matches[3];
$found[$key]++;
}
}
$data = $line."\n";
if ($is_compress) {
$bytes = gzwrite($file, $data);
} else {
$bytes = fwrite($file, $data);
}
if ($bytes !== strlen($data)) {
throw new Exception(
pht(
'Failed to write %d byte(s) to "%s".',
new PhutilNumber(strlen($data)),
$output_name));
}
}
if ($is_compress) {
$ok = gzclose($file);
} else {
$ok = fclose($file);
}
if ($ok !== true) {
throw new Exception(
pht(
'Failed to close file "%s".',
$output_file));
}
} catch (Exception $ex) {
try {
if ($output_file !== null) {
Filesystem::remove($output_file);
}
} catch (Exception $ex) {
// Ignore any exception.
}
throw $ex;
}
// Give the user a chance to catch things if the results are crazy.
$console->writeErr(
pht(
'Adjusted **%s** create statements and **%s** use statements.',
new PhutilNumber($found['create']),
new PhutilNumber($found['use']))."\n");
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementDatabasesWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementDatabasesWorkflow.php | <?php
final class PhabricatorStorageManagementDatabasesWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('databases')
->setExamples('**databases** [__options__]')
->setSynopsis(pht('List databases.'));
}
protected function isReadOnlyWorkflow() {
return true;
}
public function didExecute(PhutilArgumentParser $args) {
$api = $this->getAnyAPI();
$patches = $this->getPatches();
$databases = $api->getDatabaseList($patches, true);
echo implode("\n", $databases)."\n";
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementUpgradeWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementUpgradeWorkflow.php | <?php
final class PhabricatorStorageManagementUpgradeWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('upgrade')
->setExamples('**upgrade** [__options__]')
->setSynopsis(pht('Upgrade database schemata.'))
->setArguments(
array(
array(
'name' => 'apply',
'param' => 'patch',
'help' => pht(
'Apply __patch__ explicitly. This is an advanced feature for '.
'development and debugging; you should not normally use this '.
'flag. This skips adjustment.'),
),
array(
'name' => 'no-quickstart',
'help' => pht(
'Build storage patch-by-patch from scratch, even if it could '.
'be loaded from the quickstart template.'),
),
array(
'name' => 'init-only',
'help' => pht(
'Initialize storage only; do not apply patches or adjustments.'),
),
array(
'name' => 'no-adjust',
'help' => pht(
'Do not apply storage adjustments after storage upgrades.'),
),
));
}
public function didExecute(PhutilArgumentParser $args) {
$console = PhutilConsole::getConsole();
$patches = $this->getPatches();
if (!$this->isDryRun() && !$this->isForce()) {
$console->writeOut(
phutil_console_wrap(
pht(
'Before running storage upgrades, you should take down the '.
'web interface and stop any running daemons (you can disable '.
'this warning with %s).',
'--force')));
if (!phutil_console_confirm(pht('Are you ready to continue?'))) {
$console->writeOut("%s\n", pht('Cancelled.'));
return 1;
}
}
$apply_only = $args->getArg('apply');
if ($apply_only) {
if (empty($patches[$apply_only])) {
throw new PhutilArgumentUsageException(
pht(
"%s argument '%s' is not a valid patch. ".
"Use '%s' to show patch status.",
'--apply',
$apply_only,
'./bin/storage status'));
}
}
$no_quickstart = $args->getArg('no-quickstart');
$init_only = $args->getArg('init-only');
$no_adjust = $args->getArg('no-adjust');
$apis = $this->getMasterAPIs();
$this->upgradeSchemata($apis, $apply_only, $no_quickstart, $init_only);
if ($apply_only || $init_only) {
echo tsprintf(
"%s\n",
pht('Declining to synchronize static tables.'));
} else {
echo tsprintf(
"%s\n",
pht('Synchronizing static tables...'));
$this->synchronizeSchemata();
}
if ($no_adjust || $init_only || $apply_only) {
$console->writeOut(
"%s\n",
pht('Declining to apply storage adjustments.'));
} else {
foreach ($apis as $api) {
$err = $this->adjustSchemata($api, false);
if ($err) {
return $err;
}
}
}
return 0;
}
private function synchronizeSchemata() {
// Synchronize the InnoDB fulltext stopwords table from the stopwords file
// on disk.
$table = new PhabricatorSearchDocument();
$conn = $table->establishConnection('w');
$table_ref = PhabricatorSearchDocument::STOPWORDS_TABLE;
$stopwords_database = queryfx_all(
$conn,
'SELECT value FROM %T',
$table_ref);
$stopwords_database = ipull($stopwords_database, 'value', 'value');
$stopwords_path = phutil_get_library_root('phabricator');
$stopwords_path = $stopwords_path.'/../resources/sql/stopwords.txt';
$stopwords_file = Filesystem::readFile($stopwords_path);
$stopwords_file = phutil_split_lines($stopwords_file, false);
$stopwords_file = array_fuse($stopwords_file);
$rem_words = array_diff_key($stopwords_database, $stopwords_file);
if ($rem_words) {
queryfx(
$conn,
'DELETE FROM %T WHERE value IN (%Ls)',
$table_ref,
$rem_words);
}
$add_words = array_diff_key($stopwords_file, $stopwords_database);
if ($add_words) {
foreach ($add_words as $word) {
queryfx(
$conn,
'INSERT IGNORE INTO %T (value) VALUES (%s)',
$table_ref,
$word);
}
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementDumpWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementDumpWorkflow.php | <?php
final class PhabricatorStorageManagementDumpWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('dump')
->setExamples('**dump** [__options__]')
->setSynopsis(pht('Dump all data in storage to stdout.'))
->setArguments(
array(
array(
'name' => 'for-replica',
'help' => pht(
'Add __--master-data__ to the __mysqldump__ command, '.
'generating a CHANGE MASTER statement in the output. This '.
'option also dumps all data, including caches.'),
),
array(
'name' => 'output',
'param' => 'file',
'help' => pht(
'Write output directly to disk. This handles errors better '.
'than using pipes. Use with __--compress__ to gzip the '.
'output.'),
),
array(
'name' => 'compress',
'help' => pht(
'With __--output__, write a compressed file to disk instead '.
'of a plaintext file.'),
),
array(
'name' => 'no-indexes',
'help' => pht(
'Do not dump data in rebuildable index tables. This means '.
'backups are smaller and faster, but you will need to manually '.
'rebuild indexes after performing a restore.'),
),
array(
'name' => 'overwrite',
'help' => pht(
'With __--output__, overwrite the output file if it already '.
'exists.'),
),
array(
'name' => 'database',
'param' => 'database-name',
'help' => pht(
'Dump only tables in the named database (or databases, if '.
'the flag is repeated). Specify database names without the '.
'namespace prefix (that is: use "differential", not '.
'"phabricator_differential").'),
'repeat' => true,
),
));
}
protected function isReadOnlyWorkflow() {
return true;
}
public function didExecute(PhutilArgumentParser $args) {
$output_file = $args->getArg('output');
$is_compress = $args->getArg('compress');
$is_overwrite = $args->getArg('overwrite');
$is_noindex = $args->getArg('no-indexes');
$is_replica = $args->getArg('for-replica');
$database_filter = $args->getArg('database');
if ($is_compress) {
if ($output_file === null) {
throw new PhutilArgumentUsageException(
pht(
'The "--compress" flag can only be used alongside "--output".'));
}
if (!function_exists('gzopen')) {
throw new PhutilArgumentUsageException(
pht(
'The "--compress" flag requires the PHP "zlib" extension, but '.
'that extension is not available. Install the extension or '.
'omit the "--compress" option.'));
}
}
if ($is_overwrite) {
if ($output_file === null) {
throw new PhutilArgumentUsageException(
pht(
'The "--overwrite" flag can only be used alongside "--output".'));
}
}
if ($is_replica && $is_noindex) {
throw new PhutilArgumentUsageException(
pht(
'The "--for-replica" flag can not be used with the '.
'"--no-indexes" flag. Replication dumps must contain a complete '.
'representation of database state.'));
}
if ($output_file !== null) {
if (Filesystem::pathExists($output_file)) {
if (!$is_overwrite) {
throw new PhutilArgumentUsageException(
pht(
'Output file "%s" already exists. Use "--overwrite" '.
'to overwrite.',
$output_file));
}
}
}
$api = $this->getSingleAPI();
$patches = $this->getPatches();
$applied = $api->getAppliedPatches();
if ($applied === null) {
throw new PhutilArgumentUsageException(
pht(
'There is no database storage initialized in the current storage '.
'namespace ("%s"). Use "bin/storage upgrade" to initialize '.
'storage or use "--namespace" to choose a different namespace.',
$api->getNamespace()));
}
$ref = $api->getRef();
$ref_key = $ref->getRefKey();
$schemata_query = id(new PhabricatorConfigSchemaQuery())
->setAPIs(array($api))
->setRefs(array($ref));
$actual_map = $schemata_query->loadActualSchemata();
$expect_map = $schemata_query->loadExpectedSchemata();
$schemata = $actual_map[$ref_key];
$expect = $expect_map[$ref_key];
if ($database_filter) {
$internal_names = array();
$expect_databases = $expect->getDatabases();
foreach ($expect_databases as $expect_database) {
$database_name = $expect_database->getName();
$internal_name = $api->getInternalDatabaseName($database_name);
if ($internal_name !== null) {
$internal_names[$internal_name] = $database_name;
}
}
ksort($internal_names);
$seen = array();
foreach ($database_filter as $filter) {
if (!isset($internal_names[$filter])) {
throw new PhutilArgumentUsageException(
pht(
'Database "%s" is unknown. This script can only dump '.
'databases known to the current version of this software. '.
'Valid databases are: %s.',
$filter,
implode(', ', array_keys($internal_names))));
}
if (isset($seen[$filter])) {
throw new PhutilArgumentUsageException(
pht(
'Database "%s" is specified more than once. Specify each '.
'database at most once.',
$filter));
}
$seen[$filter] = true;
}
$dump_databases = array_select_keys($internal_names, $database_filter);
$dump_databases = array_fuse($dump_databases);
} else {
$dump_databases = array_keys($schemata->getDatabases());
$dump_databases = array_fuse($dump_databases);
}
$with_caches = $is_replica;
$with_indexes = !$is_noindex;
$targets = array();
foreach ($schemata->getDatabases() as $database_name => $database) {
if (!isset($dump_databases[$database_name])) {
continue;
}
$expect_database = $expect->getDatabase($database_name);
foreach ($database->getTables() as $table_name => $table) {
// NOTE: It's possible for us to find tables in these database which
// we don't expect to be there. For example, an older version of
// Phabricator may have had a table that was later dropped. We assume
// these are data tables and always dump them, erring on the side of
// caution.
$persistence = PhabricatorConfigTableSchema::PERSISTENCE_DATA;
if ($expect_database) {
$expect_table = $expect_database->getTable($table_name);
if ($expect_table) {
$persistence = $expect_table->getPersistenceType();
}
}
switch ($persistence) {
case PhabricatorConfigTableSchema::PERSISTENCE_CACHE:
// When dumping tables, leave the data in cache tables in the
// database. This will be automatically rebuild after the data
// is restored and does not need to be persisted in backups.
$with_data = $with_caches;
break;
case PhabricatorConfigTableSchema::PERSISTENCE_INDEX:
// When dumping tables, leave index data behind of the caller
// specified "--no-indexes". These tables can be rebuilt manually
// from other tables, but do not rebuild automatically.
$with_data = $with_indexes;
break;
case PhabricatorConfigTableSchema::PERSISTENCE_DATA:
default:
$with_data = true;
break;
}
$targets[] = array(
'database' => $database_name,
'table' => $table_name,
'data' => $with_data,
);
}
}
list($host, $port) = $this->getBareHostAndPort($api->getHost());
$has_password = false;
$password = $api->getPassword();
if ($password) {
if (strlen($password->openEnvelope())) {
$has_password = true;
}
}
$argv = array();
$argv[] = '--hex-blob';
$argv[] = '--single-transaction';
$argv[] = '--default-character-set';
$argv[] = $api->getClientCharset();
if ($is_replica) {
$argv[] = '--master-data';
}
$argv[] = '-u';
$argv[] = $api->getUser();
$argv[] = '-h';
$argv[] = $host;
// MySQL's default "max_allowed_packet" setting is fairly conservative
// (16MB). If we try to dump a row which is larger than this limit, the
// dump will fail.
// We encourage users to increase this limit during setup, but modifying
// the "[mysqld]" section of the configuration file (instead of
// "[mysqldump]" section) won't apply to "mysqldump" and we can not easily
// detect what the "mysqldump" setting is.
// Since no user would ever reasonably want a dump to fail because a row
// was too large, just manually force this setting to the largest supported
// value.
$argv[] = '--max-allowed-packet';
$argv[] = '1G';
if ($port) {
$argv[] = '--port';
$argv[] = $port;
}
$commands = array();
foreach ($targets as $target) {
$target_argv = $argv;
if (!$target['data']) {
$target_argv[] = '--no-data';
}
if ($has_password) {
$command = csprintf(
'mysqldump -p%P %Ls -- %R %R',
$password,
$target_argv,
$target['database'],
$target['table']);
} else {
$command = csprintf(
'mysqldump %Ls -- %R %R',
$target_argv,
$target['database'],
$target['table']);
}
$commands[] = array(
'command' => $command,
'database' => $target['database'],
);
}
// Decrease the CPU priority of this process so it doesn't contend with
// other more important things.
if (function_exists('proc_nice')) {
proc_nice(19);
}
// If we are writing to a file, stream the command output to disk. This
// mode makes sure the whole command fails if there's an error (commonly,
// a full disk). See T6996 for discussion.
if ($output_file === null) {
$file = null;
} else if ($is_compress) {
$file = gzopen($output_file, 'wb1');
} else {
$file = fopen($output_file, 'wb');
}
if (($output_file !== null) && !$file) {
throw new Exception(
pht(
'Failed to open file "%s" for writing.',
$file));
}
$created = array();
try {
foreach ($commands as $spec) {
// Because we're dumping database-by-database, we need to generate our
// own CREATE DATABASE and USE statements.
$database = $spec['database'];
$preamble = array();
if (!isset($created[$database])) {
$preamble[] =
"CREATE DATABASE /*!32312 IF NOT EXISTS*/ `{$database}` ".
"/*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin */;\n";
$created[$database] = true;
}
$preamble[] = "USE `{$database}`;\n";
$preamble = implode('', $preamble);
$this->writeData($preamble, $file, $is_compress, $output_file);
// See T13328. The "mysql" command may produce output very quickly.
// Don't buffer more than a fixed amount.
$future = id(new ExecFuture('%C', $spec['command']))
->setReadBufferSize(32 * 1024 * 1024);
$iterator = id(new FutureIterator(array($future)))
->setUpdateInterval(0.010);
foreach ($iterator as $ready) {
list($stdout, $stderr) = $future->read();
$future->discardBuffers();
if (strlen($stderr)) {
fwrite(STDERR, $stderr);
}
$this->writeData($stdout, $file, $is_compress, $output_file);
if ($ready !== null) {
$ready->resolvex();
}
}
}
if (!$file) {
$ok = true;
} else if ($is_compress) {
$ok = gzclose($file);
} else {
$ok = fclose($file);
}
if ($ok !== true) {
throw new Exception(
pht(
'Failed to close file "%s".',
$output_file));
}
} catch (Exception $ex) {
// If we might have written a partial file to disk, try to remove it so
// we don't leave any confusing artifacts laying around.
try {
if ($file !== null) {
Filesystem::remove($output_file);
}
} catch (Exception $ex) {
// Ignore any errors we hit.
}
throw $ex;
}
return 0;
}
private function writeData($data, $file, $is_compress, $output_file) {
if (!strlen($data)) {
return;
}
if (!$file) {
$ok = fwrite(STDOUT, $data);
} else if ($is_compress) {
$ok = gzwrite($file, $data);
} else {
$ok = fwrite($file, $data);
}
if ($ok !== strlen($data)) {
throw new Exception(
pht(
'Failed to write %d byte(s) to file "%s".',
new PhutilNumber(strlen($data)),
$output_file));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementPartitionWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementPartitionWorkflow.php | <?php
final class PhabricatorStorageManagementPartitionWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('partition')
->setExamples('**partition** [__options__]')
->setSynopsis(pht('Commit partition configuration to databases.'))
->setArguments(array());
}
public function didExecute(PhutilArgumentParser $args) {
echo tsprintf(
"%s\n",
pht('Committing configured partition map to databases...'));
foreach ($this->getMasterAPIs() as $api) {
$ref = $api->getRef();
$conn = $ref->newManagementConnection();
$state = $ref->getPartitionStateForCommit();
queryfx(
$conn,
'INSERT INTO %T.%T (stateKey, stateValue) VALUES (%s, %s)
ON DUPLICATE KEY UPDATE stateValue = VALUES(stateValue)',
$api->getDatabaseName('meta_data'),
PhabricatorStorageManagementAPI::TABLE_HOSTSTATE,
'cluster.databases',
$state);
echo tsprintf(
"%s\n",
pht(
'Wrote configuration on database host "%s".',
$ref->getRefKey()));
}
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementDestroyWorkflow.php | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementDestroyWorkflow.php | <?php
final class PhabricatorStorageManagementDestroyWorkflow
extends PhabricatorStorageManagementWorkflow {
protected function didConstruct() {
$this
->setName('destroy')
->setExamples('**destroy** [__options__]')
->setSynopsis(pht('Permanently destroy all storage and data.'))
->setArguments(
array(
array(
'name' => 'unittest-fixtures',
'help' => pht(
'Restrict **destroy** operations to databases created '.
'by %s test fixtures.',
'PhabricatorTestCase'),
),
));
}
public function didExecute(PhutilArgumentParser $args) {
$api = $this->getSingleAPI();
$host_display = $api->getDisplayName();
if (!$this->isDryRun() && !$this->isForce()) {
if ($args->getArg('unittest-fixtures')) {
$warning = pht(
'Are you completely sure you really want to destroy all unit '.
'test fixure data on host "%s"? This operation can not be undone.',
$host_display);
echo tsprintf(
'%B',
id(new PhutilConsoleBlock())
->addParagraph($warning)
->drawConsoleString());
if (!phutil_console_confirm(pht('Destroy all unit test data?'))) {
$this->logFail(
pht('CANCELLED'),
pht('User cancelled operation.'));
exit(1);
}
} else {
$warning = pht(
'Are you completely sure you really want to permanently destroy '.
'all storage for %s data on host "%s"? This operation '.
'can not be undone and your data will not be recoverable if '.
'you proceed.',
PlatformSymbols::getPlatformServerName(),
$host_display);
echo tsprintf(
'%B',
id(new PhutilConsoleBlock())
->addParagraph($warning)
->drawConsoleString());
if (!phutil_console_confirm(pht('Permanently destroy all data?'))) {
$this->logFail(
pht('CANCELLED'),
pht('User cancelled operation.'));
exit(1);
}
if (!phutil_console_confirm(pht('Really destroy all data forever?'))) {
$this->logFail(
pht('CANCELLED'),
pht('User cancelled operation.'));
exit(1);
}
}
}
$patches = $this->getPatches();
if ($args->getArg('unittest-fixtures')) {
$conn = $api->getConn(null);
$databases = queryfx_all(
$conn,
'SELECT DISTINCT(TABLE_SCHEMA) AS db '.
'FROM INFORMATION_SCHEMA.TABLES '.
'WHERE TABLE_SCHEMA LIKE %>',
PhabricatorTestCase::NAMESPACE_PREFIX);
$databases = ipull($databases, 'db');
} else {
$databases = $api->getDatabaseList($patches);
$databases[] = $api->getDatabaseName('meta_data');
// These are legacy databases that were dropped long ago. See T2237.
$databases[] = $api->getDatabaseName('phid');
$databases[] = $api->getDatabaseName('directory');
}
asort($databases);
foreach ($databases as $database) {
if ($this->isDryRun()) {
$this->logInfo(
pht('DRY RUN'),
pht(
'Would drop database "%s" on host "%s".',
$database,
$host_display));
} else {
$this->logWarn(
pht('DESTROY'),
pht(
'Dropping database "%s" on host "%s"...',
$database,
$host_display));
queryfx(
$api->getConn(null),
'DROP DATABASE IF EXISTS %T',
$database);
}
}
if (!$this->isDryRun()) {
$this->logOkay(
pht('DONE'),
pht(
'Storage on "%s" was destroyed.',
$host_display));
}
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | <?php
/**
* @task config Configuring Storage
*/
abstract class PhabricatorLiskDAO extends LiskDAO {
private static $namespaceStack = array();
private $forcedNamespace;
const ATTACHABLE = '<attachable>';
const CONFIG_APPLICATION_SERIALIZERS = 'phabricator/serializers';
/* -( Configuring Storage )------------------------------------------------ */
/**
* @task config
*/
public static function pushStorageNamespace($namespace) {
self::$namespaceStack[] = $namespace;
}
/**
* @task config
*/
public static function popStorageNamespace() {
array_pop(self::$namespaceStack);
}
/**
* @task config
*/
public static function getDefaultStorageNamespace() {
return PhabricatorEnv::getEnvConfig('storage.default-namespace');
}
/**
* @task config
*/
public static function getStorageNamespace() {
$namespace = end(self::$namespaceStack);
if (!strlen($namespace)) {
$namespace = self::getDefaultStorageNamespace();
}
if ($namespace === null || !strlen($namespace)) {
throw new Exception(pht('No storage namespace configured!'));
}
return $namespace;
}
public function setForcedStorageNamespace($namespace) {
$this->forcedNamespace = $namespace;
return $this;
}
/**
* @task config
*/
protected function establishLiveConnection($mode) {
$namespace = self::getStorageNamespace();
$database = $namespace.'_'.$this->getApplicationName();
$is_readonly = PhabricatorEnv::isReadOnly();
if ($is_readonly && ($mode != 'r')) {
$this->raiseImproperWrite($database);
}
$connection = $this->newClusterConnection(
$this->getApplicationName(),
$database,
$mode);
// TODO: This should be testing if the mode is "r", but that would probably
// break a lot of things. Perform a more narrow test for readonly mode
// until we have greater certainty that this works correctly most of the
// time.
if ($is_readonly) {
$connection->setReadOnly(true);
}
return $connection;
}
private function newClusterConnection($application, $database, $mode) {
$master = PhabricatorDatabaseRef::getMasterDatabaseRefForApplication(
$application);
$master_exception = null;
if ($master && !$master->isSevered()) {
$connection = $master->newApplicationConnection($database);
if ($master->isReachable($connection)) {
return $connection;
} else {
if ($mode == 'w') {
$this->raiseImpossibleWrite($database);
}
PhabricatorEnv::setReadOnly(
true,
PhabricatorEnv::READONLY_UNREACHABLE);
$master_exception = $master->getConnectionException();
}
}
$replica = PhabricatorDatabaseRef::getReplicaDatabaseRefForApplication(
$application);
if ($replica) {
$connection = $replica->newApplicationConnection($database);
$connection->setReadOnly(true);
if ($replica->isReachable($connection)) {
if ($master_exception) {
// If we ended up here as the result of a failover, log the
// exception. This is seriously bad news even if we are able
// to recover from it.
$proxy_exception = new PhutilProxyException(
pht(
'Failed to connect to master database ("%s"), failing over '.
'into read-only mode.',
$database),
$master_exception);
phlog($proxy_exception);
}
return $connection;
}
}
if (!$master && !$replica) {
$this->raiseUnconfigured($database);
}
$this->raiseUnreachable($database, $master_exception);
}
private function raiseImproperWrite($database) {
throw new PhabricatorClusterImproperWriteException(
pht(
'Unable to establish a write-mode connection (to application '.
'database "%s") because this server is in read-only mode. Whatever '.
'you are trying to do does not function correctly in read-only mode.',
$database));
}
private function raiseImpossibleWrite($database) {
throw new PhabricatorClusterImpossibleWriteException(
pht(
'Unable to connect to master database ("%s"). This is a severe '.
'failure; your request did not complete.',
$database));
}
private function raiseUnconfigured($database) {
throw new Exception(
pht(
'Unable to establish a connection to any database host '.
'(while trying "%s"). No masters or replicas are configured.',
$database));
}
private function raiseUnreachable($database, Exception $proxy = null) {
$message = pht(
'Unable to establish a connection to any database host '.
'(while trying "%s"). All masters and replicas are completely '.
'unreachable.',
$database);
if ($proxy) {
$proxy_message = pht(
'%s: %s',
get_class($proxy),
$proxy->getMessage());
$message = $message."\n\n".$proxy_message;
}
throw new PhabricatorClusterStrandedException($message);
}
/**
* @task config
*/
public function getTableName() {
$str = 'phabricator';
$len = strlen($str);
$class = strtolower(get_class($this));
if (!strncmp($class, $str, $len)) {
$class = substr($class, $len);
}
$app = $this->getApplicationName();
if (!strncmp($class, $app, strlen($app))) {
$class = substr($class, strlen($app));
}
if (strlen($class)) {
return $app.'_'.$class;
} else {
return $app;
}
}
/**
* @task config
*/
abstract public function getApplicationName();
protected function getDatabaseName() {
if ($this->forcedNamespace) {
$namespace = $this->forcedNamespace;
} else {
$namespace = self::getStorageNamespace();
}
return $namespace.'_'.$this->getApplicationName();
}
/**
* Break a list of escaped SQL statement fragments (e.g., VALUES lists for
* INSERT, previously built with @{function:qsprintf}) into chunks which will
* fit under the MySQL 'max_allowed_packet' limit.
*
* If a statement is too large to fit within the limit, it is broken into
* its own chunk (but might fail when the query executes).
*/
public static function chunkSQL(
array $fragments,
$limit = null) {
if ($limit === null) {
// NOTE: Hard-code this at 1MB for now, minus a 10% safety buffer.
// Eventually we could query MySQL or let the user configure it.
$limit = (int)((1024 * 1024) * 0.90);
}
$result = array();
$chunk = array();
$len = 0;
$glue_len = strlen(', ');
foreach ($fragments as $fragment) {
if ($fragment instanceof PhutilQueryString) {
$this_len = strlen($fragment->getUnmaskedString());
} else {
$this_len = strlen($fragment);
}
if ($chunk) {
// Chunks after the first also imply glue.
$this_len += $glue_len;
}
if ($len + $this_len <= $limit) {
$len += $this_len;
$chunk[] = $fragment;
} else {
if ($chunk) {
$result[] = $chunk;
}
$len = ($this_len - $glue_len);
$chunk = array($fragment);
}
}
if ($chunk) {
$result[] = $chunk;
}
return $result;
}
protected function assertAttached($property) {
if ($property === self::ATTACHABLE) {
throw new PhabricatorDataNotAttachedException($this);
}
return $property;
}
protected function assertAttachedKey($value, $key) {
$this->assertAttached($value);
if (!array_key_exists($key, $value)) {
throw new PhabricatorDataNotAttachedException($this);
}
return $value[$key];
}
protected function detectEncodingForStorage($string) {
return phutil_is_utf8($string) ? 'utf8' : null;
}
protected function getUTF8StringFromStorage($string, $encoding) {
if ($encoding == 'utf8') {
return $string;
}
if (function_exists('mb_detect_encoding')) {
if ($encoding !== null && strlen($encoding)) {
$try_encodings = array(
$encoding,
);
} else {
// TODO: This is pretty much a guess, and probably needs to be
// configurable in the long run.
$try_encodings = array(
'JIS',
'EUC-JP',
'SJIS',
'ISO-8859-1',
);
}
$guess = mb_detect_encoding($string, $try_encodings);
if ($guess) {
return mb_convert_encoding($string, 'UTF-8', $guess);
}
}
return phutil_utf8ize($string);
}
protected function willReadData(array &$data) {
parent::willReadData($data);
static $custom;
if ($custom === null) {
$custom = $this->getConfigOption(self::CONFIG_APPLICATION_SERIALIZERS);
}
if ($custom) {
foreach ($custom as $key => $serializer) {
$data[$key] = $serializer->willReadValue($data[$key]);
}
}
}
protected function willWriteData(array &$data) {
static $custom;
if ($custom === null) {
$custom = $this->getConfigOption(self::CONFIG_APPLICATION_SERIALIZERS);
}
if ($custom) {
foreach ($custom as $key => $serializer) {
$data[$key] = $serializer->willWriteValue($data[$key]);
}
}
parent::willWriteData($data);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/LiskEphemeralObjectException.php | src/infrastructure/storage/lisk/LiskEphemeralObjectException.php | <?php
final class LiskEphemeralObjectException extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/PhabricatorQueryIterator.php | src/infrastructure/storage/lisk/PhabricatorQueryIterator.php | <?php
final class PhabricatorQueryIterator extends PhutilBufferedIterator {
private $query;
private $pager;
public function __construct(PhabricatorCursorPagedPolicyAwareQuery $query) {
$this->query = $query;
}
protected function didRewind() {
$pager = new AphrontCursorPagerView();
$page_size = $this->getPageSize();
$pager->setPageSize($page_size);
$this->pager = $pager;
}
public function key() {
return $this->current()->getID();
}
protected function loadPage() {
if (!$this->pager) {
return array();
}
$pager = clone $this->pager;
$query = clone $this->query;
$query->setDisableOverheating(true);
$results = $query->executeWithCursorPager($pager);
// If we got less than a full page of results, this was the last set of
// results. Throw away the pager so we end iteration.
if (!$pager->getHasMoreResults()) {
$this->pager = null;
} else {
$this->pager->setAfterID($pager->getNextPageID());
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/LiskMigrationIterator.php | src/infrastructure/storage/lisk/LiskMigrationIterator.php | <?php
/**
* Iterate over every object of a given type, without holding all of them in
* memory. This is useful for performing database migrations.
*
* $things = new LiskMigrationIterator(new LiskThing());
* foreach ($things as $thing) {
* // do something
* }
*
* NOTE: This only works on objects with a normal `id` column.
*
* @task storage
*/
final class LiskMigrationIterator extends PhutilBufferedIterator {
private $object;
private $cursor;
public function __construct(LiskDAO $object) {
$this->object = $object;
}
protected function didRewind() {
$this->cursor = 0;
}
public function key() {
return $this->current()->getID();
}
protected function loadPage() {
$results = $this->object->loadAllWhere(
'id > %d ORDER BY id ASC LIMIT %d',
$this->cursor,
$this->getPageSize());
if ($results) {
$this->cursor = last($results)->getID();
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/LiskRawMigrationIterator.php | src/infrastructure/storage/lisk/LiskRawMigrationIterator.php | <?php
final class LiskRawMigrationIterator extends PhutilBufferedIterator {
private $conn;
private $table;
private $cursor;
private $column = 'id';
public function __construct(AphrontDatabaseConnection $conn, $table) {
$this->conn = $conn;
$this->table = $table;
}
protected function didRewind() {
$this->cursor = 0;
}
public function key() {
return idx($this->current(), $this->column);
}
protected function loadPage() {
$page = queryfx_all(
$this->conn,
'SELECT * FROM %T WHERE %C > %d ORDER BY ID ASC LIMIT %d',
$this->table,
$this->column,
$this->cursor,
$this->getPageSize());
if ($page) {
$this->cursor = idx(last($page), $this->column);
}
return $page;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/PhabricatorDataNotAttachedException.php | src/infrastructure/storage/lisk/PhabricatorDataNotAttachedException.php | <?php
final class PhabricatorDataNotAttachedException extends Exception {
public function __construct($object) {
$stack = debug_backtrace();
// Shift off `PhabricatorDataNotAttachedException::__construct()`.
array_shift($stack);
// Shift off `PhabricatorLiskDAO::assertAttached()`.
array_shift($stack);
$frame = head($stack);
$via = null;
if (is_array($frame)) {
$method = idx($frame, 'function');
if (preg_match('/^get[A-Z]/', $method)) {
$via = ' '.pht('(via %s)', "{$method}()");
}
}
parent::__construct(
pht(
"Attempting to access attached data on %s, but the data is not ".
"actually attached. Before accessing attachable data on an object, ".
"you must load and attach it.\n\n".
"Data is normally attached by calling the corresponding %s method on ".
"the Query class when the object is loaded. You can also call the ".
"corresponding %s method explicitly.",
get_class($object).$via,
'needX()',
'attachX()'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/LiskDAO.php | src/infrastructure/storage/lisk/LiskDAO.php | <?php
/**
* Simple object-authoritative data access object that makes it easy to build
* stuff that you need to save to a database. Basically, it means that the
* amount of boilerplate code (and, particularly, boilerplate SQL) you need
* to write is greatly reduced.
*
* Lisk makes it fairly easy to build something quickly and end up with
* reasonably high-quality code when you're done (e.g., getters and setters,
* objects, transactions, reasonably structured OO code). It's also very thin:
* you can break past it and use MySQL and other lower-level tools when you
* need to in those couple of cases where it doesn't handle your workflow
* gracefully.
*
* However, Lisk won't scale past one database and lacks many of the features
* of modern DAOs like Hibernate: for instance, it does not support joins or
* polymorphic storage.
*
* This means that Lisk is well-suited for tools like Differential, but often a
* poor choice elsewhere. And it is strictly unsuitable for many projects.
*
* Lisk's model is object-authoritative: the PHP class definition is the
* master authority for what the object looks like.
*
* =Building New Objects=
*
* To create new Lisk objects, extend @{class:LiskDAO} and implement
* @{method:establishLiveConnection}. It should return an
* @{class:AphrontDatabaseConnection}; this will tell Lisk where to save your
* objects.
*
* class Dog extends LiskDAO {
*
* protected $name;
* protected $breed;
*
* public function establishLiveConnection() {
* return $some_connection_object;
* }
* }
*
* Now, you should create your table:
*
* lang=sql
* CREATE TABLE dog (
* id int unsigned not null auto_increment primary key,
* name varchar(32) not null,
* breed varchar(32) not null,
* dateCreated int unsigned not null,
* dateModified int unsigned not null
* );
*
* For each property in your class, add a column with the same name to the table
* (see @{method:getConfiguration} for information about changing this mapping).
* Additionally, you should create the three columns `id`, `dateCreated` and
* `dateModified`. Lisk will automatically manage these, using them to implement
* autoincrement IDs and timestamps. If you do not want to use these features,
* see @{method:getConfiguration} for information on disabling them. At a bare
* minimum, you must normally have an `id` column which is a primary or unique
* key with a numeric type, although you can change its name by overriding
* @{method:getIDKey} or disable it entirely by overriding @{method:getIDKey} to
* return null. Note that many methods rely on a single-part primary key and
* will no longer work (they will throw) if you disable it.
*
* As you add more properties to your class in the future, remember to add them
* to the database table as well.
*
* Lisk will now automatically handle these operations: getting and setting
* properties, saving objects, loading individual objects, loading groups
* of objects, updating objects, managing IDs, updating timestamps whenever
* an object is created or modified, and some additional specialized
* operations.
*
* = Creating, Retrieving, Updating, and Deleting =
*
* To create and persist a Lisk object, use @{method:save}:
*
* $dog = id(new Dog())
* ->setName('Sawyer')
* ->setBreed('Pug')
* ->save();
*
* Note that **Lisk automatically builds getters and setters for all of your
* object's protected properties** via @{method:__call}. If you want to add
* custom behavior to your getters or setters, you can do so by overriding the
* @{method:readField} and @{method:writeField} methods.
*
* Calling @{method:save} will persist the object to the database. After calling
* @{method:save}, you can call @{method:getID} to retrieve the object's ID.
*
* To load objects by ID, use the @{method:load} method:
*
* $dog = id(new Dog())->load($id);
*
* This will load the Dog record with ID $id into $dog, or `null` if no such
* record exists (@{method:load} is an instance method rather than a static
* method because PHP does not support late static binding, at least until PHP
* 5.3).
*
* To update an object, change its properties and save it:
*
* $dog->setBreed('Lab')->save();
*
* To delete an object, call @{method:delete}:
*
* $dog->delete();
*
* That's Lisk CRUD in a nutshell.
*
* = Queries =
*
* Often, you want to load a bunch of objects, or execute a more specialized
* query. Use @{method:loadAllWhere} or @{method:loadOneWhere} to do this:
*
* $pugs = $dog->loadAllWhere('breed = %s', 'Pug');
* $sawyer = $dog->loadOneWhere('name = %s', 'Sawyer');
*
* These methods work like @{function@arcanist:queryfx}, but only take half of
* a query (the part after the WHERE keyword). Lisk will handle the connection,
* columns, and object construction; you are responsible for the rest of it.
* @{method:loadAllWhere} returns a list of objects, while
* @{method:loadOneWhere} returns a single object (or `null`).
*
* There's also a @{method:loadRelatives} method which helps to prevent the 1+N
* queries problem.
*
* = Managing Transactions =
*
* Lisk uses a transaction stack, so code does not generally need to be aware
* of the transactional state of objects to implement correct transaction
* semantics:
*
* $obj->openTransaction();
* $obj->save();
* $other->save();
* // ...
* $other->openTransaction();
* $other->save();
* $another->save();
* if ($some_condition) {
* $other->saveTransaction();
* } else {
* $other->killTransaction();
* }
* // ...
* $obj->saveTransaction();
*
* Assuming ##$obj##, ##$other## and ##$another## live on the same database,
* this code will work correctly by establishing savepoints.
*
* Selects whose data are used later in the transaction should be included in
* @{method:beginReadLocking} or @{method:beginWriteLocking} block.
*
* @task conn Managing Connections
* @task config Configuring Lisk
* @task load Loading Objects
* @task info Examining Objects
* @task save Writing Objects
* @task hook Hooks and Callbacks
* @task util Utilities
* @task xaction Managing Transactions
* @task isolate Isolation for Unit Testing
*/
abstract class LiskDAO extends Phobject
implements AphrontDatabaseTableRefInterface {
const CONFIG_IDS = 'id-mechanism';
const CONFIG_TIMESTAMPS = 'timestamps';
const CONFIG_AUX_PHID = 'auxiliary-phid';
const CONFIG_SERIALIZATION = 'col-serialization';
const CONFIG_BINARY = 'binary';
const CONFIG_COLUMN_SCHEMA = 'col-schema';
const CONFIG_KEY_SCHEMA = 'key-schema';
const CONFIG_NO_TABLE = 'no-table';
const CONFIG_NO_MUTATE = 'no-mutate';
const SERIALIZATION_NONE = 'id';
const SERIALIZATION_JSON = 'json';
const SERIALIZATION_PHP = 'php';
const IDS_AUTOINCREMENT = 'ids-auto';
const IDS_COUNTER = 'ids-counter';
const IDS_MANUAL = 'ids-manual';
const COUNTER_TABLE_NAME = 'lisk_counter';
private static $processIsolationLevel = 0;
private static $transactionIsolationLevel = 0;
private $ephemeral = false;
private $forcedConnection;
private static $connections = array();
private static $liskMetadata = array();
protected $id;
protected $phid;
protected $dateCreated;
protected $dateModified;
/**
* Build an empty object.
*
* @return obj Empty object.
*/
public function __construct() {
$id_key = $this->getIDKey();
if ($id_key) {
$this->$id_key = null;
}
}
/* -( Managing Connections )----------------------------------------------- */
/**
* Establish a live connection to a database service. This method should
* return a new connection. Lisk handles connection caching and management;
* do not perform caching deeper in the stack.
*
* @param string Mode, either 'r' (reading) or 'w' (reading and writing).
* @return AphrontDatabaseConnection New database connection.
* @task conn
*/
abstract protected function establishLiveConnection($mode);
/**
* Return a namespace for this object's connections in the connection cache.
* Generally, the database name is appropriate. Two connections are considered
* equivalent if they have the same connection namespace and mode.
*
* @return string Connection namespace for cache
* @task conn
*/
protected function getConnectionNamespace() {
return $this->getDatabaseName();
}
abstract protected function getDatabaseName();
/**
* Get an existing, cached connection for this object.
*
* @param mode Connection mode.
* @return AphrontDatabaseConnection|null Connection, if it exists in cache.
* @task conn
*/
protected function getEstablishedConnection($mode) {
$key = $this->getConnectionNamespace().':'.$mode;
if (isset(self::$connections[$key])) {
return self::$connections[$key];
}
return null;
}
/**
* Store a connection in the connection cache.
*
* @param mode Connection mode.
* @param AphrontDatabaseConnection Connection to cache.
* @return this
* @task conn
*/
protected function setEstablishedConnection(
$mode,
AphrontDatabaseConnection $connection,
$force_unique = false) {
$key = $this->getConnectionNamespace().':'.$mode;
if ($force_unique) {
$key .= ':unique';
while (isset(self::$connections[$key])) {
$key .= '!';
}
}
self::$connections[$key] = $connection;
return $this;
}
/**
* Force an object to use a specific connection.
*
* This overrides all connection management and forces the object to use
* a specific connection when interacting with the database.
*
* @param AphrontDatabaseConnection Connection to force this object to use.
* @task conn
*/
public function setForcedConnection(AphrontDatabaseConnection $connection) {
$this->forcedConnection = $connection;
return $this;
}
/* -( Configuring Lisk )--------------------------------------------------- */
/**
* Change Lisk behaviors, like ID configuration and timestamps. If you want
* to change these behaviors, you should override this method in your child
* class and change the options you're interested in. For example:
*
* protected function getConfiguration() {
* return array(
* Lisk_DataAccessObject::CONFIG_EXAMPLE => true,
* ) + parent::getConfiguration();
* }
*
* The available options are:
*
* CONFIG_IDS
* Lisk objects need to have a unique identifying ID. The three mechanisms
* available for generating this ID are IDS_AUTOINCREMENT (default, assumes
* the ID column is an autoincrement primary key), IDS_MANUAL (you are taking
* full responsibility for ID management), or IDS_COUNTER (see below).
*
* InnoDB does not persist the value of `auto_increment` across restarts,
* and instead initializes it to `MAX(id) + 1` during startup. This means it
* may reissue the same autoincrement ID more than once, if the row is deleted
* and then the database is restarted. To avoid this, you can set an object to
* use a counter table with IDS_COUNTER. This will generally behave like
* IDS_AUTOINCREMENT, except that the counter value will persist across
* restarts and inserts will be slightly slower. If a database stores any
* DAOs which use this mechanism, you must create a table there with this
* schema:
*
* CREATE TABLE lisk_counter (
* counterName VARCHAR(64) COLLATE utf8_bin PRIMARY KEY,
* counterValue BIGINT UNSIGNED NOT NULL
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
*
* CONFIG_TIMESTAMPS
* Lisk can automatically handle keeping track of a `dateCreated' and
* `dateModified' column, which it will update when it creates or modifies
* an object. If you don't want to do this, you may disable this option.
* By default, this option is ON.
*
* CONFIG_AUX_PHID
* This option can be enabled by being set to some truthy value. The meaning
* of this value is defined by your PHID generation mechanism. If this option
* is enabled, a `phid' property will be populated with a unique PHID when an
* object is created (or if it is saved and does not currently have one). You
* need to override generatePHID() and hook it into your PHID generation
* mechanism for this to work. By default, this option is OFF.
*
* CONFIG_SERIALIZATION
* You can optionally provide a column serialization map that will be applied
* to values when they are written to the database. For example:
*
* self::CONFIG_SERIALIZATION => array(
* 'complex' => self::SERIALIZATION_JSON,
* )
*
* This will cause Lisk to JSON-serialize the 'complex' field before it is
* written, and unserialize it when it is read.
*
* CONFIG_BINARY
* You can optionally provide a map of columns to a flag indicating that
* they store binary data. These columns will not raise an error when
* handling binary writes.
*
* CONFIG_COLUMN_SCHEMA
* Provide a map of columns to schema column types.
*
* CONFIG_KEY_SCHEMA
* Provide a map of key names to key specifications.
*
* CONFIG_NO_TABLE
* Allows you to specify that this object does not actually have a table in
* the database.
*
* CONFIG_NO_MUTATE
* Provide a map of columns which should not be included in UPDATE statements.
* If you have some columns which are always written to explicitly and should
* never be overwritten by a save(), you can specify them here. This is an
* advanced, specialized feature and there are usually better approaches for
* most locking/contention problems.
*
* @return dictionary Map of configuration options to values.
*
* @task config
*/
protected function getConfiguration() {
return array(
self::CONFIG_IDS => self::IDS_AUTOINCREMENT,
self::CONFIG_TIMESTAMPS => true,
);
}
/**
* Determine the setting of a configuration option for this class of objects.
*
* @param const Option name, one of the CONFIG_* constants.
* @return mixed Option value, if configured (null if unavailable).
*
* @task config
*/
public function getConfigOption($option_name) {
$options = $this->getLiskMetadata('config');
if ($options === null) {
$options = $this->getConfiguration();
$this->setLiskMetadata('config', $options);
}
return idx($options, $option_name);
}
/* -( Loading Objects )---------------------------------------------------- */
/**
* Load an object by ID. You need to invoke this as an instance method, not
* a class method, because PHP doesn't have late static binding (until
* PHP 5.3.0). For example:
*
* $dog = id(new Dog())->load($dog_id);
*
* @param int Numeric ID identifying the object to load.
* @return obj|null Identified object, or null if it does not exist.
*
* @task load
*/
public function load($id) {
if (is_object($id)) {
$id = (string)$id;
}
if (!$id || (!is_int($id) && !ctype_digit($id))) {
return null;
}
return $this->loadOneWhere(
'%C = %d',
$this->getIDKey(),
$id);
}
/**
* Loads all of the objects, unconditionally.
*
* @return dict Dictionary of all persisted objects of this type, keyed
* on object ID.
*
* @task load
*/
public function loadAll() {
return $this->loadAllWhere('1 = 1');
}
/**
* Load all objects which match a WHERE clause. You provide everything after
* the 'WHERE'; Lisk handles everything up to it. For example:
*
* $old_dogs = id(new Dog())->loadAllWhere('age > %d', 7);
*
* The pattern and arguments are as per queryfx().
*
* @param string queryfx()-style SQL WHERE clause.
* @param ... Zero or more conversions.
* @return dict Dictionary of matching objects, keyed on ID.
*
* @task load
*/
public function loadAllWhere($pattern /* , $arg, $arg, $arg ... */) {
$args = func_get_args();
$data = call_user_func_array(
array($this, 'loadRawDataWhere'),
$args);
return $this->loadAllFromArray($data);
}
/**
* Load a single object identified by a 'WHERE' clause. You provide
* everything after the 'WHERE', and Lisk builds the first half of the
* query. See loadAllWhere(). This method is similar, but returns a single
* result instead of a list.
*
* @param string queryfx()-style SQL WHERE clause.
* @param ... Zero or more conversions.
* @return obj|null Matching object, or null if no object matches.
*
* @task load
*/
public function loadOneWhere($pattern /* , $arg, $arg, $arg ... */) {
$args = func_get_args();
$data = call_user_func_array(
array($this, 'loadRawDataWhere'),
$args);
if (count($data) > 1) {
throw new AphrontCountQueryException(
pht(
'More than one result from %s!',
__FUNCTION__.'()'));
}
$data = reset($data);
if (!$data) {
return null;
}
return $this->loadFromArray($data);
}
protected function loadRawDataWhere($pattern /* , $args... */) {
$conn = $this->establishConnection('r');
if ($conn->isReadLocking()) {
$lock_clause = qsprintf($conn, 'FOR UPDATE');
} else if ($conn->isWriteLocking()) {
$lock_clause = qsprintf($conn, 'LOCK IN SHARE MODE');
} else {
$lock_clause = qsprintf($conn, '');
}
$args = func_get_args();
$args = array_slice($args, 1);
$pattern = 'SELECT * FROM %R WHERE '.$pattern.' %Q';
array_unshift($args, $this);
array_push($args, $lock_clause);
array_unshift($args, $pattern);
return call_user_func_array(array($conn, 'queryData'), $args);
}
/**
* Reload an object from the database, discarding any changes to persistent
* properties. This is primarily useful after entering a transaction but
* before applying changes to an object.
*
* @return this
*
* @task load
*/
public function reload() {
if (!$this->getID()) {
throw new Exception(
pht("Unable to reload object that hasn't been loaded!"));
}
$result = $this->loadOneWhere(
'%C = %d',
$this->getIDKey(),
$this->getID());
if (!$result) {
throw new AphrontObjectMissingQueryException();
}
return $this;
}
/**
* Initialize this object's properties from a dictionary. Generally, you
* load single objects with loadOneWhere(), but sometimes it may be more
* convenient to pull data from elsewhere directly (e.g., a complicated
* join via @{method:queryData}) and then load from an array representation.
*
* @param dict Dictionary of properties, which should be equivalent to
* selecting a row from the table or calling
* @{method:getProperties}.
* @return this
*
* @task load
*/
public function loadFromArray(array $row) {
$valid_map = $this->getLiskMetadata('validMap', array());
$map = array();
$updated = false;
foreach ($row as $k => $v) {
// We permit (but ignore) extra properties in the array because a
// common approach to building the array is to issue a raw SELECT query
// which may include extra explicit columns or joins.
// This pathway is very hot on some pages, so we're inlining a cache
// and doing some microoptimization to avoid a strtolower() call for each
// assignment. The common path (assigning a valid property which we've
// already seen) always incurs only one empty(). The second most common
// path (assigning an invalid property which we've already seen) costs
// an empty() plus an isset().
if (empty($valid_map[$k])) {
if (isset($valid_map[$k])) {
// The value is set but empty, which means it's false, so we've
// already determined it's not valid. We don't need to check again.
continue;
}
$valid_map[$k] = $this->hasProperty($k);
$updated = true;
if (!$valid_map[$k]) {
continue;
}
}
$map[$k] = $v;
}
if ($updated) {
$this->setLiskMetadata('validMap', $valid_map);
}
$this->willReadData($map);
foreach ($map as $prop => $value) {
$this->$prop = $value;
}
$this->didReadData();
return $this;
}
/**
* Initialize a list of objects from a list of dictionaries. Usually you
* load lists of objects with @{method:loadAllWhere}, but sometimes that
* isn't flexible enough. One case is if you need to do joins to select the
* right objects:
*
* function loadAllWithOwner($owner) {
* $data = $this->queryData(
* 'SELECT d.*
* FROM owner o
* JOIN owner_has_dog od ON o.id = od.ownerID
* JOIN dog d ON od.dogID = d.id
* WHERE o.id = %d',
* $owner);
* return $this->loadAllFromArray($data);
* }
*
* This is a lot messier than @{method:loadAllWhere}, but more flexible.
*
* @param list List of property dictionaries.
* @return dict List of constructed objects, keyed on ID.
*
* @task load
*/
public function loadAllFromArray(array $rows) {
$result = array();
$id_key = $this->getIDKey();
foreach ($rows as $row) {
$obj = clone $this;
if ($id_key && isset($row[$id_key])) {
$row_id = $row[$id_key];
if (isset($result[$row_id])) {
throw new Exception(
pht(
'Rows passed to "loadAllFromArray(...)" include two or more '.
'rows with the same ID ("%s"). Rows must have unique IDs. '.
'An underlying query may be missing a GROUP BY.',
$row_id));
}
$result[$row_id] = $obj->loadFromArray($row);
} else {
$result[] = $obj->loadFromArray($row);
}
}
return $result;
}
/* -( Examining Objects )-------------------------------------------------- */
/**
* Set unique ID identifying this object. You normally don't need to call this
* method unless with `IDS_MANUAL`.
*
* @param mixed Unique ID.
* @return this
* @task save
*/
public function setID($id) {
$id_key = $this->getIDKey();
$this->$id_key = $id;
return $this;
}
/**
* Retrieve the unique ID identifying this object. This value will be null if
* the object hasn't been persisted and you didn't set it manually.
*
* @return mixed Unique ID.
*
* @task info
*/
public function getID() {
$id_key = $this->getIDKey();
return $this->$id_key;
}
public function getPHID() {
return $this->phid;
}
/**
* Test if a property exists.
*
* @param string Property name.
* @return bool True if the property exists.
* @task info
*/
public function hasProperty($property) {
return (bool)$this->checkProperty($property);
}
/**
* Retrieve a list of all object properties. This list only includes
* properties that are declared as protected, and it is expected that
* all properties returned by this function should be persisted to the
* database.
* Properties that should not be persisted must be declared as private.
*
* @return dict Dictionary of normalized (lowercase) to canonical (original
* case) property names.
*
* @task info
*/
protected function getAllLiskProperties() {
$properties = $this->getLiskMetadata('properties');
if ($properties === null) {
$class = new ReflectionClass(static::class);
$properties = array();
foreach ($class->getProperties(ReflectionProperty::IS_PROTECTED) as $p) {
$properties[strtolower($p->getName())] = $p->getName();
}
$id_key = $this->getIDKey();
if ($id_key != 'id') {
unset($properties['id']);
}
if (!$this->getConfigOption(self::CONFIG_TIMESTAMPS)) {
unset($properties['datecreated']);
unset($properties['datemodified']);
}
if ($id_key != 'phid' && !$this->getConfigOption(self::CONFIG_AUX_PHID)) {
unset($properties['phid']);
}
$this->setLiskMetadata('properties', $properties);
}
return $properties;
}
/**
* Check if a property exists on this object.
*
* @return string|null Canonical property name, or null if the property
* does not exist.
*
* @task info
*/
protected function checkProperty($property) {
$properties = $this->getAllLiskProperties();
$property = strtolower($property);
if (empty($properties[$property])) {
return null;
}
return $properties[$property];
}
/**
* Get or build the database connection for this object.
*
* @param string 'r' for read, 'w' for read/write.
* @param bool True to force a new connection. The connection will not
* be retrieved from or saved into the connection cache.
* @return AphrontDatabaseConnection Lisk connection object.
*
* @task info
*/
public function establishConnection($mode, $force_new = false) {
if ($mode != 'r' && $mode != 'w') {
throw new Exception(
pht(
"Unknown mode '%s', should be 'r' or 'w'.",
$mode));
}
if ($this->forcedConnection) {
return $this->forcedConnection;
}
if (self::shouldIsolateAllLiskEffectsToCurrentProcess()) {
$mode = 'isolate-'.$mode;
$connection = $this->getEstablishedConnection($mode);
if (!$connection) {
$connection = $this->establishIsolatedConnection($mode);
$this->setEstablishedConnection($mode, $connection);
}
return $connection;
}
if (self::shouldIsolateAllLiskEffectsToTransactions()) {
// If we're doing fixture transaction isolation, force the mode to 'w'
// so we always get the same connection for reads and writes, and thus
// can see the writes inside the transaction.
$mode = 'w';
}
// TODO: There is currently no protection on 'r' queries against writing.
$connection = null;
if (!$force_new) {
if ($mode == 'r') {
// If we're requesting a read connection but already have a write
// connection, reuse the write connection so that reads can take place
// inside transactions.
$connection = $this->getEstablishedConnection('w');
}
if (!$connection) {
$connection = $this->getEstablishedConnection($mode);
}
}
if (!$connection) {
$connection = $this->establishLiveConnection($mode);
if (self::shouldIsolateAllLiskEffectsToTransactions()) {
$connection->openTransaction();
}
$this->setEstablishedConnection(
$mode,
$connection,
$force_unique = $force_new);
}
return $connection;
}
/**
* Convert this object into a property dictionary. This dictionary can be
* restored into an object by using @{method:loadFromArray} (unless you're
* using legacy features with CONFIG_CONVERT_CAMELCASE, but in that case you
* should just go ahead and die in a fire).
*
* @return dict Dictionary of object properties.
*
* @task info
*/
protected function getAllLiskPropertyValues() {
$map = array();
foreach ($this->getAllLiskProperties() as $p) {
// We may receive a warning here for properties we've implicitly added
// through configuration; squelch it.
$map[$p] = @$this->$p;
}
return $map;
}
/* -( Writing Objects )---------------------------------------------------- */
/**
* Make an object read-only.
*
* Making an object ephemeral indicates that you will be changing state in
* such a way that you would never ever want it to be written back to the
* storage.
*/
public function makeEphemeral() {
$this->ephemeral = true;
return $this;
}
private function isEphemeralCheck() {
if ($this->ephemeral) {
throw new LiskEphemeralObjectException();
}
}
/**
* Persist this object to the database. In most cases, this is the only
* method you need to call to do writes. If the object has not yet been
* inserted this will do an insert; if it has, it will do an update.
*
* @return this
*
* @task save
*/
public function save() {
if ($this->shouldInsertWhenSaved()) {
return $this->insert();
} else {
return $this->update();
}
}
/**
* Save this object, forcing the query to use REPLACE regardless of object
* state.
*
* @return this
*
* @task save
*/
public function replace() {
$this->isEphemeralCheck();
return $this->insertRecordIntoDatabase('REPLACE');
}
/**
* Save this object, forcing the query to use INSERT regardless of object
* state.
*
* @return this
*
* @task save
*/
public function insert() {
$this->isEphemeralCheck();
return $this->insertRecordIntoDatabase('INSERT');
}
/**
* Save this object, forcing the query to use UPDATE regardless of object
* state.
*
* @return this
*
* @task save
*/
public function update() {
$this->isEphemeralCheck();
$this->willSaveObject();
$data = $this->getAllLiskPropertyValues();
// Remove columns flagged as nonmutable from the update statement.
$no_mutate = $this->getConfigOption(self::CONFIG_NO_MUTATE);
if ($no_mutate) {
foreach ($no_mutate as $column) {
unset($data[$column]);
}
}
$this->willWriteData($data);
$map = array();
foreach ($data as $k => $v) {
$map[$k] = $v;
}
$conn = $this->establishConnection('w');
$binary = $this->getBinaryColumns();
foreach ($map as $key => $value) {
if (!empty($binary[$key])) {
$map[$key] = qsprintf($conn, '%C = %nB', $key, $value);
} else {
$map[$key] = qsprintf($conn, '%C = %ns', $key, $value);
}
}
$id = $this->getID();
$conn->query(
'UPDATE %R SET %LQ WHERE %C = '.(is_int($id) ? '%d' : '%s'),
$this,
$map,
$this->getIDKey(),
$id);
// We can't detect a missing object because updating an object without
// changing any values doesn't affect rows. We could jiggle timestamps
// to catch this for objects which track them if we wanted.
$this->didWriteData();
return $this;
}
/**
* Delete this object, permanently.
*
* @return this
*
* @task save
*/
public function delete() {
$this->isEphemeralCheck();
$this->willDelete();
$conn = $this->establishConnection('w');
$conn->query(
'DELETE FROM %R WHERE %C = %d',
$this,
$this->getIDKey(),
$this->getID());
$this->didDelete();
return $this;
}
/**
* Internal implementation of INSERT and REPLACE.
*
* @param const Either "INSERT" or "REPLACE", to force the desired mode.
* @return this
*
* @task save
*/
protected function insertRecordIntoDatabase($mode) {
$this->willSaveObject();
$data = $this->getAllLiskPropertyValues();
$conn = $this->establishConnection('w');
$id_mechanism = $this->getConfigOption(self::CONFIG_IDS);
switch ($id_mechanism) {
case self::IDS_AUTOINCREMENT:
// If we are using autoincrement IDs, let MySQL assign the value for the
// ID column, if it is empty. If the caller has explicitly provided a
// value, use it.
$id_key = $this->getIDKey();
if (empty($data[$id_key])) {
unset($data[$id_key]);
}
break;
case self::IDS_COUNTER:
// If we are using counter IDs, assign a new ID if we don't already have
// one.
$id_key = $this->getIDKey();
if (empty($data[$id_key])) {
$counter_name = $this->getTableName();
$id = self::loadNextCounterValue($conn, $counter_name);
$this->setID($id);
$data[$id_key] = $id;
}
break;
case self::IDS_MANUAL:
break;
default:
throw new Exception(pht('Unknown %s mechanism!', 'CONFIG_IDs'));
}
$this->willWriteData($data);
$columns = array_keys($data);
$binary = $this->getBinaryColumns();
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/PhabricatorLiskSerializer.php | src/infrastructure/storage/lisk/PhabricatorLiskSerializer.php | <?php
abstract class PhabricatorLiskSerializer extends Phobject {
abstract public function willReadValue($value);
abstract public function willWriteValue($value);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/__tests__/LiskChunkTestCase.php | src/infrastructure/storage/lisk/__tests__/LiskChunkTestCase.php | <?php
final class LiskChunkTestCase extends PhabricatorTestCase {
public function testSQLChunking() {
$fragments = array(
'a',
'a',
'b',
'b',
'ccc',
'dd',
'e',
);
$this->assertEqual(
array(
array('a'),
array('a'),
array('b'),
array('b'),
array('ccc'),
array('dd'),
array('e'),
),
PhabricatorLiskDAO::chunkSQL($fragments, 2));
$fragments = array(
'a',
'a',
'a',
'XX',
'a',
'a',
'a',
'a',
);
$this->assertEqual(
array(
array('a', 'a', 'a'),
array('XX', 'a', 'a'),
array('a', 'a'),
),
PhabricatorLiskDAO::chunkSQL($fragments, 8));
$fragments = array(
'xxxxxxxxxx',
'yyyyyyyyyy',
'a',
'b',
'c',
'zzzzzzzzzz',
);
$this->assertEqual(
array(
array('xxxxxxxxxx'),
array('yyyyyyyyyy'),
array('a', 'b', 'c'),
array('zzzzzzzzzz'),
),
PhabricatorLiskDAO::chunkSQL($fragments, 8));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/__tests__/LiskFixtureTestCase.php | src/infrastructure/storage/lisk/__tests__/LiskFixtureTestCase.php | <?php
final class LiskFixtureTestCase extends PhabricatorTestCase {
protected function getPhabricatorTestCaseConfiguration() {
return array(
self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
);
}
public function testTransactionalIsolation1of2() {
// NOTE: These tests are verifying that data is destroyed between tests.
// If the user from either test persists, the other test will fail.
$this->assertEqual(
0,
count(id(new HarbormasterScratchTable())->loadAll()));
id(new HarbormasterScratchTable())
->setData('alincoln')
->save();
}
public function testTransactionalIsolation2of2() {
$this->assertEqual(
0,
count(id(new HarbormasterScratchTable())->loadAll()));
id(new HarbormasterScratchTable())
->setData('ugrant')
->save();
}
public function testFixturesBasicallyWork() {
$this->assertEqual(
0,
count(id(new HarbormasterScratchTable())->loadAll()));
id(new HarbormasterScratchTable())
->setData('gwashington')
->save();
$this->assertEqual(
1,
count(id(new HarbormasterScratchTable())->loadAll()));
}
public function testReadableTransactions() {
// TODO: When we have semi-durable fixtures, use those instead. This is
// extremely hacky.
LiskDAO::endIsolateAllLiskEffectsToTransactions();
try {
$data = Filesystem::readRandomCharacters(32);
$obj = new HarbormasterScratchTable();
$obj->openTransaction();
$obj->setData($data);
$obj->save();
$loaded = id(new HarbormasterScratchTable())->loadOneWhere(
'data = %s',
$data);
$obj->killTransaction();
$this->assertTrue(
($loaded !== null),
pht('Reads inside transactions should have transaction visibility.'));
LiskDAO::beginIsolateAllLiskEffectsToTransactions();
} catch (Exception $ex) {
LiskDAO::beginIsolateAllLiskEffectsToTransactions();
throw $ex;
}
}
public function testGarbageLoadCalls() {
$obj = new HarbormasterObject();
$obj->save();
$id = $obj->getID();
$load = new HarbormasterObject();
$this->assertEqual(null, $load->load(0));
$this->assertEqual(null, $load->load(-1));
$this->assertEqual(null, $load->load(9999));
$this->assertEqual(null, $load->load(''));
$this->assertEqual(null, $load->load('cow'));
$this->assertEqual(null, $load->load($id.'cow'));
$this->assertTrue((bool)$load->load((int)$id));
$this->assertTrue((bool)$load->load((string)$id));
}
public function testCounters() {
$obj = new HarbormasterObject();
$conn_w = $obj->establishConnection('w');
// Test that the counter basically behaves as expected.
$this->assertEqual(1, LiskDAO::loadNextCounterValue($conn_w, 'a'));
$this->assertEqual(2, LiskDAO::loadNextCounterValue($conn_w, 'a'));
$this->assertEqual(3, LiskDAO::loadNextCounterValue($conn_w, 'a'));
// This first insert is primarily a test that the previous LAST_INSERT_ID()
// value does not bleed into the creation of a new counter.
$this->assertEqual(1, LiskDAO::loadNextCounterValue($conn_w, 'b'));
$this->assertEqual(2, LiskDAO::loadNextCounterValue($conn_w, 'b'));
// Test alternate access/overwrite methods.
$this->assertEqual(3, LiskDAO::loadCurrentCounterValue($conn_w, 'a'));
LiskDAO::overwriteCounterValue($conn_w, 'a', 42);
$this->assertEqual(42, LiskDAO::loadCurrentCounterValue($conn_w, 'a'));
$this->assertEqual(43, LiskDAO::loadNextCounterValue($conn_w, 'a'));
// These inserts alternate database connections. Since unit tests are
// transactional by default, we need to break out of them or we'll deadlock
// since the transactions don't normally close until we exit the test.
LiskDAO::endIsolateAllLiskEffectsToTransactions();
try {
$conn_1 = $obj->establishConnection('w', $force_new = true);
$conn_2 = $obj->establishConnection('w', $force_new = true);
$this->assertEqual(1, LiskDAO::loadNextCounterValue($conn_1, 'z'));
$this->assertEqual(2, LiskDAO::loadNextCounterValue($conn_2, 'z'));
$this->assertEqual(3, LiskDAO::loadNextCounterValue($conn_1, 'z'));
$this->assertEqual(4, LiskDAO::loadNextCounterValue($conn_2, 'z'));
$this->assertEqual(5, LiskDAO::loadNextCounterValue($conn_1, 'z'));
LiskDAO::beginIsolateAllLiskEffectsToTransactions();
} catch (Exception $ex) {
LiskDAO::beginIsolateAllLiskEffectsToTransactions();
throw $ex;
}
}
public function testNonmutableColumns() {
$object = id(new HarbormasterScratchTable())
->setData('val1')
->setNonmutableData('val1')
->save();
$object->reload();
$this->assertEqual('val1', $object->getData());
$this->assertEqual('val1', $object->getNonmutableData());
$object
->setData('val2')
->setNonmutableData('val2')
->save();
$object->reload();
$this->assertEqual('val2', $object->getData());
// NOTE: This is the important test: the nonmutable column should not have
// been affected by the update.
$this->assertEqual('val1', $object->getNonmutableData());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/__tests__/LiskDAOTestCase.php | src/infrastructure/storage/lisk/__tests__/LiskDAOTestCase.php | <?php
final class LiskDAOTestCase extends PhabricatorTestCase {
public function testCheckProperty() {
$scratch = new HarbormasterScratchTable();
$scratch->getData();
$this->assertException('Exception', array($this, 'getData'));
}
public function getData() {
$isolation = new LiskIsolationTestDAO();
$isolation->getData();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/__tests__/LiskIsolationTestDAO.php | src/infrastructure/storage/lisk/__tests__/LiskIsolationTestDAO.php | <?php
final class LiskIsolationTestDAO extends LiskDAO {
protected $name;
protected $phid;
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID('TISO');
}
protected function establishLiveConnection($mode) {
throw new LiskIsolationTestDAOException(
pht(
'Isolation failure! DAO is attempting to connect to an external '.
'resource!'));
}
protected function getDatabaseName() {
return 'test';
}
public function getTableName() {
return 'test';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/__tests__/LiskIsolationTestCase.php | src/infrastructure/storage/lisk/__tests__/LiskIsolationTestCase.php | <?php
final class LiskIsolationTestCase extends PhabricatorTestCase {
public function testIsolatedWrites() {
$dao = new LiskIsolationTestDAO();
$this->assertEqual(null, $dao->getID(), pht('Expect no ID.'));
$this->assertEqual(null, $dao->getPHID(), pht('Expect no PHID.'));
$dao->save(); // Effects insert
$id = $dao->getID();
$phid = $dao->getPHID();
$this->assertTrue((bool)$id, pht('Expect ID generated.'));
$this->assertTrue((bool)$phid, pht('Expect PHID generated.'));
$dao->save(); // Effects update
$this->assertEqual($id, $dao->getID(), pht('Expect ID unchanged.'));
$this->assertEqual($phid, $dao->getPHID(), pht('Expect PHID unchanged.'));
}
public function testEphemeral() {
$dao = new LiskIsolationTestDAO();
$dao->save();
$dao->makeEphemeral();
$this->tryTestCases(
array(
$dao,
),
array(
false,
),
array($this, 'saveDAO'));
}
public function saveDAO($dao) {
$dao->save();
}
public function testIsolationContainment() {
$dao = new LiskIsolationTestDAO();
try {
$method = new ReflectionMethod($dao, 'establishLiveConnection');
$method->setAccessible(true);
$method->invoke($dao, 'r');
$this->assertFailure(
pht(
'%s did not throw an exception when instructed to '.
'explicitly connect to an external database.',
'LiskIsolationTestDAO'));
} catch (LiskIsolationTestDAOException $ex) {
// Expected, pass.
}
$this->assertTrue(true);
}
public function testMagicMethods() {
$dao = new LiskIsolationTestDAO();
$this->assertEqual(
null,
$dao->getName(),
pht('%s on empty object', 'getName()'));
$this->assertEqual(
$dao,
$dao->setName('x'),
pht('%s returns %s', 'setName()', '$this'));
$this->assertEqual(
'y',
$dao->setName('y')->getName(),
pht('%s has an effect', 'setName()'));
$ex = null;
try {
$dao->gxxName();
} catch (Exception $thrown) {
$ex = $thrown;
}
$this->assertTrue(
(bool)$ex,
pht('Typoing "%s" should throw.', 'get'));
$ex = null;
try {
$dao->sxxName('z');
} catch (Exception $thrown) {
$ex = $thrown;
}
$this->assertTrue(
(bool)$ex,
pht('Typoing "%s" should throw.', 'set'));
$ex = null;
try {
$dao->madeUpMethod();
} catch (Exception $thrown) {
$ex = $thrown;
}
$this->assertTrue(
(bool)$ex,
pht('Made up method should throw.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/lisk/__tests__/LiskIsolationTestDAOException.php | src/infrastructure/storage/lisk/__tests__/LiskIsolationTestDAOException.php | <?php
final class LiskIsolationTestDAOException extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/xsprintf/qsprintf.php | src/infrastructure/storage/xsprintf/qsprintf.php | <?php
/**
* Format an SQL query. This function behaves like `sprintf`, except that all
* the normal conversions (like "%s") will be properly escaped, and additional
* conversions are supported:
*
* %nd, %ns, %nf, %nB
* "Nullable" versions of %d, %s, %f and %B. Will produce 'NULL' if the
* argument is a strict null.
*
* %=d, %=s, %=f
* "Nullable Test" versions of %d, %s and %f. If you pass a value, you
* get "= 3"; if you pass null, you get "IS NULL". For instance, this
* will work properly if `hatID' is a nullable column and $hat is null.
*
* qsprintf($escaper, 'WHERE hatID %=d', $hat);
*
* %Ld, %Ls, %Lf, %LB
* "List" versions of %d, %s, %f and %B. These are appropriate for use in
* an "IN" clause. For example:
*
* qsprintf($escaper, 'WHERE hatID IN (%Ld)', $list_of_hats);
*
* %B ("Binary String")
* Escapes a string for insertion into a pure binary column, ignoring
* tests for characters outside of the basic multilingual plane.
*
* %C, %LC, %LK ("Column", "Key Column")
* Escapes a column name or a list of column names. The "%LK" variant
* escapes a list of key column specifications which may look like
* "column(32)".
*
* %K ("Comment")
* Escapes a comment.
*
* %Q, %LA, %LO, %LQ, %LJ ("Query Fragment")
* Injects a query fragment from a prior call to qsprintf(). The list
* variants join a list of query fragments with AND, OR, comma, or space.
*
* %Z ("Raw Query")
* Injects a raw, unescaped query fragment. Dangerous!
*
* %R ("Database and Table Reference")
* Behaves like "%T.%T" and prints a full reference to a table including
* the database. Accepts a AphrontDatabaseTableRefInterface.
*
* %P ("Password or Secret")
* Behaves like "%s", but shows "********" when the query is printed in
* logs or traces. Accepts a PhutilOpaqueEnvelope.
*
* %~ ("Substring")
* Escapes a substring query for a LIKE (or NOT LIKE) clause. For example:
*
* // Find all rows with $search as a substring of `name`.
* qsprintf($escaper, 'WHERE name LIKE %~', $search);
*
* See also %> and %<.
*
* %> ("Prefix")
* Escapes a prefix query for a LIKE clause. For example:
*
* // Find all rows where `name` starts with $prefix.
* qsprintf($escaper, 'WHERE name LIKE %>', $prefix);
*
* %< ("Suffix")
* Escapes a suffix query for a LIKE clause. For example:
*
* // Find all rows where `name` ends with $suffix.
* qsprintf($escaper, 'WHERE name LIKE %<', $suffix);
*
* %T ("Table")
* Escapes a table name. In most cases, you should use "%R" instead.
*/
function qsprintf(PhutilQsprintfInterface $escaper, $pattern /* , ... */) {
$args = func_get_args();
array_shift($args);
return new PhutilQueryString($escaper, $args);
}
function vqsprintf(PhutilQsprintfInterface $escaper, $pattern, array $argv) {
array_unshift($argv, $pattern);
return new PhutilQueryString($escaper, $argv);
}
/**
* @{function:xsprintf} callback for encoding SQL queries. See
* @{function:qsprintf}.
*/
function xsprintf_query($userdata, &$pattern, &$pos, &$value, &$length) {
$type = $pattern[$pos];
if (is_array($userdata)) {
$escaper = $userdata['escaper'];
$unmasked = $userdata['unmasked'];
} else {
$escaper = $userdata;
$unmasked = false;
}
$next = (strlen($pattern) > $pos + 1) ? $pattern[$pos + 1] : null;
$nullable = false;
$done = false;
$prefix = '';
if (!($escaper instanceof PhutilQsprintfInterface)) {
throw new InvalidArgumentException(pht('Invalid database escaper.'));
}
switch ($type) {
case '=': // Nullable test
switch ($next) {
case 'd':
case 'f':
case 's':
$pattern = substr_replace($pattern, '', $pos, 1);
$length = strlen($pattern);
$type = 's';
if ($value === null) {
$value = 'IS NULL';
$done = true;
} else {
$prefix = '= ';
$type = $next;
}
break;
default:
throw new Exception(
pht(
'Unknown conversion, try %s, %s, or %s.',
'%=d',
'%=s',
'%=f'));
}
break;
case 'n': // Nullable...
switch ($next) {
case 'd': // ...integer.
case 'f': // ...float.
case 's': // ...string.
case 'B': // ...binary string.
$pattern = substr_replace($pattern, '', $pos, 1);
$length = strlen($pattern);
$type = $next;
$nullable = true;
break;
default:
throw new XsprintfUnknownConversionException("%n{$next}");
}
break;
case 'L': // List of..
qsprintf_check_type($value, "L{$next}", $pattern);
$pattern = substr_replace($pattern, '', $pos, 1);
$length = strlen($pattern);
$type = 's';
$done = true;
switch ($next) {
case 'd': // ...integers.
$value = implode(', ', array_map('intval', $value));
break;
case 'f': // ...floats.
$value = implode(', ', array_map('floatval', $value));
break;
case 's': // ...strings.
foreach ($value as $k => $v) {
$value[$k] = "'".$escaper->escapeUTF8String((string)$v)."'";
}
$value = implode(', ', $value);
break;
case 'B': // ...binary strings.
foreach ($value as $k => $v) {
$value[$k] = "'".$escaper->escapeBinaryString((string)$v)."'";
}
$value = implode(', ', $value);
break;
case 'C': // ...columns.
foreach ($value as $k => $v) {
$value[$k] = $escaper->escapeColumnName($v);
}
$value = implode(', ', $value);
break;
case 'K': // ...key columns.
// This is like "%LC", but for escaping column lists passed to key
// specifications. These should be escaped as "`column`(123)". For
// example:
//
// ALTER TABLE `x` ADD KEY `y` (`u`(16), `v`(32));
foreach ($value as $k => $v) {
$matches = null;
if (preg_match('/\((\d+)\)\z/', $v, $matches)) {
$v = substr($v, 0, -(strlen($matches[1]) + 2));
$prefix_len = '('.((int)$matches[1]).')';
} else {
$prefix_len = '';
}
$value[$k] = $escaper->escapeColumnName($v).$prefix_len;
}
$value = implode(', ', $value);
break;
case 'Q':
// TODO: Here, and in "%LO", "%LA", and "%LJ", we should eventually
// stop accepting strings.
foreach ($value as $k => $v) {
if (is_string($v)) {
continue;
}
$value[$k] = $v->getUnmaskedString();
}
$value = implode(', ', $value);
break;
case 'O':
foreach ($value as $k => $v) {
if (is_string($v)) {
continue;
}
$value[$k] = $v->getUnmaskedString();
}
if (count($value) == 1) {
$value = '('.head($value).')';
} else {
$value = '(('.implode(') OR (', $value).'))';
}
break;
case 'A':
foreach ($value as $k => $v) {
if (is_string($v)) {
continue;
}
$value[$k] = $v->getUnmaskedString();
}
if (count($value) == 1) {
$value = '('.head($value).')';
} else {
$value = '(('.implode(') AND (', $value).'))';
}
break;
case 'J':
foreach ($value as $k => $v) {
if (is_string($v)) {
continue;
}
$value[$k] = $v->getUnmaskedString();
}
$value = implode(' ', $value);
break;
default:
throw new XsprintfUnknownConversionException("%L{$next}");
}
break;
}
if (!$done) {
qsprintf_check_type($value, $type, $pattern);
switch ($type) {
case 's': // String
if ($nullable && $value === null) {
$value = 'NULL';
} else {
$value = "'".$escaper->escapeUTF8String((string)$value)."'";
}
$type = 's';
break;
case 'B': // Binary String
if ($nullable && $value === null) {
$value = 'NULL';
} else {
$value = "'".$escaper->escapeBinaryString((string)$value)."'";
}
$type = 's';
break;
case 'Q': // Query Fragment
if ($value instanceof PhutilQueryString) {
$value = $value->getUnmaskedString();
}
$type = 's';
break;
case 'Z': // Raw Query Fragment
$type = 's';
break;
case '~': // Like Substring
case '>': // Like Prefix
case '<': // Like Suffix
$value = $escaper->escapeStringForLikeClause($value);
switch ($type) {
case '~': $value = "'%".$value."%'"; break;
case '>': $value = "'".$value."%'"; break;
case '<': $value = "'%".$value."'"; break;
}
$type = 's';
break;
case 'f': // Float
if ($nullable && $value === null) {
$value = 'NULL';
} else {
$value = (float)$value;
}
$type = 's';
break;
case 'd': // Integer
if ($nullable && $value === null) {
$value = 'NULL';
} else {
$value = (int)$value;
}
$type = 's';
break;
case 'T': // Table
case 'C': // Column
$value = $escaper->escapeColumnName($value);
$type = 's';
break;
case 'K': // Komment
$value = $escaper->escapeMultilineComment($value);
$type = 's';
break;
case 'R': // Database + Table Reference
$database_name = $value->getAphrontRefDatabaseName();
$database_name = $escaper->escapeColumnName($database_name);
$table_name = $value->getAphrontRefTableName();
$table_name = $escaper->escapeColumnName($table_name);
$value = $database_name.'.'.$table_name;
$type = 's';
break;
case 'P': // Password or Secret
if ($unmasked) {
$value = $value->openEnvelope();
$value = "'".$escaper->escapeUTF8String($value)."'";
} else {
$value = '********';
}
$type = 's';
break;
default:
throw new XsprintfUnknownConversionException($type);
}
}
if ($prefix) {
$value = $prefix.$value;
}
$pattern[$pos] = $type;
}
function qsprintf_check_type($value, $type, $query) {
switch ($type) {
case 'Ld':
case 'Ls':
case 'LC':
case 'LK':
case 'LB':
case 'Lf':
case 'LQ':
case 'LA':
case 'LO':
case 'LJ':
if (!is_array($value)) {
throw new AphrontParameterQueryException(
$query,
pht('Expected array argument for %%%s conversion.', $type));
}
if (empty($value)) {
throw new AphrontParameterQueryException(
$query,
pht('Array for %%%s conversion is empty.', $type));
}
foreach ($value as $scalar) {
qsprintf_check_scalar_type($scalar, $type, $query);
}
break;
default:
qsprintf_check_scalar_type($value, $type, $query);
break;
}
}
function qsprintf_check_scalar_type($value, $type, $query) {
switch ($type) {
case 'LQ':
case 'LA':
case 'LO':
case 'LJ':
// TODO: See T13217. Remove this eventually.
if (is_string($value)) {
phlog(
pht(
'UNSAFE: Raw string ("%s") passed to query ("%s") subclause '.
'for "%%%s" conversion. Subclause conversions should be passed '.
'a list of PhutilQueryString objects.',
$value,
$query,
$type));
break;
}
if (!($value instanceof PhutilQueryString)) {
throw new AphrontParameterQueryException(
$query,
pht(
'Expected a list of PhutilQueryString objects for %%%s '.
'conversion.',
$type));
}
break;
case 'Q':
// TODO: See T13217. Remove this eventually.
if (is_string($value)) {
phlog(
pht(
'UNSAFE: Raw string ("%s") passed to query ("%s") for "%%Q" '.
'conversion. %%Q should be passed a query string.',
$value,
$query));
break;
}
if (!($value instanceof PhutilQueryString)) {
throw new AphrontParameterQueryException(
$query,
pht('Expected a PhutilQueryString for %%%s conversion.', $type));
}
break;
case 'Z':
if (!is_string($value)) {
throw new AphrontParameterQueryException(
$query,
pht('Value for "%%Z" conversion should be a raw string.'));
}
break;
case 'LC':
case 'LK':
case 'T':
case 'C':
if (!is_string($value)) {
throw new AphrontParameterQueryException(
$query,
pht('Expected a string for %%%s conversion.', $type));
}
break;
case 'Ld':
case 'Lf':
case 'd':
case 'f':
if (!is_null($value) && !is_numeric($value)) {
throw new AphrontParameterQueryException(
$query,
pht('Expected a numeric scalar or null for %%%s conversion.', $type));
}
break;
case 'Ls':
case 's':
case 'LB':
case 'B':
case '~':
case '>':
case '<':
case 'K':
if (!is_null($value) && !is_scalar($value)) {
throw new AphrontParameterQueryException(
$query,
pht('Expected a scalar or null for %%%s conversion.', $type));
}
break;
case 'R':
if (!($value instanceof AphrontDatabaseTableRefInterface)) {
throw new AphrontParameterQueryException(
$query,
pht(
'Parameter to "%s" conversion in "qsprintf(...)" is not an '.
'instance of AphrontDatabaseTableRefInterface.',
'%R'));
}
break;
case 'P':
if (!($value instanceof PhutilOpaqueEnvelope)) {
throw new AphrontParameterQueryException(
$query,
pht(
'Parameter to "%s" conversion in "qsprintf(...)" is not an '.
'instance of PhutilOpaqueEnvelope.',
'%P'));
}
break;
default:
throw new XsprintfUnknownConversionException($type);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/xsprintf/queryfx.php | src/infrastructure/storage/xsprintf/queryfx.php | <?php
function queryfx(AphrontDatabaseConnection $conn, $sql /* , ... */) {
$argv = func_get_args();
$query = call_user_func_array('qsprintf', $argv);
$conn->setLastActiveEpoch(time());
$conn->executeQuery($query);
}
function queryfx_all(AphrontDatabaseConnection $conn, $sql /* , ... */) {
$argv = func_get_args();
call_user_func_array('queryfx', $argv);
return $conn->selectAllResults();
}
function queryfx_one(AphrontDatabaseConnection $conn, $sql /* , ... */) {
$argv = func_get_args();
$ret = call_user_func_array('queryfx_all', $argv);
if (count($ret) > 1) {
throw new AphrontCountQueryException(
pht('Query returned more than one row.'));
} else if (count($ret)) {
return reset($ret);
}
return null;
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/xsprintf/PhutilQsprintfInterface.php | src/infrastructure/storage/xsprintf/PhutilQsprintfInterface.php | <?php
interface PhutilQsprintfInterface {
public function escapeBinaryString($string);
public function escapeUTF8String($string);
public function escapeColumnName($string);
public function escapeMultilineComment($string);
public function escapeStringForLikeClause($string);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/xsprintf/AphrontDatabaseTableRefInterface.php | src/infrastructure/storage/xsprintf/AphrontDatabaseTableRefInterface.php | <?php
interface AphrontDatabaseTableRefInterface {
public function getAphrontRefDatabaseName();
public function getAphrontRefTableName();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/xsprintf/PhutilQueryString.php | src/infrastructure/storage/xsprintf/PhutilQueryString.php | <?php
final class PhutilQueryString extends Phobject {
private $maskedString;
private $unmaskedString;
public function __construct(PhutilQsprintfInterface $escaper, array $argv) {
// Immediately render the query into a static scalar value.
// This makes sure we throw immediately if there are errors in the
// parameters, which is much better than throwing later on.
// This also makes sure that later mutations to objects passed as
// parameters won't affect the outcome. Consider:
//
// $object->setTableName('X');
// $query = qsprintf($conn, '%R', $object);
// $object->setTableName('Y');
//
// We'd like "$query" to reference "X", reflecting the object as it
// existed when it was passed to "qsprintf(...)". It's surprising if the
// modification to the object after "qsprintf(...)" can affect "$query".
$masked_string = xsprintf(
'xsprintf_query',
array(
'escaper' => $escaper,
'unmasked' => false,
),
$argv);
$unmasked_string = xsprintf(
'xsprintf_query',
array(
'escaper' => $escaper,
'unmasked' => true,
),
$argv);
$this->maskedString = $masked_string;
$this->unmaskedString = $unmasked_string;
}
public function __toString() {
return $this->getMaskedString();
}
public function getUnmaskedString() {
return $this->unmaskedString;
}
public function getMaskedString() {
return $this->maskedString;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/xsprintf/AphrontDatabaseTableRef.php | src/infrastructure/storage/xsprintf/AphrontDatabaseTableRef.php | <?php
final class AphrontDatabaseTableRef
extends Phobject
implements AphrontDatabaseTableRefInterface {
private $database;
private $table;
public function __construct($database, $table) {
$this->database = $database;
$this->table = $table;
}
public function getAphrontRefDatabaseName() {
return $this->database;
}
public function getAphrontRefTableName() {
return $this->table;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontQueryException.php | src/infrastructure/storage/exception/AphrontQueryException.php | <?php
/**
* @concrete-extensible
*/
class AphrontQueryException extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontQueryTimeoutQueryException.php | src/infrastructure/storage/exception/AphrontQueryTimeoutQueryException.php | <?php
final class AphrontQueryTimeoutQueryException
extends AphrontRecoverableQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontNotSupportedQueryException.php | src/infrastructure/storage/exception/AphrontNotSupportedQueryException.php | <?php
final class AphrontNotSupportedQueryException extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontInvalidCredentialsQueryException.php | src/infrastructure/storage/exception/AphrontInvalidCredentialsQueryException.php | <?php
final class AphrontInvalidCredentialsQueryException
extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontConnectionQueryException.php | src/infrastructure/storage/exception/AphrontConnectionQueryException.php | <?php
final class AphrontConnectionQueryException extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontCharacterSetQueryException.php | src/infrastructure/storage/exception/AphrontCharacterSetQueryException.php | <?php
final class AphrontCharacterSetQueryException extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontDuplicateKeyQueryException.php | src/infrastructure/storage/exception/AphrontDuplicateKeyQueryException.php | <?php
final class AphrontDuplicateKeyQueryException extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontParameterQueryException.php | src/infrastructure/storage/exception/AphrontParameterQueryException.php | <?php
final class AphrontParameterQueryException extends AphrontQueryException {
private $query;
public function __construct($query, $message) {
parent::__construct(pht('%s Query: %s', $message, $query));
$this->query = $query;
}
public function getQuery() {
return $this->query;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontLockTimeoutQueryException.php | src/infrastructure/storage/exception/AphrontLockTimeoutQueryException.php | <?php
final class AphrontLockTimeoutQueryException
extends AphrontRecoverableQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontDeadlockQueryException.php | src/infrastructure/storage/exception/AphrontDeadlockQueryException.php | <?php
final class AphrontDeadlockQueryException
extends AphrontRecoverableQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontConnectionLostQueryException.php | src/infrastructure/storage/exception/AphrontConnectionLostQueryException.php | <?php
final class AphrontConnectionLostQueryException
extends AphrontRecoverableQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontCountQueryException.php | src/infrastructure/storage/exception/AphrontCountQueryException.php | <?php
final class AphrontCountQueryException extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontSchemaQueryException.php | src/infrastructure/storage/exception/AphrontSchemaQueryException.php | <?php
final class AphrontSchemaQueryException extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontObjectMissingQueryException.php | src/infrastructure/storage/exception/AphrontObjectMissingQueryException.php | <?php
final class AphrontObjectMissingQueryException extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontRecoverableQueryException.php | src/infrastructure/storage/exception/AphrontRecoverableQueryException.php | <?php
abstract class AphrontRecoverableQueryException extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/exception/AphrontAccessDeniedQueryException.php | src/infrastructure/storage/exception/AphrontAccessDeniedQueryException.php | <?php
final class AphrontAccessDeniedQueryException
extends AphrontQueryException {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/patch/PhabricatorSQLPatchList.php | src/infrastructure/storage/patch/PhabricatorSQLPatchList.php | <?php
abstract class PhabricatorSQLPatchList extends Phobject {
abstract public function getNamespace();
abstract public function getPatches();
/**
* Examine a directory for `.php` and `.sql` files and build patch
* specifications for them.
*/
protected function buildPatchesFromDirectory($directory) {
$patch_list = Filesystem::listDirectory(
$directory,
$include_hidden = false);
sort($patch_list);
$patches = array();
foreach ($patch_list as $patch) {
$matches = null;
if (!preg_match('/\.(sql|php)$/', $patch, $matches)) {
throw new Exception(
pht(
'Unknown patch "%s" in "%s", expected ".php" or ".sql" suffix.',
$patch,
$directory));
}
$patch_type = $matches[1];
$patch_full_path = rtrim($directory, '/').'/'.$patch;
$attributes = array();
if ($patch_type === 'php') {
$attributes = $this->getPHPPatchAttributes(
$patch,
$patch_full_path);
}
$patches[$patch] = array(
'type' => $patch_type,
'name' => $patch_full_path,
) + $attributes;
}
return $patches;
}
final public static function buildAllPatches() {
$patch_lists = id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getNamespace')
->execute();
$specs = array();
$seen_namespaces = array();
$phases = PhabricatorStoragePatch::getPhaseList();
$phases = array_fuse($phases);
$default_phase = PhabricatorStoragePatch::getDefaultPhase();
foreach ($patch_lists as $patch_list) {
$last_keys = array_fill_keys(
array_keys($phases),
null);
foreach ($patch_list->getPatches() as $key => $patch) {
if (!is_array($patch)) {
throw new Exception(
pht(
"%s '%s' has a patch '%s' which is not an array.",
__CLASS__,
get_class($patch_list),
$key));
}
$valid = array(
'type' => true,
'name' => true,
'after' => true,
'legacy' => true,
'dead' => true,
'phase' => true,
);
foreach ($patch as $pkey => $pval) {
if (empty($valid[$pkey])) {
throw new Exception(
pht(
"%s '%s' has a patch, '%s', with an unknown property, '%s'.".
"Patches must have only valid keys: %s.",
__CLASS__,
get_class($patch_list),
$key,
$pkey,
implode(', ', array_keys($valid))));
}
}
if (is_numeric($key)) {
throw new Exception(
pht(
"%s '%s' has a patch with a numeric key, '%s'. ".
"Patches must use string keys.",
__CLASS__,
get_class($patch_list),
$key));
}
if (strpos($key, ':') !== false) {
throw new Exception(
pht(
"%s '%s' has a patch with a colon in the key name, '%s'. ".
"Patch keys may not contain colons.",
__CLASS__,
get_class($patch_list),
$key));
}
$namespace = $patch_list->getNamespace();
$full_key = "{$namespace}:{$key}";
if (isset($specs[$full_key])) {
throw new Exception(
pht(
"%s '%s' has a patch '%s' which duplicates an ".
"existing patch key.",
__CLASS__,
get_class($patch_list),
$key));
}
$patch['key'] = $key;
$patch['fullKey'] = $full_key;
$patch['dead'] = (bool)idx($patch, 'dead', false);
if (isset($patch['legacy'])) {
if ($namespace != 'phabricator') {
throw new Exception(
pht(
"Only patches in the '%s' namespace may contain '%s' keys.",
'phabricator',
'legacy'));
}
} else {
$patch['legacy'] = false;
}
if (!array_key_exists('phase', $patch)) {
$patch['phase'] = $default_phase;
}
$patch_phase = $patch['phase'];
if (!isset($phases[$patch_phase])) {
throw new Exception(
pht(
'Storage patch "%s" specifies it should apply in phase "%s", '.
'but this phase is unrecognized. Valid phases are: %s.',
$full_key,
$patch_phase,
implode(', ', array_keys($phases))));
}
$last_key = $last_keys[$patch_phase];
if (!array_key_exists('after', $patch)) {
if ($last_key === null && $patch_phase === $default_phase) {
throw new Exception(
pht(
"Patch '%s' is missing key 'after', and is the first patch ".
"in the patch list '%s', so its application order can not be ".
"determined implicitly. The first patch in a patch list must ".
"list the patch or patches it depends on explicitly.",
$full_key,
get_class($patch_list)));
} else {
if ($last_key === null) {
$patch['after'] = array();
} else {
$patch['after'] = array($last_key);
}
}
}
$last_keys[$patch_phase] = $full_key;
foreach ($patch['after'] as $after_key => $after) {
if (strpos($after, ':') === false) {
$patch['after'][$after_key] = $namespace.':'.$after;
}
}
$type = idx($patch, 'type');
if (!$type) {
throw new Exception(
pht(
"Patch '%s' is missing key '%s'. Every patch must have a type.",
"{$namespace}:{$key}",
'type'));
}
switch ($type) {
case 'db':
case 'sql':
case 'php':
break;
default:
throw new Exception(
pht(
"Patch '%s' has unknown patch type '%s'.",
"{$namespace}:{$key}",
$type));
}
$specs[$full_key] = $patch;
}
}
foreach ($specs as $key => $patch) {
foreach ($patch['after'] as $after) {
if (empty($specs[$after])) {
throw new Exception(
pht(
"Patch '%s' references nonexistent dependency, '%s'. ".
"Patches may only depend on patches which actually exist.",
$key,
$after));
}
$patch_phase = $patch['phase'];
$after_phase = $specs[$after]['phase'];
if ($patch_phase !== $after_phase) {
throw new Exception(
pht(
'Storage patch "%s" executes in phase "%s", but depends on '.
'patch "%s" which is in a different phase ("%s"). Patches '.
'may not have dependencies across phases.',
$key,
$patch_phase,
$after,
$after_phase));
}
}
}
$patches = array();
foreach ($specs as $full_key => $spec) {
$patches[$full_key] = new PhabricatorStoragePatch($spec);
}
// TODO: Detect cycles?
$patches = msortv($patches, 'newSortVector');
return $patches;
}
private function getPHPPatchAttributes($patch_name, $full_path) {
$data = Filesystem::readFile($full_path);
$phase_list = PhabricatorStoragePatch::getPhaseList();
$phase_map = array_fuse($phase_list);
$attributes = array();
$lines = phutil_split_lines($data, false);
foreach ($lines as $line) {
// Skip over the "PHP" line.
if (preg_match('(^<\?)', $line)) {
continue;
}
// Skip over blank lines.
if (!strlen(trim($line))) {
continue;
}
// If this is a "//" comment...
if (preg_match('(^\s*//)', $line)) {
$matches = null;
if (preg_match('(^\s*//\s*@(\S+)(?:\s+(.*))?\z)', $line, $matches)) {
$attr_key = $matches[1];
$attr_value = trim(idx($matches, 2));
switch ($attr_key) {
case 'phase':
$phase_name = $attr_value;
if (!strlen($phase_name)) {
throw new Exception(
pht(
'Storage patch "%s" specifies a "@phase" attribute with '.
'no phase value. Phase attributes must specify a value, '.
'like "@phase default".',
$patch_name));
}
if (!isset($phase_map[$phase_name])) {
throw new Exception(
pht(
'Storage patch "%s" specifies a "@phase" value ("%s"), '.
'but this is not a recognized phase. Valid phases '.
'are: %s.',
$patch_name,
$phase_name,
implode(', ', $phase_list)));
}
if (isset($attributes['phase'])) {
throw new Exception(
pht(
'Storage patch "%s" specifies a "@phase" value ("%s"), '.
'but it already has a specified phase ("%s"). Patches '.
'may not specify multiple phases.',
$patch_name,
$phase_name,
$attributes['phase']));
}
$attributes[$attr_key] = $phase_name;
break;
default:
throw new Exception(
pht(
'Storage patch "%s" specifies attribute "%s", but this '.
'attribute is unknown.',
$patch_name,
$attr_key));
}
}
continue;
}
// If this is anything else, we're all done. Attributes must be marked
// in the header of the file.
break;
}
return $attributes;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/storage/patch/PhabricatorBuiltinPatchList.php | src/infrastructure/storage/patch/PhabricatorBuiltinPatchList.php | <?php
final class PhabricatorBuiltinPatchList extends PhabricatorSQLPatchList {
public function getNamespace() {
return 'phabricator';
}
private function getPatchPath($file) {
$root = dirname(phutil_get_library_root('phabricator'));
$path = $root.'/resources/sql/patches/'.$file;
// Make sure it exists.
Filesystem::readFile($path);
return $path;
}
public function getPatches() {
$patches = array();
foreach ($this->getOldPatches() as $old_name => $old_patch) {
if (preg_match('/^db\./', $old_name)) {
$old_patch['name'] = substr($old_name, 3);
$old_patch['type'] = 'db';
} else {
if (empty($old_patch['name'])) {
$old_patch['name'] = $this->getPatchPath($old_name);
}
if (empty($old_patch['type'])) {
$matches = null;
preg_match('/\.(sql|php)$/', $old_name, $matches);
$old_patch['type'] = $matches[1];
}
}
$patches[$old_name] = $old_patch;
}
$root = dirname(phutil_get_library_root('phabricator'));
$auto_root = $root.'/resources/sql/autopatches/';
$patches += $this->buildPatchesFromDirectory($auto_root);
return $patches;
}
public function getOldPatches() {
return array(
'db.audit' => array(
'after' => array( /* First Patch */ ),
),
'db.calendar' => array(),
'db.chatlog' => array(),
'db.conduit' => array(),
'db.countdown' => array(),
'db.daemon' => array(),
'db.differential' => array(),
'db.draft' => array(),
'db.drydock' => array(),
'db.feed' => array(),
'db.file' => array(),
'db.flag' => array(),
'db.harbormaster' => array(),
'db.herald' => array(),
'db.maniphest' => array(),
'db.meta_data' => array(),
'db.metamta' => array(),
'db.oauth_server' => array(),
'db.owners' => array(),
'db.pastebin' => array(
'dead' => true,
),
'db.phame' => array(),
'db.phriction' => array(),
'db.project' => array(),
'db.repository' => array(),
'db.search' => array(),
'db.slowvote' => array(),
'db.timeline' => array(
'dead' => true,
),
'db.user' => array(),
'db.worker' => array(),
'db.xhpast' => array(),
'db.xhpastview' => array(
'dead' => true,
),
'db.cache' => array(),
'db.fact' => array(),
'db.ponder' => array(),
'db.xhprof' => array(),
'db.pholio' => array(),
'db.conpherence' => array(),
'db.config' => array(),
'db.token' => array(),
'db.phlux' => array(),
'db.phortune' => array(),
'db.phrequent' => array(),
'db.diviner' => array(),
'db.auth' => array(),
'db.doorkeeper' => array(),
'db.legalpad' => array(),
'db.policy' => array(),
'db.nuance' => array(),
'db.passphrase' => array(),
'db.dashboard' => array(),
'db.system' => array(),
'db.fund' => array(),
'db.almanac' => array(),
'db.multimeter' => array(),
'db.spaces' => array(),
'db.phurl' => array(),
'db.badges' => array(),
'db.packages' => array(),
'db.application' => array(),
'db.paste' => array(),
'0000.legacy.sql' => array(
'legacy' => 0,
),
'000.project.sql' => array(
'legacy' => 0,
),
'001.maniphest_projects.sql' => array(
'legacy' => 1,
),
'002.oauth.sql' => array(
'legacy' => 2,
),
'003.more_oauth.sql' => array(
'legacy' => 3,
),
'004.daemonrepos.sql' => array(
'legacy' => 4,
),
'005.workers.sql' => array(
'legacy' => 5,
),
'006.repository.sql' => array(
'legacy' => 6,
),
'007.daemonlog.sql' => array(
'legacy' => 7,
),
'008.repoopt.sql' => array(
'legacy' => 8,
),
'009.repo_summary.sql' => array(
'legacy' => 9,
),
'010.herald.sql' => array(
'legacy' => 10,
),
'011.badcommit.sql' => array(
'legacy' => 11,
),
'012.dropphidtype.sql' => array(
'legacy' => 12,
),
'013.commitdetail.sql' => array(
'legacy' => 13,
),
'014.shortcuts.sql' => array(
'legacy' => 14,
),
'015.preferences.sql' => array(
'legacy' => 15,
),
'016.userrealnameindex.sql' => array(
'legacy' => 16,
),
'017.sessionkeys.sql' => array(
'legacy' => 17,
),
'018.owners.sql' => array(
'legacy' => 18,
),
'019.arcprojects.sql' => array(
'legacy' => 19,
),
'020.pathcapital.sql' => array(
'legacy' => 20,
),
'021.xhpastview.sql' => array(
'legacy' => 21,
),
'022.differentialcommit.sql' => array(
'legacy' => 22,
),
'023.dxkeys.sql' => array(
'legacy' => 23,
),
'024.mlistkeys.sql' => array(
'legacy' => 24,
),
'025.commentopt.sql' => array(
'legacy' => 25,
),
'026.diffpropkey.sql' => array(
'legacy' => 26,
),
'027.metamtakeys.sql' => array(
'legacy' => 27,
),
'028.systemagent.sql' => array(
'legacy' => 28,
),
'029.cursors.sql' => array(
'legacy' => 29,
),
'030.imagemacro.sql' => array(
'legacy' => 30,
),
'031.workerrace.sql' => array(
'legacy' => 31,
),
'032.viewtime.sql' => array(
'legacy' => 32,
),
'033.privtest.sql' => array(
'legacy' => 33,
),
'034.savedheader.sql' => array(
'legacy' => 34,
),
'035.proxyimage.sql' => array(
'legacy' => 35,
),
'036.mailkey.sql' => array(
'legacy' => 36,
),
'037.setuptest.sql' => array(
'legacy' => 37,
),
'038.admin.sql' => array(
'legacy' => 38,
),
'039.userlog.sql' => array(
'legacy' => 39,
),
'040.transform.sql' => array(
'legacy' => 40,
),
'041.heraldrepetition.sql' => array(
'legacy' => 41,
),
'042.commentmetadata.sql' => array(
'legacy' => 42,
),
'043.pastebin.sql' => array(
'legacy' => 43,
),
'044.countdown.sql' => array(
'legacy' => 44,
),
'045.timezone.sql' => array(
'legacy' => 45,
),
'046.conduittoken.sql' => array(
'legacy' => 46,
),
'047.projectstatus.sql' => array(
'legacy' => 47,
),
'048.relationshipkeys.sql' => array(
'legacy' => 48,
),
'049.projectowner.sql' => array(
'legacy' => 49,
),
'050.taskdenormal.sql' => array(
'legacy' => 50,
),
'051.projectfilter.sql' => array(
'legacy' => 51,
),
'052.pastelanguage.sql' => array(
'legacy' => 52,
),
'053.feed.sql' => array(
'legacy' => 53,
),
'054.subscribers.sql' => array(
'legacy' => 54,
),
'055.add_author_to_files.sql' => array(
'legacy' => 55,
),
'056.slowvote.sql' => array(
'legacy' => 56,
),
'057.parsecache.sql' => array(
'legacy' => 57,
),
'058.missingkeys.sql' => array(
'legacy' => 58,
),
'059.engines.php' => array(
'legacy' => 59,
),
'060.phriction.sql' => array(
'legacy' => 60,
),
'061.phrictioncontent.sql' => array(
'legacy' => 61,
),
'062.phrictionmenu.sql' => array(
'legacy' => 62,
),
'063.pasteforks.sql' => array(
'legacy' => 63,
),
'064.subprojects.sql' => array(
'legacy' => 64,
),
'065.sshkeys.sql' => array(
'legacy' => 65,
),
'066.phrictioncontent.sql' => array(
'legacy' => 66,
),
'067.preferences.sql' => array(
'legacy' => 67,
),
'068.maniphestauxiliarystorage.sql' => array(
'legacy' => 68,
),
'069.heraldxscript.sql' => array(
'legacy' => 69,
),
'070.differentialaux.sql' => array(
'legacy' => 70,
),
'071.contentsource.sql' => array(
'legacy' => 71,
),
'072.blamerevert.sql' => array(
'legacy' => 72,
),
'073.reposymbols.sql' => array(
'legacy' => 73,
),
'074.affectedpath.sql' => array(
'legacy' => 74,
),
'075.revisionhash.sql' => array(
'legacy' => 75,
),
'076.indexedlanguages.sql' => array(
'legacy' => 76,
),
'077.originalemail.sql' => array(
'legacy' => 77,
),
'078.nametoken.sql' => array(
'legacy' => 78,
),
'079.nametokenindex.php' => array(
'legacy' => 79,
),
'080.filekeys.sql' => array(
'legacy' => 80,
),
'081.filekeys.php' => array(
'legacy' => 81,
),
'082.xactionkey.sql' => array(
'legacy' => 82,
),
'083.dxviewtime.sql' => array(
'legacy' => 83,
),
'084.pasteauthorkey.sql' => array(
'legacy' => 84,
),
'085.packagecommitrelationship.sql' => array(
'legacy' => 85,
),
'086.formeraffil.sql' => array(
'legacy' => 86,
),
'087.phrictiondelete.sql' => array(
'legacy' => 87,
),
'088.audit.sql' => array(
'legacy' => 88,
),
'089.projectwiki.sql' => array(
'legacy' => 89,
),
'090.forceuniqueprojectnames.php' => array(
'legacy' => 90,
),
'091.uniqueslugkey.sql' => array(
'legacy' => 91,
),
'092.dropgithubnotification.sql' => array(
'legacy' => 92,
),
'093.gitremotes.php' => array(
'legacy' => 93,
),
'094.phrictioncolumn.sql' => array(
'legacy' => 94,
),
'095.directory.sql' => array(
'legacy' => 95,
),
'096.filename.sql' => array(
'legacy' => 96,
),
'097.heraldruletypes.sql' => array(
'legacy' => 97,
),
'098.heraldruletypemigration.php' => array(
'legacy' => 98,
),
'099.drydock.sql' => array(
'legacy' => 99,
),
'100.projectxaction.sql' => array(
'legacy' => 100,
),
'101.heraldruleapplied.sql' => array(
'legacy' => 101,
),
'102.heraldcleanup.php' => array(
'legacy' => 102,
),
'103.heraldedithistory.sql' => array(
'legacy' => 103,
),
'104.searchkey.sql' => array(
'legacy' => 104,
),
'105.mimetype.sql' => array(
'legacy' => 105,
),
'106.chatlog.sql' => array(
'legacy' => 106,
),
'107.oauthserver.sql' => array(
'legacy' => 107,
),
'108.oauthscope.sql' => array(
'legacy' => 108,
),
'109.oauthclientphidkey.sql' => array(
'legacy' => 109,
),
'110.commitaudit.sql' => array(
'legacy' => 110,
),
'111.commitauditmigration.php' => array(
'legacy' => 111,
),
'112.oauthaccesscoderedirecturi.sql' => array(
'legacy' => 112,
),
'113.lastreviewer.sql' => array(
'legacy' => 113,
),
'114.auditrequest.sql' => array(
'legacy' => 114,
),
'115.prepareutf8.sql' => array(
'legacy' => 115,
),
'116.utf8-backup-first-expect-wait.sql' => array(
'legacy' => 116,
),
'117.repositorydescription.php' => array(
'legacy' => 117,
),
'118.auditinline.sql' => array(
'legacy' => 118,
),
'119.filehash.sql' => array(
'legacy' => 119,
),
'120.noop.sql' => array(
'legacy' => 120,
),
'121.drydocklog.sql' => array(
'legacy' => 121,
),
'122.flag.sql' => array(
'legacy' => 122,
),
'123.heraldrulelog.sql' => array(
'legacy' => 123,
),
'124.subpriority.sql' => array(
'legacy' => 124,
),
'125.ipv6.sql' => array(
'legacy' => 125,
),
'126.edges.sql' => array(
'legacy' => 126,
),
'127.userkeybody.sql' => array(
'legacy' => 127,
),
'128.phabricatorcom.sql' => array(
'legacy' => 128,
),
'129.savedquery.sql' => array(
'legacy' => 129,
),
'130.denormalrevisionquery.sql' => array(
'legacy' => 130,
),
'131.migraterevisionquery.php' => array(
'legacy' => 131,
),
'132.phame.sql' => array(
'legacy' => 132,
),
'133.imagemacro.sql' => array(
'legacy' => 133,
),
'134.emptysearch.sql' => array(
'legacy' => 134,
),
'135.datecommitted.sql' => array(
'legacy' => 135,
),
'136.sex.sql' => array(
'legacy' => 136,
),
'137.auditmetadata.sql' => array(
'legacy' => 137,
),
'138.notification.sql' => array(),
'holidays.sql' => array(),
'userstatus.sql' => array(),
'emailtable.sql' => array(),
'emailtableport.sql' => array(
// NOTE: This is a ".php" patch, but the key is ".sql".
'type' => 'php',
'name' => $this->getPatchPath('emailtableport.php'),
),
'emailtableremove.sql' => array(),
'phiddrop.sql' => array(),
'testdatabase.sql' => array(),
'ldapinfo.sql' => array(),
'threadtopic.sql' => array(),
'usertranslation.sql' => array(),
'differentialbookmarks.sql' => array(),
'harbormasterobject.sql' => array(),
'markupcache.sql' => array(),
'maniphestxcache.sql' => array(),
'migrate-maniphest-dependencies.php' => array(),
'migrate-differential-dependencies.php' => array(),
'phameblog.sql' => array(),
'migrate-maniphest-revisions.php' => array(),
'daemonstatus.sql' => array(),
'symbolcontexts.sql' => array(),
'migrate-project-edges.php' => array(),
'fact-raw.sql' => array(),
'ponder.sql' => array(),
'policy-project.sql' => array(),
'daemonstatuskey.sql' => array(),
'edgetype.sql' => array(),
'ponder-comments.sql' => array(),
'pastepolicy.sql' => array(),
'xhprof.sql' => array(),
'draft-metadata.sql' => array(),
'phamedomain.sql' => array(),
'ponder-mailkey.sql' => array(),
'ponder-mailkey-populate.php' => array(),
'phamepolicy.sql' => array(),
'phameoneblog.sql' => array(),
'statustxt.sql' => array(),
'daemontaskarchive.sql' => array(),
'drydocktaskid.sql' => array(),
'drydockresoucetype.sql' => array(
// NOTE: The key for this patch misspells "resource" as "resouce".
'name' => $this->getPatchPath('drydockresourcetype.sql'),
),
'liskcounters.sql' => array(),
'liskcounters.php' => array(),
'dropfileproxyimage.sql' => array(),
'repository-lint.sql' => array(),
'liskcounters-task.sql' => array(),
'pholio.sql' => array(),
'owners-exclude.sql' => array(),
'20121209.pholioxactions.sql' => array(),
'20121209.xmacroadd.sql' => array(),
'20121209.xmacromigrate.php' => array(),
'20121209.xmacromigratekey.sql' => array(),
'20121220.generalcache.sql' => array(),
'20121226.config.sql' => array(),
'20130101.confxaction.sql' => array(),
'20130102.metamtareceivedmailmessageidhash.sql' => array(),
'20130103.filemetadata.sql' => array(),
'20130111.conpherence.sql' => array(),
'20130127.altheraldtranscript.sql' => array(),
'20130201.revisionunsubscribed.php' => array(),
'20130201.revisionunsubscribed.sql' => array(),
'20130131.conpherencepics.sql' => array(),
'20130214.chatlogchannel.sql' => array(),
'20130214.chatlogchannelid.sql' => array(),
'20130214.token.sql' => array(),
'20130215.phabricatorfileaddttl.sql' => array(),
'20130217.cachettl.sql' => array(),
'20130218.updatechannelid.php' => array(),
'20130218.longdaemon.sql' => array(),
'20130219.commitsummary.sql' => array(),
'20130219.commitsummarymig.php' => array(),
'20130222.dropchannel.sql' => array(),
'20130226.commitkey.sql' => array(),
'20131302.maniphestvalue.sql' => array(),
'20130304.lintauthor.sql' => array(),
'releeph.sql' => array(),
'20130319.phabricatorfileexplicitupload.sql' => array(),
'20130319.conpherence.sql' => array(),
'20130320.phlux.sql' => array(),
'20130317.phrictionedge.sql' => array(),
'20130321.token.sql' => array(),
'20130310.xactionmeta.sql' => array(),
'20130322.phortune.sql' => array(),
'20130323.phortunepayment.sql' => array(),
'20130324.phortuneproduct.sql' => array(),
'20130330.phrequent.sql' => array(),
'20130403.conpherencecache.sql' => array(),
'20130403.conpherencecachemig.php' => array(),
'20130409.commitdrev.php' => array(),
'20130417.externalaccount.sql' => array(),
'20130423.updateexternalaccount.sql' => array(),
'20130423.phortunepaymentrevised.sql' => array(),
'20130423.conpherenceindices.sql' => array(),
'20130426.search_savedquery.sql' => array(),
'20130502.countdownrevamp1.sql' => array(),
'20130502.countdownrevamp2.php' => array(),
'20130502.countdownrevamp3.sql' => array(),
'20130507.releephrqsimplifycols.sql' => array(),
'20130507.releephrqmailkey.sql' => array(),
'20130507.releephrqmailkeypop.php' => array(),
'20130508.search_namedquery.sql' => array(),
'20130508.releephtransactions.sql' => array(),
'20130508.releephtransactionsmig.php' => array(),
'20130513.receviedmailstatus.sql' => array(),
'20130519.diviner.sql' => array(),
'20130521.dropconphimages.sql' => array(),
'20130523.maniphest_owners.sql' => array(),
'20130524.repoxactions.sql' => array(),
'20130529.macroauthor.sql' => array(),
'20130529.macroauthormig.php' => array(),
'20130530.sessionhash.php' => array(),
'20130530.macrodatekey.sql' => array(),
'20130530.pastekeys.sql' => array(),
'20130531.filekeys.sql' => array(),
'20130602.morediviner.sql' => array(),
'20130602.namedqueries.sql' => array(),
'20130606.userxactions.sql' => array(),
'20130607.xaccount.sql' => array(),
'20130611.migrateoauth.php' => array(),
'20130611.nukeldap.php' => array(),
'20130613.authdb.sql' => array(),
'20130619.authconf.php' => array(),
'20130620.diffxactions.sql' => array(),
'20130621.diffcommentphid.sql' => array(),
'20130621.diffcommentphidmig.php' => array(),
'20130621.diffcommentunphid.sql' => array(),
'20130622.doorkeeper.sql' => array(),
'20130628.legalpadv0.sql' => array(),
'20130701.conduitlog.sql' => array(),
'legalpad-mailkey.sql' => array(),
'legalpad-mailkey-populate.php' => array(),
'20130703.legalpaddocdenorm.sql' => array(),
'20130703.legalpaddocdenorm.php' => array(),
'20130709.legalpadsignature.sql' => array(),
'20130709.droptimeline.sql' => array(),
'20130711.trimrealnames.php' => array(),
'20130714.votexactions.sql' => array(),
'20130715.votecomments.php' => array(),
'20130715.voteedges.sql' => array(),
'20130711.pholioimageobsolete.sql' => array(),
'20130711.pholioimageobsolete.php' => array(),
'20130711.pholioimageobsolete2.sql' => array(),
'20130716.archivememberlessprojects.php' => array(),
'20130722.pholioreplace.sql' => array(),
'20130723.taskstarttime.sql' => array(),
'20130727.ponderquestionstatus.sql' => array(),
'20130726.ponderxactions.sql' => array(),
'20130728.ponderunique.php' => array(),
'20130728.ponderuniquekey.sql' => array(),
'20130728.ponderxcomment.php' => array(),
'20130801.pastexactions.sql' => array(),
'20130801.pastexactions.php' => array(),
'20130805.pastemailkey.sql' => array(),
'20130805.pasteedges.sql' => array(),
'20130805.pastemailkeypop.php' => array(),
'20130802.heraldphid.sql' => array(),
'20130802.heraldphids.php' => array(),
'20130802.heraldphidukey.sql' => array(),
'20130802.heraldxactions.sql' => array(),
'20130731.releephrepoid.sql' => array(),
'20130731.releephproject.sql' => array(),
'20130731.releephcutpointidentifier.sql' => array(),
'20130814.usercustom.sql' => array(),
'20130820.releephxactions.sql' => array(),
'20130826.divinernode.sql' => array(),
'20130820.filexactions.sql' => array(),
'20130820.filemailkey.sql' => array(),
'20130820.file-mailkey-populate.php' => array(),
'20130912.maniphest.1.touch.sql' => array(),
'20130912.maniphest.2.created.sql' => array(),
'20130912.maniphest.3.nameindex.sql' => array(),
'20130912.maniphest.4.fillindex.php' => array(),
'20130913.maniphest.1.migratesearch.php' => array(),
'20130914.usercustom.sql' => array(),
'20130915.maniphestcustom.sql' => array(),
'20130915.maniphestmigrate.php' => array(),
'20130919.mfieldconf.php' => array(),
'20130920.repokeyspolicy.sql' => array(),
'20130921.mtransactions.sql' => array(),
'20130921.xmigratemaniphest.php' => array(),
'20130923.mrename.sql' => array(),
'20130924.mdraftkey.sql' => array(),
'20130925.mpolicy.sql' => array(),
'20130925.xpolicy.sql' => array(),
'20130926.dcustom.sql' => array(),
'20130926.dinkeys.sql' => array(),
'20130927.audiomacro.sql' => array(),
'20130929.filepolicy.sql' => array(),
'20131004.dxedgekey.sql' => array(),
'20131004.dxreviewers.php' => array(),
'20131006.hdisable.sql' => array(),
'20131010.pstorage.sql' => array(),
'20131015.cpolicy.sql' => array(),
'20130915.maniphestqdrop.sql' => array(),
'20130926.dinline.php' => array(),
'20131020.pcustom.sql' => array(),
'20131020.col1.sql' => array(),
'20131020.pxaction.sql' => array(),
'20131020.pxactionmig.php' => array(),
'20131020.harbormaster.sql' => array(),
'20131025.repopush.sql' => array(),
'20131026.commitstatus.sql' => array(),
'20131030.repostatusmessage.sql' => array(),
'20131031.vcspassword.sql' => array(),
'20131105.buildstep.sql' => array(),
'20131106.diffphid.1.col.sql' => array(),
'20131106.diffphid.2.mig.php' => array(),
'20131106.diffphid.3.key.sql' => array(),
'20131106.nuance-v0.sql' => array(),
'20131107.buildlog.sql' => array(),
'20131112.userverified.1.col.sql' => array(),
'20131112.userverified.2.mig.php' => array(),
'20131118.ownerorder.php' => array(),
'20131119.passphrase.sql' => array(),
'20131120.nuancesourcetype.sql' => array(),
'20131121.passphraseedge.sql' => array(),
'20131121.repocredentials.1.col.sql' => array(),
'20131121.repocredentials.2.mig.php' => array(),
'20131122.repomirror.sql' => array(),
'20131123.drydockblueprintpolicy.sql' => array(),
'20131129.drydockresourceblueprint.sql' => array(),
'20131205.buildtargets.sql' => array(),
'20131204.pushlog.sql' => array(),
'20131205.buildsteporder.sql' => array(),
'20131205.buildstepordermig.php' => array(),
'20131206.phragment.sql' => array(),
'20131206.phragmentnull.sql' => array(),
'20131208.phragmentsnapshot.sql' => array(),
'20131211.phragmentedges.sql' => array(),
'20131217.pushlogphid.1.col.sql' => array(),
'20131217.pushlogphid.2.mig.php' => array(),
'20131217.pushlogphid.3.key.sql' => array(),
'20131219.pxdrop.sql' => array(),
'20131224.harbormanual.sql' => array(),
'20131227.heraldobject.sql' => array(),
'20131231.dropshortcut.sql' => array(),
);
// NOTE: STOP! Don't add new patches here.
// Use 'resources/sql/autopatches/' instead!
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.