_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5700 | Validation.validateEmail | train | public static function validateEmail($string)
{
if (filter_var($string, FILTER_VALIDATE_EMAIL)) {
return (string)$string;
}
throw new InvalidArgumentException(
sprintf(
'Provided string "%1$s" was not a valid email.',
$string
)
);
} | php | {
"resource": ""
} |
q5701 | Validation.validateURL | train | public static function validateURL($string)
{
if (filter_var($string, FILTER_VALIDATE_URL)) {
return (string)$string;
}
throw new InvalidArgumentException(
sprintf(
'Provided string "%1$s" was not a valid URL.',
$string
)
);
} | php | {
"resource": ""
} |
q5702 | BaseApplication.getUserRole | train | public function getUserRole() {
return isset($_SESSION[$this->config->roleSessionVar]) ? $_SESSION[$this->config->roleSessionVar] : $this->config->defaultRole;
} | php | {
"resource": ""
} |
q5703 | BaseApplication.read | train | public function read(Config $source) {
$path = $source->getPath();
$sourceData = (object)[
'baseurl' => $source->baseurl,
'path' => str_replace(realpath($source->getRoot()) . Consts::DS, '', $path),
'files' => [],
];
try {
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $path);
} catch (\Exception $e) {
return $sourceData;
}
$dir = opendir($path);
$config = $this->config;
while ($file = readdir($dir)) {
if ($file != '.' && $file != '..' && is_file($path . $file)) {
$file = new File($path . $file);
if ($file->isGoodFile($source)) {
$item = [
'file' => $file->getPathByRoot($source),
];
if ($config->createThumb || !$file->isImage()) {
$item['thumb'] = Image::getThumb($file, $source)->getPathByRoot($source);
}
$item['changed'] = date($config->datetimeFormat, $file->getTime());
$item['size'] = Helper::humanFileSize($file->getSize());
$item['isImage'] = $file->isImage();
$sourceData->files[] = $item;
}
}
}
return $sourceData;
} | php | {
"resource": ""
} |
q5704 | BaseApplication.getSource | train | public function getSource() {
$source = $this->config->getSource($this->request->source);
if (!$source) {
throw new \Exception('Source not found', Consts::ERROR_CODE_NOT_EXISTS);
}
return $source;
} | php | {
"resource": ""
} |
q5705 | BasicHttpClient.createBaseRequest | train | protected function createBaseRequest($relativeUrl)
{
$baseUrl = $this->getBaseUrl(false);
$request = new \Zend\Http\Request();
$request->setUri($baseUrl.$relativeUrl);
$request->setMethod(\Zend\Http\Request::METHOD_POST);
$request->getHeaders()->addHeaders(array(
'Content-Type'=>'application/x-www-form-urlencoded; charset=UTF-8',
'Accept-Encoding'=>'identity')); // plain text
$this->addDefaultParameters($request);
return $request;
} | php | {
"resource": ""
} |
q5706 | BasicHttpClient.addDefaultParameters | train | protected function addDefaultParameters(&$request)
{
$defaultParameters = array(
'all'=>1,
'dir'=>'ASC',
'start'=>0,
'limit'=>999999999);
foreach ($defaultParameters as $name=> $value)
$request->getPost()->set($name, $value);
} | php | {
"resource": ""
} |
q5707 | MetaDataQuestion.ask | train | public function ask(MetaDataSource $metadataSource, $choice = null)
{
$metaDataCollection = $this->getMetadataDao($metadataSource)->getAllMetadata();
$responseCollection = new PredefinedResponseCollection();
foreach ($metaDataCollection as $metaData) {
$response = new PredefinedResponse($metaData->getOriginalName(), $metaData->getOriginalName(), $metaData);
$response->setAdditionalData(array('source' => $metadataSource->getUniqueName()));
$responseCollection->append($response);
}
$question = new QuestionWithPredefinedResponse(
"Select Metadata",
self::QUESTION_KEY,
$responseCollection
);
$question->setPreselectedResponse($choice);
$question->setShutdownWithoutResponse(true);
return $this->context->askCollection($question);
} | php | {
"resource": ""
} |
q5708 | Tvheadend.getNodeData | train | public function getNodeData($uuid)
{
$request = new client\Request('/api/idnode/load', array(
'uuid'=>$uuid,
'meta'=>0));
$response = $this->_client->getResponse($request);
$content = json_decode($response->getContent());
if (count($content->entries) > 0)
return $content->entries[0];
else
return null;
} | php | {
"resource": ""
} |
q5709 | Tvheadend.createNetwork | train | public function createNetwork($network)
{
$request = new client\Request('/api/mpegts/network/create', array(
'class'=>$network->getClassName(),
'conf'=>json_encode($network)));
$this->_client->getResponse($request);
} | php | {
"resource": ""
} |
q5710 | Tvheadend.getNetwork | train | public function getNetwork($name)
{
// TODO: Use filtering
$networks = $this->getNetworks();
foreach ($networks as $network)
if ($network->networkname === $name)
return $network;
return null;
} | php | {
"resource": ""
} |
q5711 | Tvheadend.createMultiplex | train | public function createMultiplex($network, $multiplex)
{
$request = new client\Request('/api/mpegts/network/mux_create', array(
'uuid'=>$network->uuid,
'conf'=>json_encode($multiplex)));
$this->_client->getResponse($request);
} | php | {
"resource": ""
} |
q5712 | Tvheadend.getChannels | train | public function getChannels($filter = null)
{
$channels = array();
// Create the request
$request = new client\Request('/api/channel/grid');
if ($filter)
$request->setFilter($filter);
// Get the response
$response = $this->_client->getResponse($request);
$rawContent = $response->getContent();
$content = json_decode($rawContent);
foreach ($content->entries as $entry)
$channels[] = model\Channel::fromRawEntry($entry);
return $channels;
} | php | {
"resource": ""
} |
q5713 | Tvheadend.getServices | train | public function getServices($filter = null)
{
$services = array();
// Create the request
$request = new client\Request('/api/mpegts/service/grid');
if ($filter)
$request->setFilter($filter);
// Get the response
$response = $this->_client->getResponse($request);
$rawContent = $response->getContent();
$content = json_decode($rawContent);
foreach ($content->entries as $entry)
$services[] = model\Service::fromRawEntry($entry);
return $services;
} | php | {
"resource": ""
} |
q5714 | Tvheadend.generateCometPollBoxId | train | private function generateCometPollBoxId()
{
$request = new client\Request('/comet/poll');
$response = $this->_client->getResponse($request);
$content = json_decode($response->getContent());
$boxId = $content->boxid;
return new BoxId($boxId);
} | php | {
"resource": ""
} |
q5715 | Tvheadend.ensureValidBoxId | train | private function ensureValidBoxId($class)
{
if (!array_key_exists($class, $this->_boxIds) || $this->_boxIds[$class]->getAge() > self::MAXIMUM_BOXID_AGE)
$this->_boxIds[$class] = $this->generateCometPollBoxId();
} | php | {
"resource": ""
} |
q5716 | TubeLink.create | train | static public function create()
{
$t = new static();
$t->registerService(new Service\Youtube());
$t->registerService(new Service\Dailymotion());
$t->registerService(new Service\Vimeo());
$t->registerService(new Service\Spotify());
$t->registerService(new Service\SoundCloud());
return $t;
} | php | {
"resource": ""
} |
q5717 | EnvController.switchCommand | train | public function switchCommand($target = '')
{
if ($target === '' && $values = $this->arguments->getValues()) {
$target = $values[0];
}
if ($target === '') {
$target = $this->arguments->getOption('env');
}
$candidates = [];
foreach ($this->_getEnvTypes() as $file) {
if (strpos($file, $target) === 0) {
$candidates[] = $file;
}
}
if (count($candidates) !== 1) {
return $this->console->error(['can not one file: :env', 'env' => implode(',', $candidates)]);
}
$target = $candidates[0];
$glob = '@root/.env[._-]' . $target;
$files = $this->filesystem->glob($glob);
if ($files) {
$file = $files[0];
$this->filesystem->fileCopy($file, '@root/.env', true);
if (file_exists($file . '.php')) {
$this->filesystem->fileDelete($file . '.php');
}
$this->console->writeLn(['copy `:src` to `:dst` success.', 'src' => basename($file), 'dst' => '.env']);
return 0;
} else {
return $this->console->error(['dotenv file `:file` is not exists', 'file' => $glob]);
}
} | php | {
"resource": ""
} |
q5718 | EnvController.cacheCommand | train | public function cacheCommand()
{
$file = $this->alias->resolve('@root/.env');
if (!file_exists($file)) {
return $this->console->writeLn(['`:file` dotenv file is not exists', 'file' => $file]);
}
$data = (new Dotenv())->parse(file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
$content = '<?php' . PHP_EOL .
'return ' . var_export($data, true) . ';' . PHP_EOL;
$this->filesystem->filePut('@root/.env.php', $content);
return 0;
} | php | {
"resource": ""
} |
q5719 | EnvController.inspectCommand | train | public function inspectCommand()
{
$file = $this->alias->resolve('@root/.env');
if (!file_exists($file)) {
return $this->console->writeLn(['`:file` dotenv file is not exists', 'file' => $file]);
}
$data = (new Dotenv())->parse(file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
$this->console->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
return 0;
} | php | {
"resource": ""
} |
q5720 | AttributeForm.beforeSave | train | public function beforeSave()
{
//iteracja po elementach dodanych przez atrybuty
foreach ($this->_cmsAttributeElements as $attributeId => $element) {
//wyszukiwanie atrybutu
$attribute = $this->_findAttributeById($attributeId);
//jeśli atrybut jest zmaterializowany
if (null !== $attribute && $attribute->getJoined('cms_attribute_relation')->isMaterialized()) {
//ustawienie wartości w rekordzie
$this->getRecord()->{$attribute->key} = $element->getValue();
}
}
} | php | {
"resource": ""
} |
q5721 | AttributeForm._parseClassWithOptions | train | private function _parseClassWithOptions($classWithOptions)
{
$config = explode(':', $classWithOptions);
$class = array_shift($config);
//zwrot konfiguracji
return (new \Mmi\OptionObject)
->setClass($class)
->setConfig($config);
} | php | {
"resource": ""
} |
q5722 | BashCompletionController.completeCommand | train | public function completeCommand()
{
$arguments = array_slice($GLOBALS['argv'], 3);
$position = (int)$arguments[0];
$arguments = array_slice($arguments, 1);
$count = count($arguments);
$controller = null;
if ($count > 1) {
$controller = $arguments[1];
}
$command = null;
if ($count > 2) {
$command = $arguments[2];
if ($command !== '' && $command[0] === '-') {
$command = 'default';
}
}
$previous = $position > 0 ? $arguments[$position - 1] : null;
$current = isset($arguments[$position]) ? $arguments[$position] : '';
if ($position === 1) {
$words = $this->_getControllers();
} elseif ($current !== '' && $current[0] === '-') {
$words = $this->_getArgumentNames($controller, $command);
} elseif ($position === 2) {
$words = $this->_getCommands($controller);
} else {
$words = $this->_getArgumentValues($controller, $command, $previous);
}
$this->console->writeLn(implode(' ', $this->_filterWords($words, $current)));
return 0;
} | php | {
"resource": ""
} |
q5723 | BashCompletionController.installCommand | train | public function installCommand()
{
$content = <<<'EOT'
#!/bin/bash
_manacli(){
COMPREPLY=( $(./manacli.php bash_completion complete $COMP_CWORD "${COMP_WORDS[@]}") )
return 0;
}
complete -F _manacli manacli
EOT;
$file = '/etc/bash_completion.d/manacli';
if (DIRECTORY_SEPARATOR === '\\') {
return $this->console->error('Windows system is not support bash completion!');
}
try {
$this->filesystem->filePut($file, PHP_EOL === '\n' ? $content : str_replace("\r", '', $content));
$this->filesystem->chmod($file, 0755);
} catch (\Exception $e) {
return $this->console->error('write bash completion script failed: ' . $e->getMessage());
}
$this->console->writeLn('install bash completion script successfully');
$this->console->writeLn("please execute `source $file` command to become effective");
return 0;
} | php | {
"resource": ""
} |
q5724 | Builder.setTables | train | public function setTables()
{
foreach ($this->data['tables'] as $alias => $model) {
// set model => alias (real table name)
$this->builder->addFrom($model, $alias);
}
return null;
} | php | {
"resource": ""
} |
q5725 | Builder.setOrder | train | public function setOrder()
{
// set order position if exist
$order = [];
foreach ($this->data['order'] as $alias => $params) {
$order = array_flip($order);
if (empty($params) === false) {
foreach ($params as $field => $sort) {
$order[] = $alias . '.' . $field . ' ' . $sort;
}
}
}
$this->builder->orderBy($order);
return null;
} | php | {
"resource": ""
} |
q5726 | Builder.setGroup | train | public function setGroup()
{
// set group position if exist
$group = [];
foreach ($this->data['group'] as $table => $params) {
$params = array_flip($params);
if (empty($params) === false) {
foreach ($params as $field) {
$group[] = $table . '.' . $field;
}
}
}
$this->builder->groupBy($group);
return null;
} | php | {
"resource": ""
} |
q5727 | Builder.setWhere | train | public function setWhere()
{
// checking of Exact flag
$index = 0;
foreach ($this->data['where'] as $alias => $fields) {
foreach ($fields as $field => $type) {
// call expression handler
$this->expressionRun($alias, $field, $type, $index);
++$index;
}
}
return null;
} | php | {
"resource": ""
} |
q5728 | Builder.expressionRun | train | private function expressionRun($table, $field, $type, $index)
{
if ($type === Column::TYPE_TEXT) {
// match query
$query = "MATCH(" . $table . "." . $field . ") AGAINST (:query:)";
}
else {
// simple query
$query = $table . "." . $field . " LIKE :query:";
}
if ($index > 0) {
$this->builder->orWhere($query, $this->ftFilter($type));
}
else {
$this->builder->where($query, $this->ftFilter($type));
}
return null;
} | php | {
"resource": ""
} |
q5729 | Builder.loop | train | public function loop($hydratorset = null, $callback = null)
{
try {
// get valid result
$this->data = $this->searcher->getFields();
foreach ($this->data as $key => $values) {
// start build interface
if (empty($values) === false) {
$this->{'set' . ucfirst($key)}();
}
}
// execute query
return $this->setResult($hydratorset, $callback);
} catch (ExceptionFactory $e) {
echo $e->getMessage();
}
} | php | {
"resource": ""
} |
q5730 | Builder.ftFilter | train | protected function ftFilter($type)
{
if ($type === Column::TYPE_TEXT)
{
return array_map(function ($v) {
return trim($v, '%');
}, $this->searcher->query);
}
return $this->searcher->query;
} | php | {
"resource": ""
} |
q5731 | Builder.setResult | train | protected function setResult($hydratorset = null, $callback = null) {
$res = $this->builder->getQuery()->execute();
$call = "Searcher\\Searcher\\Hydrators\\" . ucfirst($hydratorset) . "Hydrator";
if ($res->valid() === true) {
if(class_exists($call) === true) {
$res = (new $call($res))->extract($callback);
}
return $res;
}
return null;
} | php | {
"resource": ""
} |
q5732 | Plupload.addImprintElement | train | public function addImprintElement($type, $name, $label = null, $options = [])
{
$imprint = $this->getOption('imprint');
//brak pól - pusta lista
if (null === $imprint) {
$imprint = [];
}
$imprint[] = ['type' => $type, 'name' => $name, 'label' => ($label ?: $name), 'options' => $options];
return $this->setOption('imprint', $imprint);
} | php | {
"resource": ""
} |
q5733 | Plupload._beforeRender | train | protected function _beforeRender()
{
$this->_id = $this->getOption('id');
if ($this->_form->hasRecord()) {
$this->_object = $this->_form->getFileObjectName();
$this->_objectId = $this->_form->getRecord()->getPk();
}
//jeśli wymuszony inny object
if ($this->getOption('object')) {
$this->_object = $this->getOption('object');
}
$this->_tempObject = 'tmp-' . $this->_object;
$this->_createTempFiles();
return $this;
} | php | {
"resource": ""
} |
q5734 | Metadata._readMetaData | train | protected function _readMetaData($model)
{
$modelName = is_string($model) ? $model : get_class($model);
if (!isset($this->_metadata[$modelName])) {
$data = $this->read($modelName);
if ($data !== false) {
$this->_metadata[$modelName] = $data;
} else {
$modelInstance = is_string($model) ? new $model : $model;
$data = $this->_di->getShared($modelInstance->getDb(true))->getMetadata($modelInstance->getSource(true));
$this->_metadata[$modelName] = $data;
$this->write($modelName, $data);
}
}
return $this->_metadata[$modelName];
} | php | {
"resource": ""
} |
q5735 | JParserBase.parse_string | train | static function parse_string( $src, $unicode = true, $parser = __CLASS__, $lexer = 'JTokenizer' ){
$Tokenizer = new $lexer( false, $unicode);
$tokens = $Tokenizer->get_all_tokens( $src );
unset( $src );
$Parser = new $parser;
return $Parser->parse( $tokens );
} | php | {
"resource": ""
} |
q5736 | Bag.set | train | public function set($property, $value)
{
$defaultCurrentValue = [];
$data = $this->session->get($this->_name, $defaultCurrentValue);
$data[$property] = $value;
$this->session->set($this->_name, $data);
} | php | {
"resource": ""
} |
q5737 | Bag.get | train | public function get($property = null, $default = null)
{
$defaultCurrentValue = [];
$data = $this->session->get($this->_name, $defaultCurrentValue);
if ($property === null) {
return $data;
} else {
return isset($data[$property]) ? $data[$property] : $default;
}
} | php | {
"resource": ""
} |
q5738 | Bag.has | train | public function has($property)
{
$defaultCurrentValue = [];
$data = $this->session->get($this->_name, $defaultCurrentValue);
return isset($data[$property]);
} | php | {
"resource": ""
} |
q5739 | MoveTemplateFilesToRootFolder.getTargetPath | train | protected function getTargetPath($pathname)
{
$filesystem = new Filesystem();
$templatesFolder = $this->getConfigKey('Folders', 'templates');
$folderDiff = '/' . $filesystem->findShortestPath(
SetupHelper::getRootFolder(),
$templatesFolder
);
return (string)$this->removeTemplateExtension(str_replace($folderDiff, '', $pathname));
} | php | {
"resource": ""
} |
q5740 | ClassAwake.wakeByInterfaces | train | public function wakeByInterfaces(array $directories, $interfaceNames)
{
$classCollection = $this->awake($directories);
$classes = array();
foreach ($classCollection as $className) {
$reflectionClass = new ReflectionClass($className);
$interfaces = $reflectionClass->getInterfaces();
if (is_array($interfaces) === true && isset($interfaces[$interfaceNames]) === true) {
$class = str_replace('\\', '', strrchr($className, '\\'));
$classes[$class] = $className;
}
}
return $classes;
} | php | {
"resource": ""
} |
q5741 | ClassAwake.awake | train | private function awake(array $directories)
{
$includedFiles = array();
self::$included = array_merge(self::$included, get_included_files());
foreach ($directories as $directorie) {
$iterator = new \RegexIterator(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($directorie, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::LEAVES_ONLY
),
'/^.+' . preg_quote('.php') . '$/i',
\RecursiveRegexIterator::GET_MATCH
);
foreach ($iterator as $file) {
$sourceFile = realpath($file[0]);
if (in_array($sourceFile, self::$included) === false) {
require_once $sourceFile;
}
self::$included[] = $sourceFile;
$includedFiles[] = $sourceFile;
}
}
$classes = array();
$declared = get_declared_classes();
foreach ($declared as $className) {
$rc = new \ReflectionClass($className);
$sourceFile = $rc->getFileName();
if (in_array($sourceFile, $includedFiles) === true) {
$classes[] = $className;
}
}
return $classes;
} | php | {
"resource": ""
} |
q5742 | DoctrineHelper.checkAndCreateTableByEntityName | train | public static function checkAndCreateTableByEntityName(ContainerInterface $container, $className, $force = false)
{
/** @var Registry $doctrine */
/** @var Connection $connection */
/** @var ClassMetadata $classMetadata */
$doctrine = $container->get('doctrine');
$manager = $doctrine->getManager();
$schemaTool = new SchemaTool($doctrine->getManager());
$connection = $doctrine->getConnection();
$schemaManager = $connection->getSchemaManager();
$classMetadata = $manager->getClassMetadata($className);
if ($force || !$schemaManager->tablesExist($classMetadata->getTableName())) {
if ($schemaManager instanceof SqliteSchemaManager) {
$columns = array();
$identifiers = $classMetadata->getIdentifierColumnNames();
foreach ($classMetadata->getFieldNames() as $fieldName) {
$fieldMapping = $classMetadata->getFieldMapping($fieldName);
$columnSql = $fieldMapping["fieldName"];
switch ($fieldMapping["type"]) {
case 'integer':
$columnSql .= " INTEGER ";
break;
case 'real':
case 'double':
case 'float':
$columnSql .= " REAL ";
break;
case 'datetime':
case 'date':
case 'boolean':
$columnSql .= " INTEGER ";
break;
case 'blob':
case 'file':
$columnSql .= " BLOB ";
break;
default:
$columnSql .= " TEXT ";
}
// PRIMARY KEY
in_array($fieldName, $identifiers) && $columnSql .= "PRIMARY KEY ";
$columnSql .= $fieldMapping["nullable"] ? "NULL " : "NOT NULL ";
$columns[] = $columnSql;
}
$sql = 'CREATE TABLE IF NOT EXISTS ' . $classMetadata->getTableName() . '( ' . implode(",\n", $columns) . ')';
$statement = $connection->query($sql);
} else {
$schemaTool->updateSchema(array($classMetadata), true);
}
}
} | php | {
"resource": ""
} |
q5743 | Application.actionFiles | train | public function actionFiles() {
$sources = [];
$currentSource = $this->getSource();
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $currentSource !== $source && $this->request->path !== './') {
continue;
}
if ($this->accessControl->isAllow($this->getUserRole(), $this->action, $source->getPath())) {
$sources[$key] = $this->read($source);
}
}
return [
'sources' => $sources
];
} | php | {
"resource": ""
} |
q5744 | Application.actionFolders | train | public function actionFolders() {
$sources = [];
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $key !== $this->request->source && $this->request->path !== './') {
continue;
}
$path = $source->getPath();
try {
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $path);
} catch (\Exception $e) {
continue;
}
$sourceData = (object)[
'baseurl' => $source->baseurl,
'path' => str_replace(realpath($source->getRoot()) . Consts::DS, '', $path),
'folders' => [],
];
$sourceData->folders[] = $path == $source->getRoot() ? '.' : '..';
$dir = opendir($path);
while ($file = readdir($dir)) {
if (
$file != '.' &&
$file != '..' &&
is_dir($path . $file) and
(
!$this->config->createThumb ||
$file !== $this->config->thumbFolderName
) and
!in_array($file, $this->config->excludeDirectoryNames)
) {
$sourceData->folders[] = $file;
}
}
$sources[$key] = $sourceData;
}
return [
'sources' => $sources
];
} | php | {
"resource": ""
} |
q5745 | Application.actionFileUploadRemote | train | public function actionFileUploadRemote() {
$url = $this->request->url;
if (!$url) {
throw new \Exception('Need url parameter', Consts::ERROR_CODE_BAD_REQUEST);
}
$result = parse_url($url);
if (!isset($result['host']) || !isset($result['path'])) {
throw new \Exception('Not valid URL', Consts::ERROR_CODE_BAD_REQUEST);
}
$filename = Helper::makeSafe(basename($result['path']));
if (!$filename) {
throw new \Exception('Not valid URL', Consts::ERROR_CODE_BAD_REQUEST);
}
$source = $this->config->getCompatibleSource($this->request->source);
Helper::downloadRemoteFile($url, $source->getRoot() . $filename);
$file = new File($source->getRoot() . $filename);
try {
if (!$file->isGoodFile($source)) {
throw new \Exception('Bad file', Consts::ERROR_CODE_FORBIDDEN);
}
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $source->getRoot(), $file->getExtension());
} catch (\Exception $e) {
$file->remove();
throw $e;
}
return [
'newfilename' => $file->getName(),
'baseurl' => $source->baseurl,
];
} | php | {
"resource": ""
} |
q5746 | Application.movePath | train | private function movePath() {
$source = $this->getSource();
$destinationPath = $source->getPath();
$sourcePath = $source->getPath($this->request->from);
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $destinationPath);
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $sourcePath);
if ($sourcePath) {
if ($destinationPath) {
if (is_file($sourcePath) or is_dir($sourcePath)) {
rename($sourcePath, $destinationPath . basename($sourcePath));
} else {
throw new \Exception('Not file', Consts::ERROR_CODE_NOT_EXISTS);
}
} else {
throw new \Exception('Need destination path', Consts::ERROR_CODE_BAD_REQUEST);
}
} else {
throw new \Exception('Need source path', Consts::ERROR_CODE_BAD_REQUEST);
}
} | php | {
"resource": ""
} |
q5747 | Application.actionGetLocalFileByUrl | train | public function actionGetLocalFileByUrl() {
$url = $this->request->url;
if (!$url) {
throw new \Exception('Need full url', Consts::ERROR_CODE_BAD_REQUEST);
}
$parts = parse_url($url);
if (empty($parts['path'])) {
throw new \Exception('Empty url', Consts::ERROR_CODE_BAD_REQUEST);
}
$found = false;
$path = '';
$root = '';
$key = 0;
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $key !== $this->request->source && $this->request->path !== './') {
continue;
}
$base = parse_url($source->baseurl);
$path = preg_replace('#^(/)?' . $base['path'] . '#', '', $parts['path']);
$root = $source->getPath();
if (file_exists($root . $path) && is_file($root . $path)) {
$file = new File($root . $path);
if ($file->isGoodFile($source)) {
$found = true;
break;
}
}
}
if (!$found) {
throw new \Exception('File does not exist or is above the root of the connector', Consts::ERROR_CODE_FAILED);
}
return [
'path' => str_replace($root, '', dirname($root . $path) . Consts::DS),
'name' => basename($path),
'source' => $key
];
} | php | {
"resource": ""
} |
q5748 | Model.getSource | train | public function getSource($context = null)
{
$class = static::class;
return Text::underscore(($pos = strrpos($class, '\\')) === false ? $class : substr($class, $pos + 1));
} | php | {
"resource": ""
} |
q5749 | Model.last | train | public static function last($filters = null, $fields = null)
{
$model = new static();
if (is_string($primaryKey = $model->getPrimaryKey())) {
$options['order'] = [$primaryKey => SORT_DESC];
} else {
throw new BadMethodCallException('infer `:class` order condition for last failed:', ['class' => static::class]);
}
$rs = static::query(null, $model)->select($fields)->where($filters)->limit(1)->fetch();
return isset($rs[0]) ? $rs[0] : null;
} | php | {
"resource": ""
} |
q5750 | Model.avg | train | public static function avg($field, $filters = null)
{
return (float)static::query()->where($filters)->avg($field);
} | php | {
"resource": ""
} |
q5751 | Model.assign | train | public function assign($data, $whiteList = null)
{
if ($whiteList === null) {
$whiteList = $this->getSafeFields();
}
if ($whiteList === null) {
throw new PreconditionException(['`:model` model do not define accessible fields.', 'model' => static::class]);
}
foreach ($whiteList ?: $this->getFields() as $field) {
if (isset($data[$field])) {
$value = $data[$field];
$this->{$field} = is_string($value) ? trim($value) : $value;
}
}
return $this;
} | php | {
"resource": ""
} |
q5752 | Model.delete | train | public function delete()
{
$this->eventsManager->fireEvent('model:beforeDelete', $this);
static::query(null, $this)->where($this->_getPrimaryKeyValuePairs())->delete();
$this->eventsManager->fireEvent('model:afterDelete', $this);
return $this;
} | php | {
"resource": ""
} |
q5753 | Model.toArray | train | public function toArray()
{
$data = [];
foreach (get_object_vars($this) as $field => $value) {
if ($field[0] === '_') {
continue;
}
if (is_object($value)) {
if ($value instanceof self) {
$value = $value->toArray();
} else {
continue;
}
} elseif (is_array($value) && ($first = current($value)) && $first instanceof self) {
foreach ($value as $k => $v) {
$value[$k] = $v->toArray();
}
}
if ($value !== null) {
$data[$field] = $value;
}
}
return $data;
} | php | {
"resource": ""
} |
q5754 | Model.getChangedFields | train | public function getChangedFields()
{
if ($this->_snapshot === false) {
throw new PreconditionException(['getChangedFields failed: `:model` instance is snapshot disabled', 'model' => static::class]);
}
$changed = [];
foreach ($this->getFields() as $field) {
if (isset($this->_snapshot[$field])) {
if ($this->{$field} !== $this->_snapshot[$field]) {
$changed[] = $field;
}
} elseif ($this->$field !== null) {
$changed[] = $field;
}
}
return $changed;
} | php | {
"resource": ""
} |
q5755 | Model.hasChanged | train | public function hasChanged($fields)
{
if ($this->_snapshot === false) {
throw new PreconditionException(['getChangedFields failed: `:model` instance is snapshot disabled', 'model' => static::class]);
}
/** @noinspection ForeachSourceInspection */
foreach ((array)$fields as $field) {
if (!isset($this->_snapshot[$field]) || $this->{$field} !== $this->_snapshot[$field]) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q5756 | User.hasRole | train | public function hasRole($role = "general")
{
$roleModel = new \erdiko\users\models\Role;
$roleEntity = $roleModel->findByName($role);
if (empty($roleEntity)) {
throw new \Exception("Error, role {$role} not found.");
}
$result = $this->_user->getRole() == $roleEntity->getId();
return $result;
} | php | {
"resource": ""
} |
q5757 | User.save | train | public function save($data=array())
{
if (empty($data)) {
throw new \Exception( "User data is missing" );
}
$data = (object) $data;
if ((!isset($data->email) || empty($data->email))) {
throw new \Exception( "Email is required" );
}
if ((!isset($data->password) || empty($data->password)) && !isset($data->id)) {
throw new \Exception( "Password is required" );
}
$new = false;
if (isset($data->id)) {
$entity = $this->getById($data->id);
} else {
$entity = new entity();
$new = true;
}
if (isset($data->name)) {
$entity->setName($data->name);
}
if (isset($data->email)) {
$entity->setEmail($data->email);
}
if (isset($data->password)) {
$entity->setPassword($this->getSalted($data->password));
} elseif (isset($data->new_password)){
$entity->setPassword($this->getSalted($data->new_password));
}
if (empty($data->role)) {
$data->role = $this->_getDefaultRole();
}
$entity->setRole($data->role);
if (isset($data->gateway_customer_id)) {
$entity->setGatewayCustomerId($data->gateway_customer_id);
}
if ($new) {
$this->_em->persist($entity);
} else {
$this->_em->merge($entity);
}
// Save the entity
try {
$eventType = $new ? Log::EVENT_CREATE : Log::EVENT_UPDATE;
if(isset($data->new_password)){
$eventType = Log::EVENT_PASSWORD;
unset($data->new_password);
}
unset($data->password);
$this->createUserEventLog($eventType, $data);
$this->_em->flush();
$this->setEntity($entity);
return $entity->getId();
} catch ( \Doctrine\DBAL\Exception\UniqueConstraintViolationException $e ) {
// \Erdiko::log(\Psr\Log\LogLevel::INFO, 'UniqueConstraintViolationException caught: '.$e->getMessage());
throw new \Exception( "Can not create user with duplicate email" );
}
return null;
} | php | {
"resource": ""
} |
q5758 | Model.create | train | public function create()
{
$autoIncrementField = $this->getAutoIncrementField();
if ($autoIncrementField && $this->$autoIncrementField === null) {
$this->$autoIncrementField = $this->getNextAutoIncrementId();
}
$fields = $this->getFields();
foreach ($this->getAutoFilledData(self::OP_CREATE) as $field => $value) {
/** @noinspection NotOptimalIfConditionsInspection */
if (!in_array($field, $fields, true) || $this->$field !== null) {
continue;
}
$this->$field = $value;
}
$this->validate($fields);
$this->eventsManager->fireEvent('model:beforeSave', $this);
$this->eventsManager->fireEvent('model:beforeCreate', $this);
$fieldValues = [];
$defaultValueFields = [];
foreach ($fields as $field) {
if ($this->$field !== null) {
$fieldValues[$field] = $this->$field;
} elseif ($field !== $autoIncrementField) {
$defaultValueFields[] = $field;
}
}
foreach ($this->getJsonFields() as $field) {
if (is_array($this->$field)) {
$fieldValues[$field] = json_encode($this->$field, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
/**
* @var \ManaPHP\DbInterface $connection
*/
$connection = $this->_di->getShared($this->getDb($this));
if ($autoIncrementField && $this->$autoIncrementField === null) {
$this->$autoIncrementField = (int)$connection->insert($this->getSource($this), $fieldValues, true);
} else {
$connection->insert($this->getSource($this), $fieldValues);
}
if ($defaultValueFields) {
if ($r = static::query(null, $this)->select($defaultValueFields)->where($this->_getPrimaryKeyValuePairs())->fetch(true)) {
foreach ($r[0] as $field => $value) {
$this->$field = $value;
}
}
}
$this->_snapshot = $this->toArray();
$this->eventsManager->fireEvent('model:afterCreate', $this);
$this->eventsManager->fireEvent('model:afterSave', $this);
return $this;
} | php | {
"resource": ""
} |
q5759 | UserAjax.checkAuth | train | protected function checkAuth()
{
try {
// get the JWT from the headers
list($jwt) = sscanf($_SERVER["HTTP_AUTHORIZATION"], 'Bearer %s');
// init the jwt auth class
$authenticator = new JWTAuthenticator(new User());
// get the application secret key
$config = \Erdiko::getConfig();
$secretKey = $config["site"]["secret_key"];
// collect login params
$params = array(
'secret_key' => $secretKey,
'jwt' => $jwt
);
$user = $authenticator->verify($params, 'jwt_auth');
//TODO check the user's permissions via Resource & Authorization
// no exceptions? welp, this is a valid request
return true;
} catch (\Exception $e) {
return true;
}
} | php | {
"resource": ""
} |
q5760 | EngineDataForQuestion.setShutdownWithoutResponse | train | public function setShutdownWithoutResponse($value, $customeExceptionMessage = null)
{
$this->shutdownWithoutResponse = $value;
$this->customeExceptionMessage = $customeExceptionMessage;
return $this;
} | php | {
"resource": ""
} |
q5761 | TaskApi.getTaskRequest | train | protected function getTaskRequest($id)
{
// verify the required parameter 'id' is set
if ($id === null) {
throw new \InvalidArgumentException(
'Missing the required parameter $id when calling getTask'
);
}
$resourcePath = '/tasks/{id}';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// path params
if ($id !== null) {
$resourcePath = str_replace(
'{' . 'id' . '}',
ObjectSerializer::toPathValue($id),
$resourcePath
);
}
// body params
$_tempBody = null;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json'],
['application/json']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
// this endpoint requires API key authentication
$apiKey = $this->config->getApiKeyWithPrefix('X-API-KEY');
if ($apiKey !== null) {
$headers['X-API-KEY'] = $apiKey;
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'GET',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
} | php | {
"resource": ""
} |
q5762 | CategoryController.nodeAction | train | public function nodeAction()
{
//wyłączenie layout
FrontController::getInstance()->getView()->setLayoutDisabled();
//id węzła rodzica
$this->view->parentId = ($this->parentId > 0) ? $this->parentId : null;
//pobranie drzewiastej struktury stron CMS
$this->view->categoryTree = (new \Cms\Model\CategoryModel)->getCategoryTree($this->view->parentId);
} | php | {
"resource": ""
} |
q5763 | CategoryController.createAction | train | public function createAction()
{
$this->getResponse()->setTypeJson();
$cat = new \Cms\Orm\CmsCategoryRecord();
$cat->name = $this->getPost()->name;
$cat->parentId = ($this->getPost()->parentId > 0) ? $this->getPost()->parentId : null;
$cat->order = $this->getPost()->order;
$cat->active = false;
$cat->status = \Cms\Orm\CmsCategoryRecord::STATUS_ACTIVE;
if ($cat->save()) {
$icon = '';
$disabled = false;
//ikona nieaktywnego wezla gdy nieaktywny
if (!$cat->active) {
$icon = $this->view->baseUrl . '/resource/cmsAdmin/images/folder-inactive.png';
}
//sprawdzenie uprawnień do węzła
$acl = (new \CmsAdmin\Model\CategoryAclModel)->getAcl();
if (!$acl->isAllowed(\App\Registry::$auth->getRoles(), $cat->id)) {
$disabled = true;
//ikona zablokowanego wezla gdy brak uprawnien
$icon = $this->view->baseUrl . '/resource/cmsAdmin/images/folder-disabled.png';
}
return json_encode([
'status' => true,
'id' => $cat->id,
'icon' => $icon,
'disabled' => $disabled,
'message' => $this->view->_('controller.category.create.message')
]);
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.create.error')]);
} | php | {
"resource": ""
} |
q5764 | CategoryController.renameAction | train | public function renameAction()
{
$this->getResponse()->setTypeJson();
if (null !== $cat = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
$name = trim($this->getPost()->name);
if (mb_strlen($name) < 2 || mb_strlen($name) > 64) {
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.rename.validator')]);
}
$cat->name = $name;
if ($cat->save()) {
return json_encode(['status' => true, 'id' => $cat->id, 'name' => $name, 'message' => $this->view->_('controller.category.rename.message')]);
}
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.rename.error')]);
} | php | {
"resource": ""
} |
q5765 | CategoryController.moveAction | train | public function moveAction()
{
$this->getResponse()->setTypeJson();
//brak kategorii
if (null === $masterCategory = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.move.error.missing')]);
}
//domyślnie nie ma drafta - alias
$draft = $masterCategory;
//zmiana parenta tworzy draft
if ($this->getPost()->parentId != $masterCategory->parentId) {
//tworzenie draftu
$draft = (new \Cms\Model\CategoryDraft($masterCategory))->createAndGetDraftForUser(\App\Registry::$auth->getId(), true);
}
//zapis kolejności
$draft->parentId = ($this->getPost()->parentId > 0) ? $this->getPost()->parentId : null;
$draft->order = $this->getPost()->order;
//próba zapisu
return ($draft->save() && $draft->commitVersion()) ? json_encode(['status' => true, 'id' => $masterCategory->id, 'message' => $this->view->_('controller.category.move.message')]) : json_encode(['status' => false, 'error' => $this->view->_('controller.category.move.error')]);
} | php | {
"resource": ""
} |
q5766 | CategoryController.copyAction | train | public function copyAction()
{
$this->getResponse()->setTypeJson();
if (null === $category = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
return json_encode(['status' => false, 'error' => 'Strona nie istnieje']);
}
//model do kopiowania kategorii
$copyModel = new \Cms\Model\CategoryCopy($category);
//kopiowanie z transakcją
if ($copyModel->copyWithTransaction()) {
return json_encode(['status' => true, 'id' => $copyModel->getCopyRecord()->id, 'message' => $this->view->_('controller.category.copy.message')]);
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.copy.error')]);
} | php | {
"resource": ""
} |
q5767 | CategoryController._isCategoryDuplicate | train | private function _isCategoryDuplicate($originalId)
{
$category = (new \Cms\Orm\CmsCategoryQuery)->findPk($originalId);
//znaleziono kategorię o tym samym uri
return (null !== (new \Cms\Orm\CmsCategoryQuery)
->whereId()->notEquals($category->id)
->andFieldRedirectUri()->equals(null)
->andFieldStatus()->equals(\Cms\Orm\CmsCategoryRecord::STATUS_ACTIVE)
->andQuery((new \Cms\Orm\CmsCategoryQuery)->searchByUri($category->uri))
->findFirst()) && !$category->redirectUri && !$category->customUri;
} | php | {
"resource": ""
} |
q5768 | CategoryController._setReferrer | train | private function _setReferrer($referer, $id)
{
//brak referera lub referer kieruje na stronę edycji
if (!$referer || strpos($referer, self::EDIT_MVC_PARAMS)) {
return;
}
if (strpos($referer, 'cms-content-preview')) {
return;
}
$space = new \Mmi\Session\SessionSpace(self::SESSION_SPACE_PREFIX . $id);
$space->referer = $referer;
} | php | {
"resource": ""
} |
q5769 | UserMessageRepository.findSent | train | public function findSent(User $user, $executeQuery = true)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$user->getId()}
AND um.isRemoved = false
AND um.isSent = true
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
return $executeQuery ? $query->getResult() : $query;
} | php | {
"resource": ""
} |
q5770 | UserMessageRepository.findReceivedByObjectOrSender | train | public function findReceivedByObjectOrSender(
User $receiver,
$objectOrSenderUsernameSearch,
$executeQuery = true
)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$receiver->getId()}
AND um.isRemoved = false
AND um.isSent = false
AND (
UPPER(m.object) LIKE :search
OR UPPER(m.senderUsername) LIKE :search
)
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectOrSenderUsernameSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | php | {
"resource": ""
} |
q5771 | UserMessageRepository.findSentByObject | train | public function findSentByObject(User $sender, $objectSearch, $executeQuery = true)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$sender->getId()}
AND um.isRemoved = false
AND um.isSent = true
AND UPPER(m.object) LIKE :search
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | php | {
"resource": ""
} |
q5772 | UserMessageRepository.findRemovedByObjectOrSender | train | public function findRemovedByObjectOrSender(
User $user,
$objectOrSenderUsernameSearch,
$executeQuery = true
)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$user->getId()}
AND um.isRemoved = true
AND (
UPPER(m.object) LIKE :search
OR UPPER(m.senderUsername) LIKE :search
)
GROUP BY m
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectOrSenderUsernameSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | php | {
"resource": ""
} |
q5773 | UserMessageRepository.findByMessages | train | public function findByMessages(User $user, array $messages)
{
$messageIds = array();
foreach ($messages as $message) {
$messageIds[] = $message->getId();
}
$dql = '
SELECT um
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE m.id IN (:messageIds)
AND u.id = :userId
ORDER BY m.date DESC
';
$query = $this->_em->createQuery($dql);
$query->setParameter('messageIds', $messageIds);
$query->setParameter('userId', $user->getId());
return $query->getResult();
} | php | {
"resource": ""
} |
q5774 | Stat.getUniqueObjects | train | public static function getUniqueObjects()
{
$all = (new Orm\CmsStatDateQuery)
->whereHour()->equals(null)
->andFieldDay()->equals(null)
->andFieldMonth()->equals(null)
->andFieldObjectId()->equals(null)
->orderAscObject()
->find();
$objects = [];
foreach ($all as $object) {
if (!isset($objects[$object->object])) {
$objects[$object->object] = $object->object;
}
}
return $objects;
} | php | {
"resource": ""
} |
q5775 | Stat.getRows | train | public static function getRows($object, $objectId, $year = null, $month = null, $day = null, $hour = null)
{
//nowa quera filtrująca po obiekcie i ID
$q = (new Orm\CmsStatDateQuery)
->whereObject()->equals($object)
->andFieldObjectId()->equals($objectId);
//wiązanie roku
self::_bindParam($q, 'year', $year);
//wiązanie miesiąca
self::_bindParam($q, 'month', $month);
//wiązanie dnia
self::_bindParam($q, 'day', $day);
//wiązanie godziny
self::_bindParam($q, 'hour', $hour);
//sortowanie i zwrot
return $q->orderAsc('day')
->orderAsc('month')
->orderAsc('year')
->orderAsc('hour')
->find();
} | php | {
"resource": ""
} |
q5776 | ApiKeyAuthenticationHandler.buildKey | train | private function buildKey($userObject)
{
$key = $this->classMetadata->getPropertyValue($userObject, ClassMetadata::API_KEY_PROPERTY);
if (empty($key)) {
$this->classMetadata->modifyProperty(
$userObject,
$this->keyFactory->getKey(),
ClassMetadata::API_KEY_PROPERTY
);
}
} | php | {
"resource": ""
} |
q5777 | ApiKeyAuthenticationHandler.resolveObject | train | private function resolveObject($loginProperty, array $credentials)
{
return $this->om->getRepository($this->modelName)->findOneBy([
$loginProperty => $credentials[$loginProperty],
]);
} | php | {
"resource": ""
} |
q5778 | ApiKeyAuthenticationHandler.validateCredentials | train | private function validateCredentials($object, $password)
{
return !(
null === $object
|| !$this->passwordHasher->compareWith($object->getPassword(), $password)
);
} | php | {
"resource": ""
} |
q5779 | ApiKeyAuthenticationHandler.buildEventObject | train | private function buildEventObject($user, $purgeJob = false)
{
$event = new OnLogoutEvent($user);
if ($purgeJob) {
$event->markAsPurgeJob();
}
return $event;
} | php | {
"resource": ""
} |
q5780 | UserLogEntry.fill | train | private function fill(array $args)
{
$properties = array_keys(get_object_vars($this));
foreach ($args as $key => $value) {
if (in_array($key, $properties)) {
$this->{$key} = $value;
}
}
} | php | {
"resource": ""
} |
q5781 | CmsCategoryRecord.getUrl | train | public function getUrl($https = null)
{
//pobranie linku z widoku
return \Mmi\App\FrontController::getInstance()->getView()->url(['module' => 'cms', 'controller' => 'category', 'action' => 'dispatch', 'uri' => $this->customUri ? $this->customUri : $this->uri], true, $https);
} | php | {
"resource": ""
} |
q5782 | CmsCategoryRecord.getParentRecord | train | public function getParentRecord()
{
//brak parenta
if (!$this->parentId) {
return;
}
//próba pobrania rodzica z cache
if (null === $parent = \App\Registry::$cache->load($cacheKey = 'category-' . $this->parentId)) {
//pobieranie rodzica
\App\Registry::$cache->save($parent = (new \Cms\Orm\CmsCategoryQuery)
->withType()
->findPk($this->parentId), $cacheKey, 0);
}
//zwrot rodzica
return $parent;
} | php | {
"resource": ""
} |
q5783 | CmsCategoryRecord._getChildren | train | protected function _getChildren($parentId, $activeOnly = false)
{
//inicjalizacja zapytania
$query = (new CmsCategoryQuery)
->whereParentId()->equals($parentId)
->joinLeft('cms_category_type')->on('cms_category_type_id')
->orderAscOrder()
->orderAscId();
//tylko aktywne
if ($activeOnly) {
$query->whereStatus()->equals(self::STATUS_ACTIVE);
}
//zwrot w postaci tablicy rekordów
return $query->find()->toObjectArray();
} | php | {
"resource": ""
} |
q5784 | CmsCategoryRecord._sortChildren | train | protected function _sortChildren()
{
$i = 0;
//pobranie dzieci swojego rodzica
foreach ($this->_getChildren($this->parentId, true) as $categoryRecord) {
//ten rekord musi pozostać w niezmienionej pozycji (był sortowany)
if ($categoryRecord->id == $this->id) {
continue;
}
//ten sam order wskakuje za rekord
if ($this->order == $i) {
$i++;
}
//obliczanie nowej kolejności
$categoryRecord->order = $i++;
//blokada dalszego sortowania i zapis
$categoryRecord
->setOption('block-ordering', true)
->save();
}
} | php | {
"resource": ""
} |
q5785 | SessionCleanupCommand.searchUsers | train | private function searchUsers()
{
$criteria = Criteria::create()
->where(Criteria::expr()->lte(
$this->classMetadata->getPropertyName(ClassMetadata::LAST_ACTION_PROPERTY),
new \DateTime($this->dateTimeRule))
)
->andWhere(
Criteria::expr()->neq(
$this->classMetadata->getPropertyName(ClassMetadata::API_KEY_PROPERTY),
null
)
);
return $this->getUsersByCriteria($criteria);
} | php | {
"resource": ""
} |
q5786 | SessionCleanupCommand.getUsersByCriteria | train | private function getUsersByCriteria(Criteria $criteria)
{
$repository = $this->om->getRepository($this->modelName);
if ($repository instanceof Selectable) {
$filteredUsers = $repository->matching($criteria);
} else {
$allUsers = new ArrayCollection($repository->findAll());
$filteredUsers = $allUsers->matching($criteria);
}
return $filteredUsers->toArray();
} | php | {
"resource": ""
} |
q5787 | Base32._extractBytes | train | private static function _extractBytes($byteString, $start, $length) {
if (function_exists('mb_substr')) {
return mb_substr($byteString, $start, $length, '8bit');
}
return substr($byteString, $start, $length);
} | php | {
"resource": ""
} |
q5788 | Base32._intStrToByteStr | train | private static function _intStrToByteStr($intStr) {
// Check if given value is a positive integer (string).
if (!preg_match('/[0-9]+/', (string) $intStr)) {
$msg = 'Argument 1 must be a non-negative integer or a string representing a non-negative integer.';
throw new InvalidArgumentException($msg, self::E_NO_NON_NEGATIVE_INT);
}
$byteStr = '';
// If possible, use integer type for conversion.
$int = (int) $intStr;
if ((string) $int == (string) $intStr) {
// Use of integer type is possible.
// Convert integer to byte-string.
while ($int > 0) {
$byteStr = chr($int & 255) . $byteStr;
$int >>= 8;
}
} else {
// Cannot use integer type, use BC Math library.
if (extension_loaded('bcmath')) {
// Convert integer to byte-string.
while ((int) $intStr > 0) {
$byteStr = chr(bcmod($intStr, '256')) . $byteStr;
$intStr = bcdiv($intStr, '256', 0);
}
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
}
if ($byteStr == '')
$byteStr = chr(0);
return $byteStr;
} | php | {
"resource": ""
} |
q5789 | Base32._byteStrToIntStr | train | private static function _byteStrToIntStr($byteStr) {
// Get byte count.
$byteCount = self::_byteCount($byteStr);
// Check if byte count is not 0.
if ($byteCount == 0) {
$msg = 'Empty byte-string cannot be convertet to integer.';
throw new InvalidArgumentException($msg, self::E_EMPTY_BYTESTRING);
}
// Try to use PHP's internal integer type.
if ($byteCount <= PHP_INT_SIZE) {
$int = 0;
for ($i = 0; $i < $byteCount; $i++) {
$int <<= 8;
$int |= ord($byteStr[$i]);
}
if ($int >= 0)
return $int;
}
// If we did not already return here, either the byte-string has more
// characters (bytes) than PHP_INT_SIZE, or the conversion resulted in a
// negative integer. In both cases, we need to use PHP's BC Math library and
// return the integer as string.
if (extension_loaded('bcmath')) {
$intStr = '0';
for ($i = 0; $i < $byteCount; $i++) {
$intStr = bcmul($intStr, '256', 0);
$intStr = bcadd($intStr, (string) ord($byteStr[$i]), 0);
}
return $intStr;
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
} | php | {
"resource": ""
} |
q5790 | Base32._intStrModulus | train | private static function _intStrModulus($intStr, $divisor) {
// If possible, use integer type for calculation.
$int = (int) $intStr;
if ((string) $int == (string) $intStr) {
// Use of integer type is possible.
return $int % $divisor;
} else {
// Cannot use integer type, use BC Math library.
if (extension_loaded('bcmath')) {
return bcmod($intStr, (string) $divisor);
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
}
} | php | {
"resource": ""
} |
q5791 | Base32._encodeByteStr | train | private static function _encodeByteStr($byteStr, $alphabet, $pad) {
// Check if argument is a string.
if (!is_string($byteStr)) {
$msg = 'Supplied argument 1 is not a string.';
throw new InvalidArgumentException($msg, self::E_NO_STRING);
}
// Get byte count.
$byteCount = self::_byteCount($byteStr);
// Make byte count divisible by 5.
$remainder = $byteCount % 5;
$fillbyteCount = ($remainder) ? 5 - $remainder : 0;
if ($fillbyteCount > 0)
$byteStr .= str_repeat(chr(0), $fillbyteCount);
// Iterate over blocks of 5 bytes and build encoded string.
$encodedStr = '';
for ($i = 0; $i < ($byteCount + $fillbyteCount); $i = $i + 5) {
// Convert chars to bytes.
$byte1 = ord($byteStr[$i]);
$byte2 = ord($byteStr[$i + 1]);
$byte3 = ord($byteStr[$i + 2]);
$byte4 = ord($byteStr[$i + 3]);
$byte5 = ord($byteStr[$i + 4]);
// Read first 5 bit group.
$bitGroup = $byte1 >> 3;
$encodedStr .= $alphabet[$bitGroup];
// Read second 5 bit group.
$bitGroup = ($byte1 & ~(31 << 3)) << 2 | $byte2 >> 6;
$encodedStr .= $alphabet[$bitGroup];
// Read third 5 bit group.
$bitGroup = $byte2 >> 1 & ~(3 << 5);
$encodedStr .= $alphabet[$bitGroup];
// Read fourth 5 bit group.
$bitGroup = ($byte2 & 1) << 4 | $byte3 >> 4;
$encodedStr .= $alphabet[$bitGroup];
// Read fifth 5 bit group.
$bitGroup = ($byte3 & ~(15 << 4)) << 1 | $byte4 >> 7;
$encodedStr .= $alphabet[$bitGroup];
// Read sixth 5 bit group.
$bitGroup = $byte4 >> 2 & ~(1 << 5);
$encodedStr .= $alphabet[$bitGroup];
// Read seventh 5 bit group.
$bitGroup = ($byte4 & ~(63 << 2)) << 3 | $byte5 >> 5;
$encodedStr .= $alphabet[$bitGroup];
// Read eighth 5 bit group.
$bitGroup = $byte5 & ~(7 << 5);
$encodedStr .= $alphabet[$bitGroup];
}
// Replace fillbit characters at the end of the encoded string.
$encodedStrLen = ($byteCount + $fillbyteCount) * 8 / 5;
$fillbitCharCount = (int) ($fillbyteCount * 8 / 5);
$encodedStr = substr($encodedStr, 0, $encodedStrLen - $fillbitCharCount);
if ($pad)
$encodedStr .= str_repeat($alphabet[32], $fillbitCharCount);
// Return encoded string.
return $encodedStr;
} | php | {
"resource": ""
} |
q5792 | Base32.decodeToByteStr | train | public static function decodeToByteStr($encodedStr, $allowOmittedPadding = false) {
// Check input string.
$pattern = '/[A-Z2-7]*([A-Z2-7]={0,6})?/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, self::$_commonFlippedAlphabet, '=', $allowOmittedPadding);
// Return byte-string.
return $byteStr;
} | php | {
"resource": ""
} |
q5793 | Base32.decodeHexToByteStr | train | public static function decodeHexToByteStr($encodedStr, $allowOmittedPadding = false) {
// Check input string.
$pattern = '/[0-9A-V]*([0-9A-V]={0,6})?/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, self::$_hexFlippedAlphabet, '=', $allowOmittedPadding);
// Return byte-string.
return $byteStr;
} | php | {
"resource": ""
} |
q5794 | Base32._decodeCrockford | train | private static function _decodeCrockford($to, $encodedStr, $hasCheckSymbol = false) {
// Check input string.
if ($hasCheckSymbol) {
$pattern = '/[0-9A-TV-Z-]*[0-9A-Z*~$=]-*/i';
} else {
$pattern = '/[0-9A-TV-Z-]*/i';
}
self::_checkEncodedString($encodedStr, $pattern);
// Remove hyphens from encoded string.
$encodedStr = str_replace('-', '', $encodedStr);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// If the last character is a valid Crockford check symbol, remove it from
// the encoded string.
if ($hasCheckSymbol) {
$checkSymbol = $encodedStr[$encodedStrLen - 1];
$encodedStr = self::_extractBytes($encodedStr, 0, $encodedStrLen - 1);
$encodedStrLen--;
}
// Compose Crockford decoding mapping.
$mapping = self::$_crockfordFlippedAlphabet + self::$_crockfordAdditionalCharMapping + array('_' => 0);
// Get decoded content.
if ($to == 'byteStr') {
$decoded = self::_decodeToByteStr($encodedStr, $encodedStrLen, $mapping, '_', true);
} elseif ($to == 'intStr') {
$decoded = self::_crockfordDecodeToIntStr($encodedStr, $encodedStrLen, $mapping);
}
// If check symbol is present, check if decoded string is correct.
if ($hasCheckSymbol) {
if ($to == 'byteStr') {
$intStr = self::_byteStrToIntStr($decoded);
} elseif ($to == 'intStr') {
$intStr = $decoded;
}
$modulus = (int) self::_intStrModulus($intStr, 37);
if ($modulus != $mapping[$checkSymbol]) {
throw new UnexpectedValueException('Check symbol does not match data.', self::E_CHECKSYMBOL_DOES_NOT_MATCH_DATA);
}
}
// Return byte-string.
return $decoded;
} | php | {
"resource": ""
} |
q5795 | Base32.decodeZookoToByteStr | train | public static function decodeZookoToByteStr($encodedStr) {
// Check input string.
$pattern = '/[a-km-uw-z13-9]*/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Add padding character to mapping.
$mapping = self::$_zookoFlippedAlphabet + array('_' => 0);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, $mapping, '_', true);
// Return byte-string.
return $byteStr;
} | php | {
"resource": ""
} |
q5796 | Base32._crockfordDecodeToIntStr | train | private static function _crockfordDecodeToIntStr($encodedStr, $encodedStrLen, $mapping) {
// Try to use PHP's internal integer type.
if (($encodedStrLen * 5 / 8) <= PHP_INT_SIZE) {
$int = 0;
for ($i = 0; $i < $encodedStrLen; $i++) {
$int <<= 5;
$int |= $mapping[$encodedStr[$i]];
}
if ($int >= 0)
return $int;
}
// If we did not already return here, PHP's internal integer type can not
// hold the encoded value. Now we use PHP's BC Math library instead and
// return the integer as string.
if (extension_loaded('bcmath')) {
$intStr = '0';
for ($i = 0; $i < $encodedStrLen; $i++) {
$intStr = bcmul($intStr, '32', 0);
$intStr = bcadd($intStr, (string) $mapping[$encodedStr[$i]], 0);
}
return $intStr;
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
} | php | {
"resource": ""
} |
q5797 | WebhookHandler.eachPayment | train | public function eachPayment($callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException("Argument must be callable");
}
foreach ($this->payments as $payment) {
call_user_func_array($callback, array($payment));
}
} | php | {
"resource": ""
} |
q5798 | WebhookHandler.isValidHookHash | train | private function isValidHookHash($privateKey)
{
$confirmationHash = hash('sha256', $privateKey.$this->hookAction.$this->hookDate);
return ($this->hookHash === $confirmationHash);
} | php | {
"resource": ""
} |
q5799 | CliFactory.getInstance | train | public static function getInstance(OutputInterface $output, InputInterface $input)
{
$questionHelper = new QuestionHelper();
$application = new Application('Code Generator Command Line Interface', 'Alpha');
$application->getHelperSet()->set(new FormatterHelper(), 'formatter');
$application->getHelperSet()->set($questionHelper, 'question');
$context = new CliContext(
$questionHelper,
$output,
$input,
CreateCommandFactory::getInstance($application)
);
$mainBackbone = MainBackboneFactory::getInstance($context);
$mainBackbone->run();
return $application;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.