_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 33 8k | 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(
| 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(
| php | {
"resource": ""
} |
q5702 | BaseApplication.getUserRole | train | public function getUserRole() {
return isset($_SESSION[$this->config->roleSessionVar]) | 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 | php | {
"resource": ""
} |
q5704 | BaseApplication.getSource | train | public function getSource() {
$source = $this->config->getSource($this->request->source);
if (!$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(
| php | {
"resource": ""
} |
q5706 | BasicHttpClient.addDefaultParameters | train | protected function addDefaultParameters(&$request)
{
$defaultParameters = array(
'all'=>1,
'dir'=>'ASC',
'start'=>0,
'limit'=>999999999); | 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);
| php | {
"resource": ""
} |
q5708 | Tvheadend.getNodeData | train | public function getNodeData($uuid)
{
$request = new client\Request('/api/idnode/load', array(
'uuid'=>$uuid,
'meta'=>0));
| php | {
"resource": ""
} |
q5709 | Tvheadend.createNetwork | train | public function createNetwork($network)
{
$request = new client\Request('/api/mpegts/network/create', | php | {
"resource": ""
} |
q5710 | Tvheadend.getNetwork | train | public function getNetwork($name)
{
// TODO: Use filtering
$networks = $this->getNetworks();
foreach ($networks as $network)
| php | {
"resource": ""
} |
q5711 | Tvheadend.createMultiplex | train | public function createMultiplex($network, $multiplex)
{
$request = new client\Request('/api/mpegts/network/mux_create', | 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 = | 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();
| php | {
"resource": ""
} |
q5714 | Tvheadend.generateCometPollBoxId | train | private function generateCometPollBoxId()
{
$request = new client\Request('/comet/poll');
$response | php | {
"resource": ""
} |
q5715 | Tvheadend.ensureValidBoxId | train | private function ensureValidBoxId($class)
{
if (!array_key_exists($class, $this->_boxIds) | 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());
| 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) {
| 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 | {
"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', | 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);
| php | {
"resource": ""
} |
q5721 | AttributeForm._parseClassWithOptions | train | private function _parseClassWithOptions($classWithOptions)
{
$config = explode(':', $classWithOptions);
$class = array_shift($config);
//zwrot konfiguracji
| 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] === '-') {
| 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) | php | {
"resource": ""
} |
q5724 | Builder.setTables | train | public function setTables()
{
foreach ($this->data['tables'] as $alias => $model) {
| 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);
| 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 | 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
| 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) {
| 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)}();
}
| php | {
"resource": ""
} |
q5730 | Builder.ftFilter | train | protected function ftFilter($type)
{
if ($type === Column::TYPE_TEXT)
{
return array_map(function ($v) | 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) {
| 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 = [];
| 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')) {
| 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) | php | {
"resource": ""
} |
q5735 | JParserBase.parse_string | train | static function parse_string( $src, $unicode = true, $parser = __CLASS__, $lexer = 'JTokenizer' ){
$Tokenizer = new $lexer( false, $unicode);
$tokens = | php | {
"resource": ""
} |
q5736 | Bag.set | train | public function set($property, $value)
{
$defaultCurrentValue = [];
$data = $this->session->get($this->_name, $defaultCurrentValue);
| php | {
"resource": ""
} |
q5737 | Bag.get | train | public function get($property = null, $default = null)
{
$defaultCurrentValue = [];
$data = $this->session->get($this->_name, $defaultCurrentValue);
| php | {
"resource": ""
} |
q5738 | Bag.has | train | public function has($property)
{
$defaultCurrentValue = [];
$data | php | {
"resource": ""
} |
q5739 | MoveTemplateFilesToRootFolder.getTargetPath | train | protected function getTargetPath($pathname)
{
$filesystem = new Filesystem();
$templatesFolder = $this->getConfigKey('Folders', 'templates');
$folderDiff = '/' . $filesystem->findShortestPath(
SetupHelper::getRootFolder(),
| 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) === | 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;
| 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;
| 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;
| 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 != | 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 {
| 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));
} | 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);
| php | {
"resource": ""
} |
q5748 | Model.getSource | train | public function getSource($context = null)
{
$class = static::class;
return | 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]); | php | {
"resource": ""
} |
q5750 | Model.avg | train | public static function avg($field, $filters = null)
{
| 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) {
| php | {
"resource": ""
} |
q5752 | Model.delete | train | public function delete()
{
$this->eventsManager->fireEvent('model:beforeDelete', $this);
static::query(null, $this)->where($this->_getPrimaryKeyValuePairs())->delete();
| 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 | 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 = [];
| 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) { | php | {
"resource": ""
} |
q5756 | User.hasRole | train | public function hasRole($role = "general")
{
$roleModel = new \erdiko\users\models\Role;
$roleEntity = $roleModel->findByName($role);
if (empty($roleEntity)) {
| 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 | 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);
}
| 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,
| php | {
"resource": ""
} |
q5760 | EngineDataForQuestion.setShutdownWithoutResponse | train | public function setShutdownWithoutResponse($value, $customeExceptionMessage = null)
{
| 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)
| 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;
| 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';
| 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' => | 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;
| 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()) {
| 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)
| 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')) {
| 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
| 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
| 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
| 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
| 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
| php | {
"resource": ""
} |
q5774 | Stat.getUniqueObjects | train | public static function getUniqueObjects()
{
$all = (new Orm\CmsStatDateQuery)
->whereHour()->equals(null)
->andFieldDay()->equals(null)
->andFieldMonth()->equals(null)
| 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
| 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(
| php | {
"resource": ""
} |
q5777 | ApiKeyAuthenticationHandler.resolveObject | train | private function resolveObject($loginProperty, array $credentials)
{
return $this->om->getRepository($this->modelName)->findOneBy([
| php | {
"resource": ""
} |
q5778 | ApiKeyAuthenticationHandler.validateCredentials | train | private function validateCredentials($object, $password)
{
return !(
null === $object
| php | {
"resource": ""
} |
q5779 | ApiKeyAuthenticationHandler.buildEventObject | train | private function buildEventObject($user, $purgeJob = false)
{
$event = new OnLogoutEvent($user);
if ($purgeJob) {
| php | {
"resource": ""
} |
q5780 | UserLogEntry.fill | train | private function fill(array $args)
{
$properties = array_keys(get_object_vars($this));
foreach ($args as $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' | 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-' | 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 | 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) {
| php | {
"resource": ""
} |
q5785 | SessionCleanupCommand.searchUsers | train | private function searchUsers()
{
$criteria = Criteria::create()
->where(Criteria::expr()->lte(
$this->classMetadata->getPropertyName(ClassMetadata::LAST_ACTION_PROPERTY),
| 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 {
| php | {
"resource": ""
} |
q5787 | Base32._extractBytes | train | private static function _extractBytes($byteString, $start, $length) {
if (function_exists('mb_substr')) { | 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 | 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
| 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')) {
| 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 | 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);
// | 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);
| 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);
}
| 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 + | 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 | php | {
"resource": ""
} |
q5797 | WebhookHandler.eachPayment | train | public function eachPayment($callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException("Argument must be callable");
}
| php | {
"resource": ""
} |
q5798 | WebhookHandler.isValidHookHash | train | private function isValidHookHash($privateKey)
{
$confirmationHash = hash('sha256', $privateKey.$this->hookAction.$this->hookDate);
| 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(
| php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.