_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q239600
|
SocialLoginController.auth
|
train
|
public function auth(Request $request, $action)
{
$provider = strtolower($request->attributes->get('provider'));
if (! $this->providerExists($provider)) {
return $this->createNotFoundResponse();
}
$service = $this->getServiceByProvider($provider);
$redirectUri = $service->getAuthorizationUri(['state' => $action]);
$response = new Response();
$response->setStatusCode(301);
$response->headers->set('Location', (string) $redirectUri);
return $response;
}
|
php
|
{
"resource": ""
}
|
q239601
|
SocialLoginController.callback
|
train
|
public function callback(Request $request)
{
// Check to see if this provider exists and has a callback implemented
$provider = strtolower($request->attributes->get('provider'));
if (! $this->providerExists($provider)) {
return $this->createNotFoundResponse();
}
if (! method_exists($this, $provider)) {
throw new LogicException(sprintf(
'Callback for provider \'%s\' not implemented',
$provider
));
}
// Use provider service and access token from provider to create a LoginRequest for our app
$code = $request->query->get('code');
$providerService = $this->getServiceByProvider($provider);
$providerToken = $providerService->requestAccessToken($code);
$socialLoginRequest = $this->$provider($providerService, $providerToken);
// Handle login or link-account request and redirect to the redirect-url
$state = (int) $request->query->get('state');
try {
if ($state === self::ACTION_LOGIN_WITH_ACCOUNT) {
$token = $this->service->handleLoginRequest($socialLoginRequest);
} elseif ($state === self::ACTION_LINK_ACCOUNT) {
$token = $this->service->handleLinkRequest(
$socialLoginRequest,
$this->session->get('user')
);
} else {
return new Response(
'State parameter not set',
422
);
}
$redirect = $this->config['redirect-url'];
$redirect .= '?'.http_build_query($token);
} catch (NoLinkedAccountException $e) {
$redirect = $this->config['redirect-url'];
$redirect .= '?login_failure=1&error=no_linked_account';
} catch (LinkedAccountExistsException $e) {
$redirect = $this->config['redirect-url'];
$redirect .= '?login_failure=1&error=account_already_linked';
} catch (OutOfBoundsException $e) {
$redirect = $this->config['redirect-url'];
$redirect .= '?login_failure=1';
if ($e->getCode() === SocialLoginService::EXCEPTION_ACCOUNT_NOT_FOUND) {
$redirect .= '&error=account_not_found';
}
}
$response = new Response();
$response->setStatusCode(301);
$response->headers->set('Location', $redirect);
return $response;
}
|
php
|
{
"resource": ""
}
|
q239602
|
SocialLoginController.providerExists
|
train
|
protected function providerExists($provider)
{
return (
array_key_exists($provider, $this->serviceMap) ||
array_key_exists($provider, $this->config)
);
}
|
php
|
{
"resource": ""
}
|
q239603
|
SocialLoginController.github
|
train
|
protected function github(Oauth2Service\GitHub $github, TokenInterface $token)
{
$emails = json_decode($github->request('user/emails'), true);
$user = json_decode($github->request('user'), true);
$loginRequest = new LoginRequest(
'github',
$user['id'],
$token->getAccessToken(),
$token->getEndOfLife() > 0 ? $token->getEndOfLife() : 0,
$token->getRefreshToken(),
$emails
);
return $loginRequest;
}
|
php
|
{
"resource": ""
}
|
q239604
|
SocialLoginController.google
|
train
|
protected function google(Oauth2Service\Google $google, TokenInterface $token)
{
$user = json_decode($google->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
$loginRequest = new LoginRequest(
'google',
$user['id'],
$token->getAccessToken(),
$token->getEndOfLife() > 0 ? $token->getEndOfLife() : 0,
$token->getRefreshToken(),
[$user['email']]
);
return $loginRequest;
}
|
php
|
{
"resource": ""
}
|
q239605
|
SocialLoginController.facebook
|
train
|
protected function facebook(Oauth2Service\Facebook $facebook, TokenInterface $token)
{
$user = json_decode($facebook->request('/me'), true);
$loginRequest = new LoginRequest(
'facebook',
$user['id'],
$token->getAccessToken(),
$token->getEndOfLife() > 0 ? $token->getEndOfLife() : 0,
$token->getRefreshToken(),
[$user['email']]
);
return $loginRequest;
}
|
php
|
{
"resource": ""
}
|
q239606
|
SocialLoginController.getServiceByProvider
|
train
|
public function getServiceByProvider($provider)
{
$redirect = $this->url($this->config[$provider]['callback_route'], array(
'provider' => $provider,
));
$serviceName = $this->serviceMap[$provider];
$storage = new SessionStorage(false);
$credentials = new ConsumerCredentials(
$this->config[$provider]['key'],
$this->config[$provider]['secret'],
$redirect
);
$service = $this->serviceFactory->createService(
$serviceName,
$credentials,
$storage,
$this->config[$provider]['scope']
);
return $service;
}
|
php
|
{
"resource": ""
}
|
q239607
|
Yaml.dumpToSimpleYaml
|
train
|
protected function dumpToSimpleYaml($array)
{
$parts = [];
foreach ($array as $key => $value) {
$parts[] = "$key: $value";
}
$yaml = implode("\n", $parts);
return $yaml;
}
|
php
|
{
"resource": ""
}
|
q239608
|
Yaml.parseYaml
|
train
|
public static function parseYaml($yaml)
{
if (self::$yamlParser == null) {
self::$yamlParser = new YamlParser;
}
return self::$yamlParser->parse($yaml);
}
|
php
|
{
"resource": ""
}
|
q239609
|
File.deleteAction
|
train
|
public function deleteAction($parameter) {
try {
if(!$this->request->isPost()) {
return $this->jsonResult(400, 'Please access via POST method.', 'error_access_post');
}
if(!$this->getFile()) {
return $this->jsonResult(400, 'No file was uploaded.', 'error_no_file');
}
$this->initFromSession();
$this->file = NULL;
$this->filename = NULL;
$this->filesize = NULL;
$this->saveToSession();
if(!$this->deleteFile()) {
return $this->jsonResult(400, 'Could not delete file.', 'error_delete_failed');
}
return $this->jsonResult();
}
catch(Exception $e) {
return $this->jsonResult(500, $e->getMessage());
}
}
|
php
|
{
"resource": ""
}
|
q239610
|
File.downloadAction
|
train
|
public function downloadAction($parameter) {
if(!$this->getFile()) {
return 404;
}
if(count($parameter) > 1) {
return 404;
}
if($parameter && $parameter[0] != $this->filename) {
return 404;
}
return Misc::servefile($this->file, $parameter ? FALSE : $this->filename);
}
|
php
|
{
"resource": ""
}
|
q239611
|
File.uploadAction
|
train
|
public function uploadAction($parameter) {
try {
if(!$files = $this->request->files()) {
return $this->jsonResult(400, 'Failed to upload file.', 'error_upload_failed');
}
foreach($files as $file) {
if($error = $file->getError()) {
return $this->jsonResult(400, "Failed to upload file '%s'.", "error_upload_failed_detail", [$file->getError()]);
}
}
$this->initFromSession();
$this->deleteFile();
$dir = $this->getUploadDir();
if(!Misc::recursiveMkdir($dir, 0700)) {
return $this->jsonResult(500, "Failed to create upload directory at '%s'.", "error_createdir_failed", [$dir]);
}
foreach($files as $file) {
$target = "$dir/".$file->getName();
if(!$file->moveTo($target)) {
return $this->jsonResult(500, 'Failed to move file.', 'error_move_failed');
}
}
$this->file = $target;
$this->filename = $file->getName();
$this->filesize = $file->getSize();
$this->saveToSession();
$this->cleanFiles();
return $this->jsonResult();
}
catch(Exception $e) {
return $this->jsonResult(500, $e->getMessage());
}
}
|
php
|
{
"resource": ""
}
|
q239612
|
Bookability_Availability.find
|
train
|
public function find($token, $_params = array())
{
return $this->transform($this->master->get('availability/' . $token, $_params));
}
|
php
|
{
"resource": ""
}
|
q239613
|
Bookability_Availability.month
|
train
|
public function month($token, $_params = array())
{
return $this->transform($this->master->get('availability/' . $token . '/month', $_params), true);
}
|
php
|
{
"resource": ""
}
|
q239614
|
Bookability_Availability.date
|
train
|
public function date($token, $_params = array())
{
return $this->transform($this->master->get('availability/' . $token . '/date', $_params), true);
}
|
php
|
{
"resource": ""
}
|
q239615
|
Query.fullQueryString
|
train
|
protected function fullQueryString()
{
$queryParts = [];
// Main search can be default search or full text search.
if ($this->queryString) {
if (!$this->querySwitchFulltext) {
$queryParts[] = $this->queryString;
} else {
$queryParts[] = $this->createSearchString('fulltext', $this->queryString);
}
}
// Title search can be proper title or journal title depending on the switch.
if ($this->queryStringTitle) {
if (!$this->querySwitchJournalOnly) {
$queryParts[] = $this->createSearchString('title', $this->queryStringTitle);
} else {
$queryParts[] = $this->createSearchString('journal', $this->queryStringTitle);
}
}
// Person search is a phrase search.
if ($this->queryStringPerson) {
$myQueryStringPerson = preg_replace('/^[\s"]*/', '', $this->queryStringPerson);
$myQueryStringPerson = preg_replace('/[\s"]*$/', '', $myQueryStringPerson);
$queryParts[] = $this->createSearchString('person', '"' . $myQueryStringPerson . '"');
}
if ($this->queryStringKeyword) {
$queryParts[] = $this->createSearchString('subject', $this->queryStringKeyword);
}
if ($this->queryStringDate) {
$queryParts[] = $this->createSearchString('date', $this->queryStringDate);
}
$query = implode(' and ', $queryParts);
$query = str_replace('*', '?', $query);
return $query;
}
|
php
|
{
"resource": ""
}
|
q239616
|
Query.getPazpar2BaseURL
|
train
|
public function getPazpar2BaseURL()
{
$URL = 'http://' . GeneralUtility::getIndpEnv('HTTP_HOST') . $this->getPazpar2Path();
if ($this->pazpar2BaseURL) {
$URL = $this->pazpar2BaseURL;
}
return $URL;
}
|
php
|
{
"resource": ""
}
|
q239617
|
Query.queryIsDone
|
train
|
protected function queryIsDone()
{
$result = false;
$statReplyString = $this->fetchURL($this->pazpar2StatURL());
$statReply = GeneralUtility::xml2array($statReplyString);
if ($statReply) {
// The progress variable is a string representing a number between
// 0.00 and 1.00.
// Casting it to int gives 0 as long as the value is < 1.
$progress = (int)$statReply['progress'];
$result = ($progress === 1);
if ($result === true) {
// We are done: note that and get the record count.
$this->setDidRun(true);
$this->setTotalResultCount($statReply['hits']);
}
} else {
GeneralUtility::devLog('could not parse pazpar2 stat reply', 'pazpar2', 3);
}
return $result;
}
|
php
|
{
"resource": ""
}
|
q239618
|
Query.fetchResults
|
train
|
protected function fetchResults()
{
$maxResults = 1000; // limit results
if (count($this->conf['exportFormats']) > 0) {
// limit results even more if we are creating export data
$maxResults = $maxResults / (count($this->conf['exportFormats']) + 1);
}
$recordsToFetch = 350;
$firstRecord = 0;
// get records in chunks of $recordsToFetch to avoid running out of memory
// in t3lib_div::xml2tree. We seem to typically need ~100KB per record (?).
while ($firstRecord < $maxResults) {
$recordsToFetchNow = min([$recordsToFetch, $maxResults - $firstRecord]);
$showReplyString = $this->fetchURL($this->pazpar2ShowURL($firstRecord, $recordsToFetchNow));
$firstRecord += $recordsToFetchNow;
// need xml2tree here as xml2array fails when dealing with arrays of tags with the same name
$showReplyTree = GeneralUtility::xml2tree($showReplyString);
$showReply = $showReplyTree['show'][0]['ch'];
if ($showReply) {
$status = $showReply['status'][0]['values'][0];
if ($status == 'OK') {
$this->queryIsRunning = false;
$hits = $showReply['hit'];
if ($hits) {
foreach ($hits as $hit) {
$myHit = $hit['ch'];
$key = $myHit['recid'][0]['values'][0];
// Make sure the 'medium' field exists by setting it to 'other' if necessary.
if (!array_key_exists('md-medium', $myHit)) {
$myHit['md-medium'] = [0 => ['values' => [0 => 'other']]];
}
// If there is no title information but series information, use the
// first series field for the title.
if (!(array_key_exists('md-title', $myHit) || array_key_exists('md-multivolume-title', $myHit))
&& array_key_exists('md-series-title', $myHit)
) {
$myHit['md-multivolume-title'] = [$myHit['md-series-title'][0]];
}
// Sort the location array to have the newest item first
usort($myHit['location'], [$this, 'yearSort']);
$this->results[$key] = $myHit;
}
}
} else {
GeneralUtility::devLog('pazpar2 show reply status is not "OK" but "' . $status . '"', 'pazpar2', 3);
}
} else {
GeneralUtility::devLog('could not parse pazpar2 show reply', 'pazpar2', 3);
}
}
}
|
php
|
{
"resource": ""
}
|
q239619
|
Query.pazpar2ShowURL
|
train
|
protected function pazpar2ShowURL($start = 0, $num = 500)
{
$URL = $this->getPazpar2BaseURL() . '?command=show';
$URL .= '&query=' . urlencode($this->fullQueryString());
$URL .= '&start=' . $start . '&num=' . $num;
$URL .= '&sort=' . urlencode($this->sortOrderString());
$URL .= '&block=1'; // unclear how this is advantagous but the JS client adds it
return $URL;
}
|
php
|
{
"resource": ""
}
|
q239620
|
Query.sortOrderString
|
train
|
protected function sortOrderString()
{
$sortOrderComponents = [];
foreach ($this->getSortOrder() as $sortCriterion) {
$sortOrderComponents[] = $sortCriterion['fieldName'] . ':'
. (($sortCriterion['direction'] === 'descending') ? '0' : '1');
}
$sortOrderString = implode(',', $sortOrderComponents);
return $sortOrderString;
}
|
php
|
{
"resource": ""
}
|
q239621
|
Query.yearSort
|
train
|
protected function yearSort($a, $b)
{
$aDates = $this->extractNewestDates($a);
$bDates = $this->extractNewestDates($b);
if (count($aDates) > 0 && count($bDates) > 0) {
return $bDates[0] - $aDates[0];
} elseif (count($aDates) > 0 && count($bDates) === 0) {
return -1;
} elseif (count($aDates) === 0 && count($bDates) > 0) {
return 1;
} else {
return 0;
}
}
|
php
|
{
"resource": ""
}
|
q239622
|
DataProvider.getObjects
|
train
|
public function getObjects($query, $object)
{
$this->statement = $this->db->query($query);
if ($this->statement) {
$this->statement->setFetchMode(\PDO::FETCH_CLASS, $object);
$objects = $this->statement->fetchAll();
if ($objects) {
return $objects;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239623
|
DataProvider.getObject
|
train
|
public function getObject($query, $object)
{
$this->statement = $this->db->query($query);
if ($this->statement) {
$this->statement->setFetchMode(\PDO::FETCH_CLASS, $object);
return $this->statement->fetch();
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239624
|
DataProvider.getArrays
|
train
|
public function getArrays($query)
{
$this->statement = $this->db->query($query);
if ($this->statement) {
$result = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
if ($result) {
return $result;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239625
|
ShardManager.registerShard
|
train
|
public function registerShard($shard_name, $parameters)
{
if (empty($shard_name)) {
throw new \Exception("The shard name is not specified!");
}
if (!empty($this->shard_table[$shard_name])) {
throw new \Exception("The shard '$shard_name' has been already registered!");
}
$this->shard_table[$shard_name]["parameters"] = $parameters;
return true;
}
|
php
|
{
"resource": ""
}
|
q239626
|
ShardManager.dbshard
|
train
|
public function dbshard($shard_name)
{
if (empty($shard_name) || empty($this->shard_table[$shard_name])) {
throw new \Exception("The shard '$shard_name' was not found!");
return null;
}
if (empty($this->shard_table[$shard_name]["dbworker"])) {
$this->shard_table[$shard_name]["dbworker"] = dbworker($this->shard_table[$shard_name]["parameters"], true);
}
return $this->shard_table[$shard_name]["dbworker"];
}
|
php
|
{
"resource": ""
}
|
q239627
|
VolumeManager.findByFileId
|
train
|
public function findByFileId($fileId)
{
foreach ($this->volumes as $volume) {
try {
$file = $volume->findFile($fileId);
if ($file) {
return $volume;
}
} catch (\Exception $e) {
}
}
return null;
}
|
php
|
{
"resource": ""
}
|
q239628
|
VolumeManager.findByFolderId
|
train
|
public function findByFolderId($folderId)
{
foreach ($this->volumes as $volume) {
if ($volume->findFolder($folderId)) {
return $volume;
}
}
return null;
}
|
php
|
{
"resource": ""
}
|
q239629
|
EnvironmentVariableStrategy.get
|
train
|
public function get()
{
$result = $this->_environment ? $this->_environment->getenv($this->_name) : getenv($this->_name);
return $result !== false ? $result : null;
}
|
php
|
{
"resource": ""
}
|
q239630
|
CiiPHPMessageSource.getMessageFile
|
train
|
protected function getMessageFile($category,$language)
{
if(!isset($this->_files[$category][$language]))
{
if(($pos=strpos($category,'.'))!==false && strpos($category,'ciims') === false)
{
$extensionClass=substr($category,0,$pos);
$extensionCategory=substr($category,$pos+1);
// First check if there's an extension registered for this class.
if(isset($this->extensionPaths[$extensionClass]))
$this->_files[$category][$language]=Yii::getPathOfAlias($this->extensionPaths[$extensionClass]).DS.$language.DS.$extensionCategory.'.php';
else
{
if (strpos($extensionClass, 'themes') !== false)
{
$baseClass = explode('.', $extensionCategory);
$theme = $baseClass[0];
unset($baseClass[0]);
$baseClass = implode('.', $baseClass);
$this->_files[$category][$language] = Yii::getPathOfAlias("base.themes.$theme.messages").DS.$language.DS.$baseClass.'.php';
}
else
{
// No extension registered, need to find it.
if (isset(Yii::app()->controller->module->id))
$extensionClass .= 'Module';
$class=new ReflectionClass($extensionClass);
$this->_files[$category][$language]=dirname($class->getFileName()).DS.'messages'.DS.$language.DS.$extensionCategory.'.php';
}
}
}
else
{
if (strpos($category,'ciims.') !== false)
{
$this->basePath = Yii::getPathOfAlias('application.messages.');
$this->_files[$category][$language]=$this->basePath.DS.$language.DS.str_replace('.', '/', str_replace('ciims.', '', $category)).'.php';
}
else
$this->_files[$category][$language]=$this->basePath.DS.$language.DS.$category.'.php';
}
}
return $this->_files[$category][$language];
}
|
php
|
{
"resource": ""
}
|
q239631
|
Php.parse
|
train
|
public function parse(\Pinocchio\Pinocchio $pinocchio, \Pinocchio\Highlighter\HighlighterInterface $highlighter = null) {
if (null === $highlighter) {
$highlighter = new Pygments();
}
$code = '';
// $docBlocks is initialized with an empty element for the '<?php' start of the code
$docBlocks = array('');
$previousToken = null;
$commentRegexSet = $this->getCommentRegexSet();
foreach ($this->tokenize($pinocchio->getSource()) as $token) {
if (is_array($token)) {
if ($this->isComment(token_name($token[0]))) {
$last = '';
$token[1] = str_replace("\t", self::TAB_AS_SPACES, $token[1]);
if (token_name($previousToken[0]) === self::TOKEN_NAME_COMMENT && token_name($token[0]) === self::TOKEN_NAME_COMMENT) {
$last = array_pop($docBlocks);
} else {
$code .= self::CODEBLOCK_DELIMITER;
}
$docBlocks[] = $last . preg_replace($commentRegexSet, '$1', $token[1]);
} else {
$code .= $token[1];
}
} else {
$code .= $token;
}
$previousToken = $token;
}
$codeBlocks = explode(
self::HIGHLIGHTED_CODEBLOCK_DELIMITER,
$highlighter->highlight('php', $code)
);
foreach ($codeBlocks as $codeBlock) {
$pinocchio->addCodeBlock(
sprintf(
self::HIGHLIGHT_BLOCK_HTML_PATTERN,
str_replace("\t", ' ', $codeBlock)
)
);
}
$pinocchio->setDocBlocks($this->parseDocblocks($docBlocks));
return $pinocchio;
}
|
php
|
{
"resource": ""
}
|
q239632
|
Php.getCommentRegexSet
|
train
|
public function getCommentRegexSet()
{
return array(
self::REGEX_COMMENT_SINGLE_LINE,
self::REGEX_COMMENT_MULTILINE_START,
self::REGEX_COMMENT_MULTILINE_CONT,
self::REGEX_COMMENT_MULTILINE_END,
self::REGEX_COMMENT_MULTILINE_ONE_LINER,
);
}
|
php
|
{
"resource": ""
}
|
q239633
|
Php.parseDocblocks
|
train
|
protected function parseDocblocks($rawDocBlocks)
{
$parsedDocBlocks = array();
$docBlockParser = new MarkdownParser();
foreach ($rawDocBlocks as $docBlock) {
$docBlock = preg_replace(self::REGEX_DOCBLOCK_TYPE, '$1$2 `$4` ', $docBlock);
$docBlock = preg_replace(self::REGEX_DOCBLOCK_VAR, '$1`$2`', $docBlock);
$docBlock = preg_replace(self::REGEX_DOCBLOCK_ARG, "\n<em class=\"docparam\">$1</em>", $docBlock);
$parsedDocBlocks[] = $docBlockParser->transformMarkdown($docBlock);
}
return $parsedDocBlocks;
}
|
php
|
{
"resource": ""
}
|
q239634
|
LeanRecent.update
|
train
|
public function update( $new_instance, $old_instance ) {
$post_types = get_post_types();
$selected = isset( $_REQUEST[ $this->get_field_id( 'post_type' ) ] )
? sanitize_text_field( wp_unslash( $_REQUEST[ $this->get_field_id( 'post_type' ) ] ) )
: false;
if ( in_array( $selected, $post_types, true ) ) {
$new_instance['post_type'] = $selected;
}
$number = isset( $_REQUEST[ $this->get_field_id( 'number' ) ] )
? absint( $_REQUEST[ $this->get_field_id( 'number' ) ] )
: false;
$new_instance['number'] = $number;
return $new_instance;
}
|
php
|
{
"resource": ""
}
|
q239635
|
UserHelper.GetAndStoreUsersInSession
|
train
|
public static function GetAndStoreUsersInSession($caller) {
$users = array();
if (!$caller->app()->user()->getAttribute(\Puzzlout\Framework\Enums\SessionKeys::AllUsers)) {
$manager = $caller->managers()->getDalInstance($caller->module());
$users = $manager->selectAllUsers();
$caller->app()->user->setAttribute(
\Puzzlout\Framework\Enums\SessionKeys::AllUsers, $users
);
} else {
$users = $caller->app()->user->getAttribute(\Puzzlout\Framework\Enums\SessionKeys::AllUsers);
}
return $users;
}
|
php
|
{
"resource": ""
}
|
q239636
|
UserHelper.AddNewUserToSession
|
train
|
public static function AddNewUserToSession($caller, $user) {
$users = self::GetAndStoreUsersInSession($caller);
$users[] = $user;
$caller->app()->user->setAttribute(
\Puzzlout\Framework\Enums\SessionKeys::AllUsers, $users
);
}
|
php
|
{
"resource": ""
}
|
q239637
|
UserHelper.CategorizeUsersList
|
train
|
public static function CategorizeUsersList($users) {
$list = array();
if (is_array($users) && count($users) > 0) {
foreach ($users as $user) {
$userType = $user->user_type();
$list[$userType][] = $user;
}
}
return $list;
}
|
php
|
{
"resource": ""
}
|
q239638
|
Ip.getProxyString
|
train
|
private static function getProxyString(): ?string
{
$proxyString = null;
if (\getenv('HTTP_CLIENT_IP')) {
$proxyString = \getenv('HTTP_CLIENT_IP');
} elseif (\getenv('HTTP_X_FORWARDED_FOR')) {
$proxyString = \getenv('HTTP_X_FORWARDED_FOR');
} elseif (\getenv('HTTP_X_FORWARDED')) {
$proxyString = \getenv('HTTP_X_FORWARDED');
} elseif (\getenv('HTTP_X_COMING_FROM')) {
$proxyString = \getenv('HTTP_X_COMING_FROM');
} elseif (\getenv('HTTP_FORWARDED_FOR')) {
$proxyString = \getenv('HTTP_FORWARDED_FOR');
} elseif (\getenv('HTTP_FORWARDED')) {
$proxyString = \getenv('HTTP_FORWARDED');
} elseif (\getenv('HTTP_COMING_FROM')) {
$proxyString = \getenv('HTTP_COMING_FROM');
}
return $proxyString;
}
|
php
|
{
"resource": ""
}
|
q239639
|
Ip.getFirstIP
|
train
|
private static function getFirstIP($proxyString = ''): ?string
{
\preg_match('/^(([0-9]{1,3}\.){3}[0-9]{1,3})/', $proxyString, $matches);
return (\is_array($matches) && isset($matches[1])) ? $matches[1] : null;
}
|
php
|
{
"resource": ""
}
|
q239640
|
Ip.getFullIpHost
|
train
|
private static function getFullIpHost($clientIpHost = null, $proxyIpHost = null): ?string
{
$fullIpHost = [];
if ($clientIpHost !== null) {
$fullIpHost[] = \sprintf('client: %s', $clientIpHost);
}
if ($proxyIpHost !== null) {
$fullIpHost[] = \sprintf('proxy: %s', $proxyIpHost);
}
return (\count($fullIpHost) > 0) ? \implode(', ', $fullIpHost) : null;
}
|
php
|
{
"resource": ""
}
|
q239641
|
Ip.check
|
train
|
public static function check(): array
{
$remoteAddr = \getenv('REMOTE_ADDR') ?: null;
$httpVia = \getenv('HTTP_VIA') ?: null;
$proxyString = static::getProxyString();
$ipData = static::$ipData;
if ($remoteAddr !== null) {
if ($proxyString !== null) {
$clientIP = static::getFirstIP($proxyString);
$proxyIP = $remoteAddr;
$proxyHost = static::getHost($proxyIP);
if ($clientIP !== null) {
$clientHost = static::getHost($clientIP);
$ipData['CLIENT_IP'] = $clientIP;
$ipData['CLIENT_HOST'] = $clientHost;
$ipData['CLIENT_IP_HOST'] = \sprintf('%s (%s)', $clientIP, $clientHost);
}
$ipData['PROXY_IP'] = $proxyIP;
$ipData['PROXY_HOST'] = $proxyHost;
$ipData['PROXY_IP_HOST'] = \sprintf('%s (%s)', $proxyIP, $proxyHost);
$ipData['PROXY_STRING'] = $proxyString;
} elseif ($httpVia !== null) {
$proxyHost = static::getHost($remoteAddr);
$ipData['PROXY_IP'] = $remoteAddr;
$ipData['PROXY_HOST'] = $proxyHost;
$ipData['PROXY_IP_HOST'] = \sprintf('%s (%s)', $remoteAddr, $proxyHost);
$ipData['HTTP_VIA'] = $httpVia;
} else {
$clientHost = static::getHost($remoteAddr);
$ipData['CLIENT_IP'] = $remoteAddr;
$ipData['CLIENT_HOST'] = $clientHost;
$ipData['CLIENT_IP_HOST'] = \sprintf('%s (%s)', $remoteAddr, $clientHost);
}
$ipData['FULL_IP_HOST'] = static::getFullIpHost($ipData['CLIENT_IP_HOST'], $ipData['PROXY_IP_HOST']);
}
return $ipData;
}
|
php
|
{
"resource": ""
}
|
q239642
|
JagilpeEntityListExtension.getAttributesString
|
train
|
public function getAttributesString(array $attributes = array())
{
$attributesString = '';
foreach ($attributes as $name => $values) {
$value = is_array($values) ? implode(' ', $values) : $values;
$attributesString .= ' '.$name.'="'.$value.'"';
}
return $attributesString;
}
|
php
|
{
"resource": ""
}
|
q239643
|
SQLAdapterMySQL.update
|
train
|
public function update(array $options=array()) {
$options += self::$updateDefaults;
if( empty($options['table']) ) {
throw new Exception('Empty table option');
}
if( empty($options['what']) ) {
throw new Exception('No field');
}
$OPTIONS = '';
$OPTIONS .= (!empty($options['lowpriority'])) ? ' LOW_PRIORITY' : '';
$OPTIONS .= (!empty($options['ignore'])) ? ' IGNORE' : '';
// if( is_array($options['what']) ) {
// $string = '';
// foreach( $options['what'] as $key => $value ) {
// $string .= ($string ? ', ' : '').static::escapeIdentifier($key).'='.static::formatValue($value);
// }
// $options['what'] = $string;
// }
$WHAT = $this->formatFieldList($options['what']);
$WC = ( !empty($options['where']) ) ? 'WHERE '.$options['where'] : '';
$ORDERBY = ( !empty($options['orderby']) ) ? 'ORDER BY '.$options['orderby'] : '';
$LIMIT = ( $options['number'] > 0 ) ? 'LIMIT '.
( ($options['offset'] > 0) ? $options['offset'].', ' : '' ).$options['number'] : '';
$TABLE = static::escapeIdentifier($options['table']);
$QUERY = "UPDATE {$OPTIONS} {$TABLE} SET {$WHAT} {$WC} {$ORDERBY} {$LIMIT}";
if( $options['output'] == static::SQLQUERY ) {
return $QUERY;
}
return $this->query($QUERY, PDOEXEC);
}
|
php
|
{
"resource": ""
}
|
q239644
|
SQLAdapterMySQL.insert
|
train
|
public function insert(array $options=array()) {
$options += self::$insertDefaults;
if( empty($options['table']) ) {
throw new Exception('Empty table option');
}
if( empty($options['what']) ) {
throw new Exception('No field');
}
$OPTIONS = '';
$OPTIONS .= (!empty($options['lowpriority'])) ? ' LOW_PRIORITY' : (!empty($options['delayed'])) ? ' DELAYED' : '';
$OPTIONS .= (!empty($options['ignore'])) ? ' IGNORE' : '';
$OPTIONS .= (!empty($options['into'])) ? ' INTO' : '';
$COLS = $WHAT = '';
//Is an array
if( is_array($options['what']) ) {
//Is an indexed array of fields Arrays
if( !empty($options['what'][0]) ) {
// Quoted as escapeIdentifier()
$COLS = '(`'.implode('`, `', array_keys($options['what'][0])).'`)';
foreach($options['what'] as $row) {
$WHAT .= (!empty($WHAT) ? ', ' : '').'('.implode(', ', $row).')';
}
$WHAT = 'VALUES '.$WHAT;
//Is associative fields Arrays
} else {
// $WHAT = 'SET '.parseFields($options['what'], '`');
$WHAT = 'SET '.$this->formatFieldList($options['what']);
}
//Is a string
} else {
$WHAT = $options['what'];
}
$TABLE = static::escapeIdentifier($options['table']);
$QUERY = "INSERT {$OPTIONS} {$TABLE} {$COLS} {$WHAT}";
if( $options['output'] == static::SQLQUERY ) {
return $QUERY;
}
return $this->query($QUERY, PDOEXEC);
}
|
php
|
{
"resource": ""
}
|
q239645
|
SQLAdapterMySQL.delete
|
train
|
public function delete(array $options=array()) {
$options += self::$deleteDefaults;
if( empty($options['table']) ) {
throw new Exception('Empty table option');
}
$OPTIONS = '';
$OPTIONS .= (!empty($options['lowpriority'])) ? ' LOW_PRIORITY' : '';
$OPTIONS .= (!empty($options['quick'])) ? ' QUICK' : '';
$OPTIONS .= (!empty($options['ignore'])) ? ' IGNORE' : '';
$WC = ( !empty($options['where']) ) ? 'WHERE '.$options['where'] : '';
$ORDERBY = ( !empty($options['orderby']) ) ? 'ORDER BY '.$options['orderby'] : '';
$LIMIT = ( $options['number'] > 0 ) ? 'LIMIT '.
( ($options['offset'] > 0) ? $options['offset'].', ' : '' ).$options['number'] : '';
$TABLE = static::escapeIdentifier($options['table']);
$QUERY = "DELETE {$OPTIONS} FROM {$TABLE} {$WC} {$ORDERBY} {$LIMIT}";
if( $options['output'] == static::SQLQUERY ) {
return $QUERY;
}
return $this->query($QUERY, PDOEXEC);
}
|
php
|
{
"resource": ""
}
|
q239646
|
Posix.getDimensionsFromTput
|
train
|
protected function getDimensionsFromTput() : ?array
{
if (empty($output = $this->execute('tput cols && tput lines'))) {
return null;
}
// tput will have returned the values on separate lines, so let's just explode.
$output = explode("\n", $output);
return [
'width' => (int) $output[0],
'height'=> (int) $output[1]
];
}
|
php
|
{
"resource": ""
}
|
q239647
|
UserSessionService.recover_session
|
train
|
function recover_session($token=''){
//$r = Env::getRequest();
$key = Env::getConfig("jwt")->get('key');
$expiration = Env::getConfig("jwt")->get('token_expiration');
$cookie_key= Env::getConfig("jwt")->get('cookie_key');
if(empty($key) || empty($expiration) || empty($cookie_key)){
throw new Exception("critical security failure. Please configure module",00);
}
//retrieve user token // priority order -> cookie-> headers
$result = false;
if(empty($token)){
$token = (isset($_COOKIE[$cookie_key]))? $_COOKIE[$cookie_key] : Env::getRequest()->getToken();
}
// var_dump($_COOKIE);
try{
//var_dump($token);
$decoded = array();
if(!empty($token)){
$decoded = JWT::decode($token, $key, array('HS256'));
if($decoded){
//authenticated
$result = true;
$this->setToken($token);
// var_dump($token);
if(Env::getConfig("jwt")->get('auto_renew')){
$this->create_session((array)$decoded->data);
}
//$key = $this->getEntity()->onePKName();
// $this->load_user($decoded->data->$key);
}
}
}
catch(\Firebase\JWT\ExpiredException $e){
$this->setError("Expired token, please log in again",101);
return false;
}
catch( \Exception $e){
$this->setError("Invalid token ".var_export($e,true),102);
return false;
}finally{
if ($result) {
// $this->logout();
$this->setDefaultDatas((array)$decoded->data);
return true;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239648
|
UserSessionService.create_session
|
train
|
function create_session($data){
$key = Env::getConfig("jwt")->get('key');
$expiration = Env::getConfig("jwt")->get('token_expiration');
$cookie_key= Env::getConfig("jwt")->get('cookie_key');
$token = array(
"iss" => $_SERVER['HTTP_HOST'],
"iat" => time(),
"nbf" => time(),
"exp" => time()+($expiration),
"data" => $data
);
$jwt = JWT::encode($token, $key);
$this->setToken($jwt);
$_SESSION[$cookie_key]=$jwt;
setcookie($cookie_key,$jwt,time()+$expiration,'/');
//var_dump($cookie_key);
Env::getRequest()->setToken($jwt);
$this->setDefaultDatas($data);
}
|
php
|
{
"resource": ""
}
|
q239649
|
UserSessionService.destroy
|
train
|
function destroy(){
$cookie_key= Env::getConfig("jwt")->get('cookie_key');
setcookie($cookie_key,'',time()-10000,'/');
unset($_SESSION[$cookie_key]);
session_destroy();
}
|
php
|
{
"resource": ""
}
|
q239650
|
MailMessage.getHtmlMail
|
train
|
public static function getHtmlMail($mailView, $params, $to, $from, $subject) {
if (file_exists($mailView)) {
ob_start();
require_once $mailView;
$body = ob_get_contents();
ob_end_clean();
} else {
throw new MailViewException($mailView);
}
$mail = new MailMessage($to, $from, $body, $subject);
$headers = "MIME-Version: 1.0\r\n"
. "Content-Type: text/html; charset=utf-8\r\n"
. "Content-Transfer-Encoding: 8bit\r\n"
. "From: =?UTF-8?B?" . base64_encode($params["from_name"]) . "?= <" . $from . ">\r\n"
. "X-Mailer: PHP/" . phpversion();
$mail->setHeaders($headers);
return $mail;
}
|
php
|
{
"resource": ""
}
|
q239651
|
MailMessage.getPlainMail
|
train
|
public static function getPlainMail($to, $from, $body, $subject) {
$mail = new MailMessage($to, $from, $body, $subject);
return $mail;
}
|
php
|
{
"resource": ""
}
|
q239652
|
Reconstitution.reconstituteFrom
|
train
|
public static function reconstituteFrom(CommittedEvents $history)
{
$instance = static::fromIdentity($history->getIdentity());
$instance->whenAll($history);
return $instance;
}
|
php
|
{
"resource": ""
}
|
q239653
|
ContainerHasCapableTrait._containerHas
|
train
|
protected function _containerHas($container, $key)
{
$key = $this->_normalizeKey($key);
if ($container instanceof BaseContainerInterface) {
return $container->has($key);
}
if ($container instanceof ArrayAccess) {
// Catching exceptions thrown by `offsetExists()`
try {
return $container->offsetExists($key);
} catch (RootException $e) {
throw $this->_createContainerException($this->__('Could not check for key "%1$s"', [$key]), null, $e, null);
}
}
if (is_array($container)) {
return array_key_exists($key, $container);
}
if ($container instanceof stdClass) {
return property_exists($container, $key);
}
throw $this->_createInvalidArgumentException($this->__('Not a valid container'), null, null, $container);
}
|
php
|
{
"resource": ""
}
|
q239654
|
ConfigurationValue.parse
|
train
|
public function parse() {
$value = $this->getRawValue();
$matches = [];
if (is_array($value)) {
return $value;
}
if (preg_match(self::NESTED_CONFIGURATION_REGEX, $value, $matches) === 1) {
return $this->parseNestedValue($value, $matches);
} else {
return $this->parser->parseIntelligent($value);
}
}
|
php
|
{
"resource": ""
}
|
q239655
|
KalmanFilter.value
|
train
|
function value($value, $u = 0)
{
if (null === $this->x) {
$this->x = (1 / $this->measurementVector) * $value;
$this->cov = (1 / $this->measurementVector) * $this->measurementNoise * (1 / $this->measurementVector);
} else {
// Compute prediction
$predX = ($this->stateVector * $this->x) + ($this->controlVector * $u);
$predCov = (($this->stateVector * $this->cov) * $this->stateVector) + $this->processNoise;
// Kalman gain
$K = $predCov * $this->measurementVector *
(1 / (($this->measurementVector * $predCov * $this->measurementVector) + $this->measurementNoise));
// Correction
$this->x = $predX + $K * ($value - ($this->measurementVector * $predX));
$this->cov = $predCov - ($K * $this->measurementVector * $predCov);
}
return $this->x;
}
|
php
|
{
"resource": ""
}
|
q239656
|
FinderTrait.findBy
|
train
|
public function findBy(array $wheres, array $options = [])
{
$query = $this->getSqlObject()->select();
$this->setColumns($query, $options);
$wheres = $this->addJoins($query, $wheres, $options);
$this->addWheres($query, $wheres, $options);
if (Arr::get($options, 'order')) {
$this->setOrder($query, $options['order']);
}
return $this->executeAndGetResultsAsEntity($query);
}
|
php
|
{
"resource": ""
}
|
q239657
|
FinderTrait.findAllBy
|
train
|
public function findAllBy(array $wheres, array $options = [])
{
$query = $this->getSqlObject()->select();
$this->setColumns($query, $options);
$wheres = $this->addJoins($query, $wheres, $options);
$this->addWheres($query, $wheres, $options);
$page = Arr::get($options, 'page');
if ($page && !Arr::get($options, 'order')) {
throw new LogicException('Must provide an ORDER BY if using pagination');
}
if (Arr::get($options, 'order')) {
$this->setOrder($query, $options['order']);
}
if ($page) {
$paginationData = $this->getPaginationData($query, $options);
// Set LIMIT and OFFSET
$query->limit($paginationData->getResultsPerPage());
$query->offset(($page - 1) * $paginationData->getResultsPerPage());
}
$entityIterator = $this->executeAndGetResultsAsEntityIterator($query);
if ($page) {
$entityIterator->setPaginationData($paginationData);
}
return $entityIterator;
}
|
php
|
{
"resource": ""
}
|
q239658
|
FinderTrait.setOrder
|
train
|
protected function setOrder(Select $query, array $order)
{
// Normalize to [['column', 'direction']] format if only one column
if (! is_array(Arr::get($order, 0))) {
$order = [$order];
}
foreach ($order as $key => $orderValue) {
if (is_array($orderValue)) {
// Column and direction
$query->order(
Arr::get($orderValue, 0).' '.Arr::get($orderValue, 1)
);
}
}
return $query;
}
|
php
|
{
"resource": ""
}
|
q239659
|
FinderTrait.getPaginationData
|
train
|
protected function getPaginationData(Select $query, array $options)
{
// Get pagination options
$page = (int) Arr::get($options, 'page');
if ($page < 1) {
$page = 1;
}
$resultsPerPage = Arr::get(
$options,
'resultsPerPage',
$this->resultsPerPage
);
// Get total results
$resultCount = $this->getQueryResultCount($query);
$pageCount = ceil($resultCount / $resultsPerPage);
return new PaginationData([
'page' => $page,
'page_count' => $pageCount,
'result_count' => $resultCount,
'results_per_page' => $resultsPerPage
]);
}
|
php
|
{
"resource": ""
}
|
q239660
|
FinderTrait.getQueryResultCount
|
train
|
protected function getQueryResultCount(Select $query)
{
$queryString = $this->getSqlObject()->getSqlStringForSqlObject($query, $this->dbAdapter->getPlatform());
$format = 'Select count(*) as `count` from (%s) as `query_count`';
$countQueryString = sprintf($format, $queryString);
$countQuery = $this->dbAdapter->query($countQueryString);
$result = $countQuery->execute()->current();
return (int) Arr::get($result, 'count');
}
|
php
|
{
"resource": ""
}
|
q239661
|
FinderTrait.addWheres
|
train
|
protected function addWheres(PreparableSqlInterface $query, array $wheres, array $options = [])
{
foreach ($wheres as $key => $where) {
if (is_array($where) && count($where) === 3) {
$leftOpRightSyntax = true;
$operator = $where[1];
switch ($operator) {
case '=':
$predicate = new Operator(
$where[0],
Operator::OP_EQ,
$where[2]
);
break;
case '!=':
$predicate = new Operator(
$where[0],
Operator::OP_NE,
$where[2]
);
break;
case '>':
$predicate = new Operator(
$where[0],
Operator::OP_GT,
$where[2]
);
break;
case '<':
$predicate = new Operator(
$where[0],
Operator::OP_LT,
$where[2]
);
break;
case '>=':
$predicate = new Operator(
$where[0],
Operator::OP_GTE,
$where[2]
);
break;
case '<=':
$predicate = new Operator(
$where[0],
Operator::OP_LTE,
$where[2]
);
break;
case 'LIKE':
$predicate = new Like($where[0], $where[2]);
break;
case 'NOT LIKE':
$predicate = new NotLike($where[0], $where[2]);
break;
case 'IN':
$predicate = new In($where[0], $where[2]);
break;
case 'NOT IN':
$predicate = new NotIn($where[0], $where[2]);
break;
case 'IS':
$predicate = new IsNull($where[0]);
break;
case 'IS NOT':
$predicate = new IsNotNull($where[0]);
break;
default:
$leftOpRightSyntax = false;
break;
}
if ($leftOpRightSyntax === false) {
$predicate = [$key => $where];
}
} else {
$predicate = [$key => $where];
}
$query->where($predicate);
}
return $query;
}
|
php
|
{
"resource": ""
}
|
q239662
|
ValidatorAwareTrait._setValidator
|
train
|
protected function _setValidator($validator)
{
if (!is_null($validator) && !($validator instanceof ValidatorInterface)) {
throw $this->_createInvalidArgumentException($this->__('Invalid validator'), null, null, $validator);
}
$this->validator = $validator;
}
|
php
|
{
"resource": ""
}
|
q239663
|
PathRoute.getMatchedParameters
|
train
|
protected function getMatchedParameters(array $matches): array
{
$parameters = [];
foreach ($matches as $key => $match) {
if (is_string($key)) {
$parameters[$key] = $match[0];
}
}
return array_replace_recursive($this->getParameters(), $parameters);
}
|
php
|
{
"resource": ""
}
|
q239664
|
PathRoute.getPattern
|
train
|
protected function getPattern(): string
{
$path = preg_replace_callback('~:([a-z][a-z0-9\_]+)~i', function ($match) {
return sprintf('(?<%s>%s)', $match[1], '[^\/]*');
}, $this->getPath());
return sprintf('~\G(%s)(/|\z)~', $path);
}
|
php
|
{
"resource": ""
}
|
q239665
|
SubscribeToList.prepareEmailDataForInsert
|
train
|
public function prepareEmailDataForInsert($request) {
$data = [];
$data['email_type_id'] = 1; // Primary
$data['title'] = $request->input('email');
$data['description'] = "";
$data['comments'] = "Created by front-end subscription to an email list";
$data['created_at'] = Carbon::now();
$data['created_by'] = $this->userRepository->getFirstAmongEqualsUserID();
$data['updated_at'] = Carbon::now();
$data['updated_by'] = $this->userRepository->getFirstAmongEqualsUserID();
return $data;
}
|
php
|
{
"resource": ""
}
|
q239666
|
SubscribeToList.prepareList_emailDataForInsert
|
train
|
public function prepareList_emailDataForInsert($input) {
$data = [];
$data['title'] = $input['listID']." ".$input['emailID'];
$data['list_id'] = $input['listID'];
$data['email_id'] = $input['emailID'];
$data['comments'] = "";
$data['enabled'] = 1;
$data['created_at'] = Carbon::now();
$data['created_by'] = $this->userRepository->getFirstAmongEqualsUserID();
$data['updated_at'] = Carbon::now();
$data['updated_by'] = $this->userRepository->getFirstAmongEqualsUserID();
return $data;
}
|
php
|
{
"resource": ""
}
|
q239667
|
SubscribeToList.preparePeoplesDataForInsert
|
train
|
public function preparePeoplesDataForInsert($input) {
$data = [];
$data['user_id'] = null; // Set users up as PEOPLES in the admin
$data['title'] = $input['first_name']." ".$input['surname'];
$data['salutation'] = "";
$data['first_name'] = $input['first_name'];
$data['middle_name'] = "";
$data['surname'] = $input['surname'];
$data['position'] = "";
$data['description'] = "";
$data['comments'] = "Created by front-end subscription to an email list";
$data['birthday'] = null;
$data['anniversary'] = null;
$data['created_at'] = Carbon::now();
$data['created_by'] = $this->userRepository->getFirstAmongEqualsUserID();
$data['updated_at'] = Carbon::now();
$data['updated_by'] = $this->userRepository->getFirstAmongEqualsUserID();
$data['profile'] = null;
$data['featured_image'] = null;
return $data;
}
|
php
|
{
"resource": ""
}
|
q239668
|
ImportExportController.getValidReturnUri
|
train
|
protected function getValidReturnUri( $returnUri, $default = null )
{
$match = array();
$returnUri = ltrim( str_replace( '\\', '/', $returnUri ), "\n\r\t\v\e\f" );
if ( ! preg_match( '#^/([^/].*)?$#', $returnUri, $match ) )
{
return $default;
}
return $returnUri;
}
|
php
|
{
"resource": ""
}
|
q239669
|
ImportExportController.exportAction
|
train
|
public function exportAction()
{
$params = $this->params();
$paragraphId = $params->fromRoute( 'paragraphId' );
$serviceLocator = $this->getServiceLocator();
$paragraphModel = $serviceLocator->get( 'Grid\Paragraph\Model\Paragraph\Model' );
$paragraph = $paragraphModel->find( $paragraphId );
if ( empty( $paragraph ) )
{
$this->getResponse()
->setResultCode( 404 );
return;
}
$zipFile = $serviceLocator->get( 'Grid\Customize\Model\Exporter' )
->export( $paragraph->id );
$name = strtolower( $paragraph->name );
if ( empty( $name ) )
{
$name = 'paragraph-' . $paragraph->id;
}
$response = Readfile::fromFile(
$zipFile,
'application/zip',
$name . '.zip',
true
);
$this->getEvent()
->setResponse( $response );
return $response;
}
|
php
|
{
"resource": ""
}
|
q239670
|
ExternalMemberAuthenticator.authenticateExternalMember
|
train
|
protected function authenticateExternalMember($data, ValidationResult &$result = null, Member $member = null)
{
$result = $result ?: ValidationResult::create();
$ssLoginUserName = Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME');
$email = !empty($data['Email']) ? $data['Email'] : null;
if ($email != $ssLoginUserName) {
return;
}
// Check for default admin user
$member = Member::get()->find(
Member::config()->get('unique_identifier_field'),
$ssLoginUserName
);
if (!$member) {
return;
}
$member->checkLoginPassword($data['Password'], $result);
return $member;
}
|
php
|
{
"resource": ""
}
|
q239671
|
JobRestoreManager.saveReport
|
train
|
private function saveReport(JobConfigurationInterface $configuration)
{
$report = $this->reportManager->create($configuration);
$report
->setEndedAt()
->setOutput('Job was dead and restored.')
->setSuccessful(true);
$this->reportManager->add($report, true);
}
|
php
|
{
"resource": ""
}
|
q239672
|
JobRestoreManager.isDead
|
train
|
private function isDead(JobConfigurationInterface $configuration)
{
$report = $this->reportManager->getLastStartedByConfiguration($configuration);
return $report && $report->getPid() && (false === $report->isSuccessful()) && !posix_getsid($report->getPid());
}
|
php
|
{
"resource": ""
}
|
q239673
|
ResourceConstantsClassGenerator.WriteContent
|
train
|
public function WriteContent() {
$output = $this->WriteGetListMethod();
$output .= PhpCodeSnippets::CRLF;
fwrite($this->writer, $output);
}
|
php
|
{
"resource": ""
}
|
q239674
|
ResourceConstantsClassGenerator.WriteNewArrayAndItsContents
|
train
|
public function WriteNewArrayAndItsContents($array, $arrayOpened = false, $tabAmount = 0) {
$output = "";
foreach ($array as $key => $value) {
if (is_array($value)) {
$output .= $this->WriteAssociativeArrayValueAsNewArray($key, $tabAmount); //new array opened
$output .= $this->WriteNewArrayAndItsContents($value, true, $tabAmount);
} else {
$output .= $this->WriteAssociativeArrayValueWithKeyAndValue($key, $value, $tabAmount);
}
}
if ($arrayOpened) {
$output .= $this->CloseArray($tabAmount - 1);
}
return $output;
}
|
php
|
{
"resource": ""
}
|
q239675
|
MattermostChatController.ackAction
|
train
|
public function ackAction()
{
$json = array();
$postId = $this->params()->fromQuery('postid', null);
$response = $this->mattermost->saveReaction($postId, 'ok');
$json['result'] = $response;
return new JsonModel($json);
}
|
php
|
{
"resource": ""
}
|
q239676
|
MattermostChatController.isAckAction
|
train
|
public function isAckAction()
{
$json = array();
$postId = $this->params()->fromQuery('postid', null);
$myReactions = $this->mattermost->getMyReactions($postId);
$ok = array_filter($myReactions, function($v){
return strcmp($v['emoji_name'], 'ok') == 0;
});
$json['ack'] = count($ok) == 1;
return new JsonModel($json);
}
|
php
|
{
"resource": ""
}
|
q239677
|
EbreEscoolMigrator.migrate
|
train
|
public function migrate(array $filters)
{
$this->filters =$filters;
foreach ($this->academicPeriods() as $period) {
$this->period = $period->id;
$this->setDestinationConnectionByPeriod($this->period);
$this->switchToDestinationConnection();
$this->output->info('Migrating period: ' . $period->name . '(' . $period->id . ')');
$this->migrateTeachers();
$this->migrateLocations();
$this->migrateCurriculum();
$this->migrateClassrooms();
$this->migrateEnrollments();
$this->seedDays();
$this->seedShifts();
$this->migrateTimeslots();
$this->migrateLessons();
}
}
|
php
|
{
"resource": ""
}
|
q239678
|
EbreEscoolMigrator.migrateTeachers
|
train
|
protected function migrateTeachers()
{
$this->output->info('### Migrating teachers ###');
foreach ($this->teachers() as $teacher) {
$this->showMigratingInfo($teacher, 1);
$this->output->info(' email: ' . $teacher->email);
$this->migrateTeacher($teacher);
}
$this->output->info(
'### END Migrating teachers. Migrated ' . count($this->teachers()) . ' teachers ###');
}
|
php
|
{
"resource": ""
}
|
q239679
|
EbreEscoolMigrator.migrateTeacher
|
train
|
protected function migrateTeacher(Teacher $teacher) {
$user = User::firstOrNew([
'email' => $teacher->email,
]);
$user->name = $teacher->name;
$user->password = bcrypt('secret');
$user->remember_token = str_random(10);
$user->save();
//TODO: migrate teacher codes, create roles and assign to user/teachers
}
|
php
|
{
"resource": ""
}
|
q239680
|
EbreEscoolMigrator.migrateEnrollment
|
train
|
protected function migrateEnrollment($enrollment)
{
$user = $this->migratePerson($enrollment->person);
try {
$enrollment = ScoolEnrollment::firstOrNew([
'user_id' => $user->id,
'study_id' => $this->translateStudyId($enrollment->study_id),
'course_id' => $this->translateCourseId($enrollment->course_id),
'classroom_id' => $this->translateClassroomId($enrollment->group_id)
]);
$enrollment->state='Validated';
$enrollment->save();
return $enrollment;
} catch (\Exception $e) {
$this->output->error(
'Error migrating enrollment. ' . class_basename($e) . ' ' . $e->getMessage());
return null;
}
}
|
php
|
{
"resource": ""
}
|
q239681
|
EbreEscoolMigrator.migrateLesson
|
train
|
protected function migrateLesson($oldLesson)
{
if ($this->lessonNotExists($oldLesson)) {
DB::beginTransaction();
try {
$lesson = new ScoolLesson;
$lesson->location_id = $this->translateLocationId($oldLesson->location_id);
$lesson->day_id = $this->translateDayId($oldLesson->day);
$lesson->timeslot_id = $this->translateTimeslotId($oldLesson->time_slot_id);
$lesson->state='Validated';
$lesson->save();
$lesson->addTeacher($this->translateTeacher($oldLesson->teacher_id));
$module = Module::findOrFail($this->translateModuleId($oldLesson->study_module_id));
foreach ($module->submodules as $submodule) {
$lesson->addSubmodule($submodule);
}
$classroom = Classroom::findOrFail($this->translateClassroomId($oldLesson->classroom_group_id));
$lesson->addClassroom($classroom);
$lesson_migration = new LessonMigration();
$lesson_migration->newlesson_id = $lesson->id;
$lesson_migration->lesson()->associate($oldLesson);
$lesson_migration->save();
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
$this->output->error(
'Error migrating lesson. ' . class_basename($e) . ' ' . $e->getMessage());
return null;
}
}
}
|
php
|
{
"resource": ""
}
|
q239682
|
EbreEscoolMigrator.migrateEnrollmentDetail
|
train
|
protected function migrateEnrollmentDetail($enrollmentDetail,$enrollment_id)
{
try {
$enrollment = ScoolEnrollmentSubmodule::firstOrNew([
'enrollment_id' => $enrollment_id,
'module_id' => $this->translateModuleId($enrollmentDetail->moduleid),
'submodule_id' => $this->translateSubmoduleId($enrollmentDetail->submoduleid),
]);
$enrollment->state='Validated';
$enrollment->save();
} catch (\Exception $e) {
$this->output->error(
'Error migrating enrollment detail. ' . class_basename($e) . ' ' . $e->getMessage());
}
}
|
php
|
{
"resource": ""
}
|
q239683
|
EbreEscoolMigrator.translateLocationId
|
train
|
protected function translateLocationId($oldLocationId)
{
$location = ScoolLocation::where('name',Location::findOrFail($oldLocationId)->name)->first();
if ( $location != null ) {
return $location->id;
}
throw new LocationNotFoundByNameException();
}
|
php
|
{
"resource": ""
}
|
q239684
|
EbreEscoolMigrator.translateTimeslotId
|
train
|
protected function translateTimeslotId($oldTimeslotId)
{
$timeslot = ScoolTimeslot::where('order',Timeslot::findOrFail($oldTimeslotId)->order)->first();
if ( $timeslot != null ) {
return $timeslot->id;
}
throw new TimeslotNotFoundByNameException();
}
|
php
|
{
"resource": ""
}
|
q239685
|
EbreEscoolMigrator.translateModuleId
|
train
|
protected function translateModuleId($oldModuleId)
{
$module = Module::where('name',StudyModule::findOrFail($oldModuleId)->name)->first();
if ( $module != null ) {
return $module->id;
}
throw new ModuleNotFoundByNameException();
}
|
php
|
{
"resource": ""
}
|
q239686
|
EbreEscoolMigrator.translateSubmoduleId
|
train
|
protected function translateSubmoduleId($oldSubModuleId)
{
$submodule = Submodule::where('name',StudySubModule::findOrFail($oldSubModuleId)->name)->first();
if ( $submodule != null ) {
return $submodule->id;
}
throw new SubmoduleNotFoundByNameException();
}
|
php
|
{
"resource": ""
}
|
q239687
|
EbreEscoolMigrator.translateStudyId
|
train
|
protected function translateStudyId($oldStudyId)
{
$study = ScoolStudy::where('name',Study::findOrFail($oldStudyId)->name)->first();
if ( $study != null ) {
return $study->id;
}
throw new StudyNotFoundByNameException();
}
|
php
|
{
"resource": ""
}
|
q239688
|
EbreEscoolMigrator.translateCourseId
|
train
|
protected function translateCourseId($oldCourseId)
{
$course = ScoolCourse::where('name',Course::findOrFail($oldCourseId)->name)->first();
if ( $course != null ) {
return $course->id;
}
throw new CourseNotFoundByNameException();
}
|
php
|
{
"resource": ""
}
|
q239689
|
EbreEscoolMigrator.translateClassroomId
|
train
|
protected function translateClassroomId($oldClassroomId)
{
$classroom = Classroom::where('name',ClassroomGroup::findOrFail($oldClassroomId)->name)->first();
if ( $classroom != null ) {
return $classroom->id;
}
throw new ClassroomNotFoundByNameException();
}
|
php
|
{
"resource": ""
}
|
q239690
|
EbreEscoolMigrator.migratePerson
|
train
|
protected function migratePerson($person)
{
//TODO create person in personal data table
$user = User::firstOrNew([
'email' => $person->email,
]);
$user->name = $person->name;
$user->password = bcrypt('secret');
$user->remember_token = str_random(10);
$user->save();
return $user;
}
|
php
|
{
"resource": ""
}
|
q239691
|
EbreEscoolMigrator.migrateClassrooms
|
train
|
protected function migrateClassrooms()
{
$this->output->info('### Migrating classrooms ###');
foreach ($classrooms = $this->classrooms() as $classroom) {
$this->showMigratingInfo($classroom, 1);
$this->migrateClassroom($classroom);
}
$this->output->info(
'### END Migrating classrooms. Migrated ' . count($classrooms) . ' locations ###');
}
|
php
|
{
"resource": ""
}
|
q239692
|
EbreEscoolMigrator.migrateLocations
|
train
|
protected function migrateLocations()
{
$this->output->info('### Migrating locations ###');
foreach ($this->locations() as $location) {
$this->showMigratingInfo($location, 1);
$this->migrateLocation($location);
}
$this->output->info(
'### END Migrating locations. Migrated ' . count($this->locations()) . ' locations ###');
}
|
php
|
{
"resource": ""
}
|
q239693
|
EbreEscoolMigrator.migrateLocation
|
train
|
protected function migrateLocation($srcLocation) {
$location = ScoolLocation::firstOrNew([
'name' => $srcLocation->name,
]);
$location->save();
$location->shortname = $srcLocation->shortName;
$location->description = $srcLocation->description;
$location->code = $srcLocation->external_code;
}
|
php
|
{
"resource": ""
}
|
q239694
|
EbreEscoolMigrator.migrateClassroom
|
train
|
protected function migrateClassroom($srcClassroom) {
$classroom = Classroom::firstOrNew([
'name' => $srcClassroom->name,
]);
$classroom->save();
$this->addCourseToClassroom($classroom, $srcClassroom->course_id);
$classroom->shortname = $srcClassroom->shortName;
$classroom->description = $srcClassroom->description;
$classroom->code = $srcClassroom->external_code;
}
|
php
|
{
"resource": ""
}
|
q239695
|
EbreEscoolMigrator.migrateCurriculum
|
train
|
private function migrateCurriculum()
{
foreach ($this->departments() as $department) {
$this->setDepartment($department);
$this->showMigratingInfo($department,1);
$this->migrateDepartment($department);
foreach ($this->studies($department) as $study) {
$this->setStudy($study);
$this->showMigratingInfo($study,2);
$this->migrateStudy($study);
$this->addStudyToDeparment();
foreach ($this->courses($study) as $course) {
$this->setCourse($course);
$this->showMigratingInfo($course,3);
$this->migrateCourse($course);
$this->addCourseToStudy();
foreach ($this->modules($course) as $module) {
$this->setModule($module);
$this->showMigratingInfo($module, 4);
$this->migrateModule($module);
$this->addModuleToCourse();
foreach ($this->submodules($module) as $submodule) {
$this->setSubmodule($submodule);
$this->showMigratingInfo($submodule, 5);
$this->migrateSubmodule($submodule);
$this->addSubModuleToModule();
}
}
}
}
}
}
|
php
|
{
"resource": ""
}
|
q239696
|
EbreEscoolMigrator.migrateEnrollments
|
train
|
private function migrateEnrollments()
{
$this->output->info('### Migrating enrollments ###');
foreach ($this->enrollments() as $enrollment) {
if ($enrollment->person == null ) {
$this->output->error('Skipping enrolmment because no personal data');
continue;
}
$enrollment->showMigratingInfo($this->output,1);
$newEnrollment = $this->migrateEnrollment($enrollment);
if ($newEnrollment) $this->migrateEnrollmentDetails($enrollment, $newEnrollment);
}
$this->output->info('### END Migrating enrollments ###');
}
|
php
|
{
"resource": ""
}
|
q239697
|
EbreEscoolMigrator.seedDays
|
train
|
protected function seedDays()
{
$this->output->info('### Seeding days###');
//%u ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
$timestamp = strtotime('next Monday');
$days = array();
for ($i = 1; $i < 8; $i++) {
$days[$i] = strftime('%A', $timestamp);
$timestamp = strtotime('+1 day', $timestamp);
}
foreach ($days as $dayNumber => $day) {
$this->output->info('### Seeding day: ' . $day . ' ###');
$dayModel = Day::firstOrNew([
'code' => $dayNumber,
]
);
$dayModel->name = $day;
$dayModel->code = $dayNumber;
$dayModel->lective = true;
if ($dayNumber == 6 || $dayNumber == 7) {
$dayModel->lective = false;
}
$dayModel->save();
}
$this->output->info('### END Seeding days###');
}
|
php
|
{
"resource": ""
}
|
q239698
|
EbreEscoolMigrator.migrateTimeslots
|
train
|
protected function migrateTimeslots()
{
$this->output->info('### Migrating timeslots ###');
foreach ($this->timeslots() as $timeslot) {
$timeslot->showMigratingInfo($this->output,1);
$this->migrateTimeslot($timeslot);
}
$this->output->info('### END OF Migrating timeslots ###');
}
|
php
|
{
"resource": ""
}
|
q239699
|
EbreEscoolMigrator.migrateLessons
|
train
|
protected function migrateLessons()
{
$this->output->info('### Migrating lessons ###');
if ($this->checkLessonsMigrationState()) {
foreach ($this->lessons() as $lesson) {
$lesson->showMigratingInfo($this->output,1);
$this->migrateLesson($lesson);
}
}
$this->output->info('### END OF Migrating lessons ###');
}
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.