code
stringlengths 15
9.96M
| docstring
stringlengths 1
10.1k
| func_name
stringlengths 1
124
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 6
186
| url
stringlengths 50
236
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function getID() {
$id_key = $this->getIDKey();
return $this->$id_key;
} | 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 | getID | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function hasProperty($property) {
return (bool)$this->checkProperty($property);
} | Test if a property exists.
@param string $property Property name.
@return bool True if the property exists.
@task info | hasProperty | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function checkProperty($property) {
$properties = $this->getAllLiskProperties();
$property = strtolower($property);
if (empty($properties[$property])) {
return null;
}
return $properties[$property];
} | Check if a property exists on this object.
@return string|null Canonical property name, or null if the property
does not exist.
@task info | checkProperty | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
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;
} | Get or build the database connection for this object.
@param string $mode 'r' for read, 'w' for read/write.
@param bool $force_new (optional) 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 | establishConnection | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
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;
} | 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 | getAllLiskPropertyValues | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function makeEphemeral() {
$this->ephemeral = true;
return $this;
} | 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. | makeEphemeral | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function save() {
if ($this->shouldInsertWhenSaved()) {
return $this->insert();
} else {
return $this->update();
}
} | 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 | save | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function replace() {
$this->isEphemeralCheck();
return $this->insertRecordIntoDatabase('REPLACE');
} | Save this object, forcing the query to use REPLACE regardless of object
state.
@return $this
@task save | replace | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function insert() {
$this->isEphemeralCheck();
return $this->insertRecordIntoDatabase('INSERT');
} | Save this object, forcing the query to use INSERT regardless of object
state.
@return $this
@task save | insert | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
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;
} | Delete this object, permanently.
@return $this
@task save | delete | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
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();
foreach ($data as $key => $value) {
try {
if (!empty($binary[$key])) {
$data[$key] = qsprintf($conn, '%nB', $value);
} else {
$data[$key] = qsprintf($conn, '%ns', $value);
}
} catch (AphrontParameterQueryException $parameter_exception) {
throw new Exception(
pht(
"Unable to insert or update object of class %s, field '%s' ".
"has a non-scalar value.",
get_class($this),
$key),
0,
$parameter_exception);
}
}
switch ($mode) {
case 'INSERT':
$verb = qsprintf($conn, 'INSERT');
break;
case 'REPLACE':
$verb = qsprintf($conn, 'REPLACE');
break;
default:
throw new Exception(
pht(
'Insert mode verb "%s" is not recognized, use INSERT or REPLACE.',
$mode));
}
$conn->query(
'%Q INTO %R (%LC) VALUES (%LQ)',
$verb,
$this,
$columns,
$data);
// Only use the insert id if this table is using auto-increment ids
if ($id_mechanism === self::IDS_AUTOINCREMENT) {
$this->setID($conn->getInsertID());
}
$this->didWriteData();
return $this;
} | Internal implementation of INSERT and REPLACE.
@param string $mode Either "INSERT" or "REPLACE", to force the desired
mode.
@return $this
@task save | insertRecordIntoDatabase | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function shouldInsertWhenSaved() {
$key_type = $this->getConfigOption(self::CONFIG_IDS);
if ($key_type == self::IDS_MANUAL) {
throw new Exception(
pht(
'You are using manual IDs. You must override the %s method '.
'to properly detect when to insert a new record.',
__FUNCTION__.'()'));
} else {
return !$this->getID();
}
} | Method used to determine whether to insert or update when saving.
@return bool true if the record should be inserted | shouldInsertWhenSaved | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function getTableName() {
return get_class($this);
} | Retrieve the database table name. By default, this is the class name.
@return string Table name for object storage.
@task hook | getTableName | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function getIDKey() {
return 'id';
} | Retrieve the primary key column, "id" by default. If you can not
reasonably name your ID column "id", override this method.
@return string Name of the ID column.
@task hook | getIDKey | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function generatePHID() {
$type = $this->getPHIDType();
return PhabricatorPHID::generateNewPHID($type);
} | Generate a new PHID, used by CONFIG_AUX_PHID.
@return string Unique, newly allocated PHID.
@task hook | generatePHID | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function willWriteData(array &$data) {
$this->applyLiskDataSerialization($data, false);
} | Hook to apply serialization or validation to data before it is written to
the database. See also @{method:willReadData}.
@task hook | willWriteData | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function didWriteData() {} | Hook to perform actions after data has been written to the database.
@task hook | didWriteData | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function willSaveObject() {
$use_timestamps = $this->getConfigOption(self::CONFIG_TIMESTAMPS);
if ($use_timestamps) {
if (!$this->getDateCreated()) {
$this->setDateCreated(time());
}
$this->setDateModified(time());
}
if ($this->getConfigOption(self::CONFIG_AUX_PHID) && !$this->getPHID()) {
$this->setPHID($this->generatePHID());
}
} | Hook to make internal object state changes prior to INSERT, REPLACE or
UPDATE.
@task hook | willSaveObject | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function willReadData(array &$data) {
$this->applyLiskDataSerialization($data, $deserialize = true);
} | Hook to apply serialization or validation to data as it is read from the
database. See also @{method:willWriteData}.
@task hook | willReadData | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function didReadData() {} | Hook to perform an action on data after it is read from the database.
@task hook | didReadData | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function willDelete() {} | Hook to perform an action before the deletion of an object.
@task hook | willDelete | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function didDelete() {} | Hook to perform an action after the deletion of an object.
@task hook | didDelete | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function readField($field) {
if (isset($this->$field)) {
return $this->$field;
}
return null;
} | Reads the value from a field. Override this method for custom behavior
of @{method:getField} instead of overriding getField directly.
@param string $field Canonical field name
@return mixed Value of the field
@task hook | readField | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function writeField($field, $value) {
$this->$field = $value;
} | Writes a value to a field. Override this method for custom behavior of
setField($value) instead of overriding setField directly.
@param string $field Canonical field name
@param mixed $value Value to write
@task hook | writeField | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function openTransaction() {
$this->establishConnection('w')->openTransaction();
return $this;
} | Increase transaction stack depth.
@return $this | openTransaction | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function saveTransaction() {
$this->establishConnection('w')->saveTransaction();
return $this;
} | Decrease transaction stack depth, saving work.
@return $this | saveTransaction | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function killTransaction() {
$this->establishConnection('w')->killTransaction();
return $this;
} | Decrease transaction stack depth, discarding work.
@return $this | killTransaction | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function endReadLocking() {
$this->establishConnection('w')->endReadLocking();
return $this;
} | Ends read-locking that began at an earlier @{method:beginReadLocking} call.
@return $this
@task xaction | endReadLocking | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function beginWriteLocking() {
$this->establishConnection('w')->beginWriteLocking();
return $this;
} | Begins write-locking selected rows with SELECT ... LOCK IN SHARE MODE, so
that other connections can not update or delete them (this is an
oversimplification of LOCK IN SHARE MODE semantics; consult the
MySQL documentation for details). To end write locking, call
@{method:endWriteLocking}.
@return $this
@task xaction | beginWriteLocking | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function beginIsolateAllLiskEffectsToCurrentProcess() {
self::$processIsolationLevel++;
} | @task isolate | beginIsolateAllLiskEffectsToCurrentProcess | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function endIsolateAllLiskEffectsToCurrentProcess() {
self::$processIsolationLevel--;
if (self::$processIsolationLevel < 0) {
throw new Exception(
pht('Lisk process isolation level was reduced below 0.'));
}
} | @task isolate | endIsolateAllLiskEffectsToCurrentProcess | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function shouldIsolateAllLiskEffectsToCurrentProcess() {
return (bool)self::$processIsolationLevel;
} | @task isolate | shouldIsolateAllLiskEffectsToCurrentProcess | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
private function establishIsolatedConnection($mode) {
$config = array();
return new AphrontIsolatedDatabaseConnection($config);
} | @task isolate | establishIsolatedConnection | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function beginIsolateAllLiskEffectsToTransactions() {
if (self::$transactionIsolationLevel === 0) {
self::closeAllConnections();
}
self::$transactionIsolationLevel++;
} | @task isolate | beginIsolateAllLiskEffectsToTransactions | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function endIsolateAllLiskEffectsToTransactions() {
self::$transactionIsolationLevel--;
if (self::$transactionIsolationLevel < 0) {
throw new Exception(
pht('Lisk transaction isolation level was reduced below 0.'));
} else if (self::$transactionIsolationLevel == 0) {
foreach (self::$connections as $key => $conn) {
if ($conn) {
$conn->killTransaction();
}
}
self::closeAllConnections();
}
} | @task isolate | endIsolateAllLiskEffectsToTransactions | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function shouldIsolateAllLiskEffectsToTransactions() {
return (bool)self::$transactionIsolationLevel;
} | @task isolate | shouldIsolateAllLiskEffectsToTransactions | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function applyLiskDataSerialization(array &$data, $deserialize) {
$serialization = $this->getConfigOption(self::CONFIG_SERIALIZATION);
if ($serialization) {
foreach (array_intersect_key($serialization, $data) as $col => $format) {
switch ($format) {
case self::SERIALIZATION_NONE:
break;
case self::SERIALIZATION_PHP:
if ($deserialize) {
$data[$col] = unserialize($data[$col]);
} else {
$data[$col] = serialize($data[$col]);
}
break;
case self::SERIALIZATION_JSON:
if ($deserialize) {
$data[$col] = json_decode($data[$col], true);
} else {
$data[$col] = phutil_json_encode($data[$col]);
}
break;
default:
throw new Exception(
pht("Unknown serialization format '%s'.", $format));
}
}
}
} | Applies configured serialization to a dictionary of values.
@task util | applyLiskDataSerialization | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function __call($method, $args) {
$dispatch_map = $this->getLiskMetadata('dispatchMap', array());
// NOTE: This method is very performance-sensitive (many thousands of calls
// per page on some pages), and thus has some silliness in the name of
// optimizations.
if ($method[0] === 'g') {
if (isset($dispatch_map[$method])) {
$property = $dispatch_map[$method];
} else {
if (substr($method, 0, 3) !== 'get') {
throw new Exception(pht("Unable to resolve method '%s'!", $method));
}
$property = substr($method, 3);
if (!($property = $this->checkProperty($property))) {
throw new Exception(pht('Bad getter call: %s', $method));
}
$dispatch_map[$method] = $property;
$this->setLiskMetadata('dispatchMap', $dispatch_map);
}
return $this->readField($property);
}
if ($method[0] === 's') {
if (isset($dispatch_map[$method])) {
$property = $dispatch_map[$method];
} else {
if (substr($method, 0, 3) !== 'set') {
throw new Exception(pht("Unable to resolve method '%s'!", $method));
}
$property = substr($method, 3);
$property = $this->checkProperty($property);
if (!$property) {
throw new Exception(pht('Bad setter call: %s', $method));
}
$dispatch_map[$method] = $property;
$this->setLiskMetadata('dispatchMap', $dispatch_map);
}
$this->writeField($property, $args[0]);
return $this;
}
throw new Exception(pht("Unable to resolve method '%s'.", $method));
} | Black magic. Builds implied get*() and set*() for all properties.
@param string $method Method name.
@param list $args Argument vector.
@return mixed get*() methods return the property value. set*() methods
return $this.
@task util | __call | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function __set($name, $value) {
// Hack for policy system hints, see PhabricatorPolicyRule for notes.
if ($name != '_hashKey') {
phlog(
pht(
'Wrote to undeclared property %s.',
get_class($this).'::$'.$name));
}
$this->$name = $value;
} | Warns against writing to undeclared property.
@task util | __set | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function loadNextCounterValue(
AphrontDatabaseConnection $conn_w,
$counter_name) {
// NOTE: If an insert does not touch an autoincrement row or call
// LAST_INSERT_ID(), MySQL normally does not change the value of
// LAST_INSERT_ID(). This can cause a counter's value to leak to a
// new counter if the second counter is created after the first one is
// updated. To avoid this, we insert LAST_INSERT_ID(1), to ensure the
// LAST_INSERT_ID() is always updated and always set correctly after the
// query completes.
queryfx(
$conn_w,
'INSERT INTO %T (counterName, counterValue) VALUES
(%s, LAST_INSERT_ID(1))
ON DUPLICATE KEY UPDATE
counterValue = LAST_INSERT_ID(counterValue + 1)',
self::COUNTER_TABLE_NAME,
$counter_name);
return $conn_w->getInsertID();
} | Increments a named counter and returns the next value.
@param AphrontDatabaseConnection $conn_w Database where the counter
resides.
@param string $counter_name Counter name to create
or increment.
@return int Next counter value.
@task util | loadNextCounterValue | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function loadCurrentCounterValue(
AphrontDatabaseConnection $conn_r,
$counter_name) {
$row = queryfx_one(
$conn_r,
'SELECT counterValue FROM %T WHERE counterName = %s',
self::COUNTER_TABLE_NAME,
$counter_name);
if (!$row) {
return null;
}
return (int)$row['counterValue'];
} | Returns the current value of a named counter.
@param AphrontDatabaseConnection $conn_r Database where the counter
resides.
@param string $counter_name Counter name to read.
@return int|null Current value, or `null` if the counter does not exist.
@task util | loadCurrentCounterValue | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public static function overwriteCounterValue(
AphrontDatabaseConnection $conn_w,
$counter_name,
$counter_value) {
queryfx(
$conn_w,
'INSERT INTO %T (counterName, counterValue) VALUES (%s, %d)
ON DUPLICATE KEY UPDATE counterValue = VALUES(counterValue)',
self::COUNTER_TABLE_NAME,
$counter_name,
$counter_value);
} | Overwrite a named counter, forcing it to a specific value.
If the counter does not exist, it is created.
@param AphrontDatabaseConnection $conn_w Database where the counter
resides.
@param string $counter_name Counter name to create or overwrite.
@param int $counter_value
@return void
@task util | overwriteCounterValue | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function key() {
return idx($this->current(), $this->column);
} | [\ReturnTypeWillChange] | key | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskRawMigrationIterator.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskRawMigrationIterator.php | Apache-2.0 |
public static function pushStorageNamespace($namespace) {
self::$namespaceStack[] = $namespace;
} | @task config | pushStorageNamespace | php | phorgeit/phorge | src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | Apache-2.0 |
public static function popStorageNamespace() {
array_pop(self::$namespaceStack);
} | @task config | popStorageNamespace | php | phorgeit/phorge | src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | Apache-2.0 |
public static function getDefaultStorageNamespace() {
return PhabricatorEnv::getEnvConfig('storage.default-namespace');
} | @task config | getDefaultStorageNamespace | php | phorgeit/phorge | src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | Apache-2.0 |
public static function getStorageNamespace() {
$namespace = end(self::$namespaceStack);
if (!strlen($namespace)) {
$namespace = self::getDefaultStorageNamespace();
}
if (!strlen($namespace)) {
throw new Exception(pht('No storage namespace configured!'));
}
return $namespace;
} | @task config | getStorageNamespace | php | phorgeit/phorge | src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | Apache-2.0 |
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;
} | @task config | establishLiveConnection | php | phorgeit/phorge | src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | Apache-2.0 |
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 | getTableName | php | phorgeit/phorge | src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | Apache-2.0 |
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;
} | 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). | chunkSQL | php | phorgeit/phorge | src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/PhabricatorLiskDAO.php | Apache-2.0 |
public function key() {
return $this->current()->getID();
} | [\ReturnTypeWillChange] | key | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskMigrationIterator.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskMigrationIterator.php | Apache-2.0 |
final protected function lock(PhabricatorStorageManagementAPI $api) {
// Although we're holding this lock on different databases so it could
// have the same name on each as far as the database is concerned, the
// locks would be the same within this process.
$parameters = array(
'refKey' => $api->getRef()->getRefKey(),
);
// We disable logging for this lock because we may not have created the
// log table yet, or may need to adjust it.
return PhabricatorGlobalLock::newLock('adjust', $parameters)
->setExternalConnection($api->getConn(null))
->setDisableLogging(true)
->lock();
} | Acquires a @{class:PhabricatorGlobalLock}.
@return PhabricatorGlobalLock | lock | php | phorgeit/phorge | src/infrastructure/storage/management/workflow/PhabricatorStorageManagementWorkflow.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/management/workflow/PhabricatorStorageManagementWorkflow.php | Apache-2.0 |
public function setOldName($old_name) {
$this->oldName = $old_name;
return $this;
} | Set the name to identify the old file with. Primarily cosmetic.
@param string $old_name Old file name.
@return $this
@task config | setOldName | php | phorgeit/phorge | src/infrastructure/diff/PhabricatorDifferenceEngine.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/diff/PhabricatorDifferenceEngine.php | Apache-2.0 |
public function setNewName($new_name) {
$this->newName = $new_name;
return $this;
} | Set the name to identify the new file with. Primarily cosmetic.
@param string $new_name New file name.
@return $this
@task config | setNewName | php | phorgeit/phorge | src/infrastructure/diff/PhabricatorDifferenceEngine.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/diff/PhabricatorDifferenceEngine.php | Apache-2.0 |
public function generateRawDiffFromFileContent($old, $new) {
$options = array();
// Generate diffs with full context.
$options[] = '-U65535';
$old_name = nonempty($this->oldName, '/dev/universe').' 9999-99-99';
$new_name = nonempty($this->newName, '/dev/universe').' 9999-99-99';
$options[] = '-L';
$options[] = $old_name;
$options[] = '-L';
$options[] = $new_name;
$normalize = $this->getNormalize();
if ($normalize) {
$old = $this->normalizeFile($old);
$new = $this->normalizeFile($new);
}
$old_tmp = new TempFile();
$new_tmp = new TempFile();
Filesystem::writeFile($old_tmp, $old);
Filesystem::writeFile($new_tmp, $new);
list($err, $diff) = exec_manual(
'diff %Ls %s %s',
$options,
$old_tmp,
$new_tmp);
if (!$err) {
// This indicates that the two files are the same. Build a synthetic,
// changeless diff so that we can still render the raw, unchanged file
// instead of being forced to just say "this file didn't change" since we
// don't have the content.
$entire_file = explode("\n", $old);
foreach ($entire_file as $k => $line) {
$entire_file[$k] = ' '.$line;
}
$len = count($entire_file);
$entire_file = implode("\n", $entire_file);
// TODO: If both files were identical but missing newlines, we probably
// get this wrong. Unclear if it ever matters.
// This is a bit hacky but the diff parser can handle it.
$diff = "--- {$old_name}\n".
"+++ {$new_name}\n".
"@@ -1,{$len} +1,{$len} @@\n".
$entire_file."\n";
}
return $diff;
} | Generate a raw diff from two raw files. This is a lower-level API than
@{method:generateChangesetFromFileContent}, but may be useful if you need
to use a custom parser configuration, as with Diffusion.
@param string $old Entire previous file content.
@param string $new Entire current file content.
@return string Raw diff between the two files.
@task diff | generateRawDiffFromFileContent | php | phorgeit/phorge | src/infrastructure/diff/PhabricatorDifferenceEngine.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/diff/PhabricatorDifferenceEngine.php | Apache-2.0 |
public function generateChangesetFromFileContent($old, $new) {
$diff = $this->generateRawDiffFromFileContent($old, $new);
$changes = id(new ArcanistDiffParser())->parseDiff($diff);
$diff = DifferentialDiff::newEphemeralFromRawChanges(
$changes);
return head($diff->getChangesets());
} | Generate an @{class:DifferentialChangeset} from two raw files. This is
principally useful because you can feed the output to
@{class:DifferentialChangesetParser} in order to render it.
@param string $old Entire previous file content.
@param string $new Entire current file content.
@return @{class:DifferentialChangeset} Synthetic changeset.
@task diff | generateChangesetFromFileContent | php | phorgeit/phorge | src/infrastructure/diff/PhabricatorDifferenceEngine.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/diff/PhabricatorDifferenceEngine.php | Apache-2.0 |
public function getCoverage() {
return $this->coverage;
} | Get the Coverage, expressed as a string, each letter with this meaning:
N: Not Executable, C: Covered, U: Uncovered.
@return string|null | getCoverage | php | phorgeit/phorge | src/infrastructure/diff/view/PHUIDiffTableOfContentsItemView.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/diff/view/PHUIDiffTableOfContentsItemView.php | Apache-2.0 |
public function getIsHealthy() {
return $this->isHealthy;
} | Is the database currently healthy? | getIsHealthy | php | phorgeit/phorge | src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | Apache-2.0 |
public function getShouldCheck() {
return $this->shouldCheck;
} | Should this request check database health? | getShouldCheck | php | phorgeit/phorge | src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | Apache-2.0 |
public function getUpEventCount() {
return $this->upEventCount;
} | How many recent health checks were successful? | getUpEventCount | php | phorgeit/phorge | src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | Apache-2.0 |
public function getDownEventCount() {
return $this->downEventCount;
} | How many recent health checks failed? | getDownEventCount | php | phorgeit/phorge | src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | Apache-2.0 |
public function getRequiredEventCount() {
// NOTE: If you change this value, update the "Cluster: Databases" docs.
return 5;
} | Number of failures or successes we need to see in a row before we change
the state. | getRequiredEventCount | php | phorgeit/phorge | src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | Apache-2.0 |
public function getHealthCheckFrequency() {
// NOTE: If you change this value, update the "Cluster: Databases" docs.
return 3;
} | Seconds to wait between health checks. | getHealthCheckFrequency | php | phorgeit/phorge | src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php | Apache-2.0 |
public function newHost($config) {
$host = clone($this->hostType);
$host_config = $this->config + $config;
$host->setConfig($host_config);
$this->hosts[] = $host;
return $host;
} | @throws Exception | newHost | php | phorgeit/phorge | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
public function getAllHostsForRole($role) {
// if the role is explicitly set to false at the top level, then all hosts
// have the role disabled.
if (idx($this->config, $role) === false) {
return array();
}
$hosts = array();
foreach ($this->hosts as $host) {
if ($host->hasRole($role)) {
$hosts[] = $host;
}
}
return $hosts;
} | Get all configured hosts for this service which have the specified role.
@return PhabricatorSearchHost[] | getAllHostsForRole | php | phorgeit/phorge | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
public static function getAllServices() {
$cache = PhabricatorCaches::getRequestCache();
$refs = $cache->getKey(self::KEY_REFS);
if (!$refs) {
$refs = self::newRefs();
$cache->setKey(self::KEY_REFS, $refs);
}
return $refs;
} | Get a reference to all configured fulltext search cluster services
@return PhabricatorSearchService[] | getAllServices | php | phorgeit/phorge | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
public static function loadAllFulltextStorageEngines() {
return id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorFulltextStorageEngine')
->setUniqueMethod('getEngineIdentifier')
->execute();
} | Load all valid PhabricatorFulltextStorageEngine subclasses | loadAllFulltextStorageEngines | php | phorgeit/phorge | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
public static function executeSearch(PhabricatorSavedQuery $query) {
$result_set = self::newResultSet($query);
return $result_set->getPHIDs();
} | Execute a full-text query and return a list of PHIDs of matching objects.
@return string[]
@throws PhutilAggregateException | executeSearch | php | phorgeit/phorge | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
public function getEngine() {
return $this->engine;
} | @return PhabricatorFulltextStorageEngine | getEngine | php | phorgeit/phorge | src/infrastructure/cluster/search/PhabricatorSearchHost.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/search/PhabricatorSearchHost.php | Apache-2.0 |
public function getHealthRecord() {
if (!$this->healthRecord) {
$this->healthRecord = new PhabricatorClusterServiceHealthRecord(
$this->getHealthRecordCacheKey());
}
return $this->healthRecord;
} | @return PhabricatorClusterServiceHealthRecord | getHealthRecord | php | phorgeit/phorge | src/infrastructure/cluster/search/PhabricatorSearchHost.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/cluster/search/PhabricatorSearchHost.php | Apache-2.0 |
public static function weakDigest($string, $key = null) {
if ($key === null) {
$key = PhabricatorEnv::getEnvConfig('security.hmac-key');
}
if (!$key) {
throw new Exception(
pht(
"Set a '%s' in your configuration!",
'security.hmac-key'));
}
return hash_hmac('sha1', $string, $key);
} | Digest a string using HMAC+SHA1.
Because a SHA1 collision is now known, this method should be considered
weak. Callers should prefer @{method:digestWithNamedKey}.
@param string $string Input string.
@param string $key (optional)
@return string 32-byte hexadecimal SHA1+HMAC hash. | weakDigest | php | phorgeit/phorge | src/infrastructure/util/PhabricatorHash.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/PhabricatorHash.php | Apache-2.0 |
public static function digestForIndex($string) {
$hash = sha1($string, $raw_output = true);
static $map;
if ($map === null) {
$map = '0123456789'.
'abcdefghij'.
'klmnopqrst'.
'uvwxyzABCD'.
'EFGHIJKLMN'.
'OPQRSTUVWX'.
'YZ._';
}
$result = '';
for ($ii = 0; $ii < self::INDEX_DIGEST_LENGTH; $ii++) {
$result .= $map[(ord($hash[$ii]) & 0x3F)];
}
return $result;
} | Digest a string for use in, e.g., a MySQL index. This produces a short
(12-byte), case-sensitive alphanumeric string with 72 bits of entropy,
which is generally safe in most contexts (notably, URLs).
This method emphasizes compactness, and should not be used for security
related hashing (for general purpose hashing, see @{method:digest}).
@param string $string Input string.
@return string 12-byte, case-sensitive, mostly-alphanumeric hash of
the string. | digestForIndex | php | phorgeit/phorge | src/infrastructure/util/PhabricatorHash.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/PhabricatorHash.php | Apache-2.0 |
public static function digestForAnchor($string) {
$hash = sha1($string, $raw_output = true);
static $map;
if ($map === null) {
$map = '0123456789'.
'abcdefghij'.
'klmnopqrst'.
'uvwxyzABCD'.
'EFGHIJKLMN'.
'OPQRSTUVWX'.
'YZ';
}
$result = '';
$accum = 0;
$map_size = strlen($map);
for ($ii = 0; $ii < self::ANCHOR_DIGEST_LENGTH; $ii++) {
$byte = ord($hash[$ii]);
$low_bits = ($byte & 0x3F);
$accum = ($accum + $byte) % $map_size;
if ($low_bits < $map_size) {
// If an index digest would produce any alphanumeric character, just
// use that character. This means that these digests are the same as
// digests created with "digestForIndex()" in all positions where the
// output character is some character other than "." or "_".
$result .= $map[$low_bits];
} else {
// If an index digest would produce a non-alphumeric character ("." or
// "_"), pick an alphanumeric character instead. We accumulate an
// index into the alphanumeric character list to try to preserve
// entropy here. We could use this strategy for all bytes instead,
// but then these digests would differ from digests created with
// "digestForIndex()" in all positions, instead of just a small number
// of positions.
$result .= $map[$accum];
}
}
return $result;
} | Digest a string for use in HTML page anchors. This is similar to
@{method:digestForIndex} but produces purely alphanumeric output.
This tries to be mostly compatible with the index digest to limit how
much stuff we're breaking by switching to it. For additional discussion,
see T13045.
@param string $string Input string.
@return string 12-byte, case-sensitive, purely-alphanumeric hash of
the string. | digestForAnchor | php | phorgeit/phorge | src/infrastructure/util/PhabricatorHash.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/PhabricatorHash.php | Apache-2.0 |
public static function digestToLength($string, $length) {
// We need at least two more characters than the hash length to fit in a
// a 1-character prefix and a separator.
$min_length = self::INDEX_DIGEST_LENGTH + 2;
if ($length < $min_length) {
throw new Exception(
pht(
'Length parameter in %s must be at least %s, '.
'but %s was provided.',
'digestToLength()',
new PhutilNumber($min_length),
new PhutilNumber($length)));
}
// We could conceivably return the string unmodified if it's shorter than
// the specified length. Instead, always hash it. This makes the output of
// the method more recognizable and consistent (no surprising new behavior
// once you hit a string longer than `$length`) and prevents an attacker
// who can control the inputs from intentionally using the hashed form
// of a string to cause a collision.
$hash = self::digestForIndex($string);
$prefix = substr($string, 0, ($length - ($min_length - 1)));
return $prefix.'-'.$hash;
} | Shorten a string to a maximum byte length in a collision-resistant way
while retaining some degree of human-readability.
This function converts an input string into a prefix plus a hash. For
example, a very long string beginning with "crabapplepie..." might be
digested to something like "crabapp-N1wM1Nz3U84k".
This allows the maximum length of identifiers to be fixed while
maintaining a high degree of collision resistance and a moderate degree
of human readability.
@param string $string The string to shorten.
@param int $length Maximum length of the result.
@return string String shortened in a collision-resistant way. | digestToLength | php | phorgeit/phorge | src/infrastructure/util/PhabricatorHash.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/PhabricatorHash.php | Apache-2.0 |
public function setExternalConnection(AphrontDatabaseConnection $conn) {
if ($this->conn) {
throw new Exception(
pht(
'Lock is already held, and must be released before the '.
'connection may be changed.'));
}
$this->externalConnection = $conn;
return $this;
} | Use a specific database connection for locking.
By default, `PhabricatorGlobalLock` will lock on the "repository" database
(somewhat arbitrarily). In most cases this is fine, but this method can
be used to lock on a specific connection.
@param AphrontDatabaseConnection $conn
@return $this | setExternalConnection | php | phorgeit/phorge | src/infrastructure/util/PhabricatorGlobalLock.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/PhabricatorGlobalLock.php | Apache-2.0 |
protected function verifyPassword(
PhutilOpaqueEnvelope $password,
PhutilOpaqueEnvelope $hash) {
$actual_hash = $this->getPasswordHash($password)->openEnvelope();
$expect_hash = $hash->openEnvelope();
return phutil_hashes_are_identical($actual_hash, $expect_hash);
} | Verify that a password matches a hash.
The default implementation checks for equality; if a hasher embeds salt in
hashes it should override this method and perform a salt-aware comparison.
@param PhutilOpaqueEnvelope $password Password to compare.
@param PhutilOpaqueEnvelope $hash Bare password hash.
@return bool True if the passwords match.
@task hasher | verifyPassword | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
protected function canUpgradeInternalHash(PhutilOpaqueEnvelope $hash) {
return false;
} | Check if an existing hash created by this algorithm is upgradeable.
The default implementation returns `false`. However, hash algorithms which
have (for example) an internal cost function may be able to upgrade an
existing hash to a stronger one with a higher cost.
@param PhutilOpaqueEnvelope $hash Bare hash.
@return bool True if the hash can be upgraded without
changing the algorithm (for example, to a
higher cost).
@task hasher | canUpgradeInternalHash | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
final public function getPasswordHashForStorage(
PhutilOpaqueEnvelope $envelope) {
$name = $this->getHashName();
$hash = $this->getPasswordHash($envelope);
$actual_len = strlen($hash->openEnvelope());
$expect_len = $this->getHashLength();
if ($actual_len > $expect_len) {
throw new Exception(
pht(
"Password hash '%s' produced a hash of length %d, but a ".
"maximum length of %d was expected.",
$name,
new PhutilNumber($actual_len),
new PhutilNumber($expect_len)));
}
return new PhutilOpaqueEnvelope($name.':'.$hash->openEnvelope());
} | Get the hash of a password for storage.
@param PhutilOpaqueEnvelope $envelope Password text.
@return PhutilOpaqueEnvelope Hashed text.
@task hashing | getPasswordHashForStorage | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
private static function parseHashFromStorage(PhutilOpaqueEnvelope $hash) {
$raw_hash = $hash->openEnvelope();
if (strpos($raw_hash, ':') === false) {
throw new Exception(
pht(
'Malformed password hash, expected "name:hash".'));
}
list($name, $hash) = explode(':', $raw_hash);
return array(
'name' => $name,
'hash' => new PhutilOpaqueEnvelope($hash),
);
} | Parse a storage hash into its components, like the hash type and hash
data.
@return map Dictionary of information about the hash.
@task hashing | parseHashFromStorage | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getAllUsableHashers() {
$hashers = self::getAllHashers();
foreach ($hashers as $key => $hasher) {
if (!$hasher->canHashPasswords()) {
unset($hashers[$key]);
}
}
return $hashers;
} | Get all usable password hashers. This may include hashers which are
not desirable or advisable.
@return list<PhabricatorPasswordHasher> Hasher objects.
@task hashing | getAllUsableHashers | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getBestHasher() {
$hashers = self::getAllUsableHashers();
$hashers = msort($hashers, 'getStrength');
$hasher = last($hashers);
if (!$hasher) {
throw new PhabricatorPasswordHasherUnavailableException(
pht(
'There are no password hashers available which are usable for '.
'new passwords.'));
}
return $hasher;
} | Get the best (strongest) available hasher.
@return PhabricatorPasswordHasher Best hasher.
@task hashing | getBestHasher | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getHasherForHash(PhutilOpaqueEnvelope $hash) {
$info = self::parseHashFromStorage($hash);
$name = $info['name'];
$usable = self::getAllUsableHashers();
if (isset($usable[$name])) {
return $usable[$name];
}
$all = self::getAllHashers();
if (isset($all[$name])) {
throw new PhabricatorPasswordHasherUnavailableException(
pht(
'Attempting to compare a password saved with the "%s" hash. The '.
'hasher exists, but is not currently usable. %s',
$name,
$all[$name]->getInstallInstructions()));
}
throw new PhabricatorPasswordHasherUnavailableException(
pht(
'Attempting to compare a password saved with the "%s" hash. No such '.
'hasher is known.',
$name));
} | Get the hasher for a given stored hash.
@return PhabricatorPasswordHasher Corresponding hasher.
@task hashing | getHasherForHash | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function canUpgradeHash(PhutilOpaqueEnvelope $hash) {
if (!strlen($hash->openEnvelope())) {
throw new Exception(
pht('Expected a password hash, received nothing!'));
}
$current_hasher = self::getHasherForHash($hash);
$best_hasher = self::getBestHasher();
if ($current_hasher->getHashName() != $best_hasher->getHashName()) {
// If the algorithm isn't the best one, we can upgrade.
return true;
}
$info = self::parseHashFromStorage($hash);
if ($current_hasher->canUpgradeInternalHash($info['hash'])) {
// If the algorithm provides an internal upgrade, we can also upgrade.
return true;
}
// Already on the best algorithm with the best settings.
return false;
} | Test if a password is using an weaker hash than the strongest available
hash. This can be used to prompt users to upgrade, or automatically upgrade
on login.
@return bool True to indicate that rehashing this password will improve
the hash strength.
@task hashing | canUpgradeHash | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function generateNewPasswordHash(
PhutilOpaqueEnvelope $password) {
$hasher = self::getBestHasher();
return $hasher->getPasswordHashForStorage($password);
} | Generate a new hash for a password, using the best available hasher.
@param PhutilOpaqueEnvelope $password Password to hash.
@return PhutilOpaqueEnvelope Hashed password, using best available
hasher.
@task hashing | generateNewPasswordHash | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function comparePassword(
PhutilOpaqueEnvelope $password,
PhutilOpaqueEnvelope $hash) {
$hasher = self::getHasherForHash($hash);
$parts = self::parseHashFromStorage($hash);
return $hasher->verifyPassword($password, $parts['hash']);
} | Compare a password to a stored hash.
@param PhutilOpaqueEnvelope $password Password to compare.
@param PhutilOpaqueEnvelope $hash Stored password hash.
@return bool True if the passwords match.
@task hashing | comparePassword | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getCurrentAlgorithmName(PhutilOpaqueEnvelope $hash) {
$raw_hash = $hash->openEnvelope();
if (!strlen($raw_hash)) {
return pht('None');
}
try {
$current_hasher = self::getHasherForHash($hash);
return $current_hasher->getHumanReadableName();
} catch (Exception $ex) {
$info = self::parseHashFromStorage($hash);
$name = $info['name'];
return pht('Unknown ("%s")', $name);
}
} | Get the human-readable algorithm name for a given hash.
@param PhutilOpaqueEnvelope $hash Storage hash.
@return string Human-readable algorithm name. | getCurrentAlgorithmName | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getBestAlgorithmName() {
try {
$best_hasher = self::getBestHasher();
return $best_hasher->getHumanReadableName();
} catch (Exception $ex) {
return pht('Unknown');
}
} | Get the human-readable algorithm name for the best available hash.
@return string Human-readable name for best hash. | getBestAlgorithmName | php | phorgeit/phorge | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
protected function getNextObjectSeed() {
self::$storageFixtureObjectSeed += mt_rand(1, 100);
return self::$storageFixtureObjectSeed;
} | Returns an integer seed to use when building unique identifiers (e.g.,
non-colliding usernames). The seed is unstable and its value will change
between test runs, so your tests must not rely on it.
@return int A unique integer. | getNextObjectSeed | php | phorgeit/phorge | src/infrastructure/testing/PhabricatorTestCase.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/testing/PhabricatorTestCase.php | Apache-2.0 |
public static function assertExecutingUnitTests() {
if (!self::$testsAreRunning) {
throw new Exception(
pht(
'Executing test code outside of test execution! '.
'This code path can only be run during unit tests.'));
}
} | Throws unless tests are currently executing. This method can be used to
guard code which is specific to unit tests and should not normally be
reachable.
If tests aren't currently being executed, throws an exception. | assertExecutingUnitTests | php | phorgeit/phorge | src/infrastructure/testing/PhabricatorTestCase.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/testing/PhabricatorTestCase.php | Apache-2.0 |
protected function willBeginWork() {
if ($this->workState != self::WORKSTATE_BUSY) {
$this->workState = self::WORKSTATE_BUSY;
$this->idleSince = null;
$this->emitOverseerMessage(self::MESSAGETYPE_BUSY, null);
}
return $this;
} | Prepare to become busy. This may autoscale the pool up.
This notifies the overseer that the daemon has become busy. If daemons
that are part of an autoscale pool are continuously busy for a prolonged
period of time, the overseer may scale up the pool.
@return $this
@task autoscale | willBeginWork | php | phorgeit/phorge | src/infrastructure/daemon/PhutilDaemon.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/PhutilDaemon.php | Apache-2.0 |
protected function willBeginIdle() {
if ($this->workState != self::WORKSTATE_IDLE) {
$this->workState = self::WORKSTATE_IDLE;
$this->idleSince = time();
$this->emitOverseerMessage(self::MESSAGETYPE_IDLE, null);
}
return $this;
} | Prepare to idle. This may autoscale the pool down.
This notifies the overseer that the daemon is no longer busy. If daemons
that are part of an autoscale pool are idle for a prolonged period of
time, they may exit to scale the pool down.
@return $this
@task autoscale | willBeginIdle | php | phorgeit/phorge | src/infrastructure/daemon/PhutilDaemon.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/PhutilDaemon.php | Apache-2.0 |
public static function sudoCommandAsDaemonUser($command) {
$user = PhabricatorEnv::getEnvConfig('phd.user');
if (!$user) {
// No daemon user is set, so just run this as ourselves.
return $command;
}
// We may reach this method while already running as the daemon user: for
// example, active and passive synchronization of clustered repositories
// run the same commands through the same code, but as different users.
// By default, `sudo` won't let you sudo to yourself, so we can get into
// trouble if we're already running as the daemon user unless the host has
// been configured to let the daemon user run commands as itself.
// Since this is silly and more complicated than doing this check, don't
// use `sudo` if we're already running as the correct user.
if (function_exists('posix_getuid')) {
$uid = posix_getuid();
$info = posix_getpwuid($uid);
if ($info && $info['name'] == $user) {
return $command;
}
}
// Get the absolute path so we're safe against the caller wiping out
// PATH.
$sudo = Filesystem::resolveBinary('sudo');
if (!$sudo) {
throw new Exception(pht("Unable to find 'sudo'!"));
}
// Flags here are:
//
// -E: Preserve the environment.
// -n: Non-interactive. Exit with an error instead of prompting.
// -u: Which user to sudo to.
return csprintf('%s -E -n -u %s -- %C', $sudo, $user, $command);
} | Format a command so it executes as the daemon user, if a daemon user is
defined. This wraps the provided command in `sudo -u ...`, roughly.
@param PhutilCommandString $command Command to execute.
@return PhutilCommandString `sudo` version of the command. | sudoCommandAsDaemonUser | php | phorgeit/phorge | src/infrastructure/daemon/PhabricatorDaemon.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/PhabricatorDaemon.php | Apache-2.0 |
public function shouldReloadDaemons() {
return false;
} | This method is used to indicate to the overseer that daemons should reload.
@return bool True if the daemons should reload, otherwise false. | shouldReloadDaemons | php | phorgeit/phorge | src/infrastructure/daemon/PhutilDaemonOverseerModule.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/PhutilDaemonOverseerModule.php | Apache-2.0 |
public function shouldWakePool(PhutilDaemonPool $pool) {
return false;
} | Should a hibernating daemon pool be awoken immediately?
@return bool True to awaken the pool immediately. | shouldWakePool | php | phorgeit/phorge | src/infrastructure/daemon/PhutilDaemonOverseerModule.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/PhutilDaemonOverseerModule.php | Apache-2.0 |
private function generateDaemonID() {
return substr(getmypid().':'.Filesystem::readRandomCharacters(12), 0, 12);
} | Generate a unique ID for this daemon.
@return string A unique daemon ID. | generateDaemonID | php | phorgeit/phorge | src/infrastructure/daemon/PhutilDaemonHandle.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/PhutilDaemonHandle.php | Apache-2.0 |
public function hasAutomaticPolicy() {
return false;
} | Specify that the collector has an automatic retention policy and
is not configurable.
@return bool True if the collector has an automatic retention policy.
@task info | hasAutomaticPolicy | php | phorgeit/phorge | src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | Apache-2.0 |
public function getDefaultRetentionPolicy() {
throw new PhutilMethodNotImplementedException();
} | Get the default retention policy for this collector.
Return the age (in seconds) when resources start getting collected, or
`null` to retain resources indefinitely.
@return int|null Lifetime, or `null` for indefinite retention.
@task info | getDefaultRetentionPolicy | php | phorgeit/phorge | src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | Apache-2.0 |
public function getRetentionPolicy() {
if ($this->hasAutomaticPolicy()) {
throw new Exception(
pht(
'Can not get retention policy of collector with automatic '.
'policy.'));
}
$config = PhabricatorEnv::getEnvConfig('phd.garbage-collection');
$const = $this->getCollectorConstant();
return idx($config, $const, $this->getDefaultRetentionPolicy());
} | Get the effective retention policy.
@return int|null Lifetime, or `null` for indefinite retention.
@task info | getRetentionPolicy | php | phorgeit/phorge | src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | Apache-2.0 |
final public function getCollectorConstant() {
return $this->getPhobjectClassConstant('COLLECTORCONST', 64);
} | Get a unique string constant identifying this collector.
@return string Collector constant.
@task info | getCollectorConstant | php | phorgeit/phorge | src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | Apache-2.0 |
final public function runCollector() {
// Don't do anything if this collector is configured with an indefinite
// retention policy.
if (!$this->hasAutomaticPolicy()) {
$policy = $this->getRetentionPolicy();
if (!$policy) {
return false;
}
}
// Hold a lock while performing collection to avoid racing other daemons
// running the same collectors.
$params = array(
'collector' => $this->getCollectorConstant(),
);
$lock = PhabricatorGlobalLock::newLock('gc', $params);
try {
$lock->lock(5);
} catch (PhutilLockException $ex) {
return false;
}
try {
$result = $this->collectGarbage();
} catch (Exception $ex) {
$lock->unlock();
throw $ex;
}
$lock->unlock();
return $result;
} | Run the collector.
@return bool True if there is more garbage to collect.
@task collect | runCollector | php | phorgeit/phorge | src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.