sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function update(array $sets, $conditions = [])
{
if (count($sets)) {
$primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id';
if (empty($conditions)) {
if (isset($sets[ $primaryKey ])) {
$conditions = [$primaryKey => $sets[ $primaryKey ]];
}
}
if (method_exists($this, 'updateRecordSets')) {
$this->updateRecordSets($sets);
}
if (method_exists($this, 'beforeUpdate')) {
$sets = $this->beforeUpdate($sets);
}
if (method_exists($this, 'getRecordOrdering')) {
if ($this->recordOrdering === true && empty($sets[ 'record_ordering' ])) {
$sets[ 'record_ordering' ] = $this->getRecordOrdering($this->table);
}
}
if ($this->qb->table($this->table)->update($sets, $conditions)) {
if (method_exists($this, 'afterUpdate')) {
return $this->afterUpdate();
}
return true;
}
}
return false;
} | ModifierTrait::update
@param array $sets
@param array $conditions
@return bool | entailment |
public function updateOrInsert(array $sets, array $conditions = [])
{
if (count($sets)) {
$primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id';
if (empty($conditions)) {
if (isset($sets[ $primaryKey ])) {
$conditions = [$primaryKey => $sets[ $primaryKey ]];
} else {
$conditions = $sets;
}
}
// Try to find
if ($result = $this->qb->from($this->table)->getWhere($conditions)) {
return $this->update($sets, $conditions);
} else {
return $this->insert($sets);
}
}
return false;
} | ModifierTrait::updateOrInsert
@param array $sets
@param array $conditions
@return bool | entailment |
public function updateMany(array $sets)
{
$primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id';
if (method_exists($this, 'updateRecordSets')) {
foreach ($sets as $key => $set) {
$this->updateRecordSets($sets[ $key ]);
}
}
if (method_exists($this, 'beforeUpdateMany')) {
$this->beforeUpdateMany($sets);
}
if ($this->qb->table($this->table)->updateBatch($sets, $primaryKey)) {
if (method_exists($this, 'afterUpdateMany')) {
return $this->afterUpdateMany();
}
return $this->db->getAffectedRows();
}
return false;
} | ModifierTrait::updateMany
@param array $sets
@return bool|int | entailment |
public function delete($id)
{
$primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id';
if (method_exists($this, 'beforeDelete')) {
$this->beforeDelete();
}
if ($this->qb->table($this->table)->limit(1)->delete([$primaryKey => $id])) {
if (method_exists($this, 'afterDelete')) {
return $this->afterDelete();
}
return true;
}
return false;
} | ModifierTrait::delete
@param int $id
@return bool | entailment |
public function deleteBy($conditions = [])
{
if (count($conditions)) {
if (method_exists($this, 'beforeDelete')) {
$this->beforeDelete();
}
if (method_exists($this, 'beforeDelete')) {
$this->beforeDelete();
}
if ($this->qb->table($this->table)->limit(1)->delete($conditions)) {
if (method_exists($this, 'afterDelete')) {
return $this->afterDelete();
}
return $this->db->getAffectedRows();
}
}
return false;
} | ModifierTrait::deleteBy
@param array $conditions
@return bool | entailment |
public function deleteMany(array $ids)
{
$primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id';
if (method_exists($this, 'beforeDelete')) {
$this->beforeDelete();
}
$this->qb->whereIn($primaryKey, $ids);
if ($this->qb->table($this->table)->delete()) {
if (method_exists($this, 'afterDelete')) {
return $this->afterDelete();
}
return $this->db->getAffectedRows();
}
return false;
} | ModifierTrait::deleteMany
@param array $ids
@return bool|int | entailment |
private function updateRecordStatus($id, $recordStatus, $method)
{
$sets[ 'record_status' ] = $recordStatus;
$primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id';
if (method_exists($this, 'updateRecordSets')) {
$this->updateRecordSets($sets);
}
if (method_exists($this, $beforeMethod = 'before' . ucfirst($method))) {
call_user_func_array([&$this, $beforeMethod], [$sets]);
}
if ($this->qb->table($this->table)->limit(1)->update($sets, [$primaryKey => $id])) {
if (method_exists($this, $afterMethod = 'after' . ucfirst($method))) {
return call_user_func([&$this, $beforeMethod]);
}
return true;
}
return false;
} | ModifierTrait::updateRecordStatus
@param int $id
@return bool | entailment |
private function updateRecordStatusMany(array $ids, $recordStatus, $method)
{
if (count($ids)) {
$sets[ 'record_status' ] = $recordStatus;
$primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id';
$this->qb->whereIn($primaryKey, $ids);
if (method_exists($this, 'updateRecordSets')) {
$this->updateRecordSets($sets[ $key ]);
}
if (method_exists($this, $beforeMethod = 'before' . ucfirst($method))) {
call_user_func_array([&$this, $beforeMethod], [$sets]);
}
if ($this->qb->table($this->table)->update($sets)) {
if (method_exists($this, $afterMethod = 'after' . ucfirst($method))) {
return call_user_func([&$this, $beforeMethod]);
}
return $this->getAffectedRows();
}
}
return false;
} | ModifierTrait::updateRecordStatusMany
@param array $ids
@return bool|int | entailment |
private function updateRecordStatusManyBy($conditions = [], $recordStatus, $method)
{
if (count($conditions)) {
$sets[ 'record_status' ] = $recordStatus;
if (method_exists($this, 'updateRecordSets')) {
$this->updateRecordSets($sets);
}
if (method_exists($this, $beforeMethod = 'before' . ucfirst($method))) {
call_user_func_array([&$this, $beforeMethod], [$sets]);
}
if ($this->qb->table($this->table)->update($sets, $conditions)) {
if (method_exists($this, $afterMethod = 'after' . ucfirst($method))) {
return call_user_func([&$this, $beforeMethod]);
}
return $this->getAffectedRows();
}
}
return false;
} | ModifierTrait::updateRecordStatusManyBy
@param array $ids
@param array $conditions
@return bool|int | entailment |
public function getResource(): object
{
\mysqli_report(MYSQLI_REPORT_ALL);
return new mysqli(
$this->options['host'],
$this->options['user'],
$this->options['password'],
$this->options['database'],
$this->options['port']
);
} | Get Resource.
@return object | entailment |
public function getMessages()
{
if (empty($this->messages)) {
$intent = $this->event->get('intent');
$session = $this->payload->get('session');
$message = new IncomingMessage($intent['name'], $session['user']['userId'], $session['sessionId'], $this->payload);
if (! is_null($intent) && array_key_exists('slots', $intent)) {
$message->addExtras('slots', Collection::make($intent['slots']));
}
$this->messages = [$message];
}
return $this->messages;
} | Retrieve the chat message.
@return array | entailment |
public function display($level = 1)
{
$this->attributes->removeAttributeClass('display-*');
$this->attributes->addAttributeClass('display-' . (int)$level);
return $this;
} | Heading::display
@param int $level
@return static | entailment |
public static function callProcedure(string $procedureName): void
{
$query = 'call '.$procedureName.'()';
self::$dl->executeNone($query);
} | Class a stored procedure without arguments.
@param string $procedureName The name of the procedure. | entailment |
public static function checkTableExists(string $tableName): bool
{
$query = sprintf('
select 1
from information_schema.TABLES
where table_schema = database()
and table_name = %s', self::$dl->quoteString($tableName));
return !empty(self::executeSingleton0($query));
} | Checks if a table exists in the current schema.
@param string $tableName The name of the table.
@return bool | entailment |
public static function connect(string $host, string $user, string $passWord, string $database, int $port = 3306): void
{
self::$dl = new StaticDataLayer();
self::$dl->connect($host, $user, $passWord, $database, $port);
} | Connects to a MySQL instance.
Wrapper around [mysqli::__construct](http://php.net/manual/mysqli.construct.php), however on failure an exception
is thrown.
@param string $host The hostname.
@param string $user The MySQL user name.
@param string $passWord The password.
@param string $database The default database.
@param int $port The port number. | entailment |
public static function disconnect(): void
{
if (self::$dl!==null)
{
self::$dl->disconnect();
self::$dl = null;
}
} | Closes the connection to the MySQL instance, if connected. | entailment |
public static function dropRoutine(string $routineType, string $routineName): void
{
$query = sprintf('drop %s if exists `%s`', $routineType, $routineName);
self::executeNone($query);
} | Drops a routine if it exists.
@param string $routineType The type of the routine (function of procedure).
@param string $routineName The name of the routine. | entailment |
public static function dropTemporaryTable(string $tableName): void
{
$query = sprintf('drop temporary table `%s`', $tableName);
self::executeNone($query);
} | Drops a temporary table.
@param string $tableName the name of the temporary table. | entailment |
public static function executeNone(string $query): int
{
self::logQuery($query);
return self::$dl->executeNone($query);
} | @param string $query The SQL statement.
@return int The number of affected rows (if any). | entailment |
public static function executeRow0(string $query): ?array
{
self::logQuery($query);
return self::$dl->executeRow0($query);
} | Executes a query that returns 0 or 1 row.
Throws an exception if the query selects 2 or more rows.
@param string $query The SQL statement.
@return array|null The selected row. | entailment |
public static function executeRow1(string $query): array
{
self::logQuery($query);
return self::$dl->executeRow1($query);
} | Executes a query that returns 1 and only 1 row.
Throws an exception if the query selects none, 2 or more rows.
@param string $query The SQL statement.
@return array The selected row. | entailment |
public static function executeRows(string $query): array
{
self::logQuery($query);
return self::$dl->executeRows($query);
} | Executes a query that returns 0 or more rows.
@param string $query The SQL statement.
@return array[] | entailment |
public static function executeSingleton0(string $query)
{
self::logQuery($query);
return self::$dl->executeSingleton0($query);
} | Executes a query that returns 0 or 1 row.
Throws an exception if the query selects 2 or more rows.
@param string $query The SQL statement.
@return mixed The selected row. | entailment |
public static function executeSingleton1(string $query)
{
self::logQuery($query);
return self::$dl->executeSingleton1($query);
} | Executes a query that returns 1 and only 1 row with 1 column.
Throws an exception if the query selects none, 2 or more rows.
@param string $query The SQL statement.
@return mixed The selected row. | entailment |
public static function getCorrectSqlMode(string $sqlMode): string
{
$query = sprintf('set sql_mode = %s', self::$dl->quoteString($sqlMode));
self::executeNone($query);
$query = 'select @@sql_mode';
return (string)self::executeSingleton1($query);
} | Selects the SQL mode in the order as preferred by MySQL.
@param string $sqlMode The SQL mode.
@return string | entailment |
public static function getLabelsFromTable(string $tableName, string $idColumnName, string $labelColumnName): array
{
$query = "
select `%s` id
, `%s` label
from `%s`
where nullif(`%s`,'') is not null";
$query = sprintf($query, $idColumnName, $labelColumnName, $tableName, $labelColumnName);
return self::executeRows($query);
} | Selects all labels from a table with labels.
@param string $tableName The table name.
@param string $idColumnName The name of the auto increment column.
@param string $labelColumnName The name of the column with labels.
@return array[] | entailment |
public static function getTableColumns(string $schemaName, string $tableName): array
{
$sql = sprintf('
select COLUMN_NAME as column_name
, COLUMN_TYPE as column_type
, IS_NULLABLE as is_nullable
, CHARACTER_SET_NAME as character_set_name
, COLLATION_NAME as collation_name
, EXTRA as extra
from information_schema.COLUMNS
where TABLE_SCHEMA = %s
and TABLE_NAME = %s
order by ORDINAL_POSITION',
self::$dl->quoteString($schemaName),
self::$dl->quoteString($tableName));
return self::$dl->executeRows($sql);
} | Selects metadata of all columns of table.
@param string $schemaName The name of the table schema.
@param string $tableName The name of the table.
@return array[] | entailment |
public static function getTablePrimaryKeys(string $schemaName, string $tableName): array
{
$sql = sprintf('
show index from %s.%s
where Key_name = \'PRIMARY\'',
$schemaName,
$tableName);
return self::$dl->executeRows($sql);
} | Selects all primary keys from table.
@param string $schemaName The name of the table schema.
@param string $tableName The name of the table.
@return array[] | entailment |
public static function getTablesNames(string $schemaName): array
{
$sql = sprintf("
select TABLE_NAME as table_name
from information_schema.TABLES
where TABLE_SCHEMA = %s
and TABLE_TYPE = 'BASE TABLE'
order by TABLE_NAME", self::$dl->quoteString($schemaName));
return self::$dl->executeRows($sql);
} | Selects all table names in a schema.
@param string $schemaName The name of the schema.
@return array[] | entailment |
public static function setCharacterSet(string $characterSet, string $collate): void
{
$sql = sprintf('set names %s collate %s', self::$dl->quoteString($characterSet), self::$dl->quoteString($collate));
self::executeNone($sql);
} | Sets the default character set and collate.
@param string $characterSet The character set.
@param string $collate The collate. | entailment |
public static function setSqlMode(string $sqlMode): void
{
$sql = sprintf('set sql_mode = %s', self::$dl->quoteString($sqlMode));
self::executeNone($sql);
} | Sets the SQL mode.
@param string $sqlMode The SQL mode. | entailment |
private static function logQuery(string $query): void
{
$query = trim($query);
if (strpos($query, "\n")!==false)
{
// Query is a multi line query.
self::$io->logVeryVerbose('Executing query:');
self::$io->logVeryVerbose('<sql>%s</sql>', $query);
}
else
{
// Query is a single line query.
self::$io->logVeryVerbose('Executing query: <sql>%s</sql>', $query);
}
} | Logs the query on the console.
@param string $query The query. | entailment |
public function setPassword(string $newPassword): void
{
//hash provided password
$this->password = $this->passwordUtility->hash($newPassword);
} | Set new user password without do any check.
<pre><code class="php">$password = new Password();
$user = new User($password);
$user->setPassword('newPassword');
</code></pre>
@param string $newPassword
@return void | entailment |
public function changePassword(string $newPassword, string $oldPassword): bool
{
//verfy password match
if ($this->passwordUtility->verify($oldPassword, $this->password)) {
//if match set new password
$this->password = $this->passwordUtility->hash($newPassword);
return true;
}
return false;
} | Change user password only after check old password.
<pre><code class="php">$password = new Password();
$user = new User($password);
$user->changePassword('newPassword', 'oldPassword');
</code></pre>
@param string $newPassword
@param string $oldPassword
@return bool | entailment |
public function render()
{
if ($this->fluid) {
$this->attributes->removeAttributeClass('container');
$this->attributes->addAttributeClass('container-fluid');
}
return parent::render();
} | Container::render
@return string | entailment |
protected function filter($type, $offset = null, $filter = FILTER_DEFAULT)
{
if (services()->has('xssProtection')) {
if ( ! services()->get('xssProtection')->verify()) {
$string = parent::filter($type, $offset, $filter);
if (is_string($string)) {
return Xss::clean($string);
}
}
}
return parent::filter($type, $offset, $filter);
} | Input::filter
@param int $type
@param null $offset
@param int $filter
@return mixed|\O2System\Spl\DataStructures\SplArrayObject|string | entailment |
public function optionName($name)
{
if (empty($this->optionPath)) {
$this->optionPath = PATH_APP . 'Modules' . DIRECTORY_SEPARATOR;
}
$this->optionName = $name;
} | Plugin::optionName
@param string $name | entailment |
public function execute()
{
parent::execute();
if (empty($this->optionName)) {
output()->write(
(new Format())
->setContextualClass(Format::DANGER)
->setString(language()->getLine('CLI_MAKE_MODULE_E_NAME'))
->setNewLinesAfter(1)
);
exit(EXIT_ERROR);
}
$moduleType = empty($this->moduleType)
? 'Plugins'
: ucfirst(plural($this->moduleType));
if (strpos($this->optionPath, $moduleType) === false) {
$modulePath = $this->optionPath . $moduleType . DIRECTORY_SEPARATOR . $this->optionName . DIRECTORY_SEPARATOR;
} else {
$modulePath = $this->optionPath . $this->optionName . DIRECTORY_SEPARATOR;
}
if ( ! is_dir($modulePath)) {
mkdir($modulePath, 0777, true);
} else {
output()->write(
(new Format())
->setContextualClass(Format::DANGER)
->setString(language()->getLine('CLI_MAKE_PLUGIN_E_EXISTS', [$modulePath]))
->setNewLinesAfter(1)
);
exit(EXIT_ERROR);
}
$jsonProperties[ 'name' ] = readable(
pathinfo($modulePath, PATHINFO_FILENAME),
true
);
if (empty($this->namespace)) {
@list($moduleDirectory, $moduleName) = explode($moduleType, dirname($modulePath));
$namespace = loader()->getDirNamespace($moduleDirectory) .
$moduleType . '\\' . prepare_class_name(
$this->optionName
) . '\\';
} else {
$namespace = $this->namespace;
$jsonProperties[ 'namespace' ] = rtrim($namespace, '\\') . '\\';
}
$jsonProperties[ 'created' ] = date('d M Y');
loader()->addNamespace($namespace, $modulePath);
$fileContent = json_encode($jsonProperties, JSON_PRETTY_PRINT);
$filePath = $modulePath . strtolower(singular($moduleType)) . '.json';
file_put_contents($filePath, $fileContent);
$this->optionPath = $modulePath;
$this->optionFilename = prepare_filename($this->optionName) . '.php';
(new Controller())
->optionPath($this->optionPath)
->optionFilename($this->optionFilename);
if (is_dir($modulePath)) {
output()->write(
(new Format())
->setContextualClass(Format::SUCCESS)
->setString(language()->getLine('CLI_MAKE_PLUGIN_S_MAKE', [$modulePath]))
->setNewLinesAfter(1)
);
exit(EXIT_SUCCESS);
}
} | Plugin::execute | entailment |
protected function initRequests()
{
$this->useragent = 'Wikimate '.self::VERSION.' (https://github.com/hamstar/Wikimate)';
$this->session = new Requests_Session($this->api, $this->headers, $this->data, $this->options);
$this->session->useragent = $this->useragent;
} | Set up a Requests_Session with appropriate user agent.
@return void | entailment |
public function login($username, $password, $domain = null)
{
//Logger::log("Logging in");
$details = array(
'action' => 'login',
'lgname' => $username,
'lgpassword' => $password,
'format' => 'json'
);
// If $domain is provided, set the corresponding detail in the request information array
if (is_string($domain)) {
$details['lgdomain'] = $domain;
}
// Send the login request
$response = $this->session->post($this->api, array(), $details);
// Check if we got an API result or the API doc page (invalid request)
if (strpos($response->body, "This is an auto-generated MediaWiki API documentation page") !== false) {
$this->error = array();
$this->error['login'] = 'The API could not understand the first login request';
return false;
}
$loginResult = json_decode($response->body);
if ($this->debugMode) {
echo "Login request:\n";
print_r($details);
echo "Login request response:\n";
print_r($loginResult);
}
if (isset($loginResult->login->result) && $loginResult->login->result == 'NeedToken') {
//Logger::log("Sending token {$loginResult->login->token}");
$details['lgtoken'] = strtolower(trim($loginResult->login->token));
// Send the confirm token request
$loginResult = $this->session->post($this->api, array(), $details)->body;
// Check if we got an API result or the API doc page (invalid request)
if (strpos($loginResult, "This is an auto-generated MediaWiki API documentation page") !== false) {
$this->error = array();
$this->error['login'] = 'The API could not understand the confirm token request';
return false;
}
$loginResult = json_decode($loginResult);
if ($this->debugMode) {
echo "Confirm token request:\n";
print_r($details);
echo "Confirm token response:\n";
print_r($loginResult);
}
if ($loginResult->login->result != 'Success') {
// Some more comprehensive error checking
$this->error = array();
switch ($loginResult->login->result) {
case 'NotExists':
$this->error['login'] = 'The username does not exist';
break;
default:
$this->error['login'] = 'The API result was: ' . $loginResult->login->result;
break;
}
return false;
}
}
//Logger::log("Logged in");
return true;
} | Logs in to the wiki.
@param string $username The user name
@param string $password The user password
@param string $domain The domain (optional)
@return boolean True if logged in | entailment |
public function debugRequestsConfig($echo = false)
{
if ($echo) {
echo "<pre>Requests options:\n";
print_r($this->session->options);
echo "Requests headers:\n";
print_r($this->session->headers);
echo "</pre>";
return true;
}
return $this->session->options;
} | Get or print the Requests configuration.
@param boolean $echo Whether to echo the options
@return array Options if $echo is false
@return boolean True if options have been echoed to STDOUT | entailment |
public function query($array)
{
$array['action'] = 'query';
$array['format'] = 'php';
$apiResult = $this->session->get($this->api.'?'.http_build_query($array));
return unserialize($apiResult->body);
} | Performs a query to the wiki API with the given details.
@param array $array Array of details to be passed in the query
@return array Unserialized php output from the wiki API | entailment |
public function edit($array)
{
$headers = array(
'Content-Type' => "application/x-www-form-urlencoded"
);
$array['action'] = 'edit';
$array['format'] = 'php';
$apiResult = $this->session->post($this->api, $headers, $array);
return unserialize($apiResult->body);
} | Perfoms an edit query to the wiki API.
@param array $array Array of details to be passed in the query
@return array Unserialized php output from the wiki API | entailment |
public function download($url)
{
$getResult = $this->session->get($url);
if (!$getResult->success) {
$this->error = array();
$this->error['file'] = 'Download error (HTTP status: ' . $getResult->status_code . ')';
$this->error['http'] = $getResult->status_code;
return null;
}
return $getResult->body;
} | Downloads data from the given URL.
@param string $url The URL to download from
@return mixed The downloaded data (string), or null if error | entailment |
public function upload($array)
{
$array['action'] = 'upload';
$array['format'] = 'php';
// Construct multipart body: https://www.mediawiki.org/wiki/API:Upload#Sample_Raw_Upload
$boundary = '---Wikimate-' . md5(microtime());
$body = '';
foreach ($array as $fieldName => $fieldData) {
$body .= "--{$boundary}\r\n";
$body .= 'Content-Disposition: form-data; name="' . $fieldName . '"';
// Process the (binary) file
if ($fieldName == 'file') {
$body .= '; filename="' . $array['filename'] . '"' . "\r\n";
$body .= "Content-Type: application/octet-stream; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: binary\r\n";
// Process text parameters
} else {
$body .= "\r\n";
$body .= "Content-Type: text/plain; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: 8bit\r\n";
}
$body .= "\r\n{$fieldData}\r\n";
}
$body .= "--{$boundary}--\r\n";
// Construct multipart headers
$headers = array(
'Content-Type' => "multipart/form-data; boundary={$boundary}",
'Content-Length' => strlen($body),
);
$apiResult = $this->session->post($this->api, $headers, $body);
return unserialize($apiResult->body);
} | Uploads a file to the wiki API.
@param array $array Array of details to be used in the upload
@return array Unserialized php output from the wiki API | entailment |
public function getText($refresh = false)
{
if ($refresh) { // We want to query the API
// Specify relevant page properties to retrieve
$data = array(
'titles' => $this->title,
'prop' => 'info|revisions',
'rvprop' => 'content', // Need to get page text
'intoken' => 'edit',
);
$r = $this->wikimate->query($data); // Run the query
// Check for errors
if (isset($r['error'])) {
$this->error = $r['error']; // Set the error if there was one
return null;
} else {
$this->error = null; // Reset the error status
}
// Get the page (there should only be one)
$page = array_pop($r['query']['pages']);
unset($r, $data);
// Abort if invalid page title
if (isset($page['invalid'])) {
$this->invalid = true;
return null;
}
$this->edittoken = $page['edittoken'];
$this->starttimestamp = $page['starttimestamp'];
if (!isset($page['missing'])) {
// Update the existence if the page is there
$this->exists = true;
// Put the content into text
$this->text = $page['revisions'][0]['*'];
}
unset($page);
// Now we need to get the section headers, if any
preg_match_all('/(={1,6}).*?\1 *(?:\n|$)/', $this->text, $matches);
// Set the intro section (between title and first section)
$this->sections->byIndex[0]['offset'] = 0;
$this->sections->byName['intro']['offset'] = 0;
// Check for section header matches
if (empty($matches[0])) {
// Define lengths for page consisting only of intro section
$this->sections->byIndex[0]['length'] = strlen($this->text);
$this->sections->byName['intro']['length'] = strlen($this->text);
} else {
// Array of section header matches
$sections = $matches[0];
// Set up the current section
$currIndex = 0;
$currName = 'intro';
// Collect offsets and lengths from section header matches
foreach ($sections as $section) {
// Get the current offset
$currOffset = strpos($this->text, $section, $this->sections->byIndex[$currIndex]['offset']);
// Are we still on the first section?
if ($currIndex == 0) {
$this->sections->byIndex[$currIndex]['length'] = $currOffset;
$this->sections->byIndex[$currIndex]['depth'] = 0;
$this->sections->byName[$currName]['length'] = $currOffset;
$this->sections->byName[$currName]['depth'] = 0;
}
// Get the current name and index
$currName = trim(str_replace('=', '', $section));
$currIndex++;
// Search for existing name and create unique one
$cName = $currName;
for ($seq = 2; array_key_exists($cName, $this->sections->byName); $seq++) {
$cName = $currName . '_' . $seq;
}
if ($seq > 2) {
$currName = $cName;
}
// Set the offset and depth (from the matched ='s) for the current section
$this->sections->byIndex[$currIndex]['offset'] = $currOffset;
$this->sections->byIndex[$currIndex]['depth'] = strlen($matches[1][$currIndex-1]);
$this->sections->byName[$currName]['offset'] = $currOffset;
$this->sections->byName[$currName]['depth'] = strlen($matches[1][$currIndex-1]);
// If there is a section after this, set the length of this one
if (isset($sections[$currIndex])) {
// Get the offset of the next section
$nextOffset = strpos($this->text, $sections[$currIndex], $currOffset);
// Calculate the length of this one
$length = $nextOffset - $currOffset;
// Set the length of this section
$this->sections->byIndex[$currIndex]['length'] = $length;
$this->sections->byName[$currName]['length'] = $length;
}
else {
// Set the length of last section
$this->sections->byIndex[$currIndex]['length'] = strlen($this->text) - $currOffset;
$this->sections->byName[$currName]['length'] = strlen($this->text) - $currOffset;
}
}
}
}
return $this->text; // Return the text in any case
} | Gets the text of the page. If refresh is true,
then this method will query the wiki API again for the page details.
@param boolean $refresh True to query the wiki API again
@return mixed The text of the page (string), or null if error | entailment |
public function getSection($section, $includeHeading = false, $includeSubsections = true)
{
// Check if we have a section name or index
if (is_int($section)) {
if (!isset($this->sections->byIndex[$section])) {
return false;
}
$coords = $this->sections->byIndex[$section];
} else if (is_string($section)) {
if (!isset($this->sections->byName[$section])) {
return false;
}
$coords = $this->sections->byName[$section];
}
// Extract the offset, depth and (initial) length
@extract($coords);
// Find subsections if requested, and not the intro
if ($includeSubsections && $offset > 0) {
$found = false;
foreach ($this->sections->byName as $section) {
if ($found) {
// Include length of this subsection
if ($depth < $section['depth']) {
$length += $section['length'];
// Done if not a subsection
} else {
break;
}
} else {
// Found our section if same offset
if ($offset == $section['offset']) {
$found = true;
}
}
}
}
// Extract text of section, and its subsections if requested
$text = substr($this->text, $offset, $length);
// Whack off the heading if requested, and not the intro
if (!$includeHeading && $offset > 0) {
// Chop off the first line
$text = substr($text, strpos($text, "\n"));
}
return $text;
} | Returns the requested section, with its subsections, if any.
Section can be the following:
- section name (string, e.g. "History")
- section index (int, e.g. 3)
@param mixed $section The section to get
@param boolean $includeHeading False to get section text only,
true to include heading too
@param boolean $includeSubsections False to get section text only,
true to include subsections too
@return string Wikitext of the section on the page,
or false if section is undefined | entailment |
public function getAllSections($includeHeading = false, $keyNames = self::SECTIONLIST_BY_INDEX)
{
$sections = array();
switch ($keyNames) {
case self::SECTIONLIST_BY_INDEX:
$array = array_keys($this->sections->byIndex);
break;
case self::SECTIONLIST_BY_NAME:
$array = array_keys($this->sections->byName);
break;
default:
throw new Exception('Unexpected parameter $keyNames given to WikiPage::getAllSections()');
break;
}
foreach ($array as $key) {
$sections[$key] = $this->getSection($key, $includeHeading);
}
return $sections;
} | Return all the sections of the page in an array - the key names can be
set to name or index by using the following for the second param:
- self::SECTIONLIST_BY_NAME
- self::SECTIONLIST_BY_INDEX
@param boolean $includeHeading False to get section text only
@param integer $keyNames Modifier for the array key names
@return array Array of sections
@throw Exception If $keyNames is not a supported constant | entailment |
public function setText($text, $section = null, $minor = false, $summary = null)
{
$data = array(
'title' => $this->title,
'text' => $text,
'md5' => md5($text),
'bot' => "true",
'token' => $this->edittoken,
'starttimestamp' => $this->starttimestamp,
);
// Set options from arguments
if (!is_null($section)) {
// Obtain section index in case it is a name
$data['section'] = $this->findSection($section);
if ($data['section'] == -1) {
return false;
}
}
if ($minor) {
$data['minor'] = $minor;
}
if (!is_null($summary)) {
$data['summary'] = $summary;
}
// Make sure we don't create a page by accident or overwrite another one
if (!$this->exists) {
$data['createonly'] = "true"; // createonly if not exists
} else {
$data['nocreate'] = "true"; // Don't create, it should exist
}
$r = $this->wikimate->edit($data); // The edit query
// Check if it worked
if (isset($r['edit']['result']) && $r['edit']['result'] == 'Success') {
$this->exists = true;
if (is_null($section)) {
$this->text = $text;
}
// Get the new starttimestamp
$data = array(
'titles' => $this->title,
'prop' => 'info',
'intoken' => 'edit',
);
$r = $this->wikimate->query($data);
$page = array_pop($r['query']['pages']); // Get the page
$this->starttimestamp = $page['starttimestamp']; // Update the starttimestamp
$this->error = null; // Reset the error status
return true;
}
// Return error response
if (isset($r['error'])) {
$this->error = $r['error'];
} else {
$this->error = array();
$this->error['page'] = 'Unexpected edit response: '.$r['edit']['result'];
}
return false;
} | Sets the text in the page. Updates the starttimestamp to the timestamp
after the page edit (if the edit is successful).
Section can be the following:
- section name (string, e.g. "History")
- section index (int, e.g. 3)
- a new section (the string "new")
- the whole page (null)
@param string $text The article text
@param string $section The section to edit (whole page by default)
@param boolean $minor True for minor edit
@param string $summary Summary text, and section header in case
of new section
@return boolean True if page was edited successfully | entailment |
public function setSection($text, $section = 0, $summary = null, $minor = false)
{
return $this->setText($text, $section, $minor, $summary);
} | Sets the text of the given section.
Essentially an alias of WikiPage:setText()
with the summary and minor parameters switched.
Section can be the following:
- section name (string, e.g. "History")
- section index (int, e.g. 3)
- a new section (the string "new")
- the whole page (null)
@param string $text The text of the section
@param mixed $section The section to edit (intro by default)
@param string $summary Summary text, and section header in case
of new section
@param boolean $minor True for minor edit
@return boolean True if the section was saved | entailment |
public function newSection($name, $text)
{
return $this->setSection($text, $section = 'new', $summary = $name, $minor = false);
} | Alias of WikiPage::setSection() specifically for creating new sections.
@param string $name The heading name for the new section
@param string $text The text of the new section
@return boolean True if the section was saved | entailment |
public function delete($reason = null)
{
$data = array(
'title' => $this->title,
'token' => $this->edittoken,
);
// Set options from arguments
if (!is_null($reason)) {
$data['reason'] = $reason;
}
$r = $this->wikimate->delete($data); // The delete query
// Check if it worked
if (isset($r['delete'])) {
$this->exists = false; // The page was deleted
$this->error = null; // Reset the error status
return true;
}
$this->error = $r['error']; // Return error response
return false;
} | Delete the page.
@param string $reason Reason for the deletion
@return boolean True if page was deleted successfully | entailment |
private function findSection($section)
{
// Check section type
if (is_int($section) || $section === 'new') {
return $section;
} else if (is_string($section)) {
// Search section names for related index
$sections = array_keys($this->sections->byName);
$index = array_search($section, $sections);
// Return index if found
if ($index !== false) {
return $index;
}
}
// Return error message and value
$this->error = array();
$this->error['page'] = "Section '$section' was not found on this page";
return -1;
} | Find a section's index by name.
If a section index or 'new' is passed, it is returned directly.
@param mixed $section The section name or index to find
@return mixed The section index, or -1 if not found | entailment |
public function getInfo($refresh = false, $history = null)
{
if ($refresh) { // We want to query the API
// Specify relevant file properties to retrieve
$data = array(
'titles' => 'File:' . $this->filename,
'prop' => 'info|imageinfo',
'iiprop' => 'bitdepth|canonicaltitle|comment|parsedcomment|'
. 'commonmetadata|metadata|extmetadata|mediatype|'
. 'mime|thumbmime|sha1|size|timestamp|url|user|userid',
'intoken' => 'edit',
);
// Add optional history parameters
if (is_array($history)) {
foreach ($history as $key => $val) {
$data[$key] = $val;
}
// Retrieve archive name property as well
$data['iiprop'] .= '|archivename';
}
$r = $this->wikimate->query($data); // Run the query
// Check for errors
if (isset($r['error'])) {
$this->error = $r['error']; // Set the error if there was one
return null;
} else {
$this->error = null; // Reset the error status
}
// Get the page (there should only be one)
$page = array_pop($r['query']['pages']);
unset($r, $data);
// Abort if invalid file title
if (isset($page['invalid'])) {
$this->invalid = true;
return null;
}
$this->edittoken = $page['edittoken'];
// Check that file is present and has info
if (!isset($page['missing']) && isset($page['imageinfo'])) {
// Update the existence if the file is there
$this->exists = true;
// Put the content into info & history
$this->info = $page['imageinfo'][0];
$this->history = $page['imageinfo'];
}
unset($page);
}
return $this->info; // Return the info in any case
} | Gets the information of the file. If refresh is true,
then this method will query the wiki API again for the file details.
@param boolean $refresh True to query the wiki API again
@param array $history An optional array of revision history parameters
@return mixed The info of the file (array), or null if error | entailment |
public function getAnon($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
// Check for anon flag
return isset($this->info['anon']) ? true : false;
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
// Check for anon flag
return isset($info['anon']) ? true : false;
} | Returns the anonymous flag of this file,
or of its specified revision.
If true, then getUser()'s value represents an anonymous IP address.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The anonymous flag of this file (boolean),
or null if revision not found | entailment |
public function getAspectRatio($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
// Check for dimensions
if ($this->info['height'] > 0) {
return $this->info['width'] / $this->info['height'];
} else {
return 0;
}
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return -1;
}
// Check for dimensions
if (isset($info['height'])) {
return $info['width'] / $info['height'];
} else {
return 0;
}
} | Returns the aspect ratio of this image,
or of its specified revision.
Returns 0 if file is not an image (and thus has no dimensions).
@param mixed $revision The index or timestamp of the revision (optional)
@return float The aspect ratio of this image, or 0 if no dimensions,
or -1 if revision not found | entailment |
public function getBitDepth($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return (int)$this->info['bitdepth'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return -1;
}
return (int)$info['bitdepth'];
} | Returns the bit depth of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return integer The bit depth of this file,
or -1 if revision not found | entailment |
public function getCanonicalTitle($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['canonicaltitle'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['canonicaltitle'];
} | Returns the canonical title of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The canonical title of this file (string),
or null if revision not found | entailment |
public function getComment($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['comment'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['comment'];
} | Returns the edit comment of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The edit comment of this file (string),
or null if revision not found | entailment |
public function getCommonMetadata($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['commonmetadata'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['commonmetadata'];
} | Returns the common metadata of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The common metadata of this file (array),
or null if revision not found | entailment |
public function getDescriptionUrl($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['descriptionurl'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['descriptionurl'];
} | Returns the description URL of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The description URL of this file (string),
or null if revision not found | entailment |
public function getExtendedMetadata($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['extmetadata'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['extmetadata'];
} | Returns the extended metadata of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The extended metadata of this file (array),
or null if revision not found | entailment |
public function getHeight($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return (int)$this->info['height'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return -1;
}
return (int)$info['height'];
} | Returns the height of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return integer The height of this file, or -1 if revision not found | entailment |
public function getMediaType($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['mediatype'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['mediatype'];
} | Returns the media type of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The media type of this file (string),
or null if revision not found | entailment |
public function getMetadata($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['metadata'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['metadata'];
} | Returns the Exif metadata of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The metadata of this file (array),
or null if revision not found | entailment |
public function getMime($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['mime'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['mime'];
} | Returns the MIME type of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The MIME type of this file (string),
or null if revision not found | entailment |
public function getParsedComment($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['parsedcomment'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['parsedcomment'];
} | Returns the parsed edit comment of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The parsed edit comment of this file (string),
or null if revision not found | entailment |
public function getSha1($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['sha1'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['sha1'];
} | Returns the SHA-1 hash of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The SHA-1 hash of this file (string),
or null if revision not found | entailment |
public function getSize($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return (int)$this->info['size'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return -1;
}
return (int)$info['size'];
} | Returns the size of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return integer The size of this file, or -1 if revision not found | entailment |
public function getThumbMime($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return (isset($this->info['thumbmime']) ? $this->info['thumbmime'] : '');
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
// Check for thumbnail MIME type
return (isset($info['thumbmime']) ? $info['thumbmime'] : '');
} | Returns the MIME type of this file's thumbnail,
or of its specified revision.
Returns empty string if property not available for this file type.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The MIME type of this file's thumbnail (string),
or '' if unavailable, or null if revision not found | entailment |
public function getTimestamp($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['timestamp'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['timestamp'];
} | Returns the timestamp of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The timestamp of this file (string),
or null if revision not found | entailment |
public function getUrl($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['url'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['url'];
} | Returns the URL of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The URL of this file (string),
or null if revision not found | entailment |
public function getUser($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return $this->info['user'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
return $info['user'];
} | Returns the user who uploaded this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return mixed The user of this file (string),
or null if revision not found | entailment |
public function getUserId($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return (int)$this->info['userid'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return -1;
}
return (int)$info['userid'];
} | Returns the ID of the user who uploaded this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return integer The user ID of this file,
or -1 if revision not found | entailment |
public function getWidth($revision = null)
{
// Without revision, use current info
if (!isset($revision)) {
return (int)$this->info['width'];
}
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return -1;
}
return (int)$info['width'];
} | Returns the width of this file,
or of its specified revision.
@param mixed $revision The index or timestamp of the revision (optional)
@return integer The width of this file, or -1 if revision not found | entailment |
public function getHistory($refresh = false, $limit = null, $startts = null, $endts = null)
{
if ($refresh) { // We want to query the API
// Collect optional history parameters
$history = array();
if (!is_null($limit)) {
$history['iilimit'] = $limit;
} else {
$history['iilimit'] = 'max';
}
if (!is_null($startts)) {
$history['iistart'] = $startts;
}
if (!is_null($endts)) {
$history['iiend'] = $endts;
}
// Get file revision history
if ($this->getInfo($refresh, $history) === null) {
return null;
}
}
return $this->history;
} | Returns the revision history of this file with all properties.
The initial history at object creation contains only the
current revision of the file. To obtain more revisions,
set $refresh to true and also optionally set $limit and
the timestamps.
The maximum limit is 500 for user accounts and 5000 for bot accounts.
Timestamps can be in several formats as described here:
https://www.mediawiki.org/w/api.php?action=help&modules=main#main.2Fdatatypes
@param boolean $refresh True to query the wiki API again
@param integer $limit The number of file revisions to return
(the maximum number by default)
@param string $startts The start timestamp of the listing (optional)
@param string $endts The end timestamp of the listing (optional)
@return mixed The array of selected file revisions, or null if error | entailment |
public function getRevision($revision)
{
// Select revision by index
if (is_int($revision)) {
if (isset($this->history[$revision])) {
return $this->history[$revision];
}
// Search revision by timestamp
} else {
foreach ($this->history as $history) {
if ($history['timestamp'] == $revision) {
return $history;
}
}
}
// Return error message
$this->error = array();
$this->error['file'] = "Revision '$revision' was not found for this file";
return null;
} | Returns the properties of the specified file revision.
Revision can be the following:
- revision timestamp (string, e.g. "2001-01-15T14:56:00Z")
- revision index (int, e.g. 3)
The most recent revision has index 0,
and it increments towards older revisions.
A timestamp must be in ISO 8601 format.
@param mixed $revision The index or timestamp of the revision
@return mixed The properties (array), or null if not found | entailment |
public function getArchivename($revision)
{
// Obtain the properties of the revision
if (($info = $this->getRevision($revision)) === null) {
return null;
}
// Check for archive name
if (!isset($info['archivename'])) {
// Return error message
$this->error = array();
$this->error['file'] = 'This revision contains no archive name';
return null;
}
return $info['archivename'];
} | Returns the archive name of the specified file revision.
Revision can be the following:
- revision timestamp (string, e.g. "2001-01-15T14:56:00Z")
- revision index (int, e.g. 3)
The most recent revision has index 0,
and it increments towards older revisions.
A timestamp must be in ISO 8601 format.
@param mixed $revision The index or timestamp of the revision
@return mixed The archive name (string), or null if not found | entailment |
public function downloadData()
{
// Download file, or handle error
$data = $this->wikimate->download($this->getUrl());
if ($data === null) {
$this->error = $this->wikimate->getError(); // Copy error if there was one
} else {
$this->error = null; // Reset the error status
}
return $data;
} | Downloads and returns the current file's contents,
or null if an error occurs.
@return mixed Contents (string), or null if error | entailment |
public function downloadFile($path)
{
// Download contents of current file
if (($data = $this->downloadData()) === null) {
return false;
}
// Write contents to specified path
if (@file_put_contents($path, $data) === false) {
$this->error = array();
$this->error['file'] = "Unable to write file '$path'";
return false;
}
return true;
} | Downloads the current file's contents and writes it to the given path.
@param string $path The file path to write to
@return boolean True if path was written successfully | entailment |
private function uploadCommon(array $params, $comment, $text = null, $overwrite = false)
{
// Check whether to overwrite existing file
if ($this->exists && !$overwrite) {
$this->error = array();
$this->error['file'] = 'Cannot overwrite existing file';
return false;
}
// Collect upload parameters
$params['filename'] = $this->filename;
$params['comment'] = $comment;
$params['ignorewarnings'] = $overwrite;
$params['token'] = $this->edittoken;
if (!is_null($text)) {
$params['text'] = $text;
}
// Upload file, or handle error
$r = $this->wikimate->upload($params);
if (isset($r['upload']['result']) && $r['upload']['result'] == 'Success') {
// Update the file's properties
$this->info = $r['upload']['imageinfo'];
$this->error = null; // Reset the error status
return true;
}
// Return error response
if (isset($r['error'])) {
$this->error = $r['error'];
} else {
$this->error = array();
$this->error['file'] = 'Unexpected upload response: '.$r['upload']['result'];
}
return false;
} | Uploads to the current file using the given parameters.
$text is only used for the page contents of a new file,
not an existing one (update that via WikiPage::setText()).
If no $text is specified, $comment will be used as new page text.
@param array $params The upload parameters
@param string $comment Upload comment for the file
@param string $text The article text for the file page
@param boolean $overwrite True to overwrite existing file
@return boolean True if uploading was successful | entailment |
public function uploadData($data, $comment, $text = null, $overwrite = false)
{
// Collect upload parameter
$params = array(
'file' => $data,
);
// Upload contents to current file
return $this->uploadCommon($params, $comment, $text, $overwrite);
} | Uploads the given contents to the current file.
$text is only used for the page contents of a new file,
not an existing one (update that via WikiPage::setText()).
If no $text is specified, $comment will be used as new page text.
@param string $data The data to upload
@param string $comment Upload comment for the file
@param string $text The article text for the file page
@param boolean $overwrite True to overwrite existing file
@return boolean True if uploading was successful | entailment |
public function uploadFile($path, $comment, $text = null, $overwrite = false)
{
// Read contents from specified path
if (($data = @file_get_contents($path)) === false) {
$this->error = array();
$this->error['file'] = "Unable to read file '$path'";
return false;
}
// Upload contents to current file
return $this->uploadData($data, $comment, $text, $overwrite);
} | Reads contents from the given path and uploads it to the current file.
$text is only used for the page contents of a new file,
not an existing one (update that via WikiPage::setText()).
If no $text is specified, $comment will be used as new page text.
@param string $path The file path to upload
@param string $comment Upload comment for the file
@param string $text The article text for the file page
@param boolean $overwrite True to overwrite existing file
@return boolean True if uploading was successful | entailment |
public function uploadFromUrl($url, $comment, $text = null, $overwrite = false)
{
// Collect upload parameter
$params = array(
'url' => $url,
);
// Upload URL to current file
return $this->uploadCommon($params, $comment, $text, $overwrite);
} | Uploads file contents from the given URL to the current file.
$text is only used for the page contents of a new file,
not an existing one (update that via WikiPage::setText()).
If no $text is specified, $comment will be used as new page text.
@param string $url The URL from which to upload
@param string $comment Upload comment for the file
@param string $text The article text for the file page
@param boolean $overwrite True to overwrite existing file
@return boolean True if uploading was successful | entailment |
protected function pushChildNode(Element $node)
{
$node->attributes->addAttributeClass('list-group-item');
if ($node instanceof Lists\Item) {
$node->setContextualClassPrefix('list-group-item');
}
parent::pushChildNode($node);
} | ListGroup::pushChildNode
@param \O2System\Framework\Libraries\Ui\Element $node | entailment |
public function setId(int $objectId): int
{
if ($this->objectId !== 0) {
throw new UnexpectedValueException('ObjectId property is immutable.');
}
$this->objectId = $objectId;
$this->rId = $objectId;
return $objectId;
} | Set the id for the object.
<pre><code class="php">$object = new DomainObject($dependencies);
$object->setId(5);
</code></pre>
@param int $objectId New object id.
@throws UnexpectedValueException If the id on the object is already set.
@return int New object id. | entailment |
public function setHeader($text, $tagName = 'h1')
{
$this->header = new Element($tagName);
$this->header->entity->setEntityName('header');
$this->header->textContent->push($text);
return $this;
} | PageHeader::setHeader
@param string $text
@param string $tagName
@return static | entailment |
public function setSubText($text)
{
$this->subText = new Element('small');
$this->subText->entity->setEntityName('sub-text');
$this->subText->textContent->push($text);
return $this;
} | PageHeader::setSubText
@param string $text
@return static | entailment |
public function render()
{
$output[] = $this->open();
if ($this->subText instanceof Element) {
$this->header->childNodes->push($this->subText);
}
$output[] = $this->header;
$output[] = $this->close();
return implode(PHP_EOL, $output);
} | PageHeader::render
@return string | entailment |
public function handle(RoutesJavascriptGenerator $generator)
{
$path = $this->getPath() . '/' . $this->argument('name');
$middleware = $this->option('middleware');
if ($this->option('filter')) {
$this->warn("Filter option is deprecated, as Laravel 5 doesn't use filters anymore." . PHP_EOL .
"Please change your code to use --middleware (or -m) instead.");
$middleware = $this->option('filter');
}
$options = [
'middleware' => $middleware,
'object' => $this->option('object'),
'prefix' => $this->option('prefix'),
];
if ($generator->make($this->getPath(), $this->argument('name'), $options)) {
$this->info("Created {$path}");
return 0;
}
$this->error("Could not create {$path}");
return 1;
} | Execute the console command.
@param RoutesJavascriptGenerator $generator
@return int | entailment |
public function createLink($label, $href = null, $position = self::NAVBAR_LEFT)
{
if ( ! is_object($label) && isset($href)) {
$label = new Link($label, $href);
}
switch ($position) {
default:
case self::NAVBAR_LEFT:
$node = $this->left->createList($label);
break;
case self::NAVBAR_RIGHT:
$node = $this->right->createList($label);
break;
}
return $node;
} | Links::createLink
@param string|Link $label
@param string|null $href
@param int $position
@return mixed | entailment |
public function optionPath($path)
{
$path = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $path);
$path = PATH_ROOT . str_replace(PATH_ROOT, '', $path);
if (pathinfo($path, PATHINFO_EXTENSION)) {
$this->optionFilename(pathinfo($path, PATHINFO_FILENAME));
$path = dirname($path);
}
$this->optionPath = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
return $this;
} | Make::optionPath
@param string $path
@return static | entailment |
public function optionFilename($name)
{
$name = str_replace('.php', '', $name);
$this->optionFilename = prepare_filename($name) . '.php';
$this->optionPath = empty($this->optionPath) ? modules()->top()->getRealPath() : $this->optionPath;
} | Make::optionFilename
@param string $name | entailment |
protected static function getSetting(array $settings,
bool $mandatory,
string $sectionName,
string $settingName)
{
// Test if the section exists.
if (!array_key_exists($sectionName, $settings))
{
if ($mandatory)
{
throw new RuntimeException("Section '%s' not found in configuration file.", $sectionName);
}
else
{
return null;
}
}
// Test if the setting in the section exists.
if (!array_key_exists($settingName, $settings[$sectionName]))
{
if ($mandatory)
{
throw new RuntimeException("Setting '%s' not found in section '%s' configuration file.",
$settingName,
$sectionName);
}
else
{
return null;
}
}
return $settings[$sectionName][$settingName];
} | Returns the value of a setting.
@param array $settings The settings as returned by parse_ini_file.
@param bool $mandatory If set and setting $settingName is not found in section $sectionName an exception
will be thrown.
@param string $sectionName The name of the section of the requested setting.
@param string $settingName The name of the setting of the requested setting.
@return mixed | entailment |
protected function writeTwoPhases(string $filename, string $data): void
{
$write_flag = true;
if (file_exists($filename))
{
$old_data = file_get_contents($filename);
if ($data==$old_data) $write_flag = false;
}
if ($write_flag)
{
$tmp_filename = $filename.'.tmp';
file_put_contents($tmp_filename, $data);
rename($tmp_filename, $filename);
$this->io->text(sprintf('Wrote <fso>%s</fso>', OutputFormatter::escape($filename)));
}
else
{
$this->io->text(sprintf('File <fso>%s</fso> is up to date', OutputFormatter::escape($filename)));
}
} | Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the file
already exists and its content is equal to the data that must be written no action is taken. This has the
following advantages:
* In case of some write error (e.g. disk full) the original file is kept in tact and no file with partially data
is written.
* Renaming a file is atomic. So, running processes will never read a partially written data.
@param string $filename The name of the file were the data must be stored.
@param string $data The data that must be written. | entailment |
protected function readConfigFile(string $configFilename): array
{
$settings = parse_ini_file($configFilename, true);
$this->phpStratumMetadataFilename = self::getSetting($settings, true, 'loader', 'metadata');
$this->sourcePattern = self::getSetting($settings, true, 'loader', 'sources');
$this->sqlMode = self::getSetting($settings, true, 'loader', 'sql_mode');
$this->characterSet = self::getSetting($settings, true, 'loader', 'character_set');
$this->collate = self::getSetting($settings, true, 'loader', 'collate');
$this->constantClassName = self::getSetting($settings, false, 'constants', 'class');
$this->nameMangler = self::getSetting($settings, false, 'wrapper', 'mangler_class');
return $settings;
} | Reads parameters from the configuration file.
@param string $configFilename
@return array | entailment |
private function detectNameConflicts(): void
{
// Get same method names from array
list($sources_by_path, $sources_by_method) = $this->getDuplicates();
// Add every not unique method name to myErrorFileNames
foreach ($sources_by_path as $source)
{
$this->errorFilenames[] = $source['path_name'];
}
// Log the sources files with duplicate method names.
foreach ($sources_by_method as $method => $sources)
{
$tmp = [];
foreach ($sources as $source)
{
$tmp[] = $source['path_name'];
}
$this->io->error(sprintf("The following source files would result wrapper methods with equal name '%s'",
$method));
$this->io->listing($tmp);
}
// Remove duplicates from mySources.
foreach ($this->sources as $i => $source)
{
if (isset($sources_by_path[$source['path_name']]))
{
unset($this->sources[$i]);
}
}
} | Detects stored routines that would result in duplicate wrapper method name. | entailment |
private function dropObsoleteRoutines(): void
{
// Make a lookup table from routine name to source.
$lookup = [];
foreach ($this->sources as $source)
{
$lookup[$source['routine_name']] = $source;
}
// Drop all routines not longer in sources.
foreach ($this->rdbmsOldMetadata as $old_routine)
{
if (!isset($lookup[$old_routine['routine_name']]))
{
$this->io->logInfo('Dropping %s <dbo>%s</dbo>',
strtolower($old_routine['routine_type']),
$old_routine['routine_name']);
DataLayer::dropRoutine($old_routine['routine_type'], $old_routine['routine_name']);
}
}
} | Drops obsolete stored routines (i.e. stored routines that exits in the current schema but for which we don't have
a source file). | entailment |
private function findSourceFiles(): void
{
$helper = new SourceFinderHelper(dirname($this->configFilename));
$filenames = $helper->findSources($this->sourcePattern);
foreach ($filenames as $filename)
{
$routineName = pathinfo($filename, PATHINFO_FILENAME);
$this->sources[] = ['path_name' => $filename,
'routine_name' => $routineName,
'method_name' => $this->methodName($routineName)];
}
} | Searches recursively for all source files. | entailment |
private function findSourceFilesFromList(array $filenames): void
{
foreach ($filenames as $filename)
{
if (!file_exists($filename))
{
$this->io->error(sprintf("File not exists: '%s'", $filename));
$this->errorFilenames[] = $filename;
}
else
{
$routineName = pathinfo($filename, PATHINFO_FILENAME);
$this->sources[] = ['path_name' => $filename,
'routine_name' => $routineName,
'method_name' => $this->methodName($routineName)];
}
}
} | Finds all source files that actually exists from a list of file names.
@param string[] $filenames The list of file names. | entailment |