sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function generateKey($processArgs)
{
$process = new Process(sprintf('openssl %s', $processArgs));
$process->setTimeout(3600);
$process->run(function ($type, $buffer) {
$this->io->write($buffer);
});
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$process->getExitCode();
} | Generate a RSA key.
@param string $processArgs
@param Outputinterface $output
@throws ProcessFailedException | entailment |
public function addField($name, array $attributes)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$this->fields[$name] = $attributes;
return $this;
} | Adds a field in the table
@param *string $name Column name
@param *array $attributes Column attributes
@return Eden\Mysql\Create | entailment |
public function addKey($name, array $fields)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$this->keys[$name] = $fields;
return $this;
} | Adds an index key
@param *string $name Name of key
@param *array $fields List of key fields
@return Eden\Mysql\Create | entailment |
public function addUniqueKey($name, array $fields)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$this->uniqueKeys[$name] = $fields;
return $this;
} | Adds a unique key
@param *string $name Name of key
@param *array $fields List of key fields
@return Eden\Mysql\Create | entailment |
protected function convertToResource($data)
{
return File::make($this->client, $this->bib, $this->representation, $data->pid)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return File | entailment |
protected function convertToResource($data)
{
return Location::make($this->client, $this->library, $data->code)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return Location | entailment |
public function registerAction()
{
$userIdentityField = $this->container->getParameter('rch_jwt_user.user_identity_field');
$userManager = $this->container->get('fos_user.user_manager');
$userClass = $userManager->getClass();
$rules = [
$userIdentityField => [
'requirements' => ['email' == $userIdentityField ? new Email() : '[^/]+'],
],
'password' => ['requirements' => '[^/]+'],
];
$params = $this->get('rch_jwt_user.credential_fetcher')
->create($rules)
->all();
$user = $this->createUser($params, $userManager);
return $this->renderToken($user, 201);
} | Register a new User and authenticate it.
Required request parameters: %user_identity_field% (configured), password
@return object The authentication token | entailment |
public function loginFromOAuthResponseAction()
{
$userManager = $this->container->get('fos_user.user_manager');
$userIdentityField = $this->container->get('rch_jwt_user.user_identity_field');
$data = $this->get('rch_jwt_user.credential_fetcher')
->create([
$userIdentityField => ['requirements' => $userIdentityField == 'email' ? new Email() : '[^/+]'],
'facebook_id' => ['requirements' => '\d+'],
'facebook_access_token' => ['requirements' => '[^/]+'],
])
->all();
if (true !== $this->isValidFacebookAccount($data['facebook_id'], $data['facebook_access_token'])) {
throw new InvalidPropertyUserException('The given facebook_id does not correspond to a valid acount');
}
$user = $userManager->findUserBy(['facebookId' => $data['facebook_id']]);
if ($user) {
return $this->renderToken($user);
}
$user = $userManager->findUserBy([$userIdentityField => $data[$userIdentityField]]);
if ($user) {
$user->setFacebookId($data['facebook_id']);
$userManager->updateUser($user);
return $this->renderToken($user);
}
$data['password'] = $this->generateRandomPassword();
return $this->renderToken($this->createUser($data));
} | Registers and authenticates User from a facebook OAuth Response.
@return object The authentication token | entailment |
protected function createUser(array $data, UserProviderInterface $userManager)
{
$userIdentityfield = $this->container->getParameter('rch_jwt_user.user_identity_field');
$user = $userManager->createUser()
->setUsername($data[$userIdentityfield])
->setEmail($data[$userIdentityfield])
->setEnabled(true)
->setPlainPassword($data['password']);
if (isset($data['facebook_id'])) {
$user->setFacebookId($data['facebook_id']);
}
try {
$userManager->updateUser($user);
} catch (\Exception $e) {
$message = $e->getMessage() ?: 'An error occured while creating the user.';
throw new UserException(422, $message, $e);
}
return $user;
} | Creates a new User.
@param array $data
@param bool $isOAuth
@return UserInterface $user | entailment |
protected function renderToken(UserInterface $user, $statusCode = 200)
{
$body = [
'token' => $this->container->get('lexik_jwt_authentication.jwt_manager')->create($user),
'refresh_token' => $this->attachRefreshToken($user),
'user' => $user->getUsername(),
];
return new JsonResponse($body, $statusCode);
} | Generates a JWT from given User.
@param UserInterface $user
@param int $statusCode
@return array Response body containing the User and its tokens | entailment |
protected function attachRefreshToken(UserInterface $user)
{
$refreshTokenManager = $this->container->get('gesdinet.jwtrefreshtoken.refresh_token_manager');
$refreshToken = $refreshTokenManager->getLastFromUsername($user->getUsername());
$refreshTokenTtl = $this->container->getParameter('gesdinet_jwt_refresh_token.ttl');
if (!$refreshToken instanceof RefreshToken) {
$refreshToken = $refreshTokenManager->create();
$expirationDate = new \DateTime();
$expirationDate->modify(sprintf('+%s seconds', $refreshTokenTtl));
$refreshToken->setUsername($user->getUsername());
$refreshToken->setRefreshToken();
$refreshToken->setValid($expirationDate);
$refreshTokenManager->save($refreshToken);
}
return $refreshToken->getRefreshToken();
} | Provides a refresh token.
@param UserInterface $user
@return string The refresh Json Web Token. | entailment |
protected function isValidFacebookAccount($id, $accessToken)
{
$client = new \Goutte\Client();
$client->request('GET', sprintf('https://graph.facebook.com/me?access_token=%s', $accessToken));
$response = json_decode($client->getResponse()->getContent());
if ($response->error) {
throw new InvalidPropertyUserException($response->error->message);
}
return $response->id == $id;
} | @param int $facebookId Facebook account id
@param string $facebookAccessToken Facebook access token
@return bool Facebook account status | entailment |
protected function createJsonResponseForException(UserException $exception)
{
$message = $exception->getMessage();
$statusCode = $exception->getStatusCode();
$content = ['error' => str_replace('"', '\'', $message)];
return new JsonResponse($content, $statusCode);
} | Create JsonResponse for Exception.
@param UserException $exception
@return JsonResponse | entailment |
public function handle()
{
if (is_null($this->argument('character_id')))
$this->warn('No character id specified. Using null token.');
else
$refresh_token = RefreshToken::findOrFail($this->argument('character_id'));
$this->argument('job_class')::dispatch($refresh_token ?? null);
$this->info('Job dispatched!');
} | Execute the console command. | entailment |
public function renameTable($table, $name)
{
//Argument 1 must be a string, 2 must be string
Argument::i()->test(1, 'string')->argument(2, 'string');
$this->query = 'RENAME TABLE `' . $table . '` TO `' . $name . '`';
return $this;
} | Query for renaming a table
@param *string $table The name of the table
@param *string $name The new name of the table
@return Eden\Mysql\Utility | entailment |
public function showColumns($table, $where = null)
{
//Argument 1 must be a string, 2 must be string null
Argument::i()->test(1, 'string')->test(2, 'string', 'null');
$where = $where ? ' WHERE '.$where : null;
$this->query = 'SHOW FULL COLUMNS FROM `' . $table .'`' . $where;
return $this;
} | Query for showing all columns of a table
@param *string $table The name of the table
@param *string|null $where Filter/s
@return Eden\Mysql\Utility | entailment |
public function showTables($like = null)
{
Argument::i()->test(1, 'string', 'null');
$like = $like ? ' LIKE '.$like : null;
$this->query = 'SHOW TABLES'.$like;
return $this;
} | Query for showing all tables
@param string|null $like The like pattern
@return Eden\Mysql\Utility | entailment |
protected function convertToResource($data)
{
return Representation::make($this->client, $this->bib, $data->id)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return Representation | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('rch_jwt_user');
$rootNode
->children()
->scalarNode('user_class')
->isRequired()
->cannotBeEmpty()
->validate()
->ifString()
->then(function ($class) {
if (!class_exists('\\'.$class)) {
throw new InvalidConfigurationException(sprintf('"rch_jwt_user.user_class" option must be a valid class, "%s" given', $class));
}
return $class;
})
->end()
->end()
->scalarNode('user_identity_field')
->cannotBeEmpty()
->defaultValue('username')
->end()
->scalarNode('passphrase')
->cannotBeEmpty()
->defaultValue('')
->end()
->end();
return $treeBuilder;
} | {@inheritdoc} | entailment |
protected function configureProperties(OptionsResolver $resolver)
{
parent::configureProperties($resolver);
$resolver
->setRequired('socket')
->setAllowedTypes('socket', 'string');
$resolver
->setDefined('socket_owner')
->setAllowedTypes('socket_owner', 'string');
// TODO: octal vs. decimal value
$resolver->setDefined('socket_mode')
->setAllowedTypes('socket_mode', 'integer');
} | {@inheritdoc} | entailment |
public function handle()
{
$esi = app('esi-client')->get();
$esi->setVersion(''); // meta URI lives in /
Configuration::getInstance()->cache = NullCache::class;
try {
$esi->invoke('get', '/ping');
} catch (RequestFailedException $e) {
$this->error('ESI does not appear to be available: ' . $e->getMessage());
}
$this->info('ESI appears to be OK');
} | Execute the console command.
@throws \Seat\Eseye\Exceptions\InvalidContainerDataException | entailment |
public function prepend(ContainerBuilder $container)
{
$kernelRootDir = $container->getParameter('kernel.root_dir');
$configs = $this->processConfiguration(new Configuration(), $container->getExtensionConfig($this->getAlias()));
$fosUserProviderId = 'fos_user.user_provider.username_email';
$container->setParameter('rch_jwt_user.passphrase', $configs['passphrase']);
$container->setParameter('rch_jwt_user.user_class', $configs['user_class']);
$container->setParameter('rch_jwt_user.user_identity_field', $configs['user_identity_field']);
$container->setParameter('rch_jwt_user.user_provider', $fosUserProviderId);
$configurations = [
'fos_user' => [
'user_class' => $configs['user_class'],
'firewall_name' => 'main',
'db_driver' => 'orm',
],
'lexik_jwt_authentication' => [
'private_key_path' => $kernelRootDir.'/../var/jwt/private.pem',
'public_key_path' => $kernelRootDir.'/../var/jwt/public.pem',
'pass_phrase' => $configs['passphrase'],
'user_identity_field' => $configs['user_identity_field'],
],
'gesdinet_jwt_refresh_token' => [
'ttl' => 86400,
'user_provider' => $fosUserProviderId,
],
];
foreach ($configurations as $extension => $config) {
$container->prependExtensionConfig($extension, $configurations[$extension]);
}
} | {@inheritdoc} | entailment |
public function updateCMSFields(FieldList $fields)
{
if (Config::inst()->get(SeoObjectExtension::class, 'use_webmaster_tag')) {
$fields->addFieldToTab(
"Root.SEO",
TextareaField::create(
"GoogleWebmasterMetaTag",
_t('SEO.SEOGoogleWebmasterMetaTag', 'Google webmaster meta tag')
)->setRightTitle(_t(
'SEO.SEOGoogleWebmasterMetaTagRightTitle',
"Full Google webmaster meta tag For example <meta name=\"google-site-verification\" content=\"hjhjhJHG12736JHGdfsdf\" />"
))
);
}
} | updateCMSFields.
Update Silverstripe CMS Fields for SEO Module
@param FieldList | entailment |
public function handle()
{
$this->line('SeAT Admin Login URL Generator');
$admin = User::firstOrNew(['name' => 'admin']);
if (! $admin->exists) {
$this->warn('User \'admin\' does not exist. It will be created.');
$admin->fill([
'name' => 'admin',
'character_owner_hash' => 'none',
]);
$admin->id = 1; // Needed as id is not fillable
$admin->group_id = Group::create()->id;
$admin->save();
}
$this->line('Searching for the \'Superuser\' role');
$role = Role::where('title', 'Superuser')->first();
if (! $role) {
$this->comment('Creating the Superuser role');
$role = Role::create(['title' => 'Superuser']);
}
$this->line('Checking if the Superuser role has the superuser permission');
$role_permissions = $this->getCompleteRole($role->id)->permissions;
if (! $role_permissions->contains('superuser')) {
$this->comment('Adding the superuser permission to the role');
$this->giveRolePermission($role->id, 'superuser', false);
}
$this->line('Checking if \'admin\' is a super user');
if (! $admin->has('superuser')) {
$this->comment('Adding \'admin\' to the Superuser role');
$this->giveGroupRole($admin->group->id, $role->id);
}
$this->line('Generating authentication token');
$token = str_random(32);
cache(['admin_login_token' => $token], 60);
$this->line('');
$this->info('Your authentication URL is valid for 60 seconds.');
$this->line(route('auth.admin.login', ['token' => $token]));
// Analytics
$this->dispatch((new Analytics((new AnalyticsContainer)
->set('type', 'event')
->set('ec', 'admin')
->set('ea', 'password_reset')
->set('el', 'console'))));
} | Execute the console command.
@throws \Exception | entailment |
public function setRequirements()
{
if (!isset($this->options['requirements']) || $this->options['requirements'] === null) {
return $this;
}
$requirements = $this->options['requirements'];
if (!is_array($requirements)) {
$requirements = [$requirements];
}
foreach ($requirements as $constraint) {
$this->requirements[] = $constraint;
}
unset($this->options['requirements']);
return $this;
} | Set requirements. | entailment |
public function removeSection($section)
{
if ($has = $this->hasSection($section)) {
unset($this->sections[$section]);
}
return $has;
} | Removes a section by name.
@param string $section
@return bool | entailment |
public function toArray()
{
$ini = [];
foreach ($this->sections as $sectionName => $section) {
$ini[$sectionName] = $section->getProperties();
}
return $ini;
} | Converts the configuration to array.
@return array | entailment |
public function mapSection($section, $className)
{
if (false === class_exists($className)) {
throw new \InvalidArgumentException('This section class does not exist');
} elseif (false === is_a($className, 'Supervisor\Configuration\Section', true)) {
throw new \InvalidArgumentException('This section class must implement Supervisor\Configuration\Section');
}
$this->sectionMap[$section] = $className;
} | Adds or overrides a default section mapping.
@param string $section
@param string $className | entailment |
public function findSection($section)
{
if (isset($this->sectionMap[$section])) {
return $this->sectionMap[$section];
}
return false;
} | Finds a section class by name.
@param string $section
@return string|bool | entailment |
protected function configureProperties(OptionsResolver $resolver)
{
parent::configureProperties($resolver);
$resolver->setDefined('buffer_size')
->setAllowedTypes('buffer_size', 'integer');
$resolver->setDefined('events');
$this->configureArrayProperty('events', $resolver);
$resolver
->setDefined('result_handler')
->setAllowedTypes('result_handler', 'string');
} | {@inheritdoc} | entailment |
protected function convertToResource($data)
{
return Item::make($this->client, $this->bib, $this->holding, $data->item_data->pid)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return Item | entailment |
public function fromBarcode($barcode)
{
$destinationUrl = $this->client->getRedirectLocation('/items', ['item_barcode' => $barcode]);
// Extract the MMS ID from the redirect target URL.
// Example: https://api-eu.hosted.exlibrisgroup.com/almaws/v1/bibs/999211285764702204/holdings/22156746440002204/items/23156746430002204
if (!is_null($destinationUrl) && preg_match('$bibs/([0-9]+)/holdings/([0-9]+)/items/([0-9]+)$', $destinationUrl, $matches)) {
$mms_id = $matches[1];
$holding_id = $matches[2];
$item_id = $matches[3];
$bib = Bib::make($this->client, $mms_id);
$holding = Holding::make($this->client, $bib, $holding_id);
return Item::make($this->client, $bib, $holding, $item_id);
}
} | Get an Item object from a barcode.
@param string $barcode
@return Item|null | entailment |
public function connect(array $options = array())
{
$host = $port = null;
if (!is_null($this->host)) {
$host = 'host='.$this->host.';';
if (!is_null($this->port)) {
$port = 'port='.$this->port.';';
}
}
$connection = 'mysql:'.$host.$port.'dbname='.$this->name;
$this->connection = new \PDO($connection, $this->user, $this->pass, $options);
$this->trigger('mysql-connect');
return $this;
} | Connects to the database
@param array $options the connection options
@return | entailment |
public function subselect($parentQuery, $select = '*')
{
//Argument 2 must be a string
Argument::i()->test(2, 'string');
return Subselect::i($parentQuery, $select);
} | Returns the Subselect query builder
@param string $parentQuery The parent query
@param string $select List of columns
@return Eden\Mysql\Subselect | entailment |
public function getColumns($table, $filters = null)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$query = $this->utility();
if (is_array($filters)) {
foreach ($filters as $i => $filter) {
//array('post_id=%s AND post_title IN %s', 123, array('asd'));
$format = array_shift($filter);
$filter = $this->bind($filter);
$filters[$i] = vsprintf($format, $filter);
}
}
$query->showColumns($table, $filters);
return $this->query($query, $this->getBinds());
} | Returns the columns and attributes given the table name
@param string $table The name of the table
@param array $filters Where filters
@return array|false | entailment |
public function getPrimaryKey($table)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$query = $this->utility();
$results = $this->getColumns($table, "`Key` = 'PRI'");
return isset($results[0]['Field']) ? $results[0]['Field'] : null;
} | Peturns the primary key name given the table
@param string $table Table name
@return string | entailment |
public function getSchema()
{
$backup = array();
$tables = $this->getTables();
foreach ($tables as $table) {
$backup[] = $this->getBackup();
}
return implode("\n\n", $backup);
} | Returns the whole enitre schema and rows
of the current databse
@return string | entailment |
public function getTables($like = null)
{
//Argument 1 must be a string or null
Argument::i()->test(1, 'string', 'null');
$query = $this->utility();
$like = $like ? $this->bind($like) : null;
$results = $this->query($query->showTables($like), $q->getBinds());
$newResults = array();
foreach ($results as $result) {
foreach ($result as $key => $value) {
$newResults[] = $value;
break;
}
}
return $newResults;
} | Returns a listing of tables in the DB
@param string|null $like The like pattern
@return attay|false | entailment |
public function getTableSchema($table)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$backup = array();
//get the schema
$schema = $this->getColumns($table);
if (count($schema)) {
//lets rebuild this schema
$query = $this->create()->setName($table);
foreach ($schema as $field) {
//first try to parse what we can from each field
$fieldTypeArray = explode(' ', $field['Type']);
$typeArray = explode('(', $fieldTypeArray[0]);
$type = $typeArray[0];
$length = str_replace(')', '', $typeArray[1]);
$attribute = isset($fieldTypeArray[1]) ? $fieldTypeArray[1] : null;
$null = strtolower($field['Null']) == 'no' ? false : true;
$increment = strtolower($field['Extra']) == 'auto_increment' ? true : false;
//lets now add a field to our schema class
$q->addField($field['Field'], array(
'type' => $type,
'length' => $length,
'attribute' => $attribute,
'null' => $null,
'default' => $field['Default'],
'auto_increment' => $increment));
//set keys where found
switch ($field['Key']) {
case 'PRI':
$query->addPrimaryKey($field['Field']);
break;
case 'UNI':
$query->addUniqueKey($field['Field'], array($field['Field']));
break;
case 'MUL':
$query->addKey($field['Field'], array($field['Field']));
break;
}
}
//store the query but dont run it
$backup[] = $query;
}
//get the rows
$rows = $this->query($this->select->from($table)->getQuery());
if (count($rows)) {
//lets build an insert query
$query = $this->insert($table);
foreach ($rows as $index => $row) {
foreach ($row as $key => $value) {
$query->set($key, $this->getBinds($value), $index);
}
}
//store the query but dont run it
$backup[] = $query->getQuery(true);
}
return implode("\n\n", $backup);
} | Returns the whole enitre schema and rows
of the current table
@param *string $table Name of table
@return string | entailment |
public function attach(Task $task, $task_name = null)
{
if (is_null($task_name)) {
$task_name = count($this->tasks);
}
$this->tasks[$task_name] = $task;
curl_multi_add_handle($this->curl, $task->createCurl());
$deferred = new Deferred();
$this->deferred[$task_name] = $deferred;
return $deferred->promise();
} | add new task and return a promise
@param Task $task
@param null $task_name
@return \React\Promise\PromiseInterface | entailment |
public function fire()
{
Assets::withChain([
new Locations($this->token), new Names($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Bookmarks::withChain([
new Folders($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Contacts::withChain([
new Labels($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Contracts::withChain([
new Items($this->token), new Bids($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Info::dispatch($this->token)->onQueue($this->queue);
AllianceHistory::dispatch($this->token)->onQueue($this->queue);
Blueprints::dispatch($this->token)->onQueue($this->queue);
ContainerLogs::dispatch($this->token)->onQueue($this->queue);
Divisions::dispatch($this->token)->onQueue($this->queue);
Facilities::dispatch($this->token)->onQueue($this->queue);
IssuedMedals::dispatch($this->token)->onQueue($this->queue);
Medals::dispatch($this->token)->onQueue($this->queue);
Members::dispatch($this->token)->onQueue($this->queue);
MembersLimit::dispatch($this->token)->onQueue($this->queue);
MemberTracking::dispatch($this->token)->onQueue($this->queue);
Roles::withChain([
new RoleHistories($this->token), ]
)->dispatch($this->token)->onQueue($this->queue);
Shareholders::dispatch($this->token)->onQueue($this->queue);
Standings::dispatch($this->token)->onQueue($this->queue);
Starbases::withChain([
new StarbaseDetails($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Structures::dispatch($this->token)->onQueue($this->queue);
CustomsOffices::withChain([
new CustomsOfficeLocations($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Titles::withChain([
new MembersTitles($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Jobs::dispatch($this->token)->onQueue($this->queue);
Extractions::dispatch($this->token)->onQueue($this->queue);
Observers::withChain([
new ObserverDetails($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Recent::withChain([
new Detail($this->token),
])->dispatch($this->token)->onQueue($this->queue);
Orders::dispatch($this->token)->onQueue($this->queue);
Balances::dispatch($this->token)->onQueue($this->queue);
Journals::dispatch($this->token)->onQueue($this->queue);
Transactions::dispatch($this->token)->onQueue($this->queue);
} | Fires the command.
@return mixed | entailment |
public function get($user_id, $params = [])
{
return User::make($this->client, $user_id)
->setParams($params);
} | Get a User object by id.
@param $user_id int
@param $params array Additional query string parameters
@return User | entailment |
public function search($query, array $options = [])
{
// Max number of records to fetch. Set to 0 to fetch all.
$limit = array_key_exists('limit', $options) ? $options['limit'] : 0;
// Set to true to do a phrase search
$phrase = array_key_exists('phrase', $options) ? $options['phrase'] : false;
// Set to true to expand all query results to full records.
// Please note that this will make queries significantly slower!
$expand = array_key_exists('expand', $options) ? $options['expand'] : false;
// Number of records to fetch each batch. Usually no need to change this.
$batchSize = array_key_exists('batchSize', $options) ? $options['batchSize'] : 10;
if ($limit != 0 && $limit < $batchSize) {
$batchSize = $limit;
}
// The API will throw a 400 response if you include properly encoded spaces,
// but underscores work as a substitute.
$query = explode(' AND ', $query);
$query = $phrase ? str_replace(' ', '_', $query) : str_replace(' ', ',', $query);
$query = implode(' AND ', $query);
$offset = 0;
while (true) {
$response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);
// The API sometimes returns total_record_count: -1, with no further error message.
// Seems to indicate that the query was not understood.
// See: https://github.com/scriptotek/php-alma-client/issues/8
if ($response->total_record_count == -1) {
throw new InvalidQuery($query);
}
if ($response->total_record_count == 0) {
break;
}
if (!isset($response->user) || empty($response->user)) {
// We cannot trust the value in 'total_record_count', so if there are no more records,
// we have to assume the result set is depleted.
// See: https://github.com/scriptotek/php-alma-client/issues/7
break;
}
foreach ($response->user as $data) {
$offset++;
// Contacts without a primary identifier will have the primary_id
// field populated with something weird like "no primary id (123456789023)".
// We ignore those.
// See: https://github.com/scriptotek/php-alma-client/issues/6
if (strpos($data->primary_id, 'no primary id') === 0) {
continue;
}
$user = User::make($this->client, $data->primary_id)
->init($data);
if ($expand) {
$user->init();
}
yield $user;
}
if ($offset >= $response->total_record_count) {
break;
}
if ($limit != 0 && $offset >= $limit) {
break;
}
}
} | Iterates over all users matching the given query.
Handles continuation.
@param string $query
@param array $options
@return \Generator | entailment |
public function get($mms_id, $expand = null)
{
$params = ['expand' => $expand];
return Bib::make($this->client, $mms_id)
->setParams($params);
} | Get a Bib object.
@param string $mms_id
@param array $expand Expand the bibliographic record with additional information.
@return Bib | entailment |
public function fromBarcode($barcode)
{
$destinationUrl = $this->client->getRedirectLocation('/items', ['item_barcode' => $barcode]);
// Extract the MMS ID from the redirect target URL.
// Example: https://api-eu.hosted.exlibrisgroup.com/almaws/v1/bibs/999211285764702204/holdings/22156746440002204/items/23156746430002204
if (!is_null($destinationUrl) && preg_match('$bibs/([0-9]+)/holdings/([0-9]+)/items/([0-9]+)$', $destinationUrl, $matches)) {
$mmsId = $matches[1];
return $this->get($mmsId);
}
} | Get a Bib object from a item barcode.
@param string $barcode
@return Bib | entailment |
public function fromHoldingsId($holdings_id)
{
$data = $this->client->getXML('/bibs', ['holdings_id' => $holdings_id]);
return $this->get($data->text('bib/mms_id'))
->init($data->first('bib'));
} | Get a Bib object from a holdings ID.
@param string $holdings_id
@return Bib | entailment |
public function search($cql, $batchSize = 10)
{
$this->client->assertHasSruClient();
foreach ($this->client->sru->all($cql, $batchSize) as $sruRecord) {
yield Bib::fromSruRecord($sruRecord, $this->client);
}
} | Get Bib records from SRU search. You must have an SRU client connected
to the Alma client (see `Client::setSruClient()`).
Returns a generator that handles continuation under the hood.
@param string $cql The CQL query
@param int $batchSize Number of records to return in each batch.
@return \Generator|Bib[] | entailment |
public function handle()
{
// Start by warning the user about the command that will be run
$this->comment('Warning! This Laravel command uses exec() to execute a ');
$this->comment('mysql shell command to import an extracted dump. Due');
$this->comment('to the way the command is constructed, should someone ');
$this->comment('view the current running processes of your server, they ');
$this->comment('will be able to see your SeAT database users password.');
$this->line('');
$this->line('Ensure that you understand this before continuing.');
// Test that we have valid Database details. An exception
// will be thrown if this fails.
DB::connection()->getDatabaseName();
if (! $this->confirm('Are you sure you want to update to the latest EVE SDE?', true)) {
$this->warn('Exiting');
return;
}
// Request the json from eveseat/resources
$this->json = $this->getJsonResource();
// Ensure we got a response, else fail.
if (! $this->json) {
$this->warn('Unable to reach the resources endpoint.');
return;
}
// Check if we should attempt getting the
// version string locally
if ($this->option('local')) {
$version_number = env('SDE_VERSION', null);
if (! is_null($version_number)) {
$this->comment('Using locally sourced version number of: ' . $version_number);
$this->json->version = env('SDE_VERSION');
} else {
$this->warn('Unable to determine the version number override. ' .
'Using remote version: ' . $this->json->version);
}
}
// Avoid an existing SDE to be accidentally installed again
// except if the user explicitly ask for it
if ($this->json->version == Seat::get('installed_sde') &&
$this->option('force') == false
) {
$this->warn('You are already running the latest SDE version.');
$this->warn('If you want to install it again, run this command with --force argument.');
return;
}
// Ask for a confirmation before installing an existing SDE version
if ($this->option('force') == true) {
$this->warn('You will re-download and install the current SDE version.');
if (! $this->confirm('Are you sure ?', true)) {
$this->info('Nothing has been updated.');
return;
}
}
//TODO: Allow for tables to be specified in config file
// Show a final confirmation with some info on what
// we are going to be doing.
$this->info('The local SDE data will be updated to ' . $this->json->version);
$this->info(count($this->json->tables) . ' tables will be updated: ' .
implode(', ', $this->json->tables));
$this->info('Download format will be: ' . $this->json->format);
$this->line('');
$this->info('The SDE will be imported to mysql://' .
config('database.connections.mysql.username') . '@' .
config('database.connections.mysql.host') . ':' .
config('database.connections.mysql.port') . '/' .
config('database.connections.mysql.database'));
if (! $this->confirm('Does the above look OK?', true)) {
$this->warn('Exiting');
return;
}
if (! $this->isStorageOk()) {
$this->error('Storage path is not OK. Please check permissions');
return;
}
// Download the SDE's
$this->getSde();
$this->importSde();
Seat::set('installed_sde', $this->json->version);
$this->line('SDE Update Command Complete');
// Analytics
dispatch((new Analytics((new AnalyticsContainer)
->set('type', 'event')
->set('ec', 'queues')
->set('ea', 'update_sde')
->set('el', 'console')
->set('ev', $this->json->version)))
->onQueue('medium'));
} | Query the eveseat/resources repository for SDE
related information.
@throws \Seat\Services\Exceptions\SettingException | entailment |
public function getJsonResource()
{
$result = $this->getGuzzle()->request('GET',
'https://raw.githubusercontent.com/eveseat/resources/master/sde.json', [
'headers' => ['Accept' => 'application/json'],
]);
if ($result->getStatusCode() != 200)
return json_encode([]);
return json_decode($result->getBody());
} | Query the eveseat/resources repository for SDE
related information.
@return mixed | entailment |
public function getGuzzle()
{
if ($this->guzzle)
return $this->guzzle;
$this->guzzle = new Client();
return $this->guzzle;
} | Get an instance of Guzzle.
@return \GuzzleHttp\Client | entailment |
public function isStorageOk()
{
$storage = storage_path() . '/sde/' . $this->json->version . '/';
$this->info('Storage path is: ' . $storage);
if (File::isWritable(storage_path())) {
// Check that the path exists
if (! File::exists($storage))
File::makeDirectory($storage, 0755, true);
// Set the storage path
$this->storage_path = $storage;
return true;
}
return false;
} | Check that the storage path is ok. I needed it
will be automatically created.
@return bool | entailment |
public function getSde()
{
$this->line('Downloading...');
$bar = $this->getProgressBar(count($this->json->tables));
foreach ($this->json->tables as $table) {
$url = str_replace(':version', $this->json->version, $this->json->url) .
$table . $this->json->format;
$destination = $this->storage_path . $table . $this->json->format;
$file_handler = fopen($destination, 'w');
$result = $this->getGuzzle()->request('GET', $url, [
'sink' => $file_handler, ]);
fclose($file_handler);
if ($result->getStatusCode() != 200)
$this->error('Unable to download ' . $url .
'. The HTTP response was: ' . $result->getStatusCode());
$bar->advance();
}
$bar->finish();
$this->line('');
} | Download the EVE Sde from Fuzzwork and save it
in the storage_path/sde folder. | entailment |
public function getProgressBar($iterations)
{
$bar = $this->output->createProgressBar($iterations);
$bar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s% %memory:6s%');
return $bar;
} | Get a new progress bar to display based on the
amount of iterations we expect to use.
@param $iterations
@return \Symfony\Component\Console\Helper\ProgressBar | entailment |
public function importSde()
{
$this->line('Importing...');
$bar = $this->getProgressBar(count($this->json->tables));
foreach ($this->json->tables as $table) {
$archive_path = $this->storage_path . $table . $this->json->format;
$extracted_path = $this->storage_path . $table . '.sql';
if (! File::exists($archive_path)) {
$this->warn($archive_path . ' seems to be invalid. Skipping.');
continue;
}
// Get 2 handles ready for both the in and out files
$input_file = bzopen($archive_path, 'r');
$output_file = fopen($extracted_path, 'w');
// Write the $output_file in chunks
while ($chunk = bzread($input_file, 4096))
fwrite($output_file, $chunk, 4096);
// Close the files
bzclose($input_file);
fclose($output_file);
// With the output file ready, prepare the scary exec() command
// that should be run. A sample $import_command is:
// mysql -u root -h 127.0.0.1 seat < /tmp/sample.sql
$import_command = 'mysql -u ' . config('database.connections.mysql.username') .
// Check if the password is longer than 0. If not, don't specify the -p flag
(strlen(config('database.connections.mysql.password')) ? ' -p' : '')
// Append this regardless. Escape special chars in the password too.
. escapeshellcmd(config('database.connections.mysql.password')) .
' -h ' . config('database.connections.mysql.host') .
' -P ' . config('database.connections.mysql.port') .
' ' . config('database.connections.mysql.database') .
' < ' . $extracted_path;
// Run the command... (*scared_face*)
exec($import_command, $output, $exit_code);
if ($exit_code !== 0)
$this->error('Warning: Import failed with exit code ' .
$exit_code . ' and command outut: ' . implode('\n', $output));
$bar->advance();
}
$bar->finish();
$this->line('');
} | Extract the SDE files downloaded and run the MySQL command
to import them into the database. | entailment |
public function connect(array $options = array())
{
$this->connection = new \PDO('sqlite:'.$this->path);
$this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->trigger('connect');
return $this;
} | Connects to the database
@param array $options The connection options
@return Eden\Sqlite\Index | entailment |
public function getColumns($table)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$query = $this->utility()->showColumns($table);
$results = $this->query($query, $this->getBinds());
$columns = array();
foreach ($results as $column) {
$key = null;
if ($column['pk'] == 1) {
$key = 'PRI';
}
$columns[] = array(
'Field' => $column['name'],
'Type' => $column['type'],
'Default' => $column['dflt_value'],
'Null' => $column['notnull'] != 1,
'Key' => $key);
}
return $columns;
} | Returns the columns and attributes given the table name
@param *string $table The name of the table
@return array|false | entailment |
public function insertRows($table, array $settings, $bind = true)
{
//argument test
Argument::i()
//Argument 1 must be a string
->test(1, 'string')
//Argument 3 must be an array or bool
->test(3, 'array', 'bool');
//this is an array of arrays
foreach ($settings as $index => $setting) {
//SQLite no available multi insert
//there's work arounds, but no performance gain
$this->insertRow($table, $setting, $bind);
}
return $this;
} | Inserts multiple rows into a table
@param *string $table Table name
@param array $setting Key/value 2D array matching table columns
@param bool|array $bind Whether to compute with binded variables
@return Eden\Sqlite\Index | entailment |
public function select($select = 'ROWID,*')
{
//Argument 1 must be a string or array
Argument::i()->test(1, 'string', 'array');
return \Eden\Sql\Select::i($select);
} | Returns the select query builder
@param string|array $select Column list
@return Eden\Sql\Select | entailment |
public function all($status = 'ACTIVE')
{
$ids = [$this->data->primary_id];
foreach ($this->data->user_identifier as $identifier) {
if (is_null($status) || $identifier->status == $status) {
$ids[] = $identifier->value;
}
}
return $ids;
} | Get a flat array of all the user IDs.
@param string $status (Default: 'ACTIVE').
@return string[] | entailment |
public function allOfType($value, $status = 'ACTIVE')
{
$ids = [];
foreach ($this->data->user_identifier as $identifier) {
if ($identifier->id_type->value == $value && (is_null($status) || $identifier->status == $status)) {
$ids[] = $identifier->value;
}
}
return $ids;
} | Get all active user identifiers of a given type, like 'BARCODE' or 'UNIV_ID'.
@param string $value
@param string $status
@return array | entailment |
public function firstOfType($value, $status = 'ACTIVE')
{
foreach ($this->data->user_identifier as $identifier) {
if ($identifier->id_type->value == $value && (is_null($status) || $identifier->status == $status)) {
return $identifier->value;
}
}
} | Get the first active user identifier of a given type, like 'BARCODE' or 'UNIV_ID'.
@param string $value
@param string $status
@return null|string | entailment |
public function load(Configuration $configuration = null)
{
if (!$this->filesystem->has($this->file)) {
throw new LoaderException(sprintf('File "%s" not found', $this->file));
}
if (!$fileContents = $this->filesystem->read($this->file)) {
throw new LoaderException(sprintf('Reading file "%s" failed', $this->file));
}
try {
$ini = $this->getParser()->parse($fileContents);
} catch (ParserException $e) {
throw new LoaderException('Cannot parse INI', 0, $e);
}
return $this->parseSections($ini, $configuration);
} | {@inheritdoc} | entailment |
protected function onData($data)
{
if (is_null($this->totalRecordCount)) {
$this->totalRecordCount = $data->total_record_count;
}
if (!isset($data->{$this->responseKey})) {
return;
}
foreach ($data->{$this->responseKey} as $result) {
$this->resources[] = $this->convertToResource($result);
}
} | Called when data is available on the object.
The resource classes can use this method to process the data.
@param $data | entailment |
protected function convertToResource($data)
{
return Request::make($this->client, User::make($this->client, $data->user_primary_id), $data->request_id)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return Request | entailment |
public function register()
{
$this->mergeConfigFrom(
__DIR__ . '/../../config/alma.php',
'alma'
);
$this->app->singleton(AlmaClient::class, function ($app) {
// Create Alma client
$alma = new AlmaClient(
$app['config']->get('alma.iz.key'),
$app['config']->get('alma.region')
);
// Set network zone key, if any
$alma->nz->setKey($app['config']->get('alma.nz.key'));
// Optionally, attach SRU client for institution zone
if ($app['config']->get('alma.iz.sru')) {
$alma->setSruClient(new SruClient(
$app['config']->get('alma.iz.sru'),
['version' => '1.2', 'schema' => 'marcxml']
));
}
// Optionally, attach SRU client for network zone
if ($app['config']->get('alma.nz.sru')) {
$alma->nz->setSruClient(new SruClient(
$app['config']->get('alma.nz.sru'),
['version' => '1.2', 'schema' => 'marcxml']
));
}
return $alma;
});
} | Register the service provider.
@return void | entailment |
public function addForeignKey($name, $table, $key)
{
//argument test
Argument::i()
->test(1, 'string') //Argument 1 must be a string
->test(2, 'string') //Argument 2 must be a string
->test(3, 'string'); //Argument 3 must be a string
$this->keys[$name] = array($table, $key);
return $this;
} | Adds an index key
@param *string $name Name of column
@param *string $table Name of foreign table
@param *string $key Name of key
@return Eden\Sqlite\Create | entailment |
public function getQuery($unbind = false)
{
$table = '"'.$this->name.'"';
$fields = array();
foreach ($this->fields as $name => $attr) {
$field = array('"'.$name.'"');
if (isset($attr['type'])) {
$field[] = isset($attr['length']) ?
$attr['type'] . '('.$attr['length'].')' :
$attr['type'];
}
if (isset($attr['primary'])) {
$field[] = 'PRIMARY KEY';
}
if (isset($attr['attribute'])) {
$field[] = $attr['attribute'];
}
if (isset($attr['null'])) {
if ($attr['null'] == false) {
$field[] = 'NOT NULL';
} else {
$field[] = 'DEFAULT NULL';
}
}
if (isset($attr['default'])&& $attr['default'] !== false) {
if (!isset($attr['null']) || $attr['null'] == false) {
if (is_string($attr['default'])) {
$field[] = 'DEFAULT \''.$attr['default'] . '\'';
} else if (is_numeric($attr['default'])) {
$field[] = 'DEFAULT '.$attr['default'];
}
}
}
$fields[] = implode(' ', $field);
}
$fields = !empty($fields) ? implode(', ', $fields) : '';
$uniques = array();
foreach ($this->uniqueKeys as $key => $value) {
$uniques[] = 'UNIQUE "'. $key .'" ("'.implode('", "', $value).'")';
}
$uniques = !empty($uniques) ? ', ' . implode(", \n", $uniques) : '';
$keys = array();
foreach ($this->keys as $key => $value) {
$keys[] = 'FOREIGN KEY "'. $key .'" REFERENCES '.$value[0].'('.$value[1].')';
}
$keys = !empty($keys) ? ', ' . implode(", \n", $keys) : '';
return sprintf(
'CREATE TABLE %s (%s%s%s)',
$table,
$fields,
$unique,
$keys
);
} | Returns the string version of the query
@param bool $unbind Whether to unbind variables
@return string | entailment |
protected function convertToResource($data)
{
return ResourceSharingRequest::make($this->client, $data->request_id)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return mixed | entailment |
protected function convertToResource($data)
{
$bib = $this->client->bibs->get($data->resource_metadata->mms_id->value);
return RequestedResource::make($this->client, $this->library, $this->params['circ_desk'], $bib)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return mixed | entailment |
public static function Jaro($string1, $string2) {
$str1_len = strlen($string1);
$str2_len = strlen($string2);
// theoretical distance
$distance = (int) floor(min($str1_len, $str2_len) / 2.0);
// get common characters
$commons1 = self::getCommonCharacters($string1, $string2, $distance);
$commons2 = self::getCommonCharacters($string2, $string1, $distance);
if (($commons1_len = strlen($commons1)) == 0) {
return 0;
}
if (($commons2_len = strlen($commons2)) == 0) {
return 0;
}
// calculate transpositions
$transpositions = 0;
$upperBound = min($commons1_len, $commons2_len);
for ($i = 0; $i < $upperBound; $i++) {
if ($commons1[$i] != $commons2[$i]) {
$transpositions++;
}
}
$transpositions /= 2.0;
// return the Jaro distance
return ($commons1_len / ($str1_len) + $commons2_len / ($str2_len) +
($commons1_len - $transpositions) / ($commons1_len)) / 3.0;
} | The higher the Jaro–Winkler distance for two strings is, the more
similar the strings are. The Jaro–Winkler distance metric is designed
and best suited for short strings such as person names. The score is
normalized such that 0 equates to no similarity and 1 is an exact match.
@param type $string1
@param type $string2
@return int | entailment |
protected static function sum_hash($c, $h) {
$h = ($h * self::HASH_PRIME) % pow(2, 32);
$h = ($h ^ $c) % pow(2, 32);
return $h;
} | /* A simple non-rolling hash, based on the FNV hash | entailment |
public function digestAuth($realm, array $users)
{
if ($this->isCLIRequest()) {
return;
}
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
$this->sendAuthenticateHeader($realm);
exit();
}
if (!($data = $this->httpDigestParse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) {
$this->sendAuthenticateHeader($realm);
exit();
}
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'] . ':' . $data['uri']);
$valid_response = md5($A1 . ':' . $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $A2);
if ($data['response'] != $valid_response) {
$this->sendAuthenticateHeader($realm);
exit();
}
} | Perform digest HTTP authentication
Note: HTTP authentication is disabled, if application
runs in command-line (CLI) mode
@param string $realm
@param array $users username => password | entailment |
protected function isSSLRequest()
{
if (isset($_SERVER['HTTPS'])) {
if ('on' == strtolower($_SERVER['HTTPS'])) {
return true;
}
if ('1' == $_SERVER['HTTPS']) {
return true;
}
} elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
return true;
}
return false;
} | Checks, if application is requested via secure SSL
@return bool | entailment |
public function handle()
{
$this->line('SeAT Cache Clearing Tool');
$this->line('');
if (! $this->confirm('Are you sure you want to clear ALL caches (file/redis/db)?', true)) {
$this->warn('Exiting without clearing cache');
return;
}
$this->clear_redis_cache();
// If we are not clearing
if (! $this->option('skip-eseye')) {
$this->clear_eseye_cache();
}
// Analytics
dispatch((new Analytics((new AnalyticsContainer)
->set('type', 'event')
->set('ec', 'admin')
->set('ea', 'cache_clear')
->set('el', 'console')))
->onQueue('medium'));
} | Execute the console command. | entailment |
public function clear_redis_cache()
{
$redis_host = config('database.redis.default.host');
$redis_port = config('database.redis.default.port');
$this->info('Clearing the Redis Cache at: ' . $redis_host . ':' . $redis_port);
try {
$redis = new Client([
'host' => $redis_host,
'port' => $redis_port,
]);
$redis->flushall();
$redis->disconnect();
} catch (Exception $e) {
$this->error('Failed to clear the Redis Cache. Error: ' . $e->getMessage());
}
} | Flush all keys in Redis. | entailment |
public function clear_eseye_cache()
{
// Eseye Cache Clearing
$eseye_cache = config('eveapi.config.eseye_cache');
if (File::isWritable($eseye_cache)) {
$this->info('Clearing the Eseye Cache at: ' . $eseye_cache);
if (! File::deleteDirectory($eseye_cache, true))
$this->error('Failed to clear the Eseye Cache directory. Check permissions.');
} else {
$this->warn('Eseye Cache directory at ' . $eseye_cache . ' is not writable');
}
} | Clear the Eseye Storage Cache. | entailment |
protected function onData($data)
{
if (isset($this->bib_data)) {
$this->bib->init($this->bib_data);
}
if (isset($this->holding_data)) {
$this->holding->init($this->holding_data);
}
} | Called when data is available to be processed.
@param mixed $data | entailment |
public function checkOut(User $user, Library $library, $circ_desk = 'DEFAULT_CIRC_DESK')
{
$postData = [
'library' => ['value' => $library->code],
'circ_desk' => ['value' => $circ_desk],
];
$data = $this->client->postJSON(
$this->url('/loans', ['user_id' => $user->id]),
$postData
);
return Loan::make($this->client, $user, $data->loan_id)
->init($data);
} | Create a new loan.
@param User $user
@param Library $library
@param string $circ_desk
@throws \Scriptotek\Alma\Exception\RequestFailed
@return Loan | entailment |
public function scanIn(Library $library, $circ_desk = 'DEFAULT_CIRC_DESK', $params = [])
{
$params['op'] = 'scan';
$params['library'] = $library->code;
$params['circ_desk'] = $circ_desk;
$data = $this->client->postJSON($this->url('', $params));
return ScanInResponse::make($this->client, $data);
} | Perform scan-in on item.
@param Library $library
@param string $circ_desk
@param array $params
@throws \Scriptotek\Alma\Exception\RequestFailed
@return ScanInResponse | entailment |
public function getLoan()
{
$data = $this->client->getJSON($this->url('/loans'));
if ($data->total_record_count == 1) {
return Loan::make(
$this->client,
User::make($this->client, $data->item_loan[0]->user_id),
$data->item_loan[0]->loan_id
)->init($data->item_loan[0]);
}
} | Get the current loan as a Loan object, or null if the item is not loaned out.
@returns Loan|null | entailment |
public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event)
{
$data = $event->getData();
$data['user'] = $event->getUser()->getUsername();
$event->setData($data);
} | Add public data to the authentication response.
@param AuthenticationSuccessEvent $event | entailment |
public function handle()
{
$tokens = RefreshToken::all()
->when($this->argument('character_id'), function ($tokens) {
return $tokens->where('character_id', $this->argument('character_id'));
})
->each(function ($token) {
// Fire the class to update corporation information
(new CorporationTokenShouldUpdate($token, 'default'))->fire();
});
$this->info('Processed ' . $tokens->count() . ' refresh tokens.');
} | Execute the console command. | entailment |
protected function fetchBatch($attempt = 1, $chunkSize = null)
{
if ($this->isFinished) {
return;
}
$results = $this->client->getXML($this->url('', [
'path' => $this->resumptionToken ? null : $this->path,
'limit' => $chunkSize ?: $this->chunkSize,
'token' => $this->resumptionToken,
'filter' => $this->filter ? str_replace(['\''], ['''], $this->filter) : null,
]));
$results->registerXPathNamespaces([
'rowset' => 'urn:schemas-microsoft-com:xml-analysis:rowset',
'xsd' => 'http://www.w3.org/2001/XMLSchema',
'saw-sql' => 'urn:saw-sql',
]);
$this->readColumnHeaders($results);
$rows = $results->all('//rowset:Row');
foreach ($rows as $row) {
$this->resources[] = $this->convertToResource($row);
}
$this->resumptionToken = $results->text('/report/QueryResult/ResumptionToken') ?: $this->resumptionToken;
$this->isFinished = ($results->text('/report/QueryResult/IsFinished') === 'true');
if (!count($rows) && !$this->isFinished) {
// If the Analytics server spends too long time preparing the results, it can
// sometimes return an empty result set. If this happens, we should just wait
// a little and retry the request.
// See: https://bitbucket.org/uwlib/uwlib-alma-analytic-tools/wiki/Understanding_Analytic_GET_Requests#!analytic-still-loading
if ($attempt >= self::$maxAttempts) {
// Give up
throw new RequestFailed(
'Not getting any data from the Analytics server - max number of retries exhausted.'
);
}
// Sleep for a few seconds, then retry
sleep(self::$retryDelayTime);
$this->fetchBatch($attempt + 1);
}
} | Note: chunkSize must be between 25 and 1000.
@param int $attempt
@param int $chunkSize
@return void | entailment |
protected function readColumnHeaders(QuiteSimpleXMLElement $results)
{
$headers = array_map(function (QuiteSimpleXMLElement $node) {
return $node->attr('saw-sql:columnHeading');
}, $results->all('//xsd:complexType[@name="Row"]/xsd:sequence/xsd:element[position()>1]'));
if (!count($headers)) {
// No column headers included in this response. They're only
// included in the first response, so that's probably fine.
return;
}
if (!count($this->headers)) {
$this->headers = $headers;
return;
}
if (count($headers) != count($this->headers)) {
throw new \RuntimeException(sprintf(
'The number of returned columns (%d) does not match the number of assigned headers (%d).',
count($headers),
count($this->headers)
));
}
} | Read column headers from response, and check that we got the right number of columns back.
@param QuiteSimpleXMLElement $results | entailment |
public function handle()
{
$this->line('SeAT Admin Email Set Tool');
$this->info('The current admin email is: ' . Seat::get('admin_contact'));
$this->question('Please enter the new administrator email address:');
$email = $this->ask('Email: ');
while (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
// invalid email address
$this->error($email . ' is not a valid email. Please try again:');
$email = $this->ask('Email: ');
}
$this->info('Setting the administrator email to: ' . $email);
Seat::set('admin_contact', $email);
} | Execute the console command.
@throws \Seat\Services\Exceptions\SettingException | entailment |
public function getItem()
{
$bib = Bib::make($this->client, $this->data->bib_data->mms_id);
$holding = Holding::make($this->client, $bib, $this->data->holding_data->holding_id);
return Item::make(
$this->client,
$bib,
$holding,
$this->data->item_data->pid
)->init($this->data->item_data);
} | Get the scanned-in item.
@return Item | entailment |
public function getHolding()
{
$bib = Bib::make($this->client, $this->data->bib_data->mms_id);
return Holding::make(
$this->client,
$bib,
$this->data->holding_data->holding_id
)->init($this->data->holding_data);
} | Get the Holding object for the scanned-in item.
@return Holding | entailment |
public function getBib()
{
return Bib::make(
$this->client,
$this->data->bib_data->mms_id
)->init($this->data->bib_data);
} | Get the Bib object for the scanned-in item.
@return Bib | entailment |
public function handle()
{
$this->line('SeAT Diagnostics');
$this->line('If you are not already doing so, it is recommended that you ' .
'run this as the user the workers are running as.');
$this->line('Eg:');
$this->info(' sudo -u apache php artisan seat:admin:diagnose');
$this->info(' su -c "php artisan seat:admin:diagnose" -s /bin/sh www-data');
$this->line('This helps to check whether the permissions are correct.');
$this->line('');
$this->environment_info();
$this->line('');
$this->check_debug();
$this->line('');
$this->check_storage();
$this->line('');
$this->check_database();
$this->line('');
$this->check_redis();
$this->line('');
$this->check_pheal();
$this->line('');
$this->call('seat:version');
$this->line('SeAT Diagnostics complete');
} | Execute the console command. | entailment |
public function environment_info()
{
$this->line(' * Getting environment information');
// Get the current user.
$user = posix_getpwuid(posix_geteuid())['name'];
// Warn if we are running as root.
if ($user === 'root') {
$this->error('WARNING: This command is running as root!');
$this->error('WARNING: Running as root means that we will probably be able to access ' .
'any file on your system. This command will not be able to help diagnose permission ' .
'problems this way.');
}
$this->info('Current User: ' . $user);
$this->info('PHP Version: ' . phpversion());
$this->info('Host OS: ' . php_uname());
$this->info('SeAT Basepath: ' . base_path());
} | Print some information about the current environment. | entailment |
public function check_storage()
{
$this->line(' * Checking storage');
if (! File::isWritable(storage_path()))
$this->error(storage_path() . ' is not writable');
else
$this->info(storage_path() . ' is writable');
if (! File::isWritable(config('eveapi.config.eseye_logfile')))
$this->error(config('eveapi.config.eseye_logfile') . ' is not writable');
else
$this->info(config('eveapi.config.eseye_logfile') . ' is writable');
if (! File::isWritable(config('eveapi.config.eseye_cache')))
$this->error(config('eveapi.config.eseye_cache') . ' is not writable');
else
$this->info(config('eveapi.config.eseye_cache') . ' is writable');
if (! File::isWritable(storage_path() . '/sde/'))
$this->error(storage_path() . '/sde/' . ' is not writable');
else
$this->info(storage_path() . '/sde/' . ' is writable');
if (! File::isWritable(storage_path(sprintf('logs/laravel-%s.log', carbon()->toDateString()))))
$this->error(storage_path(sprintf('logs/laravel-%s.log is not writable', carbon()->toDateString())));
else
$this->info(storage_path(sprintf('logs/laravel-%s.log is writable', carbon()->toDateString())));
} | Check access to some important storage paths. | entailment |
public function check_database()
{
$this->line(' * Checking Database');
$this->table(['Setting', 'Value'], [
['Connection', env('DB_CONNECTION')],
['Host', env('DB_HOST')],
['Database', env('DB_DATABASE')],
['Username', env('DB_USERNAME')],
['Password', str_repeat('*', strlen(env('DB_PASSWORD')))],
]);
try {
$this->info('Connection OK to database: ' .
DB::connection()->getDatabaseName());
} catch (Exception $e) {
$this->error('Unable to connect to database server: ' . $e->getMessage());
}
} | Check if database access is OK. | entailment |
public function check_redis()
{
$this->line(' * Checking Redis');
$this->table(['Setting', 'Value'], [
['Host', config('database.redis.default.host')],
['Port', config('database.redis.default.port')],
['Database', config('database.redis.default.database')],
]);
$test_key = str_random(64);
try {
if (config('database.redis.default.path') && config('database.redis.default.scheme')) {
$redis = new Client([
'scheme' => config('database.redis.default.scheme'),
'path' => config('database.redis.default.path'),
]);
} else {
$redis = new Client([
'host' => config('database.redis.default.host'),
'port' => config('database.redis.default.port'),
]);
}
$this->info('Connected to Redis');
$redis->set($test_key, Carbon::now());
$this->info('Set random key of: ' . $test_key);
$redis->expire($test_key, 10);
$this->info('Set key to expire in 10 sec');
$redis->get($test_key);
$this->info('Read key OK');
} catch (Exception $e) {
$this->error('Redis test failed. ' . $e->getMessage());
}
} | Check of redis access is OK. | entailment |
public function check_pheal()
{
$this->line(' * Checking ESI Access');
$esi = app('esi-client')->get();
$esi->setVersion('v1');
Configuration::getInstance()->cache = NullCache::class;
try {
$result = $esi->invoke('get', '/status/');
$this->info('Server Online Since: ' . $result->start_time);
$this->info('Online Players: ' . $result->players);
} catch (RequestFailedException $e) {
$this->error('ESI does not appear to be available: ' . $e->getMessage());
}
$this->info('ESI appears to be OK');
} | Check if access to the EVE API OK. | entailment |
public function init($data = null)
{
if ($this->initialized) {
return $this;
}
if (is_null($data)) {
$data = $this->fetchData();
}
if ($this->isInitialized($data)) {
$this->initialized = true;
}
$this->data = $data;
if ($this->initialized) {
$this->onData($data);
}
return $this;
} | Load data onto this object. Chainable method.
@param \stdClass|QuiteSimpleXMLElement $data
@return $this | entailment |
protected function url($path = '', $query = [])
{
$path = $this->urlBase() . $path;
$query = http_build_query(array_merge($this->params, $query));
$url = $path;
if (!empty($query)) {
$url .= '?' . $query;
}
return $url;
} | Build a relative URL for a resource.
@param string $path
@param array $query
@return string | entailment |
public function getItem()
{
if (isset($this->barcode)) {
return $this->client->items->fromBarcode($this->barcode);
}
} | Get the related Item, if any.
@return Item|null | entailment |
protected function convertToResource($data)
{
return Collection::make($this->client, $data->id)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return Representation | entailment |
public function parseSections(array $sections, Configuration $configuration = null)
{
if (is_null($configuration)) {
$configuration = new Configuration();
}
foreach ($sections as $sectionName => $section) {
$name = explode(':', $sectionName, 2);
$class = $configuration->findSection($name[0]);
if (false === $class) {
$class = 'Supervisor\Configuration\Section\GenericSection';
$name[1] = $sectionName;
}
if (isset($name[1])) {
$section = new $class($name[1], $section);
} else {
$section = new $class($section);
}
$configuration->addSection($section);
}
return $configuration;
} | Parses a section array.
@param array $sections
@param Configuration|null $configuration
@return Configuration | entailment |
protected function renderHtml($data)
{
$html = $this->getHtmlPrefix();
$html .= $this->arrayToHtml($data);
$html .= $this->getHtmlPostfix();
return $html;
} | Render Array as HTML (thanks to joind.in's -api project!)
This code is cribbed from https://github.com/joindin/joindin-api/blob/master/src/views/HtmlView.php
@return string | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.