repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
concrete5/concrete5
concrete/src/Package/PackageService.php
PackageService.getClass
public function getClass($pkgHandle) { $cache = $this->application->make('cache/request'); $item = $cache->getItem('package/class/' . $pkgHandle); $cl = $item->get(); if ($item->isMiss()) { $item->lock(); // loads and instantiates the object $cl = \Concrete\Core\Foundation\ClassLoader::getInstance(); $cl->registerPackageController($pkgHandle); $class = '\\Concrete\\Package\\' . camelcase($pkgHandle) . '\\Controller'; try { $cl = $this->application->make($class); } catch (\Exception $ex) { $cl = $this->application->make('Concrete\Core\Package\BrokenPackage', [$pkgHandle]); } $cache->save($item->set($cl)); } return clone $cl; }
php
public function getClass($pkgHandle) { $cache = $this->application->make('cache/request'); $item = $cache->getItem('package/class/' . $pkgHandle); $cl = $item->get(); if ($item->isMiss()) { $item->lock(); // loads and instantiates the object $cl = \Concrete\Core\Foundation\ClassLoader::getInstance(); $cl->registerPackageController($pkgHandle); $class = '\\Concrete\\Package\\' . camelcase($pkgHandle) . '\\Controller'; try { $cl = $this->application->make($class); } catch (\Exception $ex) { $cl = $this->application->make('Concrete\Core\Package\BrokenPackage', [$pkgHandle]); } $cache->save($item->set($cl)); } return clone $cl; }
[ "public", "function", "getClass", "(", "$", "pkgHandle", ")", "{", "$", "cache", "=", "$", "this", "->", "application", "->", "make", "(", "'cache/request'", ")", ";", "$", "item", "=", "$", "cache", "->", "getItem", "(", "'package/class/'", ".", "$", "pkgHandle", ")", ";", "$", "cl", "=", "$", "item", "->", "get", "(", ")", ";", "if", "(", "$", "item", "->", "isMiss", "(", ")", ")", "{", "$", "item", "->", "lock", "(", ")", ";", "// loads and instantiates the object", "$", "cl", "=", "\\", "Concrete", "\\", "Core", "\\", "Foundation", "\\", "ClassLoader", "::", "getInstance", "(", ")", ";", "$", "cl", "->", "registerPackageController", "(", "$", "pkgHandle", ")", ";", "$", "class", "=", "'\\\\Concrete\\\\Package\\\\'", ".", "camelcase", "(", "$", "pkgHandle", ")", ".", "'\\\\Controller'", ";", "try", "{", "$", "cl", "=", "$", "this", "->", "application", "->", "make", "(", "$", "class", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "$", "cl", "=", "$", "this", "->", "application", "->", "make", "(", "'Concrete\\Core\\Package\\BrokenPackage'", ",", "[", "$", "pkgHandle", "]", ")", ";", "}", "$", "cache", "->", "save", "(", "$", "item", "->", "set", "(", "$", "cl", ")", ")", ";", "}", "return", "clone", "$", "cl", ";", "}" ]
Get the controller of a package given its handle. @param string $pkgHandle Handle of package @return Package
[ "Get", "the", "controller", "of", "a", "package", "given", "its", "handle", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Package/PackageService.php#L265-L287
train
concrete5/concrete5
concrete/src/Localization/Translation/Local/Stats.php
Stats.getFileDisplayName
public function getFileDisplayName() { $base = str_replace(DIRECTORY_SEPARATOR, '/', DIR_BASE); if (strpos($this->filename, $base) === 0) { $path = substr($this->filename, strlen($base) + 1); } else { $path = $this->filename; } return str_replace('/', DIRECTORY_SEPARATOR, $path); }
php
public function getFileDisplayName() { $base = str_replace(DIRECTORY_SEPARATOR, '/', DIR_BASE); if (strpos($this->filename, $base) === 0) { $path = substr($this->filename, strlen($base) + 1); } else { $path = $this->filename; } return str_replace('/', DIRECTORY_SEPARATOR, $path); }
[ "public", "function", "getFileDisplayName", "(", ")", "{", "$", "base", "=", "str_replace", "(", "DIRECTORY_SEPARATOR", ",", "'/'", ",", "DIR_BASE", ")", ";", "if", "(", "strpos", "(", "$", "this", "->", "filename", ",", "$", "base", ")", "===", "0", ")", "{", "$", "path", "=", "substr", "(", "$", "this", "->", "filename", ",", "strlen", "(", "$", "base", ")", "+", "1", ")", ";", "}", "else", "{", "$", "path", "=", "$", "this", "->", "filename", ";", "}", "return", "str_replace", "(", "'/'", ",", "DIRECTORY_SEPARATOR", ",", "$", "path", ")", ";", "}" ]
Get the display name of the translation file. @return string
[ "Get", "the", "display", "name", "of", "the", "translation", "file", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Localization/Translation/Local/Stats.php#L75-L85
train
concrete5/concrete5
concrete/src/User/Event/DeactivateUser.php
DeactivateUser.create
public static function create(UserEntity $userEntity, UserEntity $actorEntity = null, DateTime $dateCreated = null) { return new self($userEntity, $actorEntity, $dateCreated); }
php
public static function create(UserEntity $userEntity, UserEntity $actorEntity = null, DateTime $dateCreated = null) { return new self($userEntity, $actorEntity, $dateCreated); }
[ "public", "static", "function", "create", "(", "UserEntity", "$", "userEntity", ",", "UserEntity", "$", "actorEntity", "=", "null", ",", "DateTime", "$", "dateCreated", "=", "null", ")", "{", "return", "new", "self", "(", "$", "userEntity", ",", "$", "actorEntity", ",", "$", "dateCreated", ")", ";", "}" ]
Factory method for creating new User event objects @param \Concrete\Core\Entity\User\User $userEntity The user being deactivated @param \Concrete\Core\Entity\User\User|null $actorEntity The user running the deactivate action @param \DateTime|null $dateCreated @return \Concrete\Core\User\Event\DeactivateUser
[ "Factory", "method", "for", "creating", "new", "User", "event", "objects" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/Event/DeactivateUser.php#L110-L113
train
concrete5/concrete5
concrete/src/File/Service/Mime.php
Mime.mimeFromExtension
public function mimeFromExtension($ext) { $ext = strtolower($ext); if (array_key_exists($ext, self::$mime_types_and_extensions)) { return self::$mime_types_and_extensions[$ext]; } return false; }
php
public function mimeFromExtension($ext) { $ext = strtolower($ext); if (array_key_exists($ext, self::$mime_types_and_extensions)) { return self::$mime_types_and_extensions[$ext]; } return false; }
[ "public", "function", "mimeFromExtension", "(", "$", "ext", ")", "{", "$", "ext", "=", "strtolower", "(", "$", "ext", ")", ";", "if", "(", "array_key_exists", "(", "$", "ext", ",", "self", "::", "$", "mime_types_and_extensions", ")", ")", "{", "return", "self", "::", "$", "mime_types_and_extensions", "[", "$", "ext", "]", ";", "}", "return", "false", ";", "}" ]
Converts a file extension into a mime type. @param string $ext @return string|bool mime type string or false
[ "Converts", "a", "file", "extension", "into", "a", "mime", "type", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Service/Mime.php#L95-L103
train
concrete5/concrete5
concrete/src/Localization/LocalizationEssentialServiceProvider.php
LocalizationEssentialServiceProvider.register
public function register() { if (!$this->app->bound(TranslatorAdapterFactoryInterface::class)) { $this->app->bind(TranslatorAdapterFactoryInterface::class, function ($app, $params) { $config = $app->make('config'); $loaders = $config->get('i18n.adapters.zend.loaders', []); $loaderRepository = new TranslationLoaderRepository(); foreach ($loaders as $key => $class) { $loader = $app->build($class, [$app]); $loaderRepository->registerTranslationLoader($key, $loader); } $serviceManager = new ServiceManager(); $loaderPluginManager = new LoaderPluginManager( $serviceManager, [ 'factories' => [ GettextLoader::class => function($creationContext, $resolvedName, $options) { return $this->app->build(GettextLoader::class, ['webrootDirectory' => DIR_BASE]); } ], 'aliases' => [ 'gettext' => GettextLoader::class, ], ] ); $zendFactory = new ZendTranslatorAdapterFactory($loaderRepository, $loaderPluginManager); $plainFactory = new PlainTranslatorAdapterFactory(); return new CoreTranslatorAdapterFactory($config, $plainFactory, $zendFactory); }); } $this->app->singleton(Localization::class, function ($app) { $loc = new Localization(); $translatorAdapterFactory = $app->make(TranslatorAdapterFactoryInterface::class); $repository = new TranslatorAdapterRepository($translatorAdapterFactory); $loc->setTranslatorAdapterRepository($repository); $loc->setActiveContext(Localization::CONTEXT_UI); return $loc; }); }
php
public function register() { if (!$this->app->bound(TranslatorAdapterFactoryInterface::class)) { $this->app->bind(TranslatorAdapterFactoryInterface::class, function ($app, $params) { $config = $app->make('config'); $loaders = $config->get('i18n.adapters.zend.loaders', []); $loaderRepository = new TranslationLoaderRepository(); foreach ($loaders as $key => $class) { $loader = $app->build($class, [$app]); $loaderRepository->registerTranslationLoader($key, $loader); } $serviceManager = new ServiceManager(); $loaderPluginManager = new LoaderPluginManager( $serviceManager, [ 'factories' => [ GettextLoader::class => function($creationContext, $resolvedName, $options) { return $this->app->build(GettextLoader::class, ['webrootDirectory' => DIR_BASE]); } ], 'aliases' => [ 'gettext' => GettextLoader::class, ], ] ); $zendFactory = new ZendTranslatorAdapterFactory($loaderRepository, $loaderPluginManager); $plainFactory = new PlainTranslatorAdapterFactory(); return new CoreTranslatorAdapterFactory($config, $plainFactory, $zendFactory); }); } $this->app->singleton(Localization::class, function ($app) { $loc = new Localization(); $translatorAdapterFactory = $app->make(TranslatorAdapterFactoryInterface::class); $repository = new TranslatorAdapterRepository($translatorAdapterFactory); $loc->setTranslatorAdapterRepository($repository); $loc->setActiveContext(Localization::CONTEXT_UI); return $loc; }); }
[ "public", "function", "register", "(", ")", "{", "if", "(", "!", "$", "this", "->", "app", "->", "bound", "(", "TranslatorAdapterFactoryInterface", "::", "class", ")", ")", "{", "$", "this", "->", "app", "->", "bind", "(", "TranslatorAdapterFactoryInterface", "::", "class", ",", "function", "(", "$", "app", ",", "$", "params", ")", "{", "$", "config", "=", "$", "app", "->", "make", "(", "'config'", ")", ";", "$", "loaders", "=", "$", "config", "->", "get", "(", "'i18n.adapters.zend.loaders'", ",", "[", "]", ")", ";", "$", "loaderRepository", "=", "new", "TranslationLoaderRepository", "(", ")", ";", "foreach", "(", "$", "loaders", "as", "$", "key", "=>", "$", "class", ")", "{", "$", "loader", "=", "$", "app", "->", "build", "(", "$", "class", ",", "[", "$", "app", "]", ")", ";", "$", "loaderRepository", "->", "registerTranslationLoader", "(", "$", "key", ",", "$", "loader", ")", ";", "}", "$", "serviceManager", "=", "new", "ServiceManager", "(", ")", ";", "$", "loaderPluginManager", "=", "new", "LoaderPluginManager", "(", "$", "serviceManager", ",", "[", "'factories'", "=>", "[", "GettextLoader", "::", "class", "=>", "function", "(", "$", "creationContext", ",", "$", "resolvedName", ",", "$", "options", ")", "{", "return", "$", "this", "->", "app", "->", "build", "(", "GettextLoader", "::", "class", ",", "[", "'webrootDirectory'", "=>", "DIR_BASE", "]", ")", ";", "}", "]", ",", "'aliases'", "=>", "[", "'gettext'", "=>", "GettextLoader", "::", "class", ",", "]", ",", "]", ")", ";", "$", "zendFactory", "=", "new", "ZendTranslatorAdapterFactory", "(", "$", "loaderRepository", ",", "$", "loaderPluginManager", ")", ";", "$", "plainFactory", "=", "new", "PlainTranslatorAdapterFactory", "(", ")", ";", "return", "new", "CoreTranslatorAdapterFactory", "(", "$", "config", ",", "$", "plainFactory", ",", "$", "zendFactory", ")", ";", "}", ")", ";", "}", "$", "this", "->", "app", "->", "singleton", "(", "Localization", "::", "class", ",", "function", "(", "$", "app", ")", "{", "$", "loc", "=", "new", "Localization", "(", ")", ";", "$", "translatorAdapterFactory", "=", "$", "app", "->", "make", "(", "TranslatorAdapterFactoryInterface", "::", "class", ")", ";", "$", "repository", "=", "new", "TranslatorAdapterRepository", "(", "$", "translatorAdapterFactory", ")", ";", "$", "loc", "->", "setTranslatorAdapterRepository", "(", "$", "repository", ")", ";", "$", "loc", "->", "setActiveContext", "(", "Localization", "::", "CONTEXT_UI", ")", ";", "return", "$", "loc", ";", "}", ")", ";", "}" ]
Services that are essential for the loading of the localization functionality.
[ "Services", "that", "are", "essential", "for", "the", "loading", "of", "the", "localization", "functionality", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Localization/LocalizationEssentialServiceProvider.php#L21-L66
train
concrete5/concrete5
concrete/src/Editor/CkeditorEditor.php
CkeditorEditor.getEditorInitJSFunction
public function getEditorInitJSFunction($dynamicOptions = []) { $pluginManager = $this->getPluginManager(); if ($this->allowFileManager()) { $pluginManager->select(['concrete5filemanager', 'concrete5uploadimage']); } else { $pluginManager->deselect(['concrete5filemanager', 'concrete5uploadimage']); } $this->requireEditorAssets(); $plugins = $pluginManager->getSelectedPlugins(); $snippetsAndClasses = $this->getEditorSnippetsAndClasses(); if (!is_array($dynamicOptions)) { $dynamicOptions = []; } $defaultOptions = [ 'plugins' => implode(',', $plugins), 'stylesSet' => 'concrete5styles', 'filebrowserBrowseUrl' => 'a', 'uploadUrl' => (string) URL::to('/ccm/system/file/upload'), 'language' => $this->getLanguageOption(), 'customConfig' => '', 'allowedContent' => true, 'baseFloatZIndex' => 1990, /* Must come below modal variable in variables.less */ 'image2_captionedClass' => 'content-editor-image-captioned', 'image2_alignClasses' => [ 'content-editor-image-left', 'content-editor-image-center', 'content-editor-image-right', ], 'toolbarGroups' => $this->config->get('editor.ckeditor4.toolbar_groups'), 'snippets' => $snippetsAndClasses->snippets, 'classes' => $snippetsAndClasses->classes, 'sitemap' => $this->allowSitemap() ]; $customOptions = $this->config->get('editor.ckeditor4.custom_config_options'); if (!is_array($customOptions)) { $customOptions = []; } $options = json_encode($dynamicOptions + $customOptions + $defaultOptions); $removeEmptyIcon = '$removeEmpty[\'i\']'; $jsfunc = <<<EOL function(identifier) { window.CCM_EDITOR_SECURITY_TOKEN = "{$this->token}"; CKEDITOR.dtd.{$removeEmptyIcon} = false; if (CKEDITOR.stylesSet.get('concrete5styles') === null) { CKEDITOR.stylesSet.add('concrete5styles', {$this->getStylesJson()}); } var ckeditor = $(identifier).ckeditor({$options}).editor; ckeditor.on('blur',function(){ return false; }); ckeditor.on('remove', function(){ $(this).destroy(); }); if (CKEDITOR.env.ie) { ckeditor.on('ariaWidget', function (e) { setTimeout(function() { var \$contents = $(e.editor.ui.contentsElement.$), \$textarea = \$contents.find('>textarea.cke_source'); if (\$textarea.length === 1) { \$textarea.css({ width: \$contents.innerWidth() + 'px', height: \$contents.innerHeight() + 'px' }); } }, 50); }); } {$this->config->get('editor.ckeditor4.editor_function_options')} } EOL; return $jsfunc; }
php
public function getEditorInitJSFunction($dynamicOptions = []) { $pluginManager = $this->getPluginManager(); if ($this->allowFileManager()) { $pluginManager->select(['concrete5filemanager', 'concrete5uploadimage']); } else { $pluginManager->deselect(['concrete5filemanager', 'concrete5uploadimage']); } $this->requireEditorAssets(); $plugins = $pluginManager->getSelectedPlugins(); $snippetsAndClasses = $this->getEditorSnippetsAndClasses(); if (!is_array($dynamicOptions)) { $dynamicOptions = []; } $defaultOptions = [ 'plugins' => implode(',', $plugins), 'stylesSet' => 'concrete5styles', 'filebrowserBrowseUrl' => 'a', 'uploadUrl' => (string) URL::to('/ccm/system/file/upload'), 'language' => $this->getLanguageOption(), 'customConfig' => '', 'allowedContent' => true, 'baseFloatZIndex' => 1990, /* Must come below modal variable in variables.less */ 'image2_captionedClass' => 'content-editor-image-captioned', 'image2_alignClasses' => [ 'content-editor-image-left', 'content-editor-image-center', 'content-editor-image-right', ], 'toolbarGroups' => $this->config->get('editor.ckeditor4.toolbar_groups'), 'snippets' => $snippetsAndClasses->snippets, 'classes' => $snippetsAndClasses->classes, 'sitemap' => $this->allowSitemap() ]; $customOptions = $this->config->get('editor.ckeditor4.custom_config_options'); if (!is_array($customOptions)) { $customOptions = []; } $options = json_encode($dynamicOptions + $customOptions + $defaultOptions); $removeEmptyIcon = '$removeEmpty[\'i\']'; $jsfunc = <<<EOL function(identifier) { window.CCM_EDITOR_SECURITY_TOKEN = "{$this->token}"; CKEDITOR.dtd.{$removeEmptyIcon} = false; if (CKEDITOR.stylesSet.get('concrete5styles') === null) { CKEDITOR.stylesSet.add('concrete5styles', {$this->getStylesJson()}); } var ckeditor = $(identifier).ckeditor({$options}).editor; ckeditor.on('blur',function(){ return false; }); ckeditor.on('remove', function(){ $(this).destroy(); }); if (CKEDITOR.env.ie) { ckeditor.on('ariaWidget', function (e) { setTimeout(function() { var \$contents = $(e.editor.ui.contentsElement.$), \$textarea = \$contents.find('>textarea.cke_source'); if (\$textarea.length === 1) { \$textarea.css({ width: \$contents.innerWidth() + 'px', height: \$contents.innerHeight() + 'px' }); } }, 50); }); } {$this->config->get('editor.ckeditor4.editor_function_options')} } EOL; return $jsfunc; }
[ "public", "function", "getEditorInitJSFunction", "(", "$", "dynamicOptions", "=", "[", "]", ")", "{", "$", "pluginManager", "=", "$", "this", "->", "getPluginManager", "(", ")", ";", "if", "(", "$", "this", "->", "allowFileManager", "(", ")", ")", "{", "$", "pluginManager", "->", "select", "(", "[", "'concrete5filemanager'", ",", "'concrete5uploadimage'", "]", ")", ";", "}", "else", "{", "$", "pluginManager", "->", "deselect", "(", "[", "'concrete5filemanager'", ",", "'concrete5uploadimage'", "]", ")", ";", "}", "$", "this", "->", "requireEditorAssets", "(", ")", ";", "$", "plugins", "=", "$", "pluginManager", "->", "getSelectedPlugins", "(", ")", ";", "$", "snippetsAndClasses", "=", "$", "this", "->", "getEditorSnippetsAndClasses", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "dynamicOptions", ")", ")", "{", "$", "dynamicOptions", "=", "[", "]", ";", "}", "$", "defaultOptions", "=", "[", "'plugins'", "=>", "implode", "(", "','", ",", "$", "plugins", ")", ",", "'stylesSet'", "=>", "'concrete5styles'", ",", "'filebrowserBrowseUrl'", "=>", "'a'", ",", "'uploadUrl'", "=>", "(", "string", ")", "URL", "::", "to", "(", "'/ccm/system/file/upload'", ")", ",", "'language'", "=>", "$", "this", "->", "getLanguageOption", "(", ")", ",", "'customConfig'", "=>", "''", ",", "'allowedContent'", "=>", "true", ",", "'baseFloatZIndex'", "=>", "1990", ",", "/* Must come below modal variable in variables.less */", "'image2_captionedClass'", "=>", "'content-editor-image-captioned'", ",", "'image2_alignClasses'", "=>", "[", "'content-editor-image-left'", ",", "'content-editor-image-center'", ",", "'content-editor-image-right'", ",", "]", ",", "'toolbarGroups'", "=>", "$", "this", "->", "config", "->", "get", "(", "'editor.ckeditor4.toolbar_groups'", ")", ",", "'snippets'", "=>", "$", "snippetsAndClasses", "->", "snippets", ",", "'classes'", "=>", "$", "snippetsAndClasses", "->", "classes", ",", "'sitemap'", "=>", "$", "this", "->", "allowSitemap", "(", ")", "]", ";", "$", "customOptions", "=", "$", "this", "->", "config", "->", "get", "(", "'editor.ckeditor4.custom_config_options'", ")", ";", "if", "(", "!", "is_array", "(", "$", "customOptions", ")", ")", "{", "$", "customOptions", "=", "[", "]", ";", "}", "$", "options", "=", "json_encode", "(", "$", "dynamicOptions", "+", "$", "customOptions", "+", "$", "defaultOptions", ")", ";", "$", "removeEmptyIcon", "=", "'$removeEmpty[\\'i\\']'", ";", "$", "jsfunc", "=", " <<<EOL\n function(identifier) {\n window.CCM_EDITOR_SECURITY_TOKEN = \"{$this->token}\";\n CKEDITOR.dtd.{$removeEmptyIcon} = false;\n if (CKEDITOR.stylesSet.get('concrete5styles') === null) {\n CKEDITOR.stylesSet.add('concrete5styles', {$this->getStylesJson()});\n }\n var ckeditor = $(identifier).ckeditor({$options}).editor;\n ckeditor.on('blur',function(){\n return false;\n });\n ckeditor.on('remove', function(){\n $(this).destroy();\n });\n if (CKEDITOR.env.ie) {\n ckeditor.on('ariaWidget', function (e) {\n setTimeout(function() {\n var \\$contents = $(e.editor.ui.contentsElement.$),\n \\$textarea = \\$contents.find('>textarea.cke_source');\n if (\\$textarea.length === 1) {\n \\$textarea.css({\n width: \\$contents.innerWidth() + 'px',\n height: \\$contents.innerHeight() + 'px'\n });\n }\n }, 50);\n });\n }\n {$this->config->get('editor.ckeditor4.editor_function_options')}\n }\nEOL", ";", "return", "$", "jsfunc", ";", "}" ]
Generate the Javascript code that initialize the plugin. @param array $dynamicOptions a list of custom options that override the default ones @return string
[ "Generate", "the", "Javascript", "code", "that", "initialize", "the", "plugin", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Editor/CkeditorEditor.php#L93-L173
train
concrete5/concrete5
concrete/src/Editor/CkeditorEditor.php
CkeditorEditor.outputInlineEditorInitJSFunction
public function outputInlineEditorInitJSFunction() { $pluginManager = $this->getPluginManager(); if ($pluginManager->isSelected('autogrow')) { $pluginManager->deselect('autogrow'); } return $this->getEditorInitJSFunction(); }
php
public function outputInlineEditorInitJSFunction() { $pluginManager = $this->getPluginManager(); if ($pluginManager->isSelected('autogrow')) { $pluginManager->deselect('autogrow'); } return $this->getEditorInitJSFunction(); }
[ "public", "function", "outputInlineEditorInitJSFunction", "(", ")", "{", "$", "pluginManager", "=", "$", "this", "->", "getPluginManager", "(", ")", ";", "if", "(", "$", "pluginManager", "->", "isSelected", "(", "'autogrow'", ")", ")", "{", "$", "pluginManager", "->", "deselect", "(", "'autogrow'", ")", ";", "}", "return", "$", "this", "->", "getEditorInitJSFunction", "(", ")", ";", "}" ]
Generate the Javascript code that initialize the plugin when it will be used inline. @return string
[ "Generate", "the", "Javascript", "code", "that", "initialize", "the", "plugin", "when", "it", "will", "be", "used", "inline", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Editor/CkeditorEditor.php#L180-L188
train
concrete5/concrete5
concrete/src/Editor/CkeditorEditor.php
CkeditorEditor.outputStandardEditorInitJSFunction
public function outputStandardEditorInitJSFunction() { $options = [ 'disableAutoInline' => true, ]; $pluginManager = $this->getPluginManager(); if ($pluginManager->isSelected('sourcearea')) { $pluginManager->deselect('sourcedialog'); } return $this->getEditorInitJSFunction($options); }
php
public function outputStandardEditorInitJSFunction() { $options = [ 'disableAutoInline' => true, ]; $pluginManager = $this->getPluginManager(); if ($pluginManager->isSelected('sourcearea')) { $pluginManager->deselect('sourcedialog'); } return $this->getEditorInitJSFunction($options); }
[ "public", "function", "outputStandardEditorInitJSFunction", "(", ")", "{", "$", "options", "=", "[", "'disableAutoInline'", "=>", "true", ",", "]", ";", "$", "pluginManager", "=", "$", "this", "->", "getPluginManager", "(", ")", ";", "if", "(", "$", "pluginManager", "->", "isSelected", "(", "'sourcearea'", ")", ")", "{", "$", "pluginManager", "->", "deselect", "(", "'sourcedialog'", ")", ";", "}", "return", "$", "this", "->", "getEditorInitJSFunction", "(", "$", "options", ")", ";", "}" ]
Generate the standard Javascript code that initialize the plugin. @return string
[ "Generate", "the", "standard", "Javascript", "code", "that", "initialize", "the", "plugin", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Editor/CkeditorEditor.php#L262-L274
train
concrete5/concrete5
concrete/src/Editor/CkeditorEditor.php
CkeditorEditor.getLanguageOption
protected function getLanguageOption() { $langPath = DIR_BASE_CORE . '/js/ckeditor4/vendor/lang/'; $useLanguage = 'en'; $language = strtolower(str_replace('_', '-', Localization::activeLocale())); if (file_exists($langPath . $language . '.js')) { $useLanguage = $language; } elseif (file_exists($langPath . strtolower(Localization::activeLanguage()) . '.js')) { $useLanguage = strtolower(Localization::activeLanguage()); } else { $useLanguage = null; } return $useLanguage; }
php
protected function getLanguageOption() { $langPath = DIR_BASE_CORE . '/js/ckeditor4/vendor/lang/'; $useLanguage = 'en'; $language = strtolower(str_replace('_', '-', Localization::activeLocale())); if (file_exists($langPath . $language . '.js')) { $useLanguage = $language; } elseif (file_exists($langPath . strtolower(Localization::activeLanguage()) . '.js')) { $useLanguage = strtolower(Localization::activeLanguage()); } else { $useLanguage = null; } return $useLanguage; }
[ "protected", "function", "getLanguageOption", "(", ")", "{", "$", "langPath", "=", "DIR_BASE_CORE", ".", "'/js/ckeditor4/vendor/lang/'", ";", "$", "useLanguage", "=", "'en'", ";", "$", "language", "=", "strtolower", "(", "str_replace", "(", "'_'", ",", "'-'", ",", "Localization", "::", "activeLocale", "(", ")", ")", ")", ";", "if", "(", "file_exists", "(", "$", "langPath", ".", "$", "language", ".", "'.js'", ")", ")", "{", "$", "useLanguage", "=", "$", "language", ";", "}", "elseif", "(", "file_exists", "(", "$", "langPath", ".", "strtolower", "(", "Localization", "::", "activeLanguage", "(", ")", ")", ".", "'.js'", ")", ")", "{", "$", "useLanguage", "=", "strtolower", "(", "Localization", "::", "activeLanguage", "(", ")", ")", ";", "}", "else", "{", "$", "useLanguage", "=", "null", ";", "}", "return", "$", "useLanguage", ";", "}" ]
Get the CKEditor language configuration. @return string|null
[ "Get", "the", "CKEditor", "language", "configuration", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Editor/CkeditorEditor.php#L465-L480
train
concrete5/concrete5
concrete/src/Editor/CkeditorEditor.php
CkeditorEditor.getEditorSnippetsAndClasses
private function getEditorSnippetsAndClasses() { $obj = new stdClass(); $obj->snippets = []; $u = new User(); if ($u->isRegistered()) { $snippets = \Concrete\Core\Editor\Snippet::getActiveList(); foreach ($snippets as $sns) { $menu = new stdClass(); $menu->scsHandle = $sns->getSystemContentEditorSnippetHandle(); $menu->scsName = $sns->getSystemContentEditorSnippetName(); $obj->snippets[] = $menu; } } $c = Page::getCurrentPage(); $obj->classes = []; if (is_object($c) && !$c->isError()) { $cp = new Permissions($c); if ($cp->canViewPage()) { $pt = $c->getCollectionThemeObject(); if (is_object($pt)) { if ($pt->getThemeHandle()) { $obj->classes = $pt->getThemeEditorClasses(); } else { $siteTheme = $pt::getSiteTheme(); if (is_object($siteTheme)) { $obj->classes = $siteTheme->getThemeEditorClasses(); } } } } } else { $siteTheme = PageTheme::getSiteTheme(); if (is_object($siteTheme)) { $obj->classes = $siteTheme->getThemeEditorClasses(); } } return $obj; }
php
private function getEditorSnippetsAndClasses() { $obj = new stdClass(); $obj->snippets = []; $u = new User(); if ($u->isRegistered()) { $snippets = \Concrete\Core\Editor\Snippet::getActiveList(); foreach ($snippets as $sns) { $menu = new stdClass(); $menu->scsHandle = $sns->getSystemContentEditorSnippetHandle(); $menu->scsName = $sns->getSystemContentEditorSnippetName(); $obj->snippets[] = $menu; } } $c = Page::getCurrentPage(); $obj->classes = []; if (is_object($c) && !$c->isError()) { $cp = new Permissions($c); if ($cp->canViewPage()) { $pt = $c->getCollectionThemeObject(); if (is_object($pt)) { if ($pt->getThemeHandle()) { $obj->classes = $pt->getThemeEditorClasses(); } else { $siteTheme = $pt::getSiteTheme(); if (is_object($siteTheme)) { $obj->classes = $siteTheme->getThemeEditorClasses(); } } } } } else { $siteTheme = PageTheme::getSiteTheme(); if (is_object($siteTheme)) { $obj->classes = $siteTheme->getThemeEditorClasses(); } } return $obj; }
[ "private", "function", "getEditorSnippetsAndClasses", "(", ")", "{", "$", "obj", "=", "new", "stdClass", "(", ")", ";", "$", "obj", "->", "snippets", "=", "[", "]", ";", "$", "u", "=", "new", "User", "(", ")", ";", "if", "(", "$", "u", "->", "isRegistered", "(", ")", ")", "{", "$", "snippets", "=", "\\", "Concrete", "\\", "Core", "\\", "Editor", "\\", "Snippet", "::", "getActiveList", "(", ")", ";", "foreach", "(", "$", "snippets", "as", "$", "sns", ")", "{", "$", "menu", "=", "new", "stdClass", "(", ")", ";", "$", "menu", "->", "scsHandle", "=", "$", "sns", "->", "getSystemContentEditorSnippetHandle", "(", ")", ";", "$", "menu", "->", "scsName", "=", "$", "sns", "->", "getSystemContentEditorSnippetName", "(", ")", ";", "$", "obj", "->", "snippets", "[", "]", "=", "$", "menu", ";", "}", "}", "$", "c", "=", "Page", "::", "getCurrentPage", "(", ")", ";", "$", "obj", "->", "classes", "=", "[", "]", ";", "if", "(", "is_object", "(", "$", "c", ")", "&&", "!", "$", "c", "->", "isError", "(", ")", ")", "{", "$", "cp", "=", "new", "Permissions", "(", "$", "c", ")", ";", "if", "(", "$", "cp", "->", "canViewPage", "(", ")", ")", "{", "$", "pt", "=", "$", "c", "->", "getCollectionThemeObject", "(", ")", ";", "if", "(", "is_object", "(", "$", "pt", ")", ")", "{", "if", "(", "$", "pt", "->", "getThemeHandle", "(", ")", ")", "{", "$", "obj", "->", "classes", "=", "$", "pt", "->", "getThemeEditorClasses", "(", ")", ";", "}", "else", "{", "$", "siteTheme", "=", "$", "pt", "::", "getSiteTheme", "(", ")", ";", "if", "(", "is_object", "(", "$", "siteTheme", ")", ")", "{", "$", "obj", "->", "classes", "=", "$", "siteTheme", "->", "getThemeEditorClasses", "(", ")", ";", "}", "}", "}", "}", "}", "else", "{", "$", "siteTheme", "=", "PageTheme", "::", "getSiteTheme", "(", ")", ";", "if", "(", "is_object", "(", "$", "siteTheme", ")", ")", "{", "$", "obj", "->", "classes", "=", "$", "siteTheme", "->", "getThemeEditorClasses", "(", ")", ";", "}", "}", "return", "$", "obj", ";", "}" ]
Build an object containing the CKEditor preconfigured snippets and classes. @return \stdClass
[ "Build", "an", "object", "containing", "the", "CKEditor", "preconfigured", "snippets", "and", "classes", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Editor/CkeditorEditor.php#L487-L526
train
concrete5/concrete5
concrete/src/Cache/Driver/RedisStashDriver.php
RedisStashDriver.setOptions
protected function setOptions(array $options = []) { $options += $this->getDefaultOptions(); $this->prefix = !empty($options['prefix']) ? $options['prefix'] : null; // Normalize Server Options $servers = []; foreach ($this->getRedisServers(array_get($options, 'servers', [])) as $server) { $servers[] = $server; } // Get Redis Instance $redis = $this->getRedisInstance($servers); // select database - we use isset because the database can be 0 if (isset($options['database'])) { $redis->select($options['database']); } if (!empty($options['prefix'])) { $redis->setOption(\Redis::OPT_PREFIX, $options['prefix'] . ':'); } $this->redis = $redis; }
php
protected function setOptions(array $options = []) { $options += $this->getDefaultOptions(); $this->prefix = !empty($options['prefix']) ? $options['prefix'] : null; // Normalize Server Options $servers = []; foreach ($this->getRedisServers(array_get($options, 'servers', [])) as $server) { $servers[] = $server; } // Get Redis Instance $redis = $this->getRedisInstance($servers); // select database - we use isset because the database can be 0 if (isset($options['database'])) { $redis->select($options['database']); } if (!empty($options['prefix'])) { $redis->setOption(\Redis::OPT_PREFIX, $options['prefix'] . ':'); } $this->redis = $redis; }
[ "protected", "function", "setOptions", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "+=", "$", "this", "->", "getDefaultOptions", "(", ")", ";", "$", "this", "->", "prefix", "=", "!", "empty", "(", "$", "options", "[", "'prefix'", "]", ")", "?", "$", "options", "[", "'prefix'", "]", ":", "null", ";", "// Normalize Server Options", "$", "servers", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getRedisServers", "(", "array_get", "(", "$", "options", ",", "'servers'", ",", "[", "]", ")", ")", "as", "$", "server", ")", "{", "$", "servers", "[", "]", "=", "$", "server", ";", "}", "// Get Redis Instance", "$", "redis", "=", "$", "this", "->", "getRedisInstance", "(", "$", "servers", ")", ";", "// select database - we use isset because the database can be 0", "if", "(", "isset", "(", "$", "options", "[", "'database'", "]", ")", ")", "{", "$", "redis", "->", "select", "(", "$", "options", "[", "'database'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "options", "[", "'prefix'", "]", ")", ")", "{", "$", "redis", "->", "setOption", "(", "\\", "Redis", "::", "OPT_PREFIX", ",", "$", "options", "[", "'prefix'", "]", ".", "':'", ")", ";", "}", "$", "this", "->", "redis", "=", "$", "redis", ";", "}" ]
The options array should contain an array of servers,. The "server" option expects an array of servers, with each server being represented by an associative array. Each redis config must have either a "socket" or a "server" value, and optional "port" and "ttl" values (with the ttl representing server timeout, not cache expiration). The "database" option lets developers specific which specific database to use. The "password" option is used for clusters which required authentication. @param array $options The `concrete.cache.levels.{level}.drivers.redis.options` config item
[ "The", "options", "array", "should", "contain", "an", "array", "of", "servers", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Cache/Driver/RedisStashDriver.php#L62-L83
train
concrete5/concrete5
concrete/src/Cache/Driver/RedisStashDriver.php
RedisStashDriver.makeKeyString
protected function makeKeyString($key, $path = false) { $key = \Stash\Utilities::normalizeKeys($key); $keyString = 'cache:::'; $pathKey = ':pathdb::'; foreach ($key as $name) { //a. cache:::name //b. cache:::name0:::sub $keyString .= $name; //a. :pathdb::cache:::name //b. :pathdb::cache:::name0:::sub $pathKey = ':pathdb::' . $keyString; $pathKey = md5($pathKey); if (isset($this->keyCache[$pathKey])) { $index = $this->keyCache[$pathKey]; } else { $index = $this->redis->get($pathKey); $this->keyCache[$pathKey] = $index; } //a. cache:::name0::: //b. cache:::name0:::sub1::: $keyString .= '_' . $index . ':::'; } return $path ? $pathKey : md5($keyString); }
php
protected function makeKeyString($key, $path = false) { $key = \Stash\Utilities::normalizeKeys($key); $keyString = 'cache:::'; $pathKey = ':pathdb::'; foreach ($key as $name) { //a. cache:::name //b. cache:::name0:::sub $keyString .= $name; //a. :pathdb::cache:::name //b. :pathdb::cache:::name0:::sub $pathKey = ':pathdb::' . $keyString; $pathKey = md5($pathKey); if (isset($this->keyCache[$pathKey])) { $index = $this->keyCache[$pathKey]; } else { $index = $this->redis->get($pathKey); $this->keyCache[$pathKey] = $index; } //a. cache:::name0::: //b. cache:::name0:::sub1::: $keyString .= '_' . $index . ':::'; } return $path ? $pathKey : md5($keyString); }
[ "protected", "function", "makeKeyString", "(", "$", "key", ",", "$", "path", "=", "false", ")", "{", "$", "key", "=", "\\", "Stash", "\\", "Utilities", "::", "normalizeKeys", "(", "$", "key", ")", ";", "$", "keyString", "=", "'cache:::'", ";", "$", "pathKey", "=", "':pathdb::'", ";", "foreach", "(", "$", "key", "as", "$", "name", ")", "{", "//a. cache:::name", "//b. cache:::name0:::sub", "$", "keyString", ".=", "$", "name", ";", "//a. :pathdb::cache:::name", "//b. :pathdb::cache:::name0:::sub", "$", "pathKey", "=", "':pathdb::'", ".", "$", "keyString", ";", "$", "pathKey", "=", "md5", "(", "$", "pathKey", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "keyCache", "[", "$", "pathKey", "]", ")", ")", "{", "$", "index", "=", "$", "this", "->", "keyCache", "[", "$", "pathKey", "]", ";", "}", "else", "{", "$", "index", "=", "$", "this", "->", "redis", "->", "get", "(", "$", "pathKey", ")", ";", "$", "this", "->", "keyCache", "[", "$", "pathKey", "]", "=", "$", "index", ";", "}", "//a. cache:::name0:::", "//b. cache:::name0:::sub1:::", "$", "keyString", ".=", "'_'", ".", "$", "index", ".", "':::'", ";", "}", "return", "$", "path", "?", "$", "pathKey", ":", "md5", "(", "$", "keyString", ")", ";", "}" ]
Turns a key array into a key string. This includes running the indexing functions used to manage the Redis hierarchical storage. When requested the actual path, rather than a normalized value, is returned. @param array $key @param bool $path @return string
[ "Turns", "a", "key", "array", "into", "a", "key", "string", ".", "This", "includes", "running", "the", "indexing", "functions", "used", "to", "manage", "the", "Redis", "hierarchical", "storage", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Cache/Driver/RedisStashDriver.php#L275-L304
train
concrete5/concrete5
concrete/src/Config/ConfigStore.php
ConfigStore.get
public function get($cfKey, $pkgID = null) { if ($pkgID > 0 && isset($this->rows["{$cfKey}.{$pkgID}"])) { return $this->rowToConfigValue($this->rows["{$cfKey}.{$pkgID}"]); } else { foreach ($this->rows as $row) { if ($row['cfKey'] == $cfKey) { return $this->rowToConfigValue($row); } } } return null; }
php
public function get($cfKey, $pkgID = null) { if ($pkgID > 0 && isset($this->rows["{$cfKey}.{$pkgID}"])) { return $this->rowToConfigValue($this->rows["{$cfKey}.{$pkgID}"]); } else { foreach ($this->rows as $row) { if ($row['cfKey'] == $cfKey) { return $this->rowToConfigValue($row); } } } return null; }
[ "public", "function", "get", "(", "$", "cfKey", ",", "$", "pkgID", "=", "null", ")", "{", "if", "(", "$", "pkgID", ">", "0", "&&", "isset", "(", "$", "this", "->", "rows", "[", "\"{$cfKey}.{$pkgID}\"", "]", ")", ")", "{", "return", "$", "this", "->", "rowToConfigValue", "(", "$", "this", "->", "rows", "[", "\"{$cfKey}.{$pkgID}\"", "]", ")", ";", "}", "else", "{", "foreach", "(", "$", "this", "->", "rows", "as", "$", "row", ")", "{", "if", "(", "$", "row", "[", "'cfKey'", "]", "==", "$", "cfKey", ")", "{", "return", "$", "this", "->", "rowToConfigValue", "(", "$", "row", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
Get a config item. @param string $cfKey @param int $pkgID optional @return ConfigValue|void
[ "Get", "a", "config", "item", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Config/ConfigStore.php#L48-L61
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.getByID
public static function getByID($cnvEditorID) { $db = Database::connection(); $r = $db->fetchAssoc( 'select * from ConversationEditors where cnvEditorID = ?', array($cnvEditorID) ); return static::createFromRecord($r); }
php
public static function getByID($cnvEditorID) { $db = Database::connection(); $r = $db->fetchAssoc( 'select * from ConversationEditors where cnvEditorID = ?', array($cnvEditorID) ); return static::createFromRecord($r); }
[ "public", "static", "function", "getByID", "(", "$", "cnvEditorID", ")", "{", "$", "db", "=", "Database", "::", "connection", "(", ")", ";", "$", "r", "=", "$", "db", "->", "fetchAssoc", "(", "'select *\n from ConversationEditors\n where cnvEditorID = ?'", ",", "array", "(", "$", "cnvEditorID", ")", ")", ";", "return", "static", "::", "createFromRecord", "(", "$", "r", ")", ";", "}" ]
Returns the appropriate conversation editor object for the given cnvEditorID. @param int $cnvEditorID @return Editor|null
[ "Returns", "the", "appropriate", "conversation", "editor", "object", "for", "the", "given", "cnvEditorID", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L154-L165
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.getByHandle
public static function getByHandle($cnvEditorHandle) { $db = Database::connection(); $r = $db->fetchAssoc( 'select * from ConversationEditors where cnvEditorHandle = ?', array($cnvEditorHandle) ); return static::createFromRecord($r); }
php
public static function getByHandle($cnvEditorHandle) { $db = Database::connection(); $r = $db->fetchAssoc( 'select * from ConversationEditors where cnvEditorHandle = ?', array($cnvEditorHandle) ); return static::createFromRecord($r); }
[ "public", "static", "function", "getByHandle", "(", "$", "cnvEditorHandle", ")", "{", "$", "db", "=", "Database", "::", "connection", "(", ")", ";", "$", "r", "=", "$", "db", "->", "fetchAssoc", "(", "'select *\n from ConversationEditors\n where cnvEditorHandle = ?'", ",", "array", "(", "$", "cnvEditorHandle", ")", ")", ";", "return", "static", "::", "createFromRecord", "(", "$", "r", ")", ";", "}" ]
Returns the appropriate conversation editor object for the given cnvEditorHandle. @param $cnvEditorHandle @return Editor|null
[ "Returns", "the", "appropriate", "conversation", "editor", "object", "for", "the", "given", "cnvEditorHandle", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L174-L185
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.createFromRecord
protected static function createFromRecord($record) { if (is_array($record) && $record['cnvEditorHandle']) { /** @var \Concrete\Core\Utility\Service\Text $textHelper */ $textHelper = Core::make('helper/text'); $class = '\\Concrete\\Core\\Conversation\\Editor\\' . $textHelper->camelcase( $record['cnvEditorHandle'] ) . 'Editor'; /** @var Editor $sc Really this could be any kind of editor but this should help code completion a bit */ $sc = Core::make($class); $sc->setPropertiesFromArray($record); return $sc; } return null; }
php
protected static function createFromRecord($record) { if (is_array($record) && $record['cnvEditorHandle']) { /** @var \Concrete\Core\Utility\Service\Text $textHelper */ $textHelper = Core::make('helper/text'); $class = '\\Concrete\\Core\\Conversation\\Editor\\' . $textHelper->camelcase( $record['cnvEditorHandle'] ) . 'Editor'; /** @var Editor $sc Really this could be any kind of editor but this should help code completion a bit */ $sc = Core::make($class); $sc->setPropertiesFromArray($record); return $sc; } return null; }
[ "protected", "static", "function", "createFromRecord", "(", "$", "record", ")", "{", "if", "(", "is_array", "(", "$", "record", ")", "&&", "$", "record", "[", "'cnvEditorHandle'", "]", ")", "{", "/** @var \\Concrete\\Core\\Utility\\Service\\Text $textHelper */", "$", "textHelper", "=", "Core", "::", "make", "(", "'helper/text'", ")", ";", "$", "class", "=", "'\\\\Concrete\\\\Core\\\\Conversation\\\\Editor\\\\'", ".", "$", "textHelper", "->", "camelcase", "(", "$", "record", "[", "'cnvEditorHandle'", "]", ")", ".", "'Editor'", ";", "/** @var Editor $sc Really this could be any kind of editor but this should help code completion a bit */", "$", "sc", "=", "Core", "::", "make", "(", "$", "class", ")", ";", "$", "sc", "->", "setPropertiesFromArray", "(", "$", "record", ")", ";", "return", "$", "sc", ";", "}", "return", "null", ";", "}" ]
This function is used to instantiate a Conversation Editor object from an associative array. @param array $record an associative array of field value pairs for the ConversationEditor record @return Editor|null
[ "This", "function", "is", "used", "to", "instantiate", "a", "Conversation", "Editor", "object", "from", "an", "associative", "array", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L194-L210
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.outputConversationEditorAddMessageForm
public function outputConversationEditorAddMessageForm() { \View::element(DIRNAME_CONVERSATIONS . '/' . DIRNAME_CONVERSATION_EDITOR . '/' . $this->cnvEditorHandle . '/message', ['editor' => $this], $this->getPackageHandle()); }
php
public function outputConversationEditorAddMessageForm() { \View::element(DIRNAME_CONVERSATIONS . '/' . DIRNAME_CONVERSATION_EDITOR . '/' . $this->cnvEditorHandle . '/message', ['editor' => $this], $this->getPackageHandle()); }
[ "public", "function", "outputConversationEditorAddMessageForm", "(", ")", "{", "\\", "View", "::", "element", "(", "DIRNAME_CONVERSATIONS", ".", "'/'", ".", "DIRNAME_CONVERSATION_EDITOR", ".", "'/'", ".", "$", "this", "->", "cnvEditorHandle", ".", "'/message'", ",", "[", "'editor'", "=>", "$", "this", "]", ",", "$", "this", "->", "getPackageHandle", "(", ")", ")", ";", "}" ]
outputs an HTML block containing the add message form for the current Conversation Editor.
[ "outputs", "an", "HTML", "block", "containing", "the", "add", "message", "form", "for", "the", "current", "Conversation", "Editor", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L215-L219
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.outputConversationEditorReplyMessageForm
public function outputConversationEditorReplyMessageForm() { \View::element(DIRNAME_CONVERSATIONS . '/' . DIRNAME_CONVERSATION_EDITOR . '/' . $this->cnvEditorHandle . '/reply', ['editor' => $this], $this->getPackageHandle()); }
php
public function outputConversationEditorReplyMessageForm() { \View::element(DIRNAME_CONVERSATIONS . '/' . DIRNAME_CONVERSATION_EDITOR . '/' . $this->cnvEditorHandle . '/reply', ['editor' => $this], $this->getPackageHandle()); }
[ "public", "function", "outputConversationEditorReplyMessageForm", "(", ")", "{", "\\", "View", "::", "element", "(", "DIRNAME_CONVERSATIONS", ".", "'/'", ".", "DIRNAME_CONVERSATION_EDITOR", ".", "'/'", ".", "$", "this", "->", "cnvEditorHandle", ".", "'/reply'", ",", "[", "'editor'", "=>", "$", "this", "]", ",", "$", "this", "->", "getPackageHandle", "(", ")", ")", ";", "}" ]
Outputs an HTML block containing the message reply form for the current Conversation Editor.
[ "Outputs", "an", "HTML", "block", "containing", "the", "message", "reply", "form", "for", "the", "current", "Conversation", "Editor", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L224-L228
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.formatConversationMessageBody
public function formatConversationMessageBody($cnv, $cnvMessageBody, $config = array()) { /** @var \Concrete\Core\Html\Service\Html $htmlHelper */ $htmlHelper = Core::make('helper/html'); $cnvMessageBody = $htmlHelper->noFollowHref($cnvMessageBody); if (isset($config['htmlawed'])) { $default = array('safe' => 1, 'elements' => 'p, br, strong, em, strike, a'); $conf = array_merge($default, (array) $config['htmlawed']); $result = htmLawed($cnvMessageBody, $conf); } else { $result = $cnvMessageBody; } if (isset($config['mention']) && $config['mention'] !== false) { $users = $cnv->getConversationMessageUsers(); $needle = array(); $haystack = array(); foreach ($users as $user) { $needle[] = "@" . $user->getUserName(); $haystack[] = "<a href='" . $user->getUserPublicProfileURL() . "'>'@" . $user->getUserName() . "</a>"; } $result = str_ireplace($needle, $haystack, $result); } // Replace any potential XSS $result = $this->removeJavascriptLinks($result); return $result; }
php
public function formatConversationMessageBody($cnv, $cnvMessageBody, $config = array()) { /** @var \Concrete\Core\Html\Service\Html $htmlHelper */ $htmlHelper = Core::make('helper/html'); $cnvMessageBody = $htmlHelper->noFollowHref($cnvMessageBody); if (isset($config['htmlawed'])) { $default = array('safe' => 1, 'elements' => 'p, br, strong, em, strike, a'); $conf = array_merge($default, (array) $config['htmlawed']); $result = htmLawed($cnvMessageBody, $conf); } else { $result = $cnvMessageBody; } if (isset($config['mention']) && $config['mention'] !== false) { $users = $cnv->getConversationMessageUsers(); $needle = array(); $haystack = array(); foreach ($users as $user) { $needle[] = "@" . $user->getUserName(); $haystack[] = "<a href='" . $user->getUserPublicProfileURL() . "'>'@" . $user->getUserName() . "</a>"; } $result = str_ireplace($needle, $haystack, $result); } // Replace any potential XSS $result = $this->removeJavascriptLinks($result); return $result; }
[ "public", "function", "formatConversationMessageBody", "(", "$", "cnv", ",", "$", "cnvMessageBody", ",", "$", "config", "=", "array", "(", ")", ")", "{", "/** @var \\Concrete\\Core\\Html\\Service\\Html $htmlHelper */", "$", "htmlHelper", "=", "Core", "::", "make", "(", "'helper/html'", ")", ";", "$", "cnvMessageBody", "=", "$", "htmlHelper", "->", "noFollowHref", "(", "$", "cnvMessageBody", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "'htmlawed'", "]", ")", ")", "{", "$", "default", "=", "array", "(", "'safe'", "=>", "1", ",", "'elements'", "=>", "'p, br, strong, em, strike, a'", ")", ";", "$", "conf", "=", "array_merge", "(", "$", "default", ",", "(", "array", ")", "$", "config", "[", "'htmlawed'", "]", ")", ";", "$", "result", "=", "htmLawed", "(", "$", "cnvMessageBody", ",", "$", "conf", ")", ";", "}", "else", "{", "$", "result", "=", "$", "cnvMessageBody", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'mention'", "]", ")", "&&", "$", "config", "[", "'mention'", "]", "!==", "false", ")", "{", "$", "users", "=", "$", "cnv", "->", "getConversationMessageUsers", "(", ")", ";", "$", "needle", "=", "array", "(", ")", ";", "$", "haystack", "=", "array", "(", ")", ";", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "$", "needle", "[", "]", "=", "\"@\"", ".", "$", "user", "->", "getUserName", "(", ")", ";", "$", "haystack", "[", "]", "=", "\"<a href='\"", ".", "$", "user", "->", "getUserPublicProfileURL", "(", ")", ".", "\"'>'@\"", ".", "$", "user", "->", "getUserName", "(", ")", ".", "\"</a>\"", ";", "}", "$", "result", "=", "str_ireplace", "(", "$", "needle", ",", "$", "haystack", ",", "$", "result", ")", ";", "}", "// Replace any potential XSS", "$", "result", "=", "$", "this", "->", "removeJavascriptLinks", "(", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Returns a formatted conversation message body string, based on configuration options supplied. @param \Concrete\Core\Conversation\Conversation $cnv @param string $cnvMessageBody @param array $config @return string
[ "Returns", "a", "formatted", "conversation", "message", "body", "string", "based", "on", "configuration", "options", "supplied", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L239-L266
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.add
public static function add($cnvEditorHandle, $cnvEditorName, $pkg = false) { $pkgID = 0; if (is_object($pkg)) { $pkgID = $pkg->getPackageID(); } $db = Database::connection(); $db->insert( 'ConversationEditors', array( 'cnvEditorHandle' => $cnvEditorHandle, 'cnvEditorName' => $cnvEditorName, 'pkgID' => $pkgID, ) ); return static::getByHandle($cnvEditorHandle); }
php
public static function add($cnvEditorHandle, $cnvEditorName, $pkg = false) { $pkgID = 0; if (is_object($pkg)) { $pkgID = $pkg->getPackageID(); } $db = Database::connection(); $db->insert( 'ConversationEditors', array( 'cnvEditorHandle' => $cnvEditorHandle, 'cnvEditorName' => $cnvEditorName, 'pkgID' => $pkgID, ) ); return static::getByHandle($cnvEditorHandle); }
[ "public", "static", "function", "add", "(", "$", "cnvEditorHandle", ",", "$", "cnvEditorName", ",", "$", "pkg", "=", "false", ")", "{", "$", "pkgID", "=", "0", ";", "if", "(", "is_object", "(", "$", "pkg", ")", ")", "{", "$", "pkgID", "=", "$", "pkg", "->", "getPackageID", "(", ")", ";", "}", "$", "db", "=", "Database", "::", "connection", "(", ")", ";", "$", "db", "->", "insert", "(", "'ConversationEditors'", ",", "array", "(", "'cnvEditorHandle'", "=>", "$", "cnvEditorHandle", ",", "'cnvEditorName'", "=>", "$", "cnvEditorName", ",", "'pkgID'", "=>", "$", "pkgID", ",", ")", ")", ";", "return", "static", "::", "getByHandle", "(", "$", "cnvEditorHandle", ")", ";", "}" ]
Creates a database record for the Conversation Editor, then attempts to return the object. @param string $cnvEditorHandle @param string $cnvEditorName @param bool|Package $pkg @return Editor|null
[ "Creates", "a", "database", "record", "for", "the", "Conversation", "Editor", "then", "attempts", "to", "return", "the", "object", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L291-L308
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.getList
public static function getList($pkgID = null) { $db = Database::connection(); $queryBuilder = $db->createQueryBuilder() ->select('e.*') ->from('ConversationEditors', 'e') ->orderBy('cnvEditorHandle', 'asc'); if ($pkgID !== null) { $queryBuilder->andWhere('e.pkgID = :pkgID')->setParameter('pkgID', $pkgID); } $cnvEditors = $db->fetchAll($queryBuilder->getSQL(), $queryBuilder->getParameters()); $editors = array(); foreach ($cnvEditors as $editorRecord) { $cnvEditor = static::createFromRecord($editorRecord); $editors[] = $cnvEditor; } return $editors; }
php
public static function getList($pkgID = null) { $db = Database::connection(); $queryBuilder = $db->createQueryBuilder() ->select('e.*') ->from('ConversationEditors', 'e') ->orderBy('cnvEditorHandle', 'asc'); if ($pkgID !== null) { $queryBuilder->andWhere('e.pkgID = :pkgID')->setParameter('pkgID', $pkgID); } $cnvEditors = $db->fetchAll($queryBuilder->getSQL(), $queryBuilder->getParameters()); $editors = array(); foreach ($cnvEditors as $editorRecord) { $cnvEditor = static::createFromRecord($editorRecord); $editors[] = $cnvEditor; } return $editors; }
[ "public", "static", "function", "getList", "(", "$", "pkgID", "=", "null", ")", "{", "$", "db", "=", "Database", "::", "connection", "(", ")", ";", "$", "queryBuilder", "=", "$", "db", "->", "createQueryBuilder", "(", ")", "->", "select", "(", "'e.*'", ")", "->", "from", "(", "'ConversationEditors'", ",", "'e'", ")", "->", "orderBy", "(", "'cnvEditorHandle'", ",", "'asc'", ")", ";", "if", "(", "$", "pkgID", "!==", "null", ")", "{", "$", "queryBuilder", "->", "andWhere", "(", "'e.pkgID = :pkgID'", ")", "->", "setParameter", "(", "'pkgID'", ",", "$", "pkgID", ")", ";", "}", "$", "cnvEditors", "=", "$", "db", "->", "fetchAll", "(", "$", "queryBuilder", "->", "getSQL", "(", ")", ",", "$", "queryBuilder", "->", "getParameters", "(", ")", ")", ";", "$", "editors", "=", "array", "(", ")", ";", "foreach", "(", "$", "cnvEditors", "as", "$", "editorRecord", ")", "{", "$", "cnvEditor", "=", "static", "::", "createFromRecord", "(", "$", "editorRecord", ")", ";", "$", "editors", "[", "]", "=", "$", "cnvEditor", ";", "}", "return", "$", "editors", ";", "}" ]
Returns an array of all Editor Objects. @param null $pkgID An optional filter for Package ID @return Editor[]
[ "Returns", "an", "array", "of", "all", "Editor", "Objects", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L345-L364
train
concrete5/concrete5
concrete/src/Conversation/Editor/Editor.php
Editor.hasOptionsForm
public function hasOptionsForm() { $env = Environment::get(); $rec = $env->getRecord( DIRNAME_ELEMENTS . '/' . DIRNAME_CONVERSATIONS . '/' . DIRNAME_CONVERSATION_EDITOR . '/' . $this->cnvEditorHandle . '/' . FILENAME_CONVERSATION_EDITOR_OPTIONS, $this->getPackageHandle() ); return $rec->exists(); }
php
public function hasOptionsForm() { $env = Environment::get(); $rec = $env->getRecord( DIRNAME_ELEMENTS . '/' . DIRNAME_CONVERSATIONS . '/' . DIRNAME_CONVERSATION_EDITOR . '/' . $this->cnvEditorHandle . '/' . FILENAME_CONVERSATION_EDITOR_OPTIONS, $this->getPackageHandle() ); return $rec->exists(); }
[ "public", "function", "hasOptionsForm", "(", ")", "{", "$", "env", "=", "Environment", "::", "get", "(", ")", ";", "$", "rec", "=", "$", "env", "->", "getRecord", "(", "DIRNAME_ELEMENTS", ".", "'/'", ".", "DIRNAME_CONVERSATIONS", ".", "'/'", ".", "DIRNAME_CONVERSATION_EDITOR", ".", "'/'", ".", "$", "this", "->", "cnvEditorHandle", ".", "'/'", ".", "FILENAME_CONVERSATION_EDITOR_OPTIONS", ",", "$", "this", "->", "getPackageHandle", "(", ")", ")", ";", "return", "$", "rec", "->", "exists", "(", ")", ";", "}" ]
Returns whether or not the current Conversation Editor has an options form. @return bool
[ "Returns", "whether", "or", "not", "the", "current", "Conversation", "Editor", "has", "an", "options", "form", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Conversation/Editor/Editor.php#L407-L417
train
concrete5/concrete5
concrete/src/Support/Symbol/MetadataGenerator.php
MetadataGenerator.getCustomEntityRepositories
public function getCustomEntityRepositories() { $result = []; $app = ApplicationFacade::getFacadeApplication(); $pev = new PackageEntitiesEvent(); $app->make('director')->dispatch('on_list_package_entities', $pev); $entityManagers = array_merge([$app->make(EntityManagerInterface::class)], $pev->getEntityManagers()); foreach ($entityManagers as $entityManager) { /* @var EntityManagerInterface $entityManager */ $metadataFactory = $entityManager->getMetadataFactory(); foreach ($metadataFactory->getAllMetadata() as $metadata) { /* @var \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata */ $entityClassName = $metadata->getName(); $entityRepository = $entityManager->getRepository($entityClassName); $entityRepositoryClassName = get_class($entityRepository); switch ($entityRepositoryClassName) { case \Doctrine\ORM\EntityRepository::class: break; default: $result[$entityClassName] = $entityRepositoryClassName; break; } } } return $result; }
php
public function getCustomEntityRepositories() { $result = []; $app = ApplicationFacade::getFacadeApplication(); $pev = new PackageEntitiesEvent(); $app->make('director')->dispatch('on_list_package_entities', $pev); $entityManagers = array_merge([$app->make(EntityManagerInterface::class)], $pev->getEntityManagers()); foreach ($entityManagers as $entityManager) { /* @var EntityManagerInterface $entityManager */ $metadataFactory = $entityManager->getMetadataFactory(); foreach ($metadataFactory->getAllMetadata() as $metadata) { /* @var \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata */ $entityClassName = $metadata->getName(); $entityRepository = $entityManager->getRepository($entityClassName); $entityRepositoryClassName = get_class($entityRepository); switch ($entityRepositoryClassName) { case \Doctrine\ORM\EntityRepository::class: break; default: $result[$entityClassName] = $entityRepositoryClassName; break; } } } return $result; }
[ "public", "function", "getCustomEntityRepositories", "(", ")", "{", "$", "result", "=", "[", "]", ";", "$", "app", "=", "ApplicationFacade", "::", "getFacadeApplication", "(", ")", ";", "$", "pev", "=", "new", "PackageEntitiesEvent", "(", ")", ";", "$", "app", "->", "make", "(", "'director'", ")", "->", "dispatch", "(", "'on_list_package_entities'", ",", "$", "pev", ")", ";", "$", "entityManagers", "=", "array_merge", "(", "[", "$", "app", "->", "make", "(", "EntityManagerInterface", "::", "class", ")", "]", ",", "$", "pev", "->", "getEntityManagers", "(", ")", ")", ";", "foreach", "(", "$", "entityManagers", "as", "$", "entityManager", ")", "{", "/* @var EntityManagerInterface $entityManager */", "$", "metadataFactory", "=", "$", "entityManager", "->", "getMetadataFactory", "(", ")", ";", "foreach", "(", "$", "metadataFactory", "->", "getAllMetadata", "(", ")", "as", "$", "metadata", ")", "{", "/* @var \\Doctrine\\Common\\Persistence\\Mapping\\ClassMetadata $metadata */", "$", "entityClassName", "=", "$", "metadata", "->", "getName", "(", ")", ";", "$", "entityRepository", "=", "$", "entityManager", "->", "getRepository", "(", "$", "entityClassName", ")", ";", "$", "entityRepositoryClassName", "=", "get_class", "(", "$", "entityRepository", ")", ";", "switch", "(", "$", "entityRepositoryClassName", ")", "{", "case", "\\", "Doctrine", "\\", "ORM", "\\", "EntityRepository", "::", "class", ":", "break", ";", "default", ":", "$", "result", "[", "$", "entityClassName", "]", "=", "$", "entityRepositoryClassName", ";", "break", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Return the list of custom entity manager repositories. @return array array keys are the entity fully-qualified class names, values are the custom repository fully-qualified class names
[ "Return", "the", "list", "of", "custom", "entity", "manager", "repositories", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Support/Symbol/MetadataGenerator.php#L50-L76
train
concrete5/concrete5
concrete/jobs/index_search_all.php
IndexSearchAll.queueMessages
protected function queueMessages() { $pages = $users = $files = $sites = 0; foreach ($this->pagesToQueue() as $id) { yield "P{$id}"; $pages++; } foreach ($this->usersToQueue() as $id) { yield "U{$id}"; $users++; } foreach ($this->filesToQueue() as $id) { yield "F{$id}"; $files++; } foreach ($this->sitesToQueue() as $id) { yield "S{$id}"; $sites++; } // Yield the result very last yield 'R' . json_encode([$pages, $users, $files, $sites]); }
php
protected function queueMessages() { $pages = $users = $files = $sites = 0; foreach ($this->pagesToQueue() as $id) { yield "P{$id}"; $pages++; } foreach ($this->usersToQueue() as $id) { yield "U{$id}"; $users++; } foreach ($this->filesToQueue() as $id) { yield "F{$id}"; $files++; } foreach ($this->sitesToQueue() as $id) { yield "S{$id}"; $sites++; } // Yield the result very last yield 'R' . json_encode([$pages, $users, $files, $sites]); }
[ "protected", "function", "queueMessages", "(", ")", "{", "$", "pages", "=", "$", "users", "=", "$", "files", "=", "$", "sites", "=", "0", ";", "foreach", "(", "$", "this", "->", "pagesToQueue", "(", ")", "as", "$", "id", ")", "{", "yield", "\"P{$id}\"", ";", "$", "pages", "++", ";", "}", "foreach", "(", "$", "this", "->", "usersToQueue", "(", ")", "as", "$", "id", ")", "{", "yield", "\"U{$id}\"", ";", "$", "users", "++", ";", "}", "foreach", "(", "$", "this", "->", "filesToQueue", "(", ")", "as", "$", "id", ")", "{", "yield", "\"F{$id}\"", ";", "$", "files", "++", ";", "}", "foreach", "(", "$", "this", "->", "sitesToQueue", "(", ")", "as", "$", "id", ")", "{", "yield", "\"S{$id}\"", ";", "$", "sites", "++", ";", "}", "// Yield the result very last", "yield", "'R'", ".", "json_encode", "(", "[", "$", "pages", ",", "$", "users", ",", "$", "files", ",", "$", "sites", "]", ")", ";", "}" ]
Messages to add to the queue. @return \Iterator
[ "Messages", "to", "add", "to", "the", "queue", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/jobs/index_search_all.php#L73-L96
train
concrete5/concrete5
concrete/jobs/index_search_all.php
IndexSearchAll.clearIndex
protected function clearIndex($index) { $index->clear(Page::class); $index->clear(User::class); $index->clear(File::class); $index->clear(Site::class); }
php
protected function clearIndex($index) { $index->clear(Page::class); $index->clear(User::class); $index->clear(File::class); $index->clear(Site::class); }
[ "protected", "function", "clearIndex", "(", "$", "index", ")", "{", "$", "index", "->", "clear", "(", "Page", "::", "class", ")", ";", "$", "index", "->", "clear", "(", "User", "::", "class", ")", ";", "$", "index", "->", "clear", "(", "File", "::", "class", ")", ";", "$", "index", "->", "clear", "(", "Site", "::", "class", ")", ";", "}" ]
Clear out all indexes. @param $index
[ "Clear", "out", "all", "indexes", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/jobs/index_search_all.php#L150-L156
train
concrete5/concrete5
concrete/jobs/index_search_all.php
IndexSearchAll.pagesToQueue
protected function pagesToQueue() { $qb = $this->connection->createQueryBuilder(); // Find all pages that need indexing $query = $qb ->select('p.cID') ->from('Pages', 'p') ->leftJoin('p', 'CollectionSearchIndexAttributes', 'a', 'p.cID = a.cID') ->where('cIsActive = 1') ->andWhere($qb->expr()->orX( 'a.ak_exclude_search_index is null', 'a.ak_exclude_search_index = 0' ))->execute(); while ($id = $query->fetchColumn()) { yield $id; } }
php
protected function pagesToQueue() { $qb = $this->connection->createQueryBuilder(); // Find all pages that need indexing $query = $qb ->select('p.cID') ->from('Pages', 'p') ->leftJoin('p', 'CollectionSearchIndexAttributes', 'a', 'p.cID = a.cID') ->where('cIsActive = 1') ->andWhere($qb->expr()->orX( 'a.ak_exclude_search_index is null', 'a.ak_exclude_search_index = 0' ))->execute(); while ($id = $query->fetchColumn()) { yield $id; } }
[ "protected", "function", "pagesToQueue", "(", ")", "{", "$", "qb", "=", "$", "this", "->", "connection", "->", "createQueryBuilder", "(", ")", ";", "// Find all pages that need indexing", "$", "query", "=", "$", "qb", "->", "select", "(", "'p.cID'", ")", "->", "from", "(", "'Pages'", ",", "'p'", ")", "->", "leftJoin", "(", "'p'", ",", "'CollectionSearchIndexAttributes'", ",", "'a'", ",", "'p.cID = a.cID'", ")", "->", "where", "(", "'cIsActive = 1'", ")", "->", "andWhere", "(", "$", "qb", "->", "expr", "(", ")", "->", "orX", "(", "'a.ak_exclude_search_index is null'", ",", "'a.ak_exclude_search_index = 0'", ")", ")", "->", "execute", "(", ")", ";", "while", "(", "$", "id", "=", "$", "query", "->", "fetchColumn", "(", ")", ")", "{", "yield", "$", "id", ";", "}", "}" ]
Get Pages to add to the queue. @return \Iterator
[ "Get", "Pages", "to", "add", "to", "the", "queue", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/jobs/index_search_all.php#L163-L181
train
concrete5/concrete5
concrete/jobs/index_search_all.php
IndexSearchAll.usersToQueue
protected function usersToQueue() { /** @var Connection $db */ $db = $this->connection; $query = $db->executeQuery('SELECT uID FROM Users WHERE uIsActive = 1'); while ($id = $query->fetchColumn()) { yield $id; } }
php
protected function usersToQueue() { /** @var Connection $db */ $db = $this->connection; $query = $db->executeQuery('SELECT uID FROM Users WHERE uIsActive = 1'); while ($id = $query->fetchColumn()) { yield $id; } }
[ "protected", "function", "usersToQueue", "(", ")", "{", "/** @var Connection $db */", "$", "db", "=", "$", "this", "->", "connection", ";", "$", "query", "=", "$", "db", "->", "executeQuery", "(", "'SELECT uID FROM Users WHERE uIsActive = 1'", ")", ";", "while", "(", "$", "id", "=", "$", "query", "->", "fetchColumn", "(", ")", ")", "{", "yield", "$", "id", ";", "}", "}" ]
Get Users to add to the queue. @return \Iterator
[ "Get", "Users", "to", "add", "to", "the", "queue", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/jobs/index_search_all.php#L188-L197
train
concrete5/concrete5
concrete/jobs/index_search_all.php
IndexSearchAll.filesToQueue
protected function filesToQueue() { /** @var Connection $db */ $db = $this->connection; $query = $db->executeQuery('SELECT fID FROM Files'); while ($id = $query->fetchColumn()) { yield $id; } }
php
protected function filesToQueue() { /** @var Connection $db */ $db = $this->connection; $query = $db->executeQuery('SELECT fID FROM Files'); while ($id = $query->fetchColumn()) { yield $id; } }
[ "protected", "function", "filesToQueue", "(", ")", "{", "/** @var Connection $db */", "$", "db", "=", "$", "this", "->", "connection", ";", "$", "query", "=", "$", "db", "->", "executeQuery", "(", "'SELECT fID FROM Files'", ")", ";", "while", "(", "$", "id", "=", "$", "query", "->", "fetchColumn", "(", ")", ")", "{", "yield", "$", "id", ";", "}", "}" ]
Get Files to add to the queue. @return \Iterator
[ "Get", "Files", "to", "add", "to", "the", "queue", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/jobs/index_search_all.php#L204-L213
train
concrete5/concrete5
concrete/jobs/index_search_all.php
IndexSearchAll.sitesToQueue
protected function sitesToQueue() { /** @var Connection $db */ $db = $this->connection; $query = $db->executeQuery('SELECT siteID FROM Sites'); while ($id = $query->fetchColumn()) { yield $id; } }
php
protected function sitesToQueue() { /** @var Connection $db */ $db = $this->connection; $query = $db->executeQuery('SELECT siteID FROM Sites'); while ($id = $query->fetchColumn()) { yield $id; } }
[ "protected", "function", "sitesToQueue", "(", ")", "{", "/** @var Connection $db */", "$", "db", "=", "$", "this", "->", "connection", ";", "$", "query", "=", "$", "db", "->", "executeQuery", "(", "'SELECT siteID FROM Sites'", ")", ";", "while", "(", "$", "id", "=", "$", "query", "->", "fetchColumn", "(", ")", ")", "{", "yield", "$", "id", ";", "}", "}" ]
Get Sites to add to the queue. @return \Iterator
[ "Get", "Sites", "to", "add", "to", "the", "queue", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/jobs/index_search_all.php#L220-L229
train
concrete5/concrete5
concrete/src/Editor/LinkAbstractor.php
LinkAbstractor.translateFromEditMode
public static function translateFromEditMode($text) { $app = Application::getFacadeApplication(); $entityManager = $app->make(EntityManagerInterface::class); $resolver = $app->make(ResolverManagerInterface::class); $appUrl = Application::getApplicationURL(); $text = preg_replace( [ '/{CCM:BASE_URL}/i', ], [ $appUrl, ], $text ); //page links... $text = preg_replace( '/{CCM:CID_([0-9]+)}/i', $appUrl . '/' . DISPATCHER_FILENAME . '?cID=\\1', $text ); //images... $dom = new HtmlDomParser(); $r = $dom->str_get_html($text, true, true, DEFAULT_TARGET_CHARSET, false); if (is_object($r)) { foreach ($r->find('concrete-picture') as $picture) { $fID = $picture->fid; $attrString = ""; foreach ($picture->attr as $attr => $val) { if (!in_array($attr, self::$blackListImgAttributes)) { $attrString .= "$attr=\"$val\" "; } } $picture->outertext = '<img src="' . $resolver->resolve([ '/download_file', 'view_inline', $fID ]) . '" ' . $attrString . '/>'; } $text = (string) $r->restore_noise($r); } // now we add in support for the links $text = static::replacePlaceholder( $text, '{CCM:FID_([0-9]+)}', function ($fID) use ($resolver) { if ($fID > 0) { return $resolver->resolve(['/download_file', 'view_inline', $fID]); } } ); //file downloads... $text = static::replacePlaceholder( $text, '{CCM:FID_DL_([0-9]+)}', function ($fID) use ($resolver) { if ($fID > 0) { return $resolver->resolve(['/download_file', 'view', $fID]); } } ); return $text; }
php
public static function translateFromEditMode($text) { $app = Application::getFacadeApplication(); $entityManager = $app->make(EntityManagerInterface::class); $resolver = $app->make(ResolverManagerInterface::class); $appUrl = Application::getApplicationURL(); $text = preg_replace( [ '/{CCM:BASE_URL}/i', ], [ $appUrl, ], $text ); //page links... $text = preg_replace( '/{CCM:CID_([0-9]+)}/i', $appUrl . '/' . DISPATCHER_FILENAME . '?cID=\\1', $text ); //images... $dom = new HtmlDomParser(); $r = $dom->str_get_html($text, true, true, DEFAULT_TARGET_CHARSET, false); if (is_object($r)) { foreach ($r->find('concrete-picture') as $picture) { $fID = $picture->fid; $attrString = ""; foreach ($picture->attr as $attr => $val) { if (!in_array($attr, self::$blackListImgAttributes)) { $attrString .= "$attr=\"$val\" "; } } $picture->outertext = '<img src="' . $resolver->resolve([ '/download_file', 'view_inline', $fID ]) . '" ' . $attrString . '/>'; } $text = (string) $r->restore_noise($r); } // now we add in support for the links $text = static::replacePlaceholder( $text, '{CCM:FID_([0-9]+)}', function ($fID) use ($resolver) { if ($fID > 0) { return $resolver->resolve(['/download_file', 'view_inline', $fID]); } } ); //file downloads... $text = static::replacePlaceholder( $text, '{CCM:FID_DL_([0-9]+)}', function ($fID) use ($resolver) { if ($fID > 0) { return $resolver->resolve(['/download_file', 'view', $fID]); } } ); return $text; }
[ "public", "static", "function", "translateFromEditMode", "(", "$", "text", ")", "{", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "$", "entityManager", "=", "$", "app", "->", "make", "(", "EntityManagerInterface", "::", "class", ")", ";", "$", "resolver", "=", "$", "app", "->", "make", "(", "ResolverManagerInterface", "::", "class", ")", ";", "$", "appUrl", "=", "Application", "::", "getApplicationURL", "(", ")", ";", "$", "text", "=", "preg_replace", "(", "[", "'/{CCM:BASE_URL}/i'", ",", "]", ",", "[", "$", "appUrl", ",", "]", ",", "$", "text", ")", ";", "//page links...", "$", "text", "=", "preg_replace", "(", "'/{CCM:CID_([0-9]+)}/i'", ",", "$", "appUrl", ".", "'/'", ".", "DISPATCHER_FILENAME", ".", "'?cID=\\\\1'", ",", "$", "text", ")", ";", "//images...", "$", "dom", "=", "new", "HtmlDomParser", "(", ")", ";", "$", "r", "=", "$", "dom", "->", "str_get_html", "(", "$", "text", ",", "true", ",", "true", ",", "DEFAULT_TARGET_CHARSET", ",", "false", ")", ";", "if", "(", "is_object", "(", "$", "r", ")", ")", "{", "foreach", "(", "$", "r", "->", "find", "(", "'concrete-picture'", ")", "as", "$", "picture", ")", "{", "$", "fID", "=", "$", "picture", "->", "fid", ";", "$", "attrString", "=", "\"\"", ";", "foreach", "(", "$", "picture", "->", "attr", "as", "$", "attr", "=>", "$", "val", ")", "{", "if", "(", "!", "in_array", "(", "$", "attr", ",", "self", "::", "$", "blackListImgAttributes", ")", ")", "{", "$", "attrString", ".=", "\"$attr=\\\"$val\\\" \"", ";", "}", "}", "$", "picture", "->", "outertext", "=", "'<img src=\"'", ".", "$", "resolver", "->", "resolve", "(", "[", "'/download_file'", ",", "'view_inline'", ",", "$", "fID", "]", ")", ".", "'\" '", ".", "$", "attrString", ".", "'/>'", ";", "}", "$", "text", "=", "(", "string", ")", "$", "r", "->", "restore_noise", "(", "$", "r", ")", ";", "}", "// now we add in support for the links", "$", "text", "=", "static", "::", "replacePlaceholder", "(", "$", "text", ",", "'{CCM:FID_([0-9]+)}'", ",", "function", "(", "$", "fID", ")", "use", "(", "$", "resolver", ")", "{", "if", "(", "$", "fID", ">", "0", ")", "{", "return", "$", "resolver", "->", "resolve", "(", "[", "'/download_file'", ",", "'view_inline'", ",", "$", "fID", "]", ")", ";", "}", "}", ")", ";", "//file downloads...", "$", "text", "=", "static", "::", "replacePlaceholder", "(", "$", "text", ",", "'{CCM:FID_DL_([0-9]+)}'", ",", "function", "(", "$", "fID", ")", "use", "(", "$", "resolver", ")", "{", "if", "(", "$", "fID", ">", "0", ")", "{", "return", "$", "resolver", "->", "resolve", "(", "[", "'/download_file'", ",", "'view'", ",", "$", "fID", "]", ")", ";", "}", "}", ")", ";", "return", "$", "text", ";", "}" ]
Takes a chunk of content containing abstracted link references, and expands them to urls suitable for the rich text editor.
[ "Takes", "a", "chunk", "of", "content", "containing", "abstracted", "link", "references", "and", "expands", "them", "to", "urls", "suitable", "for", "the", "rich", "text", "editor", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Editor/LinkAbstractor.php#L231-L302
train
concrete5/concrete5
concrete/src/Editor/LinkAbstractor.php
LinkAbstractor.replacePlaceholder
protected static function replacePlaceholder($text, $pattern, callable $resolver, $caseSensitive = false) { $regex = "/{$pattern}/"; if (!$caseSensitive) { $regex .= 'i'; } if (!preg_match_all($regex, $text, $matches)) { return $text; } $replaces = array_combine($matches[0], $matches[1]); if (!$caseSensitive) { $replaces = array_change_key_case($replaces, CASE_UPPER); } foreach (array_keys($replaces) as $key) { $replaces[$key] = (string) $resolver($replaces[$key]); } return $caseSensitive ? strtr($text, $replaces) : str_ireplace(array_keys($replaces), array_values($replaces), $text); }
php
protected static function replacePlaceholder($text, $pattern, callable $resolver, $caseSensitive = false) { $regex = "/{$pattern}/"; if (!$caseSensitive) { $regex .= 'i'; } if (!preg_match_all($regex, $text, $matches)) { return $text; } $replaces = array_combine($matches[0], $matches[1]); if (!$caseSensitive) { $replaces = array_change_key_case($replaces, CASE_UPPER); } foreach (array_keys($replaces) as $key) { $replaces[$key] = (string) $resolver($replaces[$key]); } return $caseSensitive ? strtr($text, $replaces) : str_ireplace(array_keys($replaces), array_values($replaces), $text); }
[ "protected", "static", "function", "replacePlaceholder", "(", "$", "text", ",", "$", "pattern", ",", "callable", "$", "resolver", ",", "$", "caseSensitive", "=", "false", ")", "{", "$", "regex", "=", "\"/{$pattern}/\"", ";", "if", "(", "!", "$", "caseSensitive", ")", "{", "$", "regex", ".=", "'i'", ";", "}", "if", "(", "!", "preg_match_all", "(", "$", "regex", ",", "$", "text", ",", "$", "matches", ")", ")", "{", "return", "$", "text", ";", "}", "$", "replaces", "=", "array_combine", "(", "$", "matches", "[", "0", "]", ",", "$", "matches", "[", "1", "]", ")", ";", "if", "(", "!", "$", "caseSensitive", ")", "{", "$", "replaces", "=", "array_change_key_case", "(", "$", "replaces", ",", "CASE_UPPER", ")", ";", "}", "foreach", "(", "array_keys", "(", "$", "replaces", ")", "as", "$", "key", ")", "{", "$", "replaces", "[", "$", "key", "]", "=", "(", "string", ")", "$", "resolver", "(", "$", "replaces", "[", "$", "key", "]", ")", ";", "}", "return", "$", "caseSensitive", "?", "strtr", "(", "$", "text", ",", "$", "replaces", ")", ":", "str_ireplace", "(", "array_keys", "(", "$", "replaces", ")", ",", "array_values", "(", "$", "replaces", ")", ",", "$", "text", ")", ";", "}" ]
Replace a placeholder. @param string $text the text that may contain placeholders to be replaced @param string $pattern the regular expression (without enclosing '/') that captures the placeholder @param callable $resolver a callback that replaces the captured placeholder value @param bool $caseSensitive is $pattern case sensitive? @return string @since concrete5 8.5.0a3
[ "Replace", "a", "placeholder", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Editor/LinkAbstractor.php#L365-L383
train
concrete5/concrete5
concrete/src/File/Image/Thumbnail/Type/Type.php
Type.getList
public static function getList() { $app = Application::getFacadeApplication(); $em = $app->make(EntityManagerInterface::class); return $em->getRepository(ThumbnailTypeEntity::class)->findBy([], ['ftTypeWidth' => 'asc']); }
php
public static function getList() { $app = Application::getFacadeApplication(); $em = $app->make(EntityManagerInterface::class); return $em->getRepository(ThumbnailTypeEntity::class)->findBy([], ['ftTypeWidth' => 'asc']); }
[ "public", "static", "function", "getList", "(", ")", "{", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "$", "em", "=", "$", "app", "->", "make", "(", "EntityManagerInterface", "::", "class", ")", ";", "return", "$", "em", "->", "getRepository", "(", "ThumbnailTypeEntity", "::", "class", ")", "->", "findBy", "(", "[", "]", ",", "[", "'ftTypeWidth'", "=>", "'asc'", "]", ")", ";", "}" ]
Get the list of all the available thumbnail types. @return \Concrete\Core\Entity\File\Image\Thumbnail\Type\Type[]
[ "Get", "the", "list", "of", "all", "the", "available", "thumbnail", "types", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Image/Thumbnail/Type/Type.php#L38-L44
train
concrete5/concrete5
concrete/src/File/Image/Thumbnail/Type/Type.php
Type.getVersionList
public static function getVersionList() { $app = Application::getFacadeApplication(); $config = $app->make('config'); $createHightDPIVersions = (bool) $config->get('concrete.file_manager.images.create_high_dpi_thumbnails'); $types = static::getList(); $versions = []; foreach ($types as $type) { $versions[] = $type->getBaseVersion(); if ($createHightDPIVersions) { $versions[] = $type->getDoubledVersion(); } } return $versions; }
php
public static function getVersionList() { $app = Application::getFacadeApplication(); $config = $app->make('config'); $createHightDPIVersions = (bool) $config->get('concrete.file_manager.images.create_high_dpi_thumbnails'); $types = static::getList(); $versions = []; foreach ($types as $type) { $versions[] = $type->getBaseVersion(); if ($createHightDPIVersions) { $versions[] = $type->getDoubledVersion(); } } return $versions; }
[ "public", "static", "function", "getVersionList", "(", ")", "{", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "$", "config", "=", "$", "app", "->", "make", "(", "'config'", ")", ";", "$", "createHightDPIVersions", "=", "(", "bool", ")", "$", "config", "->", "get", "(", "'concrete.file_manager.images.create_high_dpi_thumbnails'", ")", ";", "$", "types", "=", "static", "::", "getList", "(", ")", ";", "$", "versions", "=", "[", "]", ";", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "$", "versions", "[", "]", "=", "$", "type", "->", "getBaseVersion", "(", ")", ";", "if", "(", "$", "createHightDPIVersions", ")", "{", "$", "versions", "[", "]", "=", "$", "type", "->", "getDoubledVersion", "(", ")", ";", "}", "}", "return", "$", "versions", ";", "}" ]
Get the list of all the available thumbnail type versions. @return \Concrete\Core\File\Image\Thumbnail\Type\Version[]
[ "Get", "the", "list", "of", "all", "the", "available", "thumbnail", "type", "versions", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Image/Thumbnail/Type/Type.php#L51-L68
train
concrete5/concrete5
concrete/src/File/Image/Thumbnail/Type/Type.php
Type.exportList
public static function exportList($node) { $child = $node->addChild('thumbnailtypes'); $list = static::getList(); foreach ($list as $link) { $linkNode = $child->addChild('thumbnailtype'); $linkNode->addAttribute('name', $link->getName()); $linkNode->addAttribute('handle', $link->getHandle()); $linkNode->addAttribute('sizingMode', $link->getSizingMode()); $linkNode->addAttribute('upscalingEnabled', $link->isUpscalingEnabled() ? '1' : '0'); $linkNode->addAttribute('keepAnimations', $link->isKeepAnimations() ? '1' : '0'); if ($link->getWidth()) { $linkNode->addAttribute('width', $link->getWidth()); } if ($link->getHeight()) { $linkNode->addAttribute('height', $link->getHeight()); } if ($link->isRequired()) { $linkNode->addAttribute('required', $link->isRequired()); } $linkNode->addAttribute('limitedToFileSets', $link->isLimitedToFileSets() ? '1' : '0'); $filesetsNode = null; foreach ($link->getAssociatedFileSets() as $afs) { $fileSet = FileSet::getByID($afs->getFileSetID()); if ($fileSet !== null) { if ($filesetsNode === null) { $filesetsNode = $linkNode->addChild('fileSets'); } $filesetsNode->addChild('fileSet')->addAttribute('name', $fileSet->getFileSetName()); } } } }
php
public static function exportList($node) { $child = $node->addChild('thumbnailtypes'); $list = static::getList(); foreach ($list as $link) { $linkNode = $child->addChild('thumbnailtype'); $linkNode->addAttribute('name', $link->getName()); $linkNode->addAttribute('handle', $link->getHandle()); $linkNode->addAttribute('sizingMode', $link->getSizingMode()); $linkNode->addAttribute('upscalingEnabled', $link->isUpscalingEnabled() ? '1' : '0'); $linkNode->addAttribute('keepAnimations', $link->isKeepAnimations() ? '1' : '0'); if ($link->getWidth()) { $linkNode->addAttribute('width', $link->getWidth()); } if ($link->getHeight()) { $linkNode->addAttribute('height', $link->getHeight()); } if ($link->isRequired()) { $linkNode->addAttribute('required', $link->isRequired()); } $linkNode->addAttribute('limitedToFileSets', $link->isLimitedToFileSets() ? '1' : '0'); $filesetsNode = null; foreach ($link->getAssociatedFileSets() as $afs) { $fileSet = FileSet::getByID($afs->getFileSetID()); if ($fileSet !== null) { if ($filesetsNode === null) { $filesetsNode = $linkNode->addChild('fileSets'); } $filesetsNode->addChild('fileSet')->addAttribute('name', $fileSet->getFileSetName()); } } } }
[ "public", "static", "function", "exportList", "(", "$", "node", ")", "{", "$", "child", "=", "$", "node", "->", "addChild", "(", "'thumbnailtypes'", ")", ";", "$", "list", "=", "static", "::", "getList", "(", ")", ";", "foreach", "(", "$", "list", "as", "$", "link", ")", "{", "$", "linkNode", "=", "$", "child", "->", "addChild", "(", "'thumbnailtype'", ")", ";", "$", "linkNode", "->", "addAttribute", "(", "'name'", ",", "$", "link", "->", "getName", "(", ")", ")", ";", "$", "linkNode", "->", "addAttribute", "(", "'handle'", ",", "$", "link", "->", "getHandle", "(", ")", ")", ";", "$", "linkNode", "->", "addAttribute", "(", "'sizingMode'", ",", "$", "link", "->", "getSizingMode", "(", ")", ")", ";", "$", "linkNode", "->", "addAttribute", "(", "'upscalingEnabled'", ",", "$", "link", "->", "isUpscalingEnabled", "(", ")", "?", "'1'", ":", "'0'", ")", ";", "$", "linkNode", "->", "addAttribute", "(", "'keepAnimations'", ",", "$", "link", "->", "isKeepAnimations", "(", ")", "?", "'1'", ":", "'0'", ")", ";", "if", "(", "$", "link", "->", "getWidth", "(", ")", ")", "{", "$", "linkNode", "->", "addAttribute", "(", "'width'", ",", "$", "link", "->", "getWidth", "(", ")", ")", ";", "}", "if", "(", "$", "link", "->", "getHeight", "(", ")", ")", "{", "$", "linkNode", "->", "addAttribute", "(", "'height'", ",", "$", "link", "->", "getHeight", "(", ")", ")", ";", "}", "if", "(", "$", "link", "->", "isRequired", "(", ")", ")", "{", "$", "linkNode", "->", "addAttribute", "(", "'required'", ",", "$", "link", "->", "isRequired", "(", ")", ")", ";", "}", "$", "linkNode", "->", "addAttribute", "(", "'limitedToFileSets'", ",", "$", "link", "->", "isLimitedToFileSets", "(", ")", "?", "'1'", ":", "'0'", ")", ";", "$", "filesetsNode", "=", "null", ";", "foreach", "(", "$", "link", "->", "getAssociatedFileSets", "(", ")", "as", "$", "afs", ")", "{", "$", "fileSet", "=", "FileSet", "::", "getByID", "(", "$", "afs", "->", "getFileSetID", "(", ")", ")", ";", "if", "(", "$", "fileSet", "!==", "null", ")", "{", "if", "(", "$", "filesetsNode", "===", "null", ")", "{", "$", "filesetsNode", "=", "$", "linkNode", "->", "addChild", "(", "'fileSets'", ")", ";", "}", "$", "filesetsNode", "->", "addChild", "(", "'fileSet'", ")", "->", "addAttribute", "(", "'name'", ",", "$", "fileSet", "->", "getFileSetName", "(", ")", ")", ";", "}", "}", "}", "}" ]
Export the list of all the thumbnail types. @param \SimpleXMLElement $node the parent node to append the thumbnailtypes XML node to
[ "Export", "the", "list", "of", "all", "the", "thumbnail", "types", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Image/Thumbnail/Type/Type.php#L75-L107
train
concrete5/concrete5
concrete/src/File/Image/Thumbnail/Type/Type.php
Type.getByID
public static function getByID($id) { if ($id) { $app = Application::getFacadeApplication(); $em = $app->make(EntityManagerInterface::class); $result = $em->find(ThumbnailTypeEntity::class, $id); } else { $result = null; } return $result; }
php
public static function getByID($id) { if ($id) { $app = Application::getFacadeApplication(); $em = $app->make(EntityManagerInterface::class); $result = $em->find(ThumbnailTypeEntity::class, $id); } else { $result = null; } return $result; }
[ "public", "static", "function", "getByID", "(", "$", "id", ")", "{", "if", "(", "$", "id", ")", "{", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "$", "em", "=", "$", "app", "->", "make", "(", "EntityManagerInterface", "::", "class", ")", ";", "$", "result", "=", "$", "em", "->", "find", "(", "ThumbnailTypeEntity", "::", "class", ",", "$", "id", ")", ";", "}", "else", "{", "$", "result", "=", "null", ";", "}", "return", "$", "result", ";", "}" ]
Get a thumbnail type given its id. @param int $id @return \Concrete\Core\Entity\File\Image\Thumbnail\Type\Type|null
[ "Get", "a", "thumbnail", "type", "given", "its", "id", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Image/Thumbnail/Type/Type.php#L116-L127
train
concrete5/concrete5
concrete/src/File/Image/Thumbnail/Type/Type.php
Type.getByHandle
public static function getByHandle($ftTypeHandle) { $ftTypeHandle = (string) $ftTypeHandle; $app = Application::getFacadeApplication(); $cache = $app->make('cache/request'); $item = $cache->getItem('file/image/thumbnail/' . $ftTypeHandle); if ($item->isMiss()) { $em = $app->make(EntityManagerInterface::class); $repo = $em->getRepository(ThumbnailTypeEntity::class); $result = $repo->findOneBy(['ftTypeHandle' => $ftTypeHandle]); $cache->save($item->set($result)); } else { $result = $item->get(); } return $result; }
php
public static function getByHandle($ftTypeHandle) { $ftTypeHandle = (string) $ftTypeHandle; $app = Application::getFacadeApplication(); $cache = $app->make('cache/request'); $item = $cache->getItem('file/image/thumbnail/' . $ftTypeHandle); if ($item->isMiss()) { $em = $app->make(EntityManagerInterface::class); $repo = $em->getRepository(ThumbnailTypeEntity::class); $result = $repo->findOneBy(['ftTypeHandle' => $ftTypeHandle]); $cache->save($item->set($result)); } else { $result = $item->get(); } return $result; }
[ "public", "static", "function", "getByHandle", "(", "$", "ftTypeHandle", ")", "{", "$", "ftTypeHandle", "=", "(", "string", ")", "$", "ftTypeHandle", ";", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "$", "cache", "=", "$", "app", "->", "make", "(", "'cache/request'", ")", ";", "$", "item", "=", "$", "cache", "->", "getItem", "(", "'file/image/thumbnail/'", ".", "$", "ftTypeHandle", ")", ";", "if", "(", "$", "item", "->", "isMiss", "(", ")", ")", "{", "$", "em", "=", "$", "app", "->", "make", "(", "EntityManagerInterface", "::", "class", ")", ";", "$", "repo", "=", "$", "em", "->", "getRepository", "(", "ThumbnailTypeEntity", "::", "class", ")", ";", "$", "result", "=", "$", "repo", "->", "findOneBy", "(", "[", "'ftTypeHandle'", "=>", "$", "ftTypeHandle", "]", ")", ";", "$", "cache", "->", "save", "(", "$", "item", "->", "set", "(", "$", "result", ")", ")", ";", "}", "else", "{", "$", "result", "=", "$", "item", "->", "get", "(", ")", ";", "}", "return", "$", "result", ";", "}" ]
Get a thumbnail type given its handle. @param string $ftTypeHandle @return \Concrete\Core\Entity\File\Image\Thumbnail\Type\Type|null
[ "Get", "a", "thumbnail", "type", "given", "its", "handle", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Image/Thumbnail/Type/Type.php#L136-L152
train
concrete5/concrete5
concrete/src/User/PrivateMessage/Limit.php
Limit.isOverLimit
public static function isOverLimit($uID) { if (Config::get('concrete.user.private_messages.throttle_max') == 0) { return false; } if (Config::get('concrete.user.private_messages.throttle_max_timespan') == 0) { return false; } $db = Loader::db(); $dt = new DateTime(); $dt->modify('-'.Config::get('concrete.user.private_messages.throttle_max_timespan').' minutes'); $v = array($uID, $dt->format('Y-m-d H:i:s')); $q = "SELECT COUNT(msgID) as sent_count FROM UserPrivateMessages WHERE uAuthorID = ? AND msgDateCreated >= ?"; $count = $db->getOne($q, $v); if ($count > Config::get('concrete.user.private_messages.throttle_max')) { self::notifyAdmin($uID); return true; } else { return false; } }
php
public static function isOverLimit($uID) { if (Config::get('concrete.user.private_messages.throttle_max') == 0) { return false; } if (Config::get('concrete.user.private_messages.throttle_max_timespan') == 0) { return false; } $db = Loader::db(); $dt = new DateTime(); $dt->modify('-'.Config::get('concrete.user.private_messages.throttle_max_timespan').' minutes'); $v = array($uID, $dt->format('Y-m-d H:i:s')); $q = "SELECT COUNT(msgID) as sent_count FROM UserPrivateMessages WHERE uAuthorID = ? AND msgDateCreated >= ?"; $count = $db->getOne($q, $v); if ($count > Config::get('concrete.user.private_messages.throttle_max')) { self::notifyAdmin($uID); return true; } else { return false; } }
[ "public", "static", "function", "isOverLimit", "(", "$", "uID", ")", "{", "if", "(", "Config", "::", "get", "(", "'concrete.user.private_messages.throttle_max'", ")", "==", "0", ")", "{", "return", "false", ";", "}", "if", "(", "Config", "::", "get", "(", "'concrete.user.private_messages.throttle_max_timespan'", ")", "==", "0", ")", "{", "return", "false", ";", "}", "$", "db", "=", "Loader", "::", "db", "(", ")", ";", "$", "dt", "=", "new", "DateTime", "(", ")", ";", "$", "dt", "->", "modify", "(", "'-'", ".", "Config", "::", "get", "(", "'concrete.user.private_messages.throttle_max_timespan'", ")", ".", "' minutes'", ")", ";", "$", "v", "=", "array", "(", "$", "uID", ",", "$", "dt", "->", "format", "(", "'Y-m-d H:i:s'", ")", ")", ";", "$", "q", "=", "\"SELECT COUNT(msgID) as sent_count FROM UserPrivateMessages WHERE uAuthorID = ? AND msgDateCreated >= ?\"", ";", "$", "count", "=", "$", "db", "->", "getOne", "(", "$", "q", ",", "$", "v", ")", ";", "if", "(", "$", "count", ">", "Config", "::", "get", "(", "'concrete.user.private_messages.throttle_max'", ")", ")", "{", "self", "::", "notifyAdmin", "(", "$", "uID", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
checks to see if a user has exceeded their limit for sending private messages. @param int $uID @return bool
[ "checks", "to", "see", "if", "a", "user", "has", "exceeded", "their", "limit", "for", "sending", "private", "messages", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/PrivateMessage/Limit.php#L21-L43
train
concrete5/concrete5
concrete/src/Logging/Channels.php
Channels.getCoreChannels
public static function getCoreChannels() { return [ self::CHANNEL_EMAIL, self::CHANNEL_EXCEPTIONS, self::CHANNEL_PACKAGES, self::CHANNEL_SECURITY, self::CHANNEL_AUTHENTICATION, self::CHANNEL_PERMISSIONS, self::CHANNEL_SPAM, self::CHANNEL_SITE_ORGANIZATION, self::CHANNEL_NETWORK, self::CHANNEL_USERS, self::CHANNEL_OPERATIONS, self::CHANNEL_API, ]; }
php
public static function getCoreChannels() { return [ self::CHANNEL_EMAIL, self::CHANNEL_EXCEPTIONS, self::CHANNEL_PACKAGES, self::CHANNEL_SECURITY, self::CHANNEL_AUTHENTICATION, self::CHANNEL_PERMISSIONS, self::CHANNEL_SPAM, self::CHANNEL_SITE_ORGANIZATION, self::CHANNEL_NETWORK, self::CHANNEL_USERS, self::CHANNEL_OPERATIONS, self::CHANNEL_API, ]; }
[ "public", "static", "function", "getCoreChannels", "(", ")", "{", "return", "[", "self", "::", "CHANNEL_EMAIL", ",", "self", "::", "CHANNEL_EXCEPTIONS", ",", "self", "::", "CHANNEL_PACKAGES", ",", "self", "::", "CHANNEL_SECURITY", ",", "self", "::", "CHANNEL_AUTHENTICATION", ",", "self", "::", "CHANNEL_PERMISSIONS", ",", "self", "::", "CHANNEL_SPAM", ",", "self", "::", "CHANNEL_SITE_ORGANIZATION", ",", "self", "::", "CHANNEL_NETWORK", ",", "self", "::", "CHANNEL_USERS", ",", "self", "::", "CHANNEL_OPERATIONS", ",", "self", "::", "CHANNEL_API", ",", "]", ";", "}" ]
Get the list of the core channel. @return string[]
[ "Get", "the", "list", "of", "the", "core", "channel", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Logging/Channels.php#L115-L131
train
concrete5/concrete5
concrete/src/Logging/Channels.php
Channels.getChannels
public static function getChannels() { $app = Facade::getFacadeApplication(); $db = $app->make(Connection::class); $channels = (array) $db->GetCol('select distinct channel from Logs order by channel asc'); return $channels; }
php
public static function getChannels() { $app = Facade::getFacadeApplication(); $db = $app->make(Connection::class); $channels = (array) $db->GetCol('select distinct channel from Logs order by channel asc'); return $channels; }
[ "public", "static", "function", "getChannels", "(", ")", "{", "$", "app", "=", "Facade", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "Connection", "::", "class", ")", ";", "$", "channels", "=", "(", "array", ")", "$", "db", "->", "GetCol", "(", "'select distinct channel from Logs order by channel asc'", ")", ";", "return", "$", "channels", ";", "}" ]
Get the list of channels that have been used. Requires the database handler. @return string[]
[ "Get", "the", "list", "of", "channels", "that", "have", "been", "used", ".", "Requires", "the", "database", "handler", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Logging/Channels.php#L139-L146
train
concrete5/concrete5
concrete/src/Logging/Channels.php
Channels.getChannelDisplayName
public static function getChannelDisplayName($channel) { $text = new Text(); switch ($channel) { case self::CHANNEL_APPLICATION: return tc('Log channel', 'Application'); case self::CHANNEL_AUTHENTICATION: return tc('Log channel', 'Authentication'); case self::CHANNEL_EMAIL: return tc('Log channel', 'Sent Emails'); case self::CHANNEL_EXCEPTIONS: return tc('Log channel', 'Exceptions'); case self::CHANNEL_SECURITY: return tc('Log channel', 'Security'); case self::CHANNEL_PACKAGES: return tc('Log channel', 'Packages'); case self::CHANNEL_SPAM: return tc('Log channel', 'Spam'); case self::CHANNEL_SITE_ORGANIZATION: return tc('Log channel', 'Site Organization'); case self::CHANNEL_USERS: return tc('Log channel', 'Users'); case self::CHANNEL_API: return tc('Log channel', 'API'); default: return tc('Log channel', $text->unhandle($channel)); } }
php
public static function getChannelDisplayName($channel) { $text = new Text(); switch ($channel) { case self::CHANNEL_APPLICATION: return tc('Log channel', 'Application'); case self::CHANNEL_AUTHENTICATION: return tc('Log channel', 'Authentication'); case self::CHANNEL_EMAIL: return tc('Log channel', 'Sent Emails'); case self::CHANNEL_EXCEPTIONS: return tc('Log channel', 'Exceptions'); case self::CHANNEL_SECURITY: return tc('Log channel', 'Security'); case self::CHANNEL_PACKAGES: return tc('Log channel', 'Packages'); case self::CHANNEL_SPAM: return tc('Log channel', 'Spam'); case self::CHANNEL_SITE_ORGANIZATION: return tc('Log channel', 'Site Organization'); case self::CHANNEL_USERS: return tc('Log channel', 'Users'); case self::CHANNEL_API: return tc('Log channel', 'API'); default: return tc('Log channel', $text->unhandle($channel)); } }
[ "public", "static", "function", "getChannelDisplayName", "(", "$", "channel", ")", "{", "$", "text", "=", "new", "Text", "(", ")", ";", "switch", "(", "$", "channel", ")", "{", "case", "self", "::", "CHANNEL_APPLICATION", ":", "return", "tc", "(", "'Log channel'", ",", "'Application'", ")", ";", "case", "self", "::", "CHANNEL_AUTHENTICATION", ":", "return", "tc", "(", "'Log channel'", ",", "'Authentication'", ")", ";", "case", "self", "::", "CHANNEL_EMAIL", ":", "return", "tc", "(", "'Log channel'", ",", "'Sent Emails'", ")", ";", "case", "self", "::", "CHANNEL_EXCEPTIONS", ":", "return", "tc", "(", "'Log channel'", ",", "'Exceptions'", ")", ";", "case", "self", "::", "CHANNEL_SECURITY", ":", "return", "tc", "(", "'Log channel'", ",", "'Security'", ")", ";", "case", "self", "::", "CHANNEL_PACKAGES", ":", "return", "tc", "(", "'Log channel'", ",", "'Packages'", ")", ";", "case", "self", "::", "CHANNEL_SPAM", ":", "return", "tc", "(", "'Log channel'", ",", "'Spam'", ")", ";", "case", "self", "::", "CHANNEL_SITE_ORGANIZATION", ":", "return", "tc", "(", "'Log channel'", ",", "'Site Organization'", ")", ";", "case", "self", "::", "CHANNEL_USERS", ":", "return", "tc", "(", "'Log channel'", ",", "'Users'", ")", ";", "case", "self", "::", "CHANNEL_API", ":", "return", "tc", "(", "'Log channel'", ",", "'API'", ")", ";", "default", ":", "return", "tc", "(", "'Log channel'", ",", "$", "text", "->", "unhandle", "(", "$", "channel", ")", ")", ";", "}", "}" ]
Get the display name of a channel. @param string $channel @return string
[ "Get", "the", "display", "name", "of", "a", "channel", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Logging/Channels.php#L155-L182
train
concrete5/concrete5
concrete/src/User/ValidationHash.php
ValidationHash.removeExpired
protected static function removeExpired($type) { switch ($type) { case UVTYPE_CHANGE_PASSWORD: $lifetime = USER_CHANGE_PASSWORD_URL_LIFETIME; break; case UVTYPE_LOGIN_FOREVER: $lifetime = USER_FOREVER_COOKIE_LIFETIME; break; default: $lifetime = 5184000; // 60 days break; } $db = Database::connection(); $db->executeQuery('DELETE FROM UserValidationHashes WHERE type = ? AND uDateGenerated <= ?', array($type, time() - $lifetime)); }
php
protected static function removeExpired($type) { switch ($type) { case UVTYPE_CHANGE_PASSWORD: $lifetime = USER_CHANGE_PASSWORD_URL_LIFETIME; break; case UVTYPE_LOGIN_FOREVER: $lifetime = USER_FOREVER_COOKIE_LIFETIME; break; default: $lifetime = 5184000; // 60 days break; } $db = Database::connection(); $db->executeQuery('DELETE FROM UserValidationHashes WHERE type = ? AND uDateGenerated <= ?', array($type, time() - $lifetime)); }
[ "protected", "static", "function", "removeExpired", "(", "$", "type", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "UVTYPE_CHANGE_PASSWORD", ":", "$", "lifetime", "=", "USER_CHANGE_PASSWORD_URL_LIFETIME", ";", "break", ";", "case", "UVTYPE_LOGIN_FOREVER", ":", "$", "lifetime", "=", "USER_FOREVER_COOKIE_LIFETIME", ";", "break", ";", "default", ":", "$", "lifetime", "=", "5184000", ";", "// 60 days", "break", ";", "}", "$", "db", "=", "Database", "::", "connection", "(", ")", ";", "$", "db", "->", "executeQuery", "(", "'DELETE FROM UserValidationHashes WHERE type = ? AND uDateGenerated <= ?'", ",", "array", "(", "$", "type", ",", "time", "(", ")", "-", "$", "lifetime", ")", ")", ";", "}" ]
Removes old entries for the supplied type. @param int $type
[ "Removes", "old", "entries", "for", "the", "supplied", "type", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/ValidationHash.php#L26-L41
train
concrete5/concrete5
concrete/src/User/ValidationHash.php
ValidationHash.add
public static function add($uID, $type, $singeHashAllowed = false, $hashLength = 64) { self::removeExpired($type); $hash = self::generate($hashLength); $db = Database::connection(); if ($singeHashAllowed) { $db->executeQuery("DELETE FROM UserValidationHashes WHERE uID = ? AND type = ?", array($uID, $type)); } $db->executeQuery("insert into UserValidationHashes (uID, uHash, uDateGenerated, type) values (?, ?, ?, ?)", array($uID, $hash, time(), intval($type))); return $hash; }
php
public static function add($uID, $type, $singeHashAllowed = false, $hashLength = 64) { self::removeExpired($type); $hash = self::generate($hashLength); $db = Database::connection(); if ($singeHashAllowed) { $db->executeQuery("DELETE FROM UserValidationHashes WHERE uID = ? AND type = ?", array($uID, $type)); } $db->executeQuery("insert into UserValidationHashes (uID, uHash, uDateGenerated, type) values (?, ?, ?, ?)", array($uID, $hash, time(), intval($type))); return $hash; }
[ "public", "static", "function", "add", "(", "$", "uID", ",", "$", "type", ",", "$", "singeHashAllowed", "=", "false", ",", "$", "hashLength", "=", "64", ")", "{", "self", "::", "removeExpired", "(", "$", "type", ")", ";", "$", "hash", "=", "self", "::", "generate", "(", "$", "hashLength", ")", ";", "$", "db", "=", "Database", "::", "connection", "(", ")", ";", "if", "(", "$", "singeHashAllowed", ")", "{", "$", "db", "->", "executeQuery", "(", "\"DELETE FROM UserValidationHashes WHERE uID = ? AND type = ?\"", ",", "array", "(", "$", "uID", ",", "$", "type", ")", ")", ";", "}", "$", "db", "->", "executeQuery", "(", "\"insert into UserValidationHashes (uID, uHash, uDateGenerated, type) values (?, ?, ?, ?)\"", ",", "array", "(", "$", "uID", ",", "$", "hash", ",", "time", "(", ")", ",", "intval", "(", "$", "type", ")", ")", ")", ";", "return", "$", "hash", ";", "}" ]
Adds a hash to the lookup table for a user and type, removes any other existing hashes for the same user and type. @param int $uID @param int $type @param bool $singeHashAllowed @param int $hashLength @return string
[ "Adds", "a", "hash", "to", "the", "lookup", "table", "for", "a", "user", "and", "type", "removes", "any", "other", "existing", "hashes", "for", "the", "same", "user", "and", "type", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/ValidationHash.php#L53-L64
train
concrete5/concrete5
concrete/src/User/ValidationHash.php
ValidationHash.getUserID
public static function getUserID($hash, $type) { self::removeExpired($type); $db = Database::connection(); $uID = $db->fetchColumn("SELECT uID FROM UserValidationHashes WHERE uHash = ? AND type = ?", array($hash, $type)); if (is_numeric($uID) && $uID > 0) { return $uID; } else { return false; } }
php
public static function getUserID($hash, $type) { self::removeExpired($type); $db = Database::connection(); $uID = $db->fetchColumn("SELECT uID FROM UserValidationHashes WHERE uHash = ? AND type = ?", array($hash, $type)); if (is_numeric($uID) && $uID > 0) { return $uID; } else { return false; } }
[ "public", "static", "function", "getUserID", "(", "$", "hash", ",", "$", "type", ")", "{", "self", "::", "removeExpired", "(", "$", "type", ")", ";", "$", "db", "=", "Database", "::", "connection", "(", ")", ";", "$", "uID", "=", "$", "db", "->", "fetchColumn", "(", "\"SELECT uID FROM UserValidationHashes WHERE uHash = ? AND type = ?\"", ",", "array", "(", "$", "hash", ",", "$", "type", ")", ")", ";", "if", "(", "is_numeric", "(", "$", "uID", ")", "&&", "$", "uID", ">", "0", ")", "{", "return", "$", "uID", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Gets the users id for a given hash and type. @param string $hash @param int $type @return int | false
[ "Gets", "the", "users", "id", "for", "a", "given", "hash", "and", "type", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/ValidationHash.php#L74-L84
train
concrete5/concrete5
concrete/src/User/ValidationHash.php
ValidationHash.getType
public static function getType($hash) { $db = Database::connection(); $type = $db->fetchColumn("SELECT type FROM UserValidationHashes WHERE uHash = ? ", array($hash)); if (is_numeric($type) && $type > 0) { return $type; } else { return false; } }
php
public static function getType($hash) { $db = Database::connection(); $type = $db->fetchColumn("SELECT type FROM UserValidationHashes WHERE uHash = ? ", array($hash)); if (is_numeric($type) && $type > 0) { return $type; } else { return false; } }
[ "public", "static", "function", "getType", "(", "$", "hash", ")", "{", "$", "db", "=", "Database", "::", "connection", "(", ")", ";", "$", "type", "=", "$", "db", "->", "fetchColumn", "(", "\"SELECT type FROM UserValidationHashes WHERE uHash = ? \"", ",", "array", "(", "$", "hash", ")", ")", ";", "if", "(", "is_numeric", "(", "$", "type", ")", "&&", "$", "type", ">", "0", ")", "{", "return", "$", "type", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Gets the hash type for a given hash. @param string $hash @return int | false
[ "Gets", "the", "hash", "type", "for", "a", "given", "hash", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/ValidationHash.php#L93-L102
train
concrete5/concrete5
concrete/src/User/ValidationHash.php
ValidationHash.isValid
public static function isValid($hash) { $type = self::getType($hash); self::removeExpired($type); return (bool) self::getUserID($hash, $type); }
php
public static function isValid($hash) { $type = self::getType($hash); self::removeExpired($type); return (bool) self::getUserID($hash, $type); }
[ "public", "static", "function", "isValid", "(", "$", "hash", ")", "{", "$", "type", "=", "self", "::", "getType", "(", "$", "hash", ")", ";", "self", "::", "removeExpired", "(", "$", "type", ")", ";", "return", "(", "bool", ")", "self", "::", "getUserID", "(", "$", "hash", ",", "$", "type", ")", ";", "}" ]
Validate the given hash @param $hash @return bool
[ "Validate", "the", "given", "hash" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/ValidationHash.php#L111-L116
train
concrete5/concrete5
concrete/src/Form/Service/Validation.php
Validation.addUploadedImage
public function addUploadedImage($field, $errorMsg = null, $emptyIsOk = true) { $const = ($emptyIsOk) ? self::VALID_UPLOADED_IMAGE : self::VALID_UPLOADED_IMAGE_REQUIRED; $this->addRequired($field, $errorMsg, $const); }
php
public function addUploadedImage($field, $errorMsg = null, $emptyIsOk = true) { $const = ($emptyIsOk) ? self::VALID_UPLOADED_IMAGE : self::VALID_UPLOADED_IMAGE_REQUIRED; $this->addRequired($field, $errorMsg, $const); }
[ "public", "function", "addUploadedImage", "(", "$", "field", ",", "$", "errorMsg", "=", "null", ",", "$", "emptyIsOk", "=", "true", ")", "{", "$", "const", "=", "(", "$", "emptyIsOk", ")", "?", "self", "::", "VALID_UPLOADED_IMAGE", ":", "self", "::", "VALID_UPLOADED_IMAGE_REQUIRED", ";", "$", "this", "->", "addRequired", "(", "$", "field", ",", "$", "errorMsg", ",", "$", "const", ")", ";", "}" ]
Adds a test to a field to ensure that, if set, it is a valid uploaded image. @param string $field @param string $errorMsg @param bool $emptyIsOk Tells whether this can be submitted as empty (e.g. the validation tests only run if someone is actually submitted in the post.)
[ "Adds", "a", "test", "to", "a", "field", "to", "ensure", "that", "if", "set", "it", "is", "a", "valid", "uploaded", "image", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Form/Service/Validation.php#L59-L63
train
concrete5/concrete5
concrete/src/Form/Service/Validation.php
Validation.addUploadedFile
public function addUploadedFile($field, $errorMsg = null, $emptyIsOk = true) { $const = ($emptyIsOk) ? self::VALID_UPLOADED_FILE : self::VALID_UPLOADED_FILE_REQUIRED; $this->addRequired($field, $errorMsg, $const); }
php
public function addUploadedFile($field, $errorMsg = null, $emptyIsOk = true) { $const = ($emptyIsOk) ? self::VALID_UPLOADED_FILE : self::VALID_UPLOADED_FILE_REQUIRED; $this->addRequired($field, $errorMsg, $const); }
[ "public", "function", "addUploadedFile", "(", "$", "field", ",", "$", "errorMsg", "=", "null", ",", "$", "emptyIsOk", "=", "true", ")", "{", "$", "const", "=", "(", "$", "emptyIsOk", ")", "?", "self", "::", "VALID_UPLOADED_FILE", ":", "self", "::", "VALID_UPLOADED_FILE_REQUIRED", ";", "$", "this", "->", "addRequired", "(", "$", "field", ",", "$", "errorMsg", ",", "$", "const", ")", ";", "}" ]
Adds a test to a field to ensure that, if set, it is a valid uploaded file. @param string $field @param string $errorMsg @param bool $emptyIsOk Tells whether this can be submitted as empty (e.g. the validation tests only run if someone is actually submitted in the post.)
[ "Adds", "a", "test", "to", "a", "field", "to", "ensure", "that", "if", "set", "it", "is", "a", "valid", "uploaded", "file", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Form/Service/Validation.php#L89-L93
train
concrete5/concrete5
concrete/src/Form/Service/Validation.php
Validation.addInteger
public function addInteger($field, $errorMsg = null, $emptyIsOk = true) { $const = ($emptyIsOk) ? self::VALID_INTEGER : self::VALID_INTEGER_REQUIRED; $this->addRequired($field, $errorMsg, $const); }
php
public function addInteger($field, $errorMsg = null, $emptyIsOk = true) { $const = ($emptyIsOk) ? self::VALID_INTEGER : self::VALID_INTEGER_REQUIRED; $this->addRequired($field, $errorMsg, $const); }
[ "public", "function", "addInteger", "(", "$", "field", ",", "$", "errorMsg", "=", "null", ",", "$", "emptyIsOk", "=", "true", ")", "{", "$", "const", "=", "(", "$", "emptyIsOk", ")", "?", "self", "::", "VALID_INTEGER", ":", "self", "::", "VALID_INTEGER_REQUIRED", ";", "$", "this", "->", "addRequired", "(", "$", "field", ",", "$", "errorMsg", ",", "$", "const", ")", ";", "}" ]
Adds a required field and tests that it is integer only. @param string $field @param string $errorMsg @param bool $emptyIsOk Tells whether this can be submitted as empty (e.g. the validation tests only run if someone is actually submitted in the post.)
[ "Adds", "a", "required", "field", "and", "tests", "that", "it", "is", "integer", "only", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Form/Service/Validation.php#L102-L106
train
concrete5/concrete5
concrete/src/Form/Service/Validation.php
Validation.addRequiredEmail
public function addRequiredEmail($field, $errorMsg = null) { $this->addRequired($field, $errorMsg, self::VALID_EMAIL); }
php
public function addRequiredEmail($field, $errorMsg = null) { $this->addRequired($field, $errorMsg, self::VALID_EMAIL); }
[ "public", "function", "addRequiredEmail", "(", "$", "field", ",", "$", "errorMsg", "=", "null", ")", "{", "$", "this", "->", "addRequired", "(", "$", "field", ",", "$", "errorMsg", ",", "self", "::", "VALID_EMAIL", ")", ";", "}" ]
Adds a required email address to the suite of tests to be run. @param string $field @param string $errorMsg
[ "Adds", "a", "required", "email", "address", "to", "the", "suite", "of", "tests", "to", "be", "run", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Form/Service/Validation.php#L124-L127
train
concrete5/concrete5
concrete/src/Editor/Plugin.php
Plugin.requireAsset
public function requireAsset($assetType, $assetHandle = false) { $list = AssetList::getInstance(); if ($assetType instanceof AssetInterface) { $this->requiredAssetGroup->addAsset($assetType); } elseif ($assetType && $assetHandle) { $ap = new AssetPointer($assetType, $assetHandle); $this->requiredAssetGroup->add($ap); } else { $r = $list->getAssetGroup($assetType); if (isset($r)) { $this->requiredAssetGroup->addGroup($r); } else { throw new Exception(t('"%s" is not a valid asset group handle', $assetType)); } } }
php
public function requireAsset($assetType, $assetHandle = false) { $list = AssetList::getInstance(); if ($assetType instanceof AssetInterface) { $this->requiredAssetGroup->addAsset($assetType); } elseif ($assetType && $assetHandle) { $ap = new AssetPointer($assetType, $assetHandle); $this->requiredAssetGroup->add($ap); } else { $r = $list->getAssetGroup($assetType); if (isset($r)) { $this->requiredAssetGroup->addGroup($r); } else { throw new Exception(t('"%s" is not a valid asset group handle', $assetType)); } } }
[ "public", "function", "requireAsset", "(", "$", "assetType", ",", "$", "assetHandle", "=", "false", ")", "{", "$", "list", "=", "AssetList", "::", "getInstance", "(", ")", ";", "if", "(", "$", "assetType", "instanceof", "AssetInterface", ")", "{", "$", "this", "->", "requiredAssetGroup", "->", "addAsset", "(", "$", "assetType", ")", ";", "}", "elseif", "(", "$", "assetType", "&&", "$", "assetHandle", ")", "{", "$", "ap", "=", "new", "AssetPointer", "(", "$", "assetType", ",", "$", "assetHandle", ")", ";", "$", "this", "->", "requiredAssetGroup", "->", "add", "(", "$", "ap", ")", ";", "}", "else", "{", "$", "r", "=", "$", "list", "->", "getAssetGroup", "(", "$", "assetType", ")", ";", "if", "(", "isset", "(", "$", "r", ")", ")", "{", "$", "this", "->", "requiredAssetGroup", "->", "addGroup", "(", "$", "r", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "t", "(", "'\"%s\" is not a valid asset group handle'", ",", "$", "assetType", ")", ")", ";", "}", "}", "}" ]
Add an asset to the assets required for this plugin. @param \Concrete\Core\Asset\AssetInterface|string $assetType The asset to require, or the asset group handle, or the asset type (in this case, specify the $assetHandle parameter) @param string|null|false $assetHandle the handle of the asset to specify (if $assetType is the asset type handle) @throws \Exception throws an Exception if the asset is not valid
[ "Add", "an", "asset", "to", "the", "assets", "required", "for", "this", "plugin", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Editor/Plugin.php#L67-L83
train
concrete5/concrete5
concrete/src/User/Login/LoginService.php
LoginService.login
public function login($username, $password) { /** * @todo Invert this so that the `new User` constructor login relies on this service */ $className = $this->userClass; $user = new $className($username, $password); if ($user->isError()) { // Throw an appropriate acception matching the exceptional state $this->handleUserError($user->getError()); } return $user; }
php
public function login($username, $password) { /** * @todo Invert this so that the `new User` constructor login relies on this service */ $className = $this->userClass; $user = new $className($username, $password); if ($user->isError()) { // Throw an appropriate acception matching the exceptional state $this->handleUserError($user->getError()); } return $user; }
[ "public", "function", "login", "(", "$", "username", ",", "$", "password", ")", "{", "/**\n * @todo Invert this so that the `new User` constructor login relies on this service\n */", "$", "className", "=", "$", "this", "->", "userClass", ";", "$", "user", "=", "new", "$", "className", "(", "$", "username", ",", "$", "password", ")", ";", "if", "(", "$", "user", "->", "isError", "(", ")", ")", "{", "// Throw an appropriate acception matching the exceptional state", "$", "this", "->", "handleUserError", "(", "$", "user", "->", "getError", "(", ")", ")", ";", "}", "return", "$", "user", ";", "}" ]
Attempt login given a username and a password @param string $username The username or email to attempt login with @param string $password The plain text password to attempt login with @return User The logged in user @throws \Concrete\Core\User\Exception\NotActiveException If the user is inactive @throws \Concrete\Core\User\Exception\InvalidCredentialsException If passed credentials don't seem valid @throws \Concrete\Core\User\Exception\NotValidatedException If the user has not yet been validated @throws \Concrete\Core\User\Exception\SessionExpiredException If the session immediately expires after login
[ "Attempt", "login", "given", "a", "username", "and", "a", "password" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/Login/LoginService.php#L101-L115
train
concrete5/concrete5
concrete/src/User/Login/LoginService.php
LoginService.failLogin
public function failLogin($username, $password) { $ipFailed = false; $userFailed = false; // Track both failed logins from this IP and attempts to login to this user account $this->ipService->logFailedLogin(); $this->loginAttemptService->trackAttempt($username, $password); // Deal with excessive logins from an IP if ($this->ipService->failedLoginsThresholdReached()) { $this->ipService->addToBlacklistForThresholdReached(); $ipFailed = true; } // If the remaining attempts are less than 0 if ($this->loginAttemptService->remainingAttempts($username, $password) <= 0) { $this->loginAttemptService->deactivate($username); $userFailed = true; } // Throw the IP ban error if we hit both ip limit and user limit at the same time if ($ipFailed) { $message = $this->ipService->getErrorMessage(); throw new FailedLoginThresholdExceededException($message); } // If the user has been automatically deactivated and the IP has not been banned if ($userFailed) { throw new UserDeactivatedException($this->config->get('concrete.user.deactivation.message')); } }
php
public function failLogin($username, $password) { $ipFailed = false; $userFailed = false; // Track both failed logins from this IP and attempts to login to this user account $this->ipService->logFailedLogin(); $this->loginAttemptService->trackAttempt($username, $password); // Deal with excessive logins from an IP if ($this->ipService->failedLoginsThresholdReached()) { $this->ipService->addToBlacklistForThresholdReached(); $ipFailed = true; } // If the remaining attempts are less than 0 if ($this->loginAttemptService->remainingAttempts($username, $password) <= 0) { $this->loginAttemptService->deactivate($username); $userFailed = true; } // Throw the IP ban error if we hit both ip limit and user limit at the same time if ($ipFailed) { $message = $this->ipService->getErrorMessage(); throw new FailedLoginThresholdExceededException($message); } // If the user has been automatically deactivated and the IP has not been banned if ($userFailed) { throw new UserDeactivatedException($this->config->get('concrete.user.deactivation.message')); } }
[ "public", "function", "failLogin", "(", "$", "username", ",", "$", "password", ")", "{", "$", "ipFailed", "=", "false", ";", "$", "userFailed", "=", "false", ";", "// Track both failed logins from this IP and attempts to login to this user account", "$", "this", "->", "ipService", "->", "logFailedLogin", "(", ")", ";", "$", "this", "->", "loginAttemptService", "->", "trackAttempt", "(", "$", "username", ",", "$", "password", ")", ";", "// Deal with excessive logins from an IP", "if", "(", "$", "this", "->", "ipService", "->", "failedLoginsThresholdReached", "(", ")", ")", "{", "$", "this", "->", "ipService", "->", "addToBlacklistForThresholdReached", "(", ")", ";", "$", "ipFailed", "=", "true", ";", "}", "// If the remaining attempts are less than 0", "if", "(", "$", "this", "->", "loginAttemptService", "->", "remainingAttempts", "(", "$", "username", ",", "$", "password", ")", "<=", "0", ")", "{", "$", "this", "->", "loginAttemptService", "->", "deactivate", "(", "$", "username", ")", ";", "$", "userFailed", "=", "true", ";", "}", "// Throw the IP ban error if we hit both ip limit and user limit at the same time", "if", "(", "$", "ipFailed", ")", "{", "$", "message", "=", "$", "this", "->", "ipService", "->", "getErrorMessage", "(", ")", ";", "throw", "new", "FailedLoginThresholdExceededException", "(", "$", "message", ")", ";", "}", "// If the user has been automatically deactivated and the IP has not been banned", "if", "(", "$", "userFailed", ")", "{", "throw", "new", "UserDeactivatedException", "(", "$", "this", "->", "config", "->", "get", "(", "'concrete.user.deactivation.message'", ")", ")", ";", "}", "}" ]
Handle a failed login attempt @param string $username The user provided username @param string $password The user provided password @throws \Concrete\Core\User\Exception\FailedLoginThresholdExceededException
[ "Handle", "a", "failed", "login", "attempt" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/Login/LoginService.php#L142-L173
train
concrete5/concrete5
concrete/src/User/Login/LoginService.php
LoginService.logLoginAttempt
public function logLoginAttempt($username, array $errors = []) { if ($this->app) { $entry = $this->app->make(LoginAttempt::class, [ $username, $this->request ? $this->request->getPath() : '', $this->getGroups($username), $errors ]); $context = $entry->getContext(); $context['ip_address'] = (string) $this->ipService->getRequestIPAddress(); $this->logger->info($entry->getMessage(), $context); } }
php
public function logLoginAttempt($username, array $errors = []) { if ($this->app) { $entry = $this->app->make(LoginAttempt::class, [ $username, $this->request ? $this->request->getPath() : '', $this->getGroups($username), $errors ]); $context = $entry->getContext(); $context['ip_address'] = (string) $this->ipService->getRequestIPAddress(); $this->logger->info($entry->getMessage(), $context); } }
[ "public", "function", "logLoginAttempt", "(", "$", "username", ",", "array", "$", "errors", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "app", ")", "{", "$", "entry", "=", "$", "this", "->", "app", "->", "make", "(", "LoginAttempt", "::", "class", ",", "[", "$", "username", ",", "$", "this", "->", "request", "?", "$", "this", "->", "request", "->", "getPath", "(", ")", ":", "''", ",", "$", "this", "->", "getGroups", "(", "$", "username", ")", ",", "$", "errors", "]", ")", ";", "$", "context", "=", "$", "entry", "->", "getContext", "(", ")", ";", "$", "context", "[", "'ip_address'", "]", "=", "(", "string", ")", "$", "this", "->", "ipService", "->", "getRequestIPAddress", "(", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "$", "entry", "->", "getMessage", "(", ")", ",", "$", "context", ")", ";", "}", "}" ]
Add a log entry for this login attempt @param $username @param array $errors
[ "Add", "a", "log", "entry", "for", "this", "login", "attempt" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/Login/LoginService.php#L181-L195
train
concrete5/concrete5
concrete/src/User/Login/LoginService.php
LoginService.getGroups
private function getGroups($username) { if (!$this->entityManager) { return []; } $db = $this->entityManager->getConnection(); $queryBuilder = $db->createQueryBuilder(); $rows = $queryBuilder ->select('g.gName', 'u.uID')->from($db->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g') ->leftJoin('g', 'UserGroups', 'ug', 'ug.gID=g.gID') ->innerJoin('ug', 'Users', 'u', 'ug.uID=u.uID AND (u.uName=? OR u.uEmail=?)') ->setParameters([$username, $username]) ->execute(); $groups = []; $uID = 0; foreach ($rows as $row) { $uID = (int) $row['uID']; $groups[] = $row['gName']; } if ($uID == USER_SUPER_ID) { $groups[] = 'SUPER'; } return $groups; }
php
private function getGroups($username) { if (!$this->entityManager) { return []; } $db = $this->entityManager->getConnection(); $queryBuilder = $db->createQueryBuilder(); $rows = $queryBuilder ->select('g.gName', 'u.uID')->from($db->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g') ->leftJoin('g', 'UserGroups', 'ug', 'ug.gID=g.gID') ->innerJoin('ug', 'Users', 'u', 'ug.uID=u.uID AND (u.uName=? OR u.uEmail=?)') ->setParameters([$username, $username]) ->execute(); $groups = []; $uID = 0; foreach ($rows as $row) { $uID = (int) $row['uID']; $groups[] = $row['gName']; } if ($uID == USER_SUPER_ID) { $groups[] = 'SUPER'; } return $groups; }
[ "private", "function", "getGroups", "(", "$", "username", ")", "{", "if", "(", "!", "$", "this", "->", "entityManager", ")", "{", "return", "[", "]", ";", "}", "$", "db", "=", "$", "this", "->", "entityManager", "->", "getConnection", "(", ")", ";", "$", "queryBuilder", "=", "$", "db", "->", "createQueryBuilder", "(", ")", ";", "$", "rows", "=", "$", "queryBuilder", "->", "select", "(", "'g.gName'", ",", "'u.uID'", ")", "->", "from", "(", "$", "db", "->", "getDatabasePlatform", "(", ")", "->", "quoteSingleIdentifier", "(", "'Groups'", ")", ",", "'g'", ")", "->", "leftJoin", "(", "'g'", ",", "'UserGroups'", ",", "'ug'", ",", "'ug.gID=g.gID'", ")", "->", "innerJoin", "(", "'ug'", ",", "'Users'", ",", "'u'", ",", "'ug.uID=u.uID AND (u.uName=? OR u.uEmail=?)'", ")", "->", "setParameters", "(", "[", "$", "username", ",", "$", "username", "]", ")", "->", "execute", "(", ")", ";", "$", "groups", "=", "[", "]", ";", "$", "uID", "=", "0", ";", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "$", "uID", "=", "(", "int", ")", "$", "row", "[", "'uID'", "]", ";", "$", "groups", "[", "]", "=", "$", "row", "[", "'gName'", "]", ";", "}", "if", "(", "$", "uID", "==", "USER_SUPER_ID", ")", "{", "$", "groups", "[", "]", "=", "'SUPER'", ";", "}", "return", "$", "groups", ";", "}" ]
Aggregate a list of groups to report @param $username @return array
[ "Aggregate", "a", "list", "of", "groups", "to", "report" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/Login/LoginService.php#L203-L231
train
concrete5/concrete5
concrete/src/User/Login/LoginService.php
LoginService.handleUserError
protected function handleUserError($errorNum) { switch ($errorNum) { case USER_INACTIVE: throw new NotActiveException(t($this->config->get('concrete.user.deactivation.message'))); case USER_SESSION_EXPIRED: throw new SessionExpiredException(t('Your session has expired. Please sign in again.')); case USER_NON_VALIDATED: throw new NotValidatedException(t( 'This account has not yet been validated. Please check the email associated with this ' . 'account and follow the link it contains.')); case USER_PASSWORD_RESET: throw new UserPasswordResetException(t('This password has been reset.')); case USER_INVALID: if ($this->config->get('concrete.user.registration.email_registration')) { $message = t('Invalid email address or password.'); } else { $message = t('Invalid username or password.'); } throw new InvalidCredentialsException($message); } throw new \RuntimeException(t('An unknown login error occurred. Please try again.')); }
php
protected function handleUserError($errorNum) { switch ($errorNum) { case USER_INACTIVE: throw new NotActiveException(t($this->config->get('concrete.user.deactivation.message'))); case USER_SESSION_EXPIRED: throw new SessionExpiredException(t('Your session has expired. Please sign in again.')); case USER_NON_VALIDATED: throw new NotValidatedException(t( 'This account has not yet been validated. Please check the email associated with this ' . 'account and follow the link it contains.')); case USER_PASSWORD_RESET: throw new UserPasswordResetException(t('This password has been reset.')); case USER_INVALID: if ($this->config->get('concrete.user.registration.email_registration')) { $message = t('Invalid email address or password.'); } else { $message = t('Invalid username or password.'); } throw new InvalidCredentialsException($message); } throw new \RuntimeException(t('An unknown login error occurred. Please try again.')); }
[ "protected", "function", "handleUserError", "(", "$", "errorNum", ")", "{", "switch", "(", "$", "errorNum", ")", "{", "case", "USER_INACTIVE", ":", "throw", "new", "NotActiveException", "(", "t", "(", "$", "this", "->", "config", "->", "get", "(", "'concrete.user.deactivation.message'", ")", ")", ")", ";", "case", "USER_SESSION_EXPIRED", ":", "throw", "new", "SessionExpiredException", "(", "t", "(", "'Your session has expired. Please sign in again.'", ")", ")", ";", "case", "USER_NON_VALIDATED", ":", "throw", "new", "NotValidatedException", "(", "t", "(", "'This account has not yet been validated. Please check the email associated with this '", ".", "'account and follow the link it contains.'", ")", ")", ";", "case", "USER_PASSWORD_RESET", ":", "throw", "new", "UserPasswordResetException", "(", "t", "(", "'This password has been reset.'", ")", ")", ";", "case", "USER_INVALID", ":", "if", "(", "$", "this", "->", "config", "->", "get", "(", "'concrete.user.registration.email_registration'", ")", ")", "{", "$", "message", "=", "t", "(", "'Invalid email address or password.'", ")", ";", "}", "else", "{", "$", "message", "=", "t", "(", "'Invalid username or password.'", ")", ";", "}", "throw", "new", "InvalidCredentialsException", "(", "$", "message", ")", ";", "}", "throw", "new", "\\", "RuntimeException", "(", "t", "(", "'An unknown login error occurred. Please try again.'", ")", ")", ";", "}" ]
Throw an exception based on the given error number @param int $errorNum The error number retrieved from the user object @throws \RuntimeException If an unknown error number is passed @throws \Concrete\Core\User\Exception\NotActiveException If the user is inactive @throws \Concrete\Core\User\Exception\InvalidCredentialsException If passed credentials don't seem valid @throws \Concrete\Core\User\Exception\NotValidatedException If the user has not yet been validated @throws \Concrete\Core\User\Exception\SessionExpiredException If the session immediately expires after login
[ "Throw", "an", "exception", "based", "on", "the", "given", "error", "number" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/Login/LoginService.php#L244-L270
train
concrete5/concrete5
concrete/src/File/Image/Svg/SanitizerOptions.php
SanitizerOptions.normalizeStringList
protected function normalizeStringList($value) { if (is_string($value)) { $strings = preg_split('/\s+/', $value, -1, PREG_SPLIT_NO_EMPTY); } elseif (is_array($value)) { $strings = array_map('trim', array_map('strval', $value)); } else { $strings = []; } return array_values(array_unique(array_map('strtolower', $strings))); }
php
protected function normalizeStringList($value) { if (is_string($value)) { $strings = preg_split('/\s+/', $value, -1, PREG_SPLIT_NO_EMPTY); } elseif (is_array($value)) { $strings = array_map('trim', array_map('strval', $value)); } else { $strings = []; } return array_values(array_unique(array_map('strtolower', $strings))); }
[ "protected", "function", "normalizeStringList", "(", "$", "value", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "strings", "=", "preg_split", "(", "'/\\s+/'", ",", "$", "value", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "strings", "=", "array_map", "(", "'trim'", ",", "array_map", "(", "'strval'", ",", "$", "value", ")", ")", ";", "}", "else", "{", "$", "strings", "=", "[", "]", ";", "}", "return", "array_values", "(", "array_unique", "(", "array_map", "(", "'strtolower'", ",", "$", "strings", ")", ")", ")", ";", "}" ]
Takes an array, keeps only strings, makes them lowercase, and returns the unique values. @param string|array $value @return string[]
[ "Takes", "an", "array", "keeps", "only", "strings", "makes", "them", "lowercase", "and", "returns", "the", "unique", "values", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Image/Svg/SanitizerOptions.php#L203-L214
train
concrete5/concrete5
concrete/src/Express/Formatter/LabelFormatter.php
LabelFormatter.format
public function format($mask, callable $matchHandler) { try { // Run a regular expression to match the mask return preg_replace_callback('/%(.*?)%/i', function ($matches) use ($matchHandler) { // Return the result returned from the matchHandler return $this->getResult($matches[1], $matchHandler) ?: ''; }, $mask); } catch (\Exception $e) { // Log any failures $this->logger->debug( 'Failed to format express mask "{mask}": {message}', ['mask' => $mask, 'message' => $e->getMessage(), 'exception' => $e] ); } }
php
public function format($mask, callable $matchHandler) { try { // Run a regular expression to match the mask return preg_replace_callback('/%(.*?)%/i', function ($matches) use ($matchHandler) { // Return the result returned from the matchHandler return $this->getResult($matches[1], $matchHandler) ?: ''; }, $mask); } catch (\Exception $e) { // Log any failures $this->logger->debug( 'Failed to format express mask "{mask}": {message}', ['mask' => $mask, 'message' => $e->getMessage(), 'exception' => $e] ); } }
[ "public", "function", "format", "(", "$", "mask", ",", "callable", "$", "matchHandler", ")", "{", "try", "{", "// Run a regular expression to match the mask", "return", "preg_replace_callback", "(", "'/%(.*?)%/i'", ",", "function", "(", "$", "matches", ")", "use", "(", "$", "matchHandler", ")", "{", "// Return the result returned from the matchHandler", "return", "$", "this", "->", "getResult", "(", "$", "matches", "[", "1", "]", ",", "$", "matchHandler", ")", "?", ":", "''", ";", "}", ",", "$", "mask", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Log any failures", "$", "this", "->", "logger", "->", "debug", "(", "'Failed to format express mask \"{mask}\": {message}'", ",", "[", "'mask'", "=>", "$", "mask", ",", "'message'", "=>", "$", "e", "->", "getMessage", "(", ")", ",", "'exception'", "=>", "$", "e", "]", ")", ";", "}", "}" ]
Format a mask using the standard format given a callable Ex: if you have attributes with handles `student_first_name` and `student_last_name` `%student_last_name%, %student_first_name%` @param $mask @param callable $matchHandler @return mixed
[ "Format", "a", "mask", "using", "the", "standard", "format", "given", "a", "callable" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Express/Formatter/LabelFormatter.php#L28-L43
train
concrete5/concrete5
concrete/src/View/AbstractView.php
AbstractView.post
public function post($key, $defaultValue = null) { $r = Request::getInstance(); return $r->post($key, $defaultValue); }
php
public function post($key, $defaultValue = null) { $r = Request::getInstance(); return $r->post($key, $defaultValue); }
[ "public", "function", "post", "(", "$", "key", ",", "$", "defaultValue", "=", "null", ")", "{", "$", "r", "=", "Request", "::", "getInstance", "(", ")", ";", "return", "$", "r", "->", "post", "(", "$", "key", ",", "$", "defaultValue", ")", ";", "}" ]
Returns the value of the item in the POST array. @param $key
[ "Returns", "the", "value", "of", "the", "item", "in", "the", "POST", "array", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/View/AbstractView.php#L124-L129
train
concrete5/concrete5
concrete/src/View/AbstractView.php
AbstractView.setThemeByPath
public function setThemeByPath($path, $theme = null, $wrapper = FILENAME_THEMES_VIEW) { $l = Router::get(); $l->setThemeByRoute($path, $theme, $wrapper); }
php
public function setThemeByPath($path, $theme = null, $wrapper = FILENAME_THEMES_VIEW) { $l = Router::get(); $l->setThemeByRoute($path, $theme, $wrapper); }
[ "public", "function", "setThemeByPath", "(", "$", "path", ",", "$", "theme", "=", "null", ",", "$", "wrapper", "=", "FILENAME_THEMES_VIEW", ")", "{", "$", "l", "=", "Router", "::", "get", "(", ")", ";", "$", "l", "->", "setThemeByRoute", "(", "$", "path", ",", "$", "theme", ",", "$", "wrapper", ")", ";", "}" ]
Legacy Items. Deprecated
[ "Legacy", "Items", ".", "Deprecated" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/View/AbstractView.php#L208-L212
train
concrete5/concrete5
concrete/src/Entity/OAuth/Client.php
Client.setConsentType
public function setConsentType($consentType) { if ($consentType !== self::CONSENT_SIMPLE && $consentType !== self::CONSENT_NONE) { throw new InvalidArgumentException('Invalid consent type provided.'); } $this->consentType = $consentType; }
php
public function setConsentType($consentType) { if ($consentType !== self::CONSENT_SIMPLE && $consentType !== self::CONSENT_NONE) { throw new InvalidArgumentException('Invalid consent type provided.'); } $this->consentType = $consentType; }
[ "public", "function", "setConsentType", "(", "$", "consentType", ")", "{", "if", "(", "$", "consentType", "!==", "self", "::", "CONSENT_SIMPLE", "&&", "$", "consentType", "!==", "self", "::", "CONSENT_NONE", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid consent type provided.'", ")", ";", "}", "$", "this", "->", "consentType", "=", "$", "consentType", ";", "}" ]
Set the level of consent this client must receive from the authenticating user @param int $consentType Client::CONSENT_SIMPLE | Client::CONSENT_NONE
[ "Set", "the", "level", "of", "consent", "this", "client", "must", "receive", "from", "the", "authenticating", "user" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Entity/OAuth/Client.php#L180-L188
train
concrete5/concrete5
concrete/src/Form/Service/Widget/UserSelector.php
UserSelector.selectUser
public function selectUser($fieldName, $uID = false) { $v = View::getRequestInstance(); $v->requireAsset('core/users'); $request = $this->app->make(Request::class); if ($request->request->has($fieldName)) { $selectedUID = $request->request->get($fieldName); } elseif ($request->query->has($fieldName)) { $selectedUID = $request->query->get($fieldName); } else { $selectedUID = $uID; } if ($selectedUID && $this->app->make(Numbers::class)->integer($selectedUID, 1)) { $userInfo = $this->app->make(UserInfoRepository::class)->getByID((int) $selectedUID); } else { $userInfo = null; } $selectedUID = $userInfo ? $userInfo->getUserID() : null; $permissions = new Checker(); if ($permissions->canAccessUserSearch()) { $identifier = $this->app->make(Identifier::class)->getString(32); $args = ['inputName' => $fieldName]; if ($userInfo) { $args['uID'] = $userInfo->getUserID(); } $args = json_encode($args); $html = <<<EOL <div data-user-selector="{$identifier}"></div> <script> $(function() { $('[data-user-selector={$identifier}]').concreteUserSelector({$args}); }); </script> EOL; } else { // Read only $uAvatar = null; if ($userInfo) { $uName = $userInfo->getUserDisplayName(); $a = $userInfo->getUserAvatar(); if ($a) { $uAvatar = $a->getPath(); } } else { $uName = t('(None Selected)'); } if (!$uAvatar) { $uAvatar = $this->app->make('config')->get('concrete.icons.user_avatar.default'); } $html = <<<EOL <div class="ccm-item-selector"> <div class="ccm-item-selector-item-selected"> <input type="hidden" name="{$fieldName}" value="{$selectedUID}"> <div class="ccm-item-selector-item-selected-thumbnail"> <img src="{$uAvatar}" alt="admin" class="u-avatar"> </div> <div class="ccm-item-selector-item-selected-title">{$uName}</div> </div> </div> EOL; } return $html; }
php
public function selectUser($fieldName, $uID = false) { $v = View::getRequestInstance(); $v->requireAsset('core/users'); $request = $this->app->make(Request::class); if ($request->request->has($fieldName)) { $selectedUID = $request->request->get($fieldName); } elseif ($request->query->has($fieldName)) { $selectedUID = $request->query->get($fieldName); } else { $selectedUID = $uID; } if ($selectedUID && $this->app->make(Numbers::class)->integer($selectedUID, 1)) { $userInfo = $this->app->make(UserInfoRepository::class)->getByID((int) $selectedUID); } else { $userInfo = null; } $selectedUID = $userInfo ? $userInfo->getUserID() : null; $permissions = new Checker(); if ($permissions->canAccessUserSearch()) { $identifier = $this->app->make(Identifier::class)->getString(32); $args = ['inputName' => $fieldName]; if ($userInfo) { $args['uID'] = $userInfo->getUserID(); } $args = json_encode($args); $html = <<<EOL <div data-user-selector="{$identifier}"></div> <script> $(function() { $('[data-user-selector={$identifier}]').concreteUserSelector({$args}); }); </script> EOL; } else { // Read only $uAvatar = null; if ($userInfo) { $uName = $userInfo->getUserDisplayName(); $a = $userInfo->getUserAvatar(); if ($a) { $uAvatar = $a->getPath(); } } else { $uName = t('(None Selected)'); } if (!$uAvatar) { $uAvatar = $this->app->make('config')->get('concrete.icons.user_avatar.default'); } $html = <<<EOL <div class="ccm-item-selector"> <div class="ccm-item-selector-item-selected"> <input type="hidden" name="{$fieldName}" value="{$selectedUID}"> <div class="ccm-item-selector-item-selected-thumbnail"> <img src="{$uAvatar}" alt="admin" class="u-avatar"> </div> <div class="ccm-item-selector-item-selected-title">{$uName}</div> </div> </div> EOL; } return $html; }
[ "public", "function", "selectUser", "(", "$", "fieldName", ",", "$", "uID", "=", "false", ")", "{", "$", "v", "=", "View", "::", "getRequestInstance", "(", ")", ";", "$", "v", "->", "requireAsset", "(", "'core/users'", ")", ";", "$", "request", "=", "$", "this", "->", "app", "->", "make", "(", "Request", "::", "class", ")", ";", "if", "(", "$", "request", "->", "request", "->", "has", "(", "$", "fieldName", ")", ")", "{", "$", "selectedUID", "=", "$", "request", "->", "request", "->", "get", "(", "$", "fieldName", ")", ";", "}", "elseif", "(", "$", "request", "->", "query", "->", "has", "(", "$", "fieldName", ")", ")", "{", "$", "selectedUID", "=", "$", "request", "->", "query", "->", "get", "(", "$", "fieldName", ")", ";", "}", "else", "{", "$", "selectedUID", "=", "$", "uID", ";", "}", "if", "(", "$", "selectedUID", "&&", "$", "this", "->", "app", "->", "make", "(", "Numbers", "::", "class", ")", "->", "integer", "(", "$", "selectedUID", ",", "1", ")", ")", "{", "$", "userInfo", "=", "$", "this", "->", "app", "->", "make", "(", "UserInfoRepository", "::", "class", ")", "->", "getByID", "(", "(", "int", ")", "$", "selectedUID", ")", ";", "}", "else", "{", "$", "userInfo", "=", "null", ";", "}", "$", "selectedUID", "=", "$", "userInfo", "?", "$", "userInfo", "->", "getUserID", "(", ")", ":", "null", ";", "$", "permissions", "=", "new", "Checker", "(", ")", ";", "if", "(", "$", "permissions", "->", "canAccessUserSearch", "(", ")", ")", "{", "$", "identifier", "=", "$", "this", "->", "app", "->", "make", "(", "Identifier", "::", "class", ")", "->", "getString", "(", "32", ")", ";", "$", "args", "=", "[", "'inputName'", "=>", "$", "fieldName", "]", ";", "if", "(", "$", "userInfo", ")", "{", "$", "args", "[", "'uID'", "]", "=", "$", "userInfo", "->", "getUserID", "(", ")", ";", "}", "$", "args", "=", "json_encode", "(", "$", "args", ")", ";", "$", "html", "=", " <<<EOL\n<div data-user-selector=\"{$identifier}\"></div>\n<script>\n$(function() {\n $('[data-user-selector={$identifier}]').concreteUserSelector({$args});\n});\n</script>\nEOL", ";", "}", "else", "{", "// Read only", "$", "uAvatar", "=", "null", ";", "if", "(", "$", "userInfo", ")", "{", "$", "uName", "=", "$", "userInfo", "->", "getUserDisplayName", "(", ")", ";", "$", "a", "=", "$", "userInfo", "->", "getUserAvatar", "(", ")", ";", "if", "(", "$", "a", ")", "{", "$", "uAvatar", "=", "$", "a", "->", "getPath", "(", ")", ";", "}", "}", "else", "{", "$", "uName", "=", "t", "(", "'(None Selected)'", ")", ";", "}", "if", "(", "!", "$", "uAvatar", ")", "{", "$", "uAvatar", "=", "$", "this", "->", "app", "->", "make", "(", "'config'", ")", "->", "get", "(", "'concrete.icons.user_avatar.default'", ")", ";", "}", "$", "html", "=", " <<<EOL\n<div class=\"ccm-item-selector\">\n <div class=\"ccm-item-selector-item-selected\">\n <input type=\"hidden\" name=\"{$fieldName}\" value=\"{$selectedUID}\">\n <div class=\"ccm-item-selector-item-selected-thumbnail\">\n <img src=\"{$uAvatar}\" alt=\"admin\" class=\"u-avatar\">\n </div>\n <div class=\"ccm-item-selector-item-selected-title\">{$uName}</div>\n </div>\n</div>\nEOL", ";", "}", "return", "$", "html", ";", "}" ]
Build the HTML to be placed in a page to choose a user using a popup dialog. @param string $fieldName the name of the field @param int|false $uID the ID of the user to be initially selected @return string @example <code> $userSelector->selectUser('userID', USER_SUPER_ID); // prints out the admin user and makes it changeable. </code>.
[ "Build", "the", "HTML", "to", "be", "placed", "in", "a", "page", "to", "choose", "a", "user", "using", "a", "popup", "dialog", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Form/Service/Widget/UserSelector.php#L45-L111
train
concrete5/concrete5
concrete/src/Form/Service/Widget/UserSelector.php
UserSelector.quickSelect
public function quickSelect($fieldName, $uID = false, $miscFields = []) { $v = View::getRequestInstance(); $v->requireAsset('selectize'); $request = $this->app->make(Request::class); if ($request->request->has($fieldName)) { $selectedUID = $request->request->get($fieldName); } elseif ($request->query->has($fieldName)) { $selectedUID = $request->query->get($fieldName); } else { $selectedUID = $uID; } if ($selectedUID && $this->app->make(Numbers::class)->integer($selectedUID, 1)) { $userInfo = $this->app->make(UserInfoRepository::class)->getByID((int) $selectedUID); } else { $userInfo = null; } $selectedUID = $userInfo ? $userInfo->getUserID() : null; $valt = $this->app->make('token'); $token = $valt->generate('quick_user_select_' . $fieldName); $identifier = $this->app->make(Identifier::class)->getString(32); $selectizeOptions = [ 'valueField' => 'value', 'labelField' => 'label', 'searchField' => ['label'], 'maxItems' => 1, ]; if ($userInfo) { $selectizeOptions += [ 'options' => [ [ 'label' => h($userInfo->getUserDisplayName()), 'value' => $selectedUID, ], ], 'items' => [ $selectedUID, ], ]; } $selectizeOptions = json_encode($selectizeOptions); $input = $this->app->make('helper/form')->hidden($fieldName, '', $miscFields); $ajaxUrlBase = json_encode(REL_DIR_FILES_TOOLS_REQUIRED . '/users/autocomplete?key=' . rawurlencode($fieldName) . '&token=' . rawurldecode($token)); return <<<EOT <span id="ccm-quick-user-selector-{$identifier}" class="ccm-quick-user-selector">{$input}</span> <script> $(function () { var options = {$selectizeOptions}; options.load = function(query, callback) { if (!query.length) { return callback(); } $.ajax({ url: {$ajaxUrlBase} + '&term=' + encodeURIComponent(query), type: 'GET', dataType: 'json', error: function() { callback(); }, success: function(res) { callback(res); } }); }; $('#ccm-quick-user-selector-{$identifier} input') .unbind() .selectize(options) ; }); </script> EOT ; }
php
public function quickSelect($fieldName, $uID = false, $miscFields = []) { $v = View::getRequestInstance(); $v->requireAsset('selectize'); $request = $this->app->make(Request::class); if ($request->request->has($fieldName)) { $selectedUID = $request->request->get($fieldName); } elseif ($request->query->has($fieldName)) { $selectedUID = $request->query->get($fieldName); } else { $selectedUID = $uID; } if ($selectedUID && $this->app->make(Numbers::class)->integer($selectedUID, 1)) { $userInfo = $this->app->make(UserInfoRepository::class)->getByID((int) $selectedUID); } else { $userInfo = null; } $selectedUID = $userInfo ? $userInfo->getUserID() : null; $valt = $this->app->make('token'); $token = $valt->generate('quick_user_select_' . $fieldName); $identifier = $this->app->make(Identifier::class)->getString(32); $selectizeOptions = [ 'valueField' => 'value', 'labelField' => 'label', 'searchField' => ['label'], 'maxItems' => 1, ]; if ($userInfo) { $selectizeOptions += [ 'options' => [ [ 'label' => h($userInfo->getUserDisplayName()), 'value' => $selectedUID, ], ], 'items' => [ $selectedUID, ], ]; } $selectizeOptions = json_encode($selectizeOptions); $input = $this->app->make('helper/form')->hidden($fieldName, '', $miscFields); $ajaxUrlBase = json_encode(REL_DIR_FILES_TOOLS_REQUIRED . '/users/autocomplete?key=' . rawurlencode($fieldName) . '&token=' . rawurldecode($token)); return <<<EOT <span id="ccm-quick-user-selector-{$identifier}" class="ccm-quick-user-selector">{$input}</span> <script> $(function () { var options = {$selectizeOptions}; options.load = function(query, callback) { if (!query.length) { return callback(); } $.ajax({ url: {$ajaxUrlBase} + '&term=' + encodeURIComponent(query), type: 'GET', dataType: 'json', error: function() { callback(); }, success: function(res) { callback(res); } }); }; $('#ccm-quick-user-selector-{$identifier} input') .unbind() .selectize(options) ; }); </script> EOT ; }
[ "public", "function", "quickSelect", "(", "$", "fieldName", ",", "$", "uID", "=", "false", ",", "$", "miscFields", "=", "[", "]", ")", "{", "$", "v", "=", "View", "::", "getRequestInstance", "(", ")", ";", "$", "v", "->", "requireAsset", "(", "'selectize'", ")", ";", "$", "request", "=", "$", "this", "->", "app", "->", "make", "(", "Request", "::", "class", ")", ";", "if", "(", "$", "request", "->", "request", "->", "has", "(", "$", "fieldName", ")", ")", "{", "$", "selectedUID", "=", "$", "request", "->", "request", "->", "get", "(", "$", "fieldName", ")", ";", "}", "elseif", "(", "$", "request", "->", "query", "->", "has", "(", "$", "fieldName", ")", ")", "{", "$", "selectedUID", "=", "$", "request", "->", "query", "->", "get", "(", "$", "fieldName", ")", ";", "}", "else", "{", "$", "selectedUID", "=", "$", "uID", ";", "}", "if", "(", "$", "selectedUID", "&&", "$", "this", "->", "app", "->", "make", "(", "Numbers", "::", "class", ")", "->", "integer", "(", "$", "selectedUID", ",", "1", ")", ")", "{", "$", "userInfo", "=", "$", "this", "->", "app", "->", "make", "(", "UserInfoRepository", "::", "class", ")", "->", "getByID", "(", "(", "int", ")", "$", "selectedUID", ")", ";", "}", "else", "{", "$", "userInfo", "=", "null", ";", "}", "$", "selectedUID", "=", "$", "userInfo", "?", "$", "userInfo", "->", "getUserID", "(", ")", ":", "null", ";", "$", "valt", "=", "$", "this", "->", "app", "->", "make", "(", "'token'", ")", ";", "$", "token", "=", "$", "valt", "->", "generate", "(", "'quick_user_select_'", ".", "$", "fieldName", ")", ";", "$", "identifier", "=", "$", "this", "->", "app", "->", "make", "(", "Identifier", "::", "class", ")", "->", "getString", "(", "32", ")", ";", "$", "selectizeOptions", "=", "[", "'valueField'", "=>", "'value'", ",", "'labelField'", "=>", "'label'", ",", "'searchField'", "=>", "[", "'label'", "]", ",", "'maxItems'", "=>", "1", ",", "]", ";", "if", "(", "$", "userInfo", ")", "{", "$", "selectizeOptions", "+=", "[", "'options'", "=>", "[", "[", "'label'", "=>", "h", "(", "$", "userInfo", "->", "getUserDisplayName", "(", ")", ")", ",", "'value'", "=>", "$", "selectedUID", ",", "]", ",", "]", ",", "'items'", "=>", "[", "$", "selectedUID", ",", "]", ",", "]", ";", "}", "$", "selectizeOptions", "=", "json_encode", "(", "$", "selectizeOptions", ")", ";", "$", "input", "=", "$", "this", "->", "app", "->", "make", "(", "'helper/form'", ")", "->", "hidden", "(", "$", "fieldName", ",", "''", ",", "$", "miscFields", ")", ";", "$", "ajaxUrlBase", "=", "json_encode", "(", "REL_DIR_FILES_TOOLS_REQUIRED", ".", "'/users/autocomplete?key='", ".", "rawurlencode", "(", "$", "fieldName", ")", ".", "'&token='", ".", "rawurldecode", "(", "$", "token", ")", ")", ";", "return", " <<<EOT\n<span id=\"ccm-quick-user-selector-{$identifier}\" class=\"ccm-quick-user-selector\">{$input}</span>\n<script>\n$(function () {\n var options = {$selectizeOptions};\n options.load = function(query, callback) {\n if (!query.length) {\n return callback();\n }\n $.ajax({\n url: {$ajaxUrlBase} + '&term=' + encodeURIComponent(query),\n type: 'GET',\n\t\t\tdataType: 'json',\n error: function() {\n callback();\n },\n success: function(res) {\n callback(res);\n }\n });\n };\n $('#ccm-quick-user-selector-{$identifier} input')\n .unbind()\n .selectize(options)\n ;\n});\n</script>\nEOT", ";", "}" ]
Build the HTML to be placed in a page to choose a user using a select with users pupulated dynamically with ajax requests. @param string $fieldName the name of the field @param int|false $uID the ID of the user to be initially selected @param array $miscFields additional fields appended to the hidden input element (a hash array of attributes name => value), possibly including 'class' @return string @example <code> $userSelector->quickSelect('userID', USER_SUPER_ID); // prints out the admin user and makes it changeable. </code>.
[ "Build", "the", "HTML", "to", "be", "placed", "in", "a", "page", "to", "choose", "a", "user", "using", "a", "select", "with", "users", "pupulated", "dynamically", "with", "ajax", "requests", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Form/Service/Widget/UserSelector.php#L127-L204
train
concrete5/concrete5
concrete/src/Form/Service/Widget/UserSelector.php
UserSelector.selectMultipleUsers
public function selectMultipleUsers($fieldName, $users = []) { $identifier = $this->app->make(Identifier::class)->getString(32); $i18n = [ 'username' => t('Username'), 'emailAddress' => t('Email Address'), 'chooseUser' => t('Choose User'), 'noUsers' => t('No users selected.'), ]; $searchLink = $this->app->make(ResolverManagerInterface::class)->resolve(['/ccm/system/dialogs/user/search']); $valn = $this->app->make(Numbers::class); $userInfoRepository = $this->app->make(UserInfoRepository::class); $preselectedUsers = ''; foreach ($users as $user) { if ($valn->integer($user)) { $user = $userInfoRepository->getById($user); } if (is_object($user)) { $preselectedUsers .= <<<EOT <tr data-ccm-user-id="{$user->getUserID()}" class="ccm-list-record"> <td><input type="hidden" name="{$fieldName}[]" value="{$user->getUserID()}" />{$user->getUserName()}</td> <td>{$user->getUserEmail()}</td> <td><a href="#" class="ccm-user-list-clear icon-link"><i class="fa fa-minus-circle ccm-user-list-clear-button"></i></a></td> </tr> EOT ; } } $noUsersStyle = $preselectedUsers === '' ? '' : ' style="display: none"'; return <<<EOT <table id="ccmUserSelect-{$identifier}" class="table table-condensed" cellspacing="0" cellpadding="0" border="0"> <thead> <tr> <th>{$i18n['username']}</th> <th>{$i18n['emailAddress']}</th> <th style="width: 1px"><a class="icon-link ccm-user-select-item dialog-launch" dialog-append-buttons="true" dialog-width="90%" dialog-height="70%" dialog-modal="false" dialog-title="{$i18n['chooseUser']}" href="{$searchLink}"><i class="fa fa-plus-circle" /></a></th> </tr> </thead> <tbody> {$preselectedUsers} <tr class="ccm-user-selected-item-none"{$noUsersStyle}><td colspan="3">{$i18n['noUsers']}</td></tr> </tbody> </table> <script> $(function() { var container = $('#ccmUserSelect-{$identifier}'), noUsersRow = container.find('tr.ccm-user-selected-item-none'), updateNoUsers = function() { if (container.find('tr[data-ccm-user-id]').length === 0) { noUsersRow.show(); } else { noUsersRow.hide(); } }, userSelectCallback = function(e, data) { e.stopPropagation(); var uID = data.uID, uName = data.uName, uEmail = data.uEmail; if (container.find('tr[data-ccm-user-id=' + uID + ']').length > 0) { return; } noUsersRow.before($('<tr data-ccm-user-id="' + uID + '" class="ccm-list-record" />') .append($('<td />') .text(uName) .prepend($('<input type="hidden" name="{$fieldName}[]" />').val(uID)) ) .append($('<td />') .text(uEmail) ) .append($('<td><a href="#" class="ccm-user-list-clear icon-link"><i class="fa fa-minus-circle ccm-user-list-clear-button"></i></a></td>')) ); updateNoUsers(); }; container.on('click', 'a.ccm-user-list-clear', function(e) { e.preventDefault(); $(this).closest('tr').remove(); updateNoUsers(); }); container.find('.ccm-user-select-item') .dialog() .on('click', function(e) { ConcreteEvent.subscribe('UserSearchDialogSelectUser', userSelectCallback) }) ; ConcreteEvent.subscribe('UserSearchDialogAfterSelectUser', function(e) { ConcreteEvent.unsubscribe('UserSearchDialogSelectUser'); jQuery.fn.dialog.closeTop(); }); }); </script> EOT ; }
php
public function selectMultipleUsers($fieldName, $users = []) { $identifier = $this->app->make(Identifier::class)->getString(32); $i18n = [ 'username' => t('Username'), 'emailAddress' => t('Email Address'), 'chooseUser' => t('Choose User'), 'noUsers' => t('No users selected.'), ]; $searchLink = $this->app->make(ResolverManagerInterface::class)->resolve(['/ccm/system/dialogs/user/search']); $valn = $this->app->make(Numbers::class); $userInfoRepository = $this->app->make(UserInfoRepository::class); $preselectedUsers = ''; foreach ($users as $user) { if ($valn->integer($user)) { $user = $userInfoRepository->getById($user); } if (is_object($user)) { $preselectedUsers .= <<<EOT <tr data-ccm-user-id="{$user->getUserID()}" class="ccm-list-record"> <td><input type="hidden" name="{$fieldName}[]" value="{$user->getUserID()}" />{$user->getUserName()}</td> <td>{$user->getUserEmail()}</td> <td><a href="#" class="ccm-user-list-clear icon-link"><i class="fa fa-minus-circle ccm-user-list-clear-button"></i></a></td> </tr> EOT ; } } $noUsersStyle = $preselectedUsers === '' ? '' : ' style="display: none"'; return <<<EOT <table id="ccmUserSelect-{$identifier}" class="table table-condensed" cellspacing="0" cellpadding="0" border="0"> <thead> <tr> <th>{$i18n['username']}</th> <th>{$i18n['emailAddress']}</th> <th style="width: 1px"><a class="icon-link ccm-user-select-item dialog-launch" dialog-append-buttons="true" dialog-width="90%" dialog-height="70%" dialog-modal="false" dialog-title="{$i18n['chooseUser']}" href="{$searchLink}"><i class="fa fa-plus-circle" /></a></th> </tr> </thead> <tbody> {$preselectedUsers} <tr class="ccm-user-selected-item-none"{$noUsersStyle}><td colspan="3">{$i18n['noUsers']}</td></tr> </tbody> </table> <script> $(function() { var container = $('#ccmUserSelect-{$identifier}'), noUsersRow = container.find('tr.ccm-user-selected-item-none'), updateNoUsers = function() { if (container.find('tr[data-ccm-user-id]').length === 0) { noUsersRow.show(); } else { noUsersRow.hide(); } }, userSelectCallback = function(e, data) { e.stopPropagation(); var uID = data.uID, uName = data.uName, uEmail = data.uEmail; if (container.find('tr[data-ccm-user-id=' + uID + ']').length > 0) { return; } noUsersRow.before($('<tr data-ccm-user-id="' + uID + '" class="ccm-list-record" />') .append($('<td />') .text(uName) .prepend($('<input type="hidden" name="{$fieldName}[]" />').val(uID)) ) .append($('<td />') .text(uEmail) ) .append($('<td><a href="#" class="ccm-user-list-clear icon-link"><i class="fa fa-minus-circle ccm-user-list-clear-button"></i></a></td>')) ); updateNoUsers(); }; container.on('click', 'a.ccm-user-list-clear', function(e) { e.preventDefault(); $(this).closest('tr').remove(); updateNoUsers(); }); container.find('.ccm-user-select-item') .dialog() .on('click', function(e) { ConcreteEvent.subscribe('UserSearchDialogSelectUser', userSelectCallback) }) ; ConcreteEvent.subscribe('UserSearchDialogAfterSelectUser', function(e) { ConcreteEvent.unsubscribe('UserSearchDialogSelectUser'); jQuery.fn.dialog.closeTop(); }); }); </script> EOT ; }
[ "public", "function", "selectMultipleUsers", "(", "$", "fieldName", ",", "$", "users", "=", "[", "]", ")", "{", "$", "identifier", "=", "$", "this", "->", "app", "->", "make", "(", "Identifier", "::", "class", ")", "->", "getString", "(", "32", ")", ";", "$", "i18n", "=", "[", "'username'", "=>", "t", "(", "'Username'", ")", ",", "'emailAddress'", "=>", "t", "(", "'Email Address'", ")", ",", "'chooseUser'", "=>", "t", "(", "'Choose User'", ")", ",", "'noUsers'", "=>", "t", "(", "'No users selected.'", ")", ",", "]", ";", "$", "searchLink", "=", "$", "this", "->", "app", "->", "make", "(", "ResolverManagerInterface", "::", "class", ")", "->", "resolve", "(", "[", "'/ccm/system/dialogs/user/search'", "]", ")", ";", "$", "valn", "=", "$", "this", "->", "app", "->", "make", "(", "Numbers", "::", "class", ")", ";", "$", "userInfoRepository", "=", "$", "this", "->", "app", "->", "make", "(", "UserInfoRepository", "::", "class", ")", ";", "$", "preselectedUsers", "=", "''", ";", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "if", "(", "$", "valn", "->", "integer", "(", "$", "user", ")", ")", "{", "$", "user", "=", "$", "userInfoRepository", "->", "getById", "(", "$", "user", ")", ";", "}", "if", "(", "is_object", "(", "$", "user", ")", ")", "{", "$", "preselectedUsers", ".=", " <<<EOT\n<tr data-ccm-user-id=\"{$user->getUserID()}\" class=\"ccm-list-record\">\n <td><input type=\"hidden\" name=\"{$fieldName}[]\" value=\"{$user->getUserID()}\" />{$user->getUserName()}</td>\n <td>{$user->getUserEmail()}</td>\n <td><a href=\"#\" class=\"ccm-user-list-clear icon-link\"><i class=\"fa fa-minus-circle ccm-user-list-clear-button\"></i></a></td>\n</tr>\nEOT", ";", "}", "}", "$", "noUsersStyle", "=", "$", "preselectedUsers", "===", "''", "?", "''", ":", "' style=\"display: none\"'", ";", "return", " <<<EOT\n<table id=\"ccmUserSelect-{$identifier}\" class=\"table table-condensed\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n <thead>\n <tr>\n <th>{$i18n['username']}</th>\n <th>{$i18n['emailAddress']}</th>\n <th style=\"width: 1px\"><a class=\"icon-link ccm-user-select-item dialog-launch\" dialog-append-buttons=\"true\" dialog-width=\"90%\" dialog-height=\"70%\" dialog-modal=\"false\" dialog-title=\"{$i18n['chooseUser']}\" href=\"{$searchLink}\"><i class=\"fa fa-plus-circle\" /></a></th>\n </tr>\n </thead>\n <tbody>\n {$preselectedUsers}\n <tr class=\"ccm-user-selected-item-none\"{$noUsersStyle}><td colspan=\"3\">{$i18n['noUsers']}</td></tr>\n </tbody>\n</table>\n<script>\n$(function() {\n var container = $('#ccmUserSelect-{$identifier}'),\n noUsersRow = container.find('tr.ccm-user-selected-item-none'),\n updateNoUsers = function() {\n if (container.find('tr[data-ccm-user-id]').length === 0) {\n noUsersRow.show();\n } else {\n noUsersRow.hide();\n }\n },\n userSelectCallback = function(e, data) {\n e.stopPropagation();\n var uID = data.uID,\n uName = data.uName,\n uEmail = data.uEmail;\n if (container.find('tr[data-ccm-user-id=' + uID + ']').length > 0) {\n return;\n }\n noUsersRow.before($('<tr data-ccm-user-id=\"' + uID + '\" class=\"ccm-list-record\" />')\n .append($('<td />')\n .text(uName)\n .prepend($('<input type=\"hidden\" name=\"{$fieldName}[]\" />').val(uID))\n )\n .append($('<td />')\n .text(uEmail)\n )\n .append($('<td><a href=\"#\" class=\"ccm-user-list-clear icon-link\"><i class=\"fa fa-minus-circle ccm-user-list-clear-button\"></i></a></td>'))\n );\n updateNoUsers();\n };\n container.on('click', 'a.ccm-user-list-clear', function(e) {\n e.preventDefault();\n $(this).closest('tr').remove();\n updateNoUsers();\n });\n container.find('.ccm-user-select-item')\n .dialog()\n .on('click', function(e) {\n ConcreteEvent.subscribe('UserSearchDialogSelectUser', userSelectCallback)\n })\n ;\n ConcreteEvent.subscribe('UserSearchDialogAfterSelectUser', function(e) {\n ConcreteEvent.unsubscribe('UserSearchDialogSelectUser');\n jQuery.fn.dialog.closeTop();\n });\n});\n</script>\nEOT", ";", "}" ]
Build the HTML to be placed in a page to choose multiple users using a popup dialog. @param string $fieldName the name of the field @param \Concrete\Core\Entity\User\User[]|\Concrete\Core\User\UserInfo[]|int[]\Traversable $users The users to be initially selected @return string
[ "Build", "the", "HTML", "to", "be", "placed", "in", "a", "page", "to", "choose", "multiple", "users", "using", "a", "popup", "dialog", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Form/Service/Widget/UserSelector.php#L214-L308
train
concrete5/concrete5
concrete/blocks/search/controller.php
Controller.highlightedMarkup
public function highlightedMarkup($fulltext, $highlight) { if (!$highlight) { return $fulltext; } $this->hText = $fulltext; $this->hHighlight = $highlight; $this->hText = @preg_replace('#' . preg_quote($this->hHighlight, '#') . '#ui', '<span style="background-color:' . $this->hColor . ';">$0</span>', $this->hText); return $this->hText; }
php
public function highlightedMarkup($fulltext, $highlight) { if (!$highlight) { return $fulltext; } $this->hText = $fulltext; $this->hHighlight = $highlight; $this->hText = @preg_replace('#' . preg_quote($this->hHighlight, '#') . '#ui', '<span style="background-color:' . $this->hColor . ';">$0</span>', $this->hText); return $this->hText; }
[ "public", "function", "highlightedMarkup", "(", "$", "fulltext", ",", "$", "highlight", ")", "{", "if", "(", "!", "$", "highlight", ")", "{", "return", "$", "fulltext", ";", "}", "$", "this", "->", "hText", "=", "$", "fulltext", ";", "$", "this", "->", "hHighlight", "=", "$", "highlight", ";", "$", "this", "->", "hText", "=", "@", "preg_replace", "(", "'#'", ".", "preg_quote", "(", "$", "this", "->", "hHighlight", ",", "'#'", ")", ".", "'#ui'", ",", "'<span style=\"background-color:'", ".", "$", "this", "->", "hColor", ".", "';\">$0</span>'", ",", "$", "this", "->", "hText", ")", ";", "return", "$", "this", "->", "hText", ";", "}" ]
Highlight parts of a text. @param string $fulltext the whole text @param string $highlight The text to be highlighted @return string
[ "Highlight", "parts", "of", "a", "text", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/blocks/search/controller.php#L144-L155
train
concrete5/concrete5
concrete/blocks/search/controller.php
Controller.view
public function view() { $this->set('title', $this->title); $this->set('buttonText', $this->buttonText); $this->set('baseSearchPath', $this->baseSearchPath); $this->set('postTo_cID', $this->postTo_cID); if ((string) $this->resultsURL !== '') { $resultsPage = null; $resultsURL = $this->resultsURL; } else { $resultsPage = $this->postTo_cID ? Page::getById($this->postTo_cID) : null; if (is_object($resultsPage) && !$resultsPage->isError()) { $resultsURL = $resultsPage->getCollectionPath(); } else { $resultsPage = null; $c = Page::getCurrentPage(); $resultsURL = $c->getCollectionPath(); } } $resultsURL = $this->app->make('helper/text')->encodePath($resultsURL); $this->set('resultTargetURL', $resultsURL); if ($resultsPage !== null) { $this->set('resultTarget', $resultsPage); } else { $this->set('resultTarget', $resultsURL); } //run query if display results elsewhere not set, or the cID of this page is set if ($resultsPage === null && (string) $this->resultsURL === '') { if ((string) $this->request->request('query') !== '' || $this->request->request('akID') || $this->request->request('month')) { $this->do_search(); } } }
php
public function view() { $this->set('title', $this->title); $this->set('buttonText', $this->buttonText); $this->set('baseSearchPath', $this->baseSearchPath); $this->set('postTo_cID', $this->postTo_cID); if ((string) $this->resultsURL !== '') { $resultsPage = null; $resultsURL = $this->resultsURL; } else { $resultsPage = $this->postTo_cID ? Page::getById($this->postTo_cID) : null; if (is_object($resultsPage) && !$resultsPage->isError()) { $resultsURL = $resultsPage->getCollectionPath(); } else { $resultsPage = null; $c = Page::getCurrentPage(); $resultsURL = $c->getCollectionPath(); } } $resultsURL = $this->app->make('helper/text')->encodePath($resultsURL); $this->set('resultTargetURL', $resultsURL); if ($resultsPage !== null) { $this->set('resultTarget', $resultsPage); } else { $this->set('resultTarget', $resultsURL); } //run query if display results elsewhere not set, or the cID of this page is set if ($resultsPage === null && (string) $this->resultsURL === '') { if ((string) $this->request->request('query') !== '' || $this->request->request('akID') || $this->request->request('month')) { $this->do_search(); } } }
[ "public", "function", "view", "(", ")", "{", "$", "this", "->", "set", "(", "'title'", ",", "$", "this", "->", "title", ")", ";", "$", "this", "->", "set", "(", "'buttonText'", ",", "$", "this", "->", "buttonText", ")", ";", "$", "this", "->", "set", "(", "'baseSearchPath'", ",", "$", "this", "->", "baseSearchPath", ")", ";", "$", "this", "->", "set", "(", "'postTo_cID'", ",", "$", "this", "->", "postTo_cID", ")", ";", "if", "(", "(", "string", ")", "$", "this", "->", "resultsURL", "!==", "''", ")", "{", "$", "resultsPage", "=", "null", ";", "$", "resultsURL", "=", "$", "this", "->", "resultsURL", ";", "}", "else", "{", "$", "resultsPage", "=", "$", "this", "->", "postTo_cID", "?", "Page", "::", "getById", "(", "$", "this", "->", "postTo_cID", ")", ":", "null", ";", "if", "(", "is_object", "(", "$", "resultsPage", ")", "&&", "!", "$", "resultsPage", "->", "isError", "(", ")", ")", "{", "$", "resultsURL", "=", "$", "resultsPage", "->", "getCollectionPath", "(", ")", ";", "}", "else", "{", "$", "resultsPage", "=", "null", ";", "$", "c", "=", "Page", "::", "getCurrentPage", "(", ")", ";", "$", "resultsURL", "=", "$", "c", "->", "getCollectionPath", "(", ")", ";", "}", "}", "$", "resultsURL", "=", "$", "this", "->", "app", "->", "make", "(", "'helper/text'", ")", "->", "encodePath", "(", "$", "resultsURL", ")", ";", "$", "this", "->", "set", "(", "'resultTargetURL'", ",", "$", "resultsURL", ")", ";", "if", "(", "$", "resultsPage", "!==", "null", ")", "{", "$", "this", "->", "set", "(", "'resultTarget'", ",", "$", "resultsPage", ")", ";", "}", "else", "{", "$", "this", "->", "set", "(", "'resultTarget'", ",", "$", "resultsURL", ")", ";", "}", "//run query if display results elsewhere not set, or the cID of this page is set", "if", "(", "$", "resultsPage", "===", "null", "&&", "(", "string", ")", "$", "this", "->", "resultsURL", "===", "''", ")", "{", "if", "(", "(", "string", ")", "$", "this", "->", "request", "->", "request", "(", "'query'", ")", "!==", "''", "||", "$", "this", "->", "request", "->", "request", "(", "'akID'", ")", "||", "$", "this", "->", "request", "->", "request", "(", "'month'", ")", ")", "{", "$", "this", "->", "do_search", "(", ")", ";", "}", "}", "}" ]
Default view method.
[ "Default", "view", "method", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/blocks/search/controller.php#L251-L287
train
concrete5/concrete5
concrete/src/File/Type/Type.php
Type.getUsedExtensionList
public static function getUsedExtensionList() { $app = Application::getFacadeApplication(); $db = $app->make('database')->connection(); $stm = $db->executeQuery("select distinct fvExtension from FileVersions where fvIsApproved = 1 and fvExtension is not null and fvExtension <> ''"); $extensions = []; while ($row = $stm->fetch()) { $extensions[] = $row['fvExtension']; } return $extensions; }
php
public static function getUsedExtensionList() { $app = Application::getFacadeApplication(); $db = $app->make('database')->connection(); $stm = $db->executeQuery("select distinct fvExtension from FileVersions where fvIsApproved = 1 and fvExtension is not null and fvExtension <> ''"); $extensions = []; while ($row = $stm->fetch()) { $extensions[] = $row['fvExtension']; } return $extensions; }
[ "public", "static", "function", "getUsedExtensionList", "(", ")", "{", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "'database'", ")", "->", "connection", "(", ")", ";", "$", "stm", "=", "$", "db", "->", "executeQuery", "(", "\"select distinct fvExtension from FileVersions where fvIsApproved = 1 and fvExtension is not null and fvExtension <> ''\"", ")", ";", "$", "extensions", "=", "[", "]", ";", "while", "(", "$", "row", "=", "$", "stm", "->", "fetch", "(", ")", ")", "{", "$", "extensions", "[", "]", "=", "$", "row", "[", "'fvExtension'", "]", ";", "}", "return", "$", "extensions", ";", "}" ]
Get the list of all the file extensions used by approved file versions. @return string[]
[ "Get", "the", "list", "of", "all", "the", "file", "extensions", "used", "by", "approved", "file", "versions", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Type/Type.php#L344-L355
train
concrete5/concrete5
concrete/src/File/Type/Type.php
Type.getUsedTypeList
public static function getUsedTypeList() { $app = Application::getFacadeApplication(); $db = $app->make('database')->connection(); $stm = $db->query('select distinct fvType from FileVersions where fvIsApproved = 1 and fvType is not null and fvType <> 0'); $types = []; while ($row = $stm->fetch()) { $types[] = (int) $row['fvType']; } return $types; }
php
public static function getUsedTypeList() { $app = Application::getFacadeApplication(); $db = $app->make('database')->connection(); $stm = $db->query('select distinct fvType from FileVersions where fvIsApproved = 1 and fvType is not null and fvType <> 0'); $types = []; while ($row = $stm->fetch()) { $types[] = (int) $row['fvType']; } return $types; }
[ "public", "static", "function", "getUsedTypeList", "(", ")", "{", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "'database'", ")", "->", "connection", "(", ")", ";", "$", "stm", "=", "$", "db", "->", "query", "(", "'select distinct fvType from FileVersions where fvIsApproved = 1 and fvType is not null and fvType <> 0'", ")", ";", "$", "types", "=", "[", "]", ";", "while", "(", "$", "row", "=", "$", "stm", "->", "fetch", "(", ")", ")", "{", "$", "types", "[", "]", "=", "(", "int", ")", "$", "row", "[", "'fvType'", "]", ";", "}", "return", "$", "types", ";", "}" ]
Get the list of all the file types used by approved file versions. @return int[]
[ "Get", "the", "list", "of", "all", "the", "file", "types", "used", "by", "approved", "file", "versions", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Type/Type.php#L362-L373
train
concrete5/concrete5
concrete/src/File/Type/Type.php
Type.getThumbnail
public function getThumbnail($fullImageTag = true) { $app = Application::getFacadeApplication(); $config = $app->make('config'); $type = ThumbnailType::getByHandle($config->get('concrete.icons.file_manager_listing.handle')); if (file_exists(DIR_AL_ICONS . '/' . $this->getExtension() . '.svg')) { $url = REL_DIR_AL_ICONS . '/' . $this->getExtension() . '.svg'; } else { $url = AL_ICON_DEFAULT; } if ($fullImageTag == true) { return sprintf( '<img src="%s" width="%s" height="%s" class="img-responsive ccm-generic-thumbnail" alt="%s">', $url, $type->getWidth(), $type->getHeight(), t(/* i18n: %s is a file type */ '%s file icon', mb_strtoupper($this->getExtension())) ); } else { return $url; } }
php
public function getThumbnail($fullImageTag = true) { $app = Application::getFacadeApplication(); $config = $app->make('config'); $type = ThumbnailType::getByHandle($config->get('concrete.icons.file_manager_listing.handle')); if (file_exists(DIR_AL_ICONS . '/' . $this->getExtension() . '.svg')) { $url = REL_DIR_AL_ICONS . '/' . $this->getExtension() . '.svg'; } else { $url = AL_ICON_DEFAULT; } if ($fullImageTag == true) { return sprintf( '<img src="%s" width="%s" height="%s" class="img-responsive ccm-generic-thumbnail" alt="%s">', $url, $type->getWidth(), $type->getHeight(), t(/* i18n: %s is a file type */ '%s file icon', mb_strtoupper($this->getExtension())) ); } else { return $url; } }
[ "public", "function", "getThumbnail", "(", "$", "fullImageTag", "=", "true", ")", "{", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "$", "config", "=", "$", "app", "->", "make", "(", "'config'", ")", ";", "$", "type", "=", "ThumbnailType", "::", "getByHandle", "(", "$", "config", "->", "get", "(", "'concrete.icons.file_manager_listing.handle'", ")", ")", ";", "if", "(", "file_exists", "(", "DIR_AL_ICONS", ".", "'/'", ".", "$", "this", "->", "getExtension", "(", ")", ".", "'.svg'", ")", ")", "{", "$", "url", "=", "REL_DIR_AL_ICONS", ".", "'/'", ".", "$", "this", "->", "getExtension", "(", ")", ".", "'.svg'", ";", "}", "else", "{", "$", "url", "=", "AL_ICON_DEFAULT", ";", "}", "if", "(", "$", "fullImageTag", "==", "true", ")", "{", "return", "sprintf", "(", "'<img src=\"%s\" width=\"%s\" height=\"%s\" class=\"img-responsive ccm-generic-thumbnail\" alt=\"%s\">'", ",", "$", "url", ",", "$", "type", "->", "getWidth", "(", ")", ",", "$", "type", "->", "getHeight", "(", ")", ",", "t", "(", "/* i18n: %s is a file type */", "'%s file icon'", ",", "mb_strtoupper", "(", "$", "this", "->", "getExtension", "(", ")", ")", ")", ")", ";", "}", "else", "{", "return", "$", "url", ";", "}", "}" ]
Returns a thumbnail for this type of file. @param bool $fullImageTag Set to true to retrieve the full HTML image tag, false to just retrieve the image URL @return string
[ "Returns", "a", "thumbnail", "for", "this", "type", "of", "file", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Type/Type.php#L400-L421
train
concrete5/concrete5
concrete/src/File/Type/Type.php
Type.getGenericTypeText
public static function getGenericTypeText($type) { switch ($type) { case static::T_IMAGE: return t('Image'); break; case static::T_VIDEO: return t('Video'); break; case static::T_TEXT: return t('Text'); break; case static::T_AUDIO: return t('Audio'); break; case static::T_DOCUMENT: return t('Document'); break; case static::T_APPLICATION: return t('Application'); break; case static::T_UNKNOWN: return t('File'); break; } }
php
public static function getGenericTypeText($type) { switch ($type) { case static::T_IMAGE: return t('Image'); break; case static::T_VIDEO: return t('Video'); break; case static::T_TEXT: return t('Text'); break; case static::T_AUDIO: return t('Audio'); break; case static::T_DOCUMENT: return t('Document'); break; case static::T_APPLICATION: return t('Application'); break; case static::T_UNKNOWN: return t('File'); break; } }
[ "public", "static", "function", "getGenericTypeText", "(", "$", "type", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "static", "::", "T_IMAGE", ":", "return", "t", "(", "'Image'", ")", ";", "break", ";", "case", "static", "::", "T_VIDEO", ":", "return", "t", "(", "'Video'", ")", ";", "break", ";", "case", "static", "::", "T_TEXT", ":", "return", "t", "(", "'Text'", ")", ";", "break", ";", "case", "static", "::", "T_AUDIO", ":", "return", "t", "(", "'Audio'", ")", ";", "break", ";", "case", "static", "::", "T_DOCUMENT", ":", "return", "t", "(", "'Document'", ")", ";", "break", ";", "case", "static", "::", "T_APPLICATION", ":", "return", "t", "(", "'Application'", ")", ";", "break", ";", "case", "static", "::", "T_UNKNOWN", ":", "return", "t", "(", "'File'", ")", ";", "break", ";", "}", "}" ]
Get the name of a generic file type. @param int $type Generic category type (one of the \Concrete\Core\File\Type\Type::T_... constants) @return string|null Returns null if the type is not recognized, its translated display name otherwise
[ "Get", "the", "name", "of", "a", "generic", "file", "type", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Type/Type.php#L456-L482
train
concrete5/concrete5
concrete/src/Entity/OAuth/RefreshTokenRepository.php
RefreshTokenRepository.revokeRefreshToken
public function revokeRefreshToken($tokenId) { $this->getEntityManager()->transactional(function(EntityManagerInterface $em) use ($tokenId) { $token = $this->find($tokenId); if ($token) { $em->remove($token); } }); }
php
public function revokeRefreshToken($tokenId) { $this->getEntityManager()->transactional(function(EntityManagerInterface $em) use ($tokenId) { $token = $this->find($tokenId); if ($token) { $em->remove($token); } }); }
[ "public", "function", "revokeRefreshToken", "(", "$", "tokenId", ")", "{", "$", "this", "->", "getEntityManager", "(", ")", "->", "transactional", "(", "function", "(", "EntityManagerInterface", "$", "em", ")", "use", "(", "$", "tokenId", ")", "{", "$", "token", "=", "$", "this", "->", "find", "(", "$", "tokenId", ")", ";", "if", "(", "$", "token", ")", "{", "$", "em", "->", "remove", "(", "$", "token", ")", ";", "}", "}", ")", ";", "}" ]
Revoke the refresh token. @param string $tokenId @throws \Exception
[ "Revoke", "the", "refresh", "token", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Entity/OAuth/RefreshTokenRepository.php#L42-L51
train
concrete5/concrete5
concrete/src/File/Type/Inspector/ImageInspector.php
ImageInspector.updateSize
private function updateSize(Version $fv, ImageInterface $image) { $result = false; try { $size = $image->getSize(); } catch (Exception $x) { $size = null; } catch (Throwable $x) { $size = null; } if ($size !== null) { $attributeCategory = $fv->getObjectAttributeCategory(); $atWidth = $attributeCategory->getAttributeKeyByHandle('width'); if ($atWidth !== null) { $fv->setAttribute($atWidth, $size->getWidth()); } $atHeight = $attributeCategory->getAttributeKeyByHandle('height'); if ($atHeight !== null) { $fv->setAttribute($atHeight, $size->getHeight()); } $result = true; } return $result; }
php
private function updateSize(Version $fv, ImageInterface $image) { $result = false; try { $size = $image->getSize(); } catch (Exception $x) { $size = null; } catch (Throwable $x) { $size = null; } if ($size !== null) { $attributeCategory = $fv->getObjectAttributeCategory(); $atWidth = $attributeCategory->getAttributeKeyByHandle('width'); if ($atWidth !== null) { $fv->setAttribute($atWidth, $size->getWidth()); } $atHeight = $attributeCategory->getAttributeKeyByHandle('height'); if ($atHeight !== null) { $fv->setAttribute($atHeight, $size->getHeight()); } $result = true; } return $result; }
[ "private", "function", "updateSize", "(", "Version", "$", "fv", ",", "ImageInterface", "$", "image", ")", "{", "$", "result", "=", "false", ";", "try", "{", "$", "size", "=", "$", "image", "->", "getSize", "(", ")", ";", "}", "catch", "(", "Exception", "$", "x", ")", "{", "$", "size", "=", "null", ";", "}", "catch", "(", "Throwable", "$", "x", ")", "{", "$", "size", "=", "null", ";", "}", "if", "(", "$", "size", "!==", "null", ")", "{", "$", "attributeCategory", "=", "$", "fv", "->", "getObjectAttributeCategory", "(", ")", ";", "$", "atWidth", "=", "$", "attributeCategory", "->", "getAttributeKeyByHandle", "(", "'width'", ")", ";", "if", "(", "$", "atWidth", "!==", "null", ")", "{", "$", "fv", "->", "setAttribute", "(", "$", "atWidth", ",", "$", "size", "->", "getWidth", "(", ")", ")", ";", "}", "$", "atHeight", "=", "$", "attributeCategory", "->", "getAttributeKeyByHandle", "(", "'height'", ")", ";", "if", "(", "$", "atHeight", "!==", "null", ")", "{", "$", "fv", "->", "setAttribute", "(", "$", "atHeight", ",", "$", "size", "->", "getHeight", "(", ")", ")", ";", "}", "$", "result", "=", "true", ";", "}", "return", "$", "result", ";", "}" ]
Update the width and height attributes of the file version starting from the image data. @param Version $fv @param ImageInterface $image @return bool true if success, false otherwise
[ "Update", "the", "width", "and", "height", "attributes", "of", "the", "file", "version", "starting", "from", "the", "image", "data", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/File/Type/Inspector/ImageInspector.php#L42-L66
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.logFailedLogin
public function logFailedLogin(AddressInterface $ip = null, $ignoreConfig = false) { if ($ignoreConfig || $this->config->get('concrete.security.ban.ip.enabled')) { if ($ip === null) { $ip = $this->getRequestIPAddress(); } $comparableIP = $ip->getComparableString(); $this->connection->executeQuery( ' INSERT INTO FailedLoginAttempts (flaIp, flaTimestamp) VALUES (?, ' . $this->connection->getDatabasePlatform()->getNowExpression() . ') ', [$ip->getComparableString()] ); $this->logger->notice(t('Failed login attempt recorded from IP address %s', $ip->toString(), ['ip_address' => $ip->toString()])); } }
php
public function logFailedLogin(AddressInterface $ip = null, $ignoreConfig = false) { if ($ignoreConfig || $this->config->get('concrete.security.ban.ip.enabled')) { if ($ip === null) { $ip = $this->getRequestIPAddress(); } $comparableIP = $ip->getComparableString(); $this->connection->executeQuery( ' INSERT INTO FailedLoginAttempts (flaIp, flaTimestamp) VALUES (?, ' . $this->connection->getDatabasePlatform()->getNowExpression() . ') ', [$ip->getComparableString()] ); $this->logger->notice(t('Failed login attempt recorded from IP address %s', $ip->toString(), ['ip_address' => $ip->toString()])); } }
[ "public", "function", "logFailedLogin", "(", "AddressInterface", "$", "ip", "=", "null", ",", "$", "ignoreConfig", "=", "false", ")", "{", "if", "(", "$", "ignoreConfig", "||", "$", "this", "->", "config", "->", "get", "(", "'concrete.security.ban.ip.enabled'", ")", ")", "{", "if", "(", "$", "ip", "===", "null", ")", "{", "$", "ip", "=", "$", "this", "->", "getRequestIPAddress", "(", ")", ";", "}", "$", "comparableIP", "=", "$", "ip", "->", "getComparableString", "(", ")", ";", "$", "this", "->", "connection", "->", "executeQuery", "(", "'\n INSERT INTO FailedLoginAttempts\n (flaIp, flaTimestamp)\n VALUES\n (?, '", ".", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", "->", "getNowExpression", "(", ")", ".", "')\n '", ",", "[", "$", "ip", "->", "getComparableString", "(", ")", "]", ")", ";", "$", "this", "->", "logger", "->", "notice", "(", "t", "(", "'Failed login attempt recorded from IP address %s'", ",", "$", "ip", "->", "toString", "(", ")", ",", "[", "'ip_address'", "=>", "$", "ip", "->", "toString", "(", ")", "]", ")", ")", ";", "}", "}" ]
Add the current IP address to the list of IPs with failed login attempts. @param AddressInterface $ip the IP address to log (if null, we'll use the current IP address) @param bool $ignoreConfig if set to true, we'll add the record even if the IP ban system is disabled in the configuration
[ "Add", "the", "current", "IP", "address", "to", "the", "list", "of", "IPs", "with", "failed", "login", "attempts", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L158-L176
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.failedLoginsThresholdReached
public function failedLoginsThresholdReached(AddressInterface $ip = null, $ignoreConfig = false) { $result = false; if ($ignoreConfig || $this->config->get('concrete.security.ban.ip.enabled')) { if ($ip === null) { $ip = $this->getRequestIPAddress(); } if (!$this->isWhitelisted($ip)) { $thresholdSeconds = (int) $this->config->get('concrete.security.ban.ip.time'); $thresholdTimestamp = new DateTime("-{$thresholdSeconds} seconds"); $rs = $this->connection->executeQuery( ' SELECT ' . $this->connection->getDatabasePlatform()->getCountExpression('lcirID') . ' AS n FROM FailedLoginAttempts WHERE flaIp = ? AND flaTimestamp > ? ', [$ip->getComparableString(), $thresholdTimestamp->format($this->connection->getDatabasePlatform()->getDateTimeFormatString())] ); $count = $rs->fetchColumn(); $rs->closeCursor(); $thresholdAttempts = (int) $this->config->get('concrete.security.ban.ip.attempts'); if ($count !== false && (int) $count >= $thresholdAttempts) { $result = true; } } } return $result; }
php
public function failedLoginsThresholdReached(AddressInterface $ip = null, $ignoreConfig = false) { $result = false; if ($ignoreConfig || $this->config->get('concrete.security.ban.ip.enabled')) { if ($ip === null) { $ip = $this->getRequestIPAddress(); } if (!$this->isWhitelisted($ip)) { $thresholdSeconds = (int) $this->config->get('concrete.security.ban.ip.time'); $thresholdTimestamp = new DateTime("-{$thresholdSeconds} seconds"); $rs = $this->connection->executeQuery( ' SELECT ' . $this->connection->getDatabasePlatform()->getCountExpression('lcirID') . ' AS n FROM FailedLoginAttempts WHERE flaIp = ? AND flaTimestamp > ? ', [$ip->getComparableString(), $thresholdTimestamp->format($this->connection->getDatabasePlatform()->getDateTimeFormatString())] ); $count = $rs->fetchColumn(); $rs->closeCursor(); $thresholdAttempts = (int) $this->config->get('concrete.security.ban.ip.attempts'); if ($count !== false && (int) $count >= $thresholdAttempts) { $result = true; } } } return $result; }
[ "public", "function", "failedLoginsThresholdReached", "(", "AddressInterface", "$", "ip", "=", "null", ",", "$", "ignoreConfig", "=", "false", ")", "{", "$", "result", "=", "false", ";", "if", "(", "$", "ignoreConfig", "||", "$", "this", "->", "config", "->", "get", "(", "'concrete.security.ban.ip.enabled'", ")", ")", "{", "if", "(", "$", "ip", "===", "null", ")", "{", "$", "ip", "=", "$", "this", "->", "getRequestIPAddress", "(", ")", ";", "}", "if", "(", "!", "$", "this", "->", "isWhitelisted", "(", "$", "ip", ")", ")", "{", "$", "thresholdSeconds", "=", "(", "int", ")", "$", "this", "->", "config", "->", "get", "(", "'concrete.security.ban.ip.time'", ")", ";", "$", "thresholdTimestamp", "=", "new", "DateTime", "(", "\"-{$thresholdSeconds} seconds\"", ")", ";", "$", "rs", "=", "$", "this", "->", "connection", "->", "executeQuery", "(", "'\n SELECT\n '", ".", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", "->", "getCountExpression", "(", "'lcirID'", ")", ".", "' AS n\n FROM\n FailedLoginAttempts\n WHERE\n flaIp = ?\n AND flaTimestamp > ?\n '", ",", "[", "$", "ip", "->", "getComparableString", "(", ")", ",", "$", "thresholdTimestamp", "->", "format", "(", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", "->", "getDateTimeFormatString", "(", ")", ")", "]", ")", ";", "$", "count", "=", "$", "rs", "->", "fetchColumn", "(", ")", ";", "$", "rs", "->", "closeCursor", "(", ")", ";", "$", "thresholdAttempts", "=", "(", "int", ")", "$", "this", "->", "config", "->", "get", "(", "'concrete.security.ban.ip.attempts'", ")", ";", "if", "(", "$", "count", "!==", "false", "&&", "(", "int", ")", "$", "count", ">=", "$", "thresholdAttempts", ")", "{", "$", "result", "=", "true", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Check if the current IP address has reached the failed login attempts threshold. @param AddressInterface $ip the IP address to log (if null, we'll use the current IP address) @param bool $ignoreConfig if set to true, we'll check the IP even if the IP ban system is disabled in the configuration @return bool
[ "Check", "if", "the", "current", "IP", "address", "has", "reached", "the", "failed", "login", "attempts", "threshold", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L186-L218
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.addToBlacklistForThresholdReached
public function addToBlacklistForThresholdReached(AddressInterface $ip = null, $ignoreConfig = false) { if ($ignoreConfig || $this->config->get('concrete.security.ban.ip.enabled')) { if ($ip === null) { $ip = $this->getRequestIPAddress(); } $banDurationMinutes = (int) $this->config->get('concrete.security.ban.ip.length'); if ($banDurationMinutes > 0) { $expires = new DateTime("+{$banDurationMinutes} minutes"); } else { $expires = null; } $this->createRange(IPFactory::rangeFromBoundaries($ip, $ip), static::IPRANGETYPE_BLACKLIST_AUTOMATIC, $expires); $this->logger->warning(t('IP address %s added to blacklist.', $ip->toString(), $expires), [ 'ip_address' => $ip->toString() ]); } }
php
public function addToBlacklistForThresholdReached(AddressInterface $ip = null, $ignoreConfig = false) { if ($ignoreConfig || $this->config->get('concrete.security.ban.ip.enabled')) { if ($ip === null) { $ip = $this->getRequestIPAddress(); } $banDurationMinutes = (int) $this->config->get('concrete.security.ban.ip.length'); if ($banDurationMinutes > 0) { $expires = new DateTime("+{$banDurationMinutes} minutes"); } else { $expires = null; } $this->createRange(IPFactory::rangeFromBoundaries($ip, $ip), static::IPRANGETYPE_BLACKLIST_AUTOMATIC, $expires); $this->logger->warning(t('IP address %s added to blacklist.', $ip->toString(), $expires), [ 'ip_address' => $ip->toString() ]); } }
[ "public", "function", "addToBlacklistForThresholdReached", "(", "AddressInterface", "$", "ip", "=", "null", ",", "$", "ignoreConfig", "=", "false", ")", "{", "if", "(", "$", "ignoreConfig", "||", "$", "this", "->", "config", "->", "get", "(", "'concrete.security.ban.ip.enabled'", ")", ")", "{", "if", "(", "$", "ip", "===", "null", ")", "{", "$", "ip", "=", "$", "this", "->", "getRequestIPAddress", "(", ")", ";", "}", "$", "banDurationMinutes", "=", "(", "int", ")", "$", "this", "->", "config", "->", "get", "(", "'concrete.security.ban.ip.length'", ")", ";", "if", "(", "$", "banDurationMinutes", ">", "0", ")", "{", "$", "expires", "=", "new", "DateTime", "(", "\"+{$banDurationMinutes} minutes\"", ")", ";", "}", "else", "{", "$", "expires", "=", "null", ";", "}", "$", "this", "->", "createRange", "(", "IPFactory", "::", "rangeFromBoundaries", "(", "$", "ip", ",", "$", "ip", ")", ",", "static", "::", "IPRANGETYPE_BLACKLIST_AUTOMATIC", ",", "$", "expires", ")", ";", "$", "this", "->", "logger", "->", "warning", "(", "t", "(", "'IP address %s added to blacklist.'", ",", "$", "ip", "->", "toString", "(", ")", ",", "$", "expires", ")", ",", "[", "'ip_address'", "=>", "$", "ip", "->", "toString", "(", ")", "]", ")", ";", "}", "}" ]
Add an IP address to the list of IPs banned for too many failed login attempts. @param AddressInterface $ip the IP to add to the blacklist (if null, we'll use the current IP address) @param bool $ignoreConfig if set to true, we'll add the IP address even if the IP ban system is disabled in the configuration
[ "Add", "an", "IP", "address", "to", "the", "list", "of", "IPs", "banned", "for", "too", "many", "failed", "login", "attempts", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L226-L243
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.createRange
public function createRange(RangeInterface $range, $type, DateTime $expiration = null) { $dateTimeFormat = $this->connection->getDatabasePlatform()->getDateTimeFormatString(); $this->connection->executeQuery( ' INSERT INTO LoginControlIpRanges (lcirIpFrom, lcirIpTo, lcirType, lcirExpires) VALUES (?, ?, ?, ?) ', [ $range->getComparableStartString(), $range->getComparableEndString(), $type, ($expiration === null) ? null : $expiration->format($dateTimeFormat), ] ); $id = $this->connection->lastInsertId(); $rs = $this->connection->executeQuery('SELECT * FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1', [$id]); $row = $rs->fetch(); $rs->closeCursor(); return IPRange::createFromRow($row, $dateTimeFormat); }
php
public function createRange(RangeInterface $range, $type, DateTime $expiration = null) { $dateTimeFormat = $this->connection->getDatabasePlatform()->getDateTimeFormatString(); $this->connection->executeQuery( ' INSERT INTO LoginControlIpRanges (lcirIpFrom, lcirIpTo, lcirType, lcirExpires) VALUES (?, ?, ?, ?) ', [ $range->getComparableStartString(), $range->getComparableEndString(), $type, ($expiration === null) ? null : $expiration->format($dateTimeFormat), ] ); $id = $this->connection->lastInsertId(); $rs = $this->connection->executeQuery('SELECT * FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1', [$id]); $row = $rs->fetch(); $rs->closeCursor(); return IPRange::createFromRow($row, $dateTimeFormat); }
[ "public", "function", "createRange", "(", "RangeInterface", "$", "range", ",", "$", "type", ",", "DateTime", "$", "expiration", "=", "null", ")", "{", "$", "dateTimeFormat", "=", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", "->", "getDateTimeFormatString", "(", ")", ";", "$", "this", "->", "connection", "->", "executeQuery", "(", "'\n INSERT INTO LoginControlIpRanges\n (lcirIpFrom, lcirIpTo, lcirType, lcirExpires)\n VALUES\n (?, ?, ?, ?)\n '", ",", "[", "$", "range", "->", "getComparableStartString", "(", ")", ",", "$", "range", "->", "getComparableEndString", "(", ")", ",", "$", "type", ",", "(", "$", "expiration", "===", "null", ")", "?", "null", ":", "$", "expiration", "->", "format", "(", "$", "dateTimeFormat", ")", ",", "]", ")", ";", "$", "id", "=", "$", "this", "->", "connection", "->", "lastInsertId", "(", ")", ";", "$", "rs", "=", "$", "this", "->", "connection", "->", "executeQuery", "(", "'SELECT * FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1'", ",", "[", "$", "id", "]", ")", ";", "$", "row", "=", "$", "rs", "->", "fetch", "(", ")", ";", "$", "rs", "->", "closeCursor", "(", ")", ";", "return", "IPRange", "::", "createFromRow", "(", "$", "row", ",", "$", "dateTimeFormat", ")", ";", "}" ]
Add persist an IP address range type. @param RangeInterface $range the IP address range to persist @param int $type The range type (one of the IPService::IPRANGETYPE_... constants) @param DateTime $expiration The optional expiration of the range type @return IPRange
[ "Add", "persist", "an", "IP", "address", "range", "type", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L254-L277
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.getRanges
public function getRanges($type, $includeExpired = false) { $sql = 'SELECT * FROM LoginControlIpRanges WHERE lcirType = ?'; $params = [(int) $type]; if (!$includeExpired) { $sql .= ' AND (lcirExpires IS NULL OR lcirExpires > ' . $this->connection->getDatabasePlatform()->getNowExpression() . ')'; } $sql .= ' ORDER BY lcirID'; $result = []; $dateTimeFormat = $this->connection->getDatabasePlatform()->getDateTimeFormatString(); $rs = $this->connection->executeQuery($sql, $params); while (($row = $rs->fetch()) !== false) { yield IPRange::createFromRow($row, $dateTimeFormat); } }
php
public function getRanges($type, $includeExpired = false) { $sql = 'SELECT * FROM LoginControlIpRanges WHERE lcirType = ?'; $params = [(int) $type]; if (!$includeExpired) { $sql .= ' AND (lcirExpires IS NULL OR lcirExpires > ' . $this->connection->getDatabasePlatform()->getNowExpression() . ')'; } $sql .= ' ORDER BY lcirID'; $result = []; $dateTimeFormat = $this->connection->getDatabasePlatform()->getDateTimeFormatString(); $rs = $this->connection->executeQuery($sql, $params); while (($row = $rs->fetch()) !== false) { yield IPRange::createFromRow($row, $dateTimeFormat); } }
[ "public", "function", "getRanges", "(", "$", "type", ",", "$", "includeExpired", "=", "false", ")", "{", "$", "sql", "=", "'SELECT * FROM LoginControlIpRanges WHERE lcirType = ?'", ";", "$", "params", "=", "[", "(", "int", ")", "$", "type", "]", ";", "if", "(", "!", "$", "includeExpired", ")", "{", "$", "sql", ".=", "' AND (lcirExpires IS NULL OR lcirExpires > '", ".", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", "->", "getNowExpression", "(", ")", ".", "')'", ";", "}", "$", "sql", ".=", "' ORDER BY lcirID'", ";", "$", "result", "=", "[", "]", ";", "$", "dateTimeFormat", "=", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", "->", "getDateTimeFormatString", "(", ")", ";", "$", "rs", "=", "$", "this", "->", "connection", "->", "executeQuery", "(", "$", "sql", ",", "$", "params", ")", ";", "while", "(", "(", "$", "row", "=", "$", "rs", "->", "fetch", "(", ")", ")", "!==", "false", ")", "{", "yield", "IPRange", "::", "createFromRow", "(", "$", "row", ",", "$", "dateTimeFormat", ")", ";", "}", "}" ]
Get the list of currently available ranges. @param int $type (one of the IPService::IPRANGETYPE_... constants) @param bool $includeExpired Include expired records? @return IPRange[]|\Generator
[ "Get", "the", "list", "of", "currently", "available", "ranges", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L287-L301
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.getRangeByID
public function getRangeByID($id) { $result = null; if ($id) { $rs = $this->connection->executeQuery( 'SELECT * FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1', [$id] ); $row = $rs->fetch(); $rs->closeCursor(); if ($row !== false) { $result = IPRange::createFromRow($row, $this->connection->getDatabasePlatform()->getDateTimeFormatString()); } } return $result; }
php
public function getRangeByID($id) { $result = null; if ($id) { $rs = $this->connection->executeQuery( 'SELECT * FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1', [$id] ); $row = $rs->fetch(); $rs->closeCursor(); if ($row !== false) { $result = IPRange::createFromRow($row, $this->connection->getDatabasePlatform()->getDateTimeFormatString()); } } return $result; }
[ "public", "function", "getRangeByID", "(", "$", "id", ")", "{", "$", "result", "=", "null", ";", "if", "(", "$", "id", ")", "{", "$", "rs", "=", "$", "this", "->", "connection", "->", "executeQuery", "(", "'SELECT * FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1'", ",", "[", "$", "id", "]", ")", ";", "$", "row", "=", "$", "rs", "->", "fetch", "(", ")", ";", "$", "rs", "->", "closeCursor", "(", ")", ";", "if", "(", "$", "row", "!==", "false", ")", "{", "$", "result", "=", "IPRange", "::", "createFromRow", "(", "$", "row", ",", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", "->", "getDateTimeFormatString", "(", ")", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Find already defined range given its record ID. @param int $id @return IPRange|null
[ "Find", "already", "defined", "range", "given", "its", "record", "ID", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L310-L326
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.deleteRange
public function deleteRange($range) { if ($range instanceof IPRange) { $id = $range->getID(); } else { $id = (int) $range; } if ($id) { $this->connection->executeQuery('DELETE FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1', [$id]); } }
php
public function deleteRange($range) { if ($range instanceof IPRange) { $id = $range->getID(); } else { $id = (int) $range; } if ($id) { $this->connection->executeQuery('DELETE FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1', [$id]); } }
[ "public", "function", "deleteRange", "(", "$", "range", ")", "{", "if", "(", "$", "range", "instanceof", "IPRange", ")", "{", "$", "id", "=", "$", "range", "->", "getID", "(", ")", ";", "}", "else", "{", "$", "id", "=", "(", "int", ")", "$", "range", ";", "}", "if", "(", "$", "id", ")", "{", "$", "this", "->", "connection", "->", "executeQuery", "(", "'DELETE FROM LoginControlIpRanges WHERE lcirID = ? LIMIT 1'", ",", "[", "$", "id", "]", ")", ";", "}", "}" ]
Delete a range record. @param IPRange|int $range
[ "Delete", "a", "range", "record", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L333-L343
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.deleteFailedLoginAttempts
public function deleteFailedLoginAttempts($maxAge = null) { $sql = 'DELETE FROM FailedLoginAttempts'; if ($maxAge) { $platform = $this->connection->getDatabasePlatform(); $sql .= ' WHERE flaTimestamp <= ' . $platform->getDateSubSecondsExpression($platform->getNowExpression(), (int) $maxAge); } return (int) $this->connection->executeQuery($sql)->rowCount(); }
php
public function deleteFailedLoginAttempts($maxAge = null) { $sql = 'DELETE FROM FailedLoginAttempts'; if ($maxAge) { $platform = $this->connection->getDatabasePlatform(); $sql .= ' WHERE flaTimestamp <= ' . $platform->getDateSubSecondsExpression($platform->getNowExpression(), (int) $maxAge); } return (int) $this->connection->executeQuery($sql)->rowCount(); }
[ "public", "function", "deleteFailedLoginAttempts", "(", "$", "maxAge", "=", "null", ")", "{", "$", "sql", "=", "'DELETE FROM FailedLoginAttempts'", ";", "if", "(", "$", "maxAge", ")", "{", "$", "platform", "=", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", ";", "$", "sql", ".=", "' WHERE flaTimestamp <= '", ".", "$", "platform", "->", "getDateSubSecondsExpression", "(", "$", "platform", "->", "getNowExpression", "(", ")", ",", "(", "int", ")", "$", "maxAge", ")", ";", "}", "return", "(", "int", ")", "$", "this", "->", "connection", "->", "executeQuery", "(", "$", "sql", ")", "->", "rowCount", "(", ")", ";", "}" ]
Delete the failed login attempts. @param int|null $maxAge the maximum age (in seconds) of the records (specify an empty value do delete all records) @return int return the number of records deleted
[ "Delete", "the", "failed", "login", "attempts", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L384-L393
train
concrete5/concrete5
concrete/src/Permission/IPService.php
IPService.deleteAutomaticBlacklist
public function deleteAutomaticBlacklist($onlyExpired = true) { $sql = 'DELETE FROM LoginControlIpRanges WHERE lcirType = ' . (int) static::IPRANGETYPE_BLACKLIST_AUTOMATIC; if ($onlyExpired) { $platform = $this->connection->getDatabasePlatform(); $sql .= ' AND lcirExpires <= ' . $platform->getNowExpression(); } return (int) $this->connection->executeQuery($sql)->rowCount(); }
php
public function deleteAutomaticBlacklist($onlyExpired = true) { $sql = 'DELETE FROM LoginControlIpRanges WHERE lcirType = ' . (int) static::IPRANGETYPE_BLACKLIST_AUTOMATIC; if ($onlyExpired) { $platform = $this->connection->getDatabasePlatform(); $sql .= ' AND lcirExpires <= ' . $platform->getNowExpression(); } return (int) $this->connection->executeQuery($sql)->rowCount(); }
[ "public", "function", "deleteAutomaticBlacklist", "(", "$", "onlyExpired", "=", "true", ")", "{", "$", "sql", "=", "'DELETE FROM LoginControlIpRanges WHERE lcirType = '", ".", "(", "int", ")", "static", "::", "IPRANGETYPE_BLACKLIST_AUTOMATIC", ";", "if", "(", "$", "onlyExpired", ")", "{", "$", "platform", "=", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", ";", "$", "sql", ".=", "' AND lcirExpires <= '", ".", "$", "platform", "->", "getNowExpression", "(", ")", ";", "}", "return", "(", "int", ")", "$", "this", "->", "connection", "->", "executeQuery", "(", "$", "sql", ")", "->", "rowCount", "(", ")", ";", "}" ]
Clear the IP addresses automatically blacklisted. @param bool $onlyExpired Clear only the expired bans?
[ "Clear", "the", "IP", "addresses", "automatically", "blacklisted", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Permission/IPService.php#L400-L409
train
concrete5/concrete5
concrete/src/Localization/Translator/Loader/Gettext.php
Gettext.fixPlurals
private function fixPlurals($filename, TextDomain $textDomain, Language $localeInfo) { $expectedNumPlurals = count($localeInfo->categories); $pluralRule = $textDomain->getPluralRule(false); if ($pluralRule === null) { // Build the plural rules $pluralRule = Rule::fromString("nplurals={$expectedNumPlurals}; plural={$localeInfo->formula};"); $textDomain->setPluralRule($pluralRule); } else { $readNumPlurals = $pluralRule->getNumPlurals(); if ($expectedNumPlurals < $readNumPlurals) { // Reduce the number of plural rules, in order to consider other systems that use wrong counts (for example, Transifex uses 4 plural rules, but gettext only defines 3) $pluralRule = Rule::fromString("nplurals={$expectedNumPlurals}; plural={$localeInfo->formula};"); $textDomain->setPluralRule($pluralRule); } elseif ($expectedNumPlurals > $readNumPlurals) { // The language file defines less plurals than the required ones. $filename = str_replace(DIRECTORY_SEPARATOR, '/', $filename); if (strpos($filename, $this->webrootDirectory . '/') === 0) { $filename = substr($filename, strlen($this->webrootDirectory)); } // Don't translate the message, otherwise we may have an infinite loop (t() -> load translations -> t() -> load translations -> ...) throw new RuntimeException(sprintf( $readNumPlurals === 1 ? 'The language file %1$s for %2$s has %3$s plural form instead of %4$s.' : 'The language file %1$s for %2$s has %3$s plural forms instead of %4$s.' , $filename, $localeInfo->name, $readNumPlurals, $expectedNumPlurals )); } } return $textDomain; }
php
private function fixPlurals($filename, TextDomain $textDomain, Language $localeInfo) { $expectedNumPlurals = count($localeInfo->categories); $pluralRule = $textDomain->getPluralRule(false); if ($pluralRule === null) { // Build the plural rules $pluralRule = Rule::fromString("nplurals={$expectedNumPlurals}; plural={$localeInfo->formula};"); $textDomain->setPluralRule($pluralRule); } else { $readNumPlurals = $pluralRule->getNumPlurals(); if ($expectedNumPlurals < $readNumPlurals) { // Reduce the number of plural rules, in order to consider other systems that use wrong counts (for example, Transifex uses 4 plural rules, but gettext only defines 3) $pluralRule = Rule::fromString("nplurals={$expectedNumPlurals}; plural={$localeInfo->formula};"); $textDomain->setPluralRule($pluralRule); } elseif ($expectedNumPlurals > $readNumPlurals) { // The language file defines less plurals than the required ones. $filename = str_replace(DIRECTORY_SEPARATOR, '/', $filename); if (strpos($filename, $this->webrootDirectory . '/') === 0) { $filename = substr($filename, strlen($this->webrootDirectory)); } // Don't translate the message, otherwise we may have an infinite loop (t() -> load translations -> t() -> load translations -> ...) throw new RuntimeException(sprintf( $readNumPlurals === 1 ? 'The language file %1$s for %2$s has %3$s plural form instead of %4$s.' : 'The language file %1$s for %2$s has %3$s plural forms instead of %4$s.' , $filename, $localeInfo->name, $readNumPlurals, $expectedNumPlurals )); } } return $textDomain; }
[ "private", "function", "fixPlurals", "(", "$", "filename", ",", "TextDomain", "$", "textDomain", ",", "Language", "$", "localeInfo", ")", "{", "$", "expectedNumPlurals", "=", "count", "(", "$", "localeInfo", "->", "categories", ")", ";", "$", "pluralRule", "=", "$", "textDomain", "->", "getPluralRule", "(", "false", ")", ";", "if", "(", "$", "pluralRule", "===", "null", ")", "{", "// Build the plural rules", "$", "pluralRule", "=", "Rule", "::", "fromString", "(", "\"nplurals={$expectedNumPlurals}; plural={$localeInfo->formula};\"", ")", ";", "$", "textDomain", "->", "setPluralRule", "(", "$", "pluralRule", ")", ";", "}", "else", "{", "$", "readNumPlurals", "=", "$", "pluralRule", "->", "getNumPlurals", "(", ")", ";", "if", "(", "$", "expectedNumPlurals", "<", "$", "readNumPlurals", ")", "{", "// Reduce the number of plural rules, in order to consider other systems that use wrong counts (for example, Transifex uses 4 plural rules, but gettext only defines 3)", "$", "pluralRule", "=", "Rule", "::", "fromString", "(", "\"nplurals={$expectedNumPlurals}; plural={$localeInfo->formula};\"", ")", ";", "$", "textDomain", "->", "setPluralRule", "(", "$", "pluralRule", ")", ";", "}", "elseif", "(", "$", "expectedNumPlurals", ">", "$", "readNumPlurals", ")", "{", "// The language file defines less plurals than the required ones.", "$", "filename", "=", "str_replace", "(", "DIRECTORY_SEPARATOR", ",", "'/'", ",", "$", "filename", ")", ";", "if", "(", "strpos", "(", "$", "filename", ",", "$", "this", "->", "webrootDirectory", ".", "'/'", ")", "===", "0", ")", "{", "$", "filename", "=", "substr", "(", "$", "filename", ",", "strlen", "(", "$", "this", "->", "webrootDirectory", ")", ")", ";", "}", "// Don't translate the message, otherwise we may have an infinite loop (t() -> load translations -> t() -> load translations -> ...)", "throw", "new", "RuntimeException", "(", "sprintf", "(", "$", "readNumPlurals", "===", "1", "?", "'The language file %1$s for %2$s has %3$s plural form instead of %4$s.'", ":", "'The language file %1$s for %2$s has %3$s plural forms instead of %4$s.'", ",", "$", "filename", ",", "$", "localeInfo", "->", "name", ",", "$", "readNumPlurals", ",", "$", "expectedNumPlurals", ")", ")", ";", "}", "}", "return", "$", "textDomain", ";", "}" ]
Fix the plural rules of the translations loaded from a file. @param string $filename @param \Zend\I18n\Translator\TextDomain $textDomain @param \Gettext\Languages\Language $localeInfo @throws \Zend\I18n\Exception\RuntimeException when the loaded file has less plural rules than the required ones
[ "Fix", "the", "plural", "rules", "of", "the", "translations", "loaded", "from", "a", "file", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Localization/Translator/Loader/Gettext.php#L56-L92
train
concrete5/concrete5
concrete/src/User/UserList.php
UserList.getResultIDs
public function getResultIDs() { $results = $this->executeGetResults(); $ids = []; foreach ($results as $result) { $ids[] = $result['uID']; } return $ids; }
php
public function getResultIDs() { $results = $this->executeGetResults(); $ids = []; foreach ($results as $result) { $ids[] = $result['uID']; } return $ids; }
[ "public", "function", "getResultIDs", "(", ")", "{", "$", "results", "=", "$", "this", "->", "executeGetResults", "(", ")", ";", "$", "ids", "=", "[", "]", ";", "foreach", "(", "$", "results", "as", "$", "result", ")", "{", "$", "ids", "[", "]", "=", "$", "result", "[", "'uID'", "]", ";", "}", "return", "$", "ids", ";", "}" ]
similar to get except it returns an array of userIDs much faster than getting a UserInfo object for each result if all you need is the user's id. @return array $userIDs
[ "similar", "to", "get", "except", "it", "returns", "an", "array", "of", "userIDs", "much", "faster", "than", "getting", "a", "UserInfo", "object", "for", "each", "result", "if", "all", "you", "need", "is", "the", "user", "s", "id", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/UserList.php#L198-L207
train
concrete5/concrete5
concrete/src/User/UserList.php
UserList.filterByIsActive
public function filterByIsActive($isActive) { $this->includeInactiveUsers(); $this->query->andWhere('u.uIsActive = :uIsActive'); $this->query->setParameter('uIsActive', $isActive); }
php
public function filterByIsActive($isActive) { $this->includeInactiveUsers(); $this->query->andWhere('u.uIsActive = :uIsActive'); $this->query->setParameter('uIsActive', $isActive); }
[ "public", "function", "filterByIsActive", "(", "$", "isActive", ")", "{", "$", "this", "->", "includeInactiveUsers", "(", ")", ";", "$", "this", "->", "query", "->", "andWhere", "(", "'u.uIsActive = :uIsActive'", ")", ";", "$", "this", "->", "query", "->", "setParameter", "(", "'uIsActive'", ",", "$", "isActive", ")", ";", "}" ]
Explicitly filters by whether a user is active or not. Does this by setting "include inactive users" to true, THEN filtering them in our out. Some settings here are redundant given the default settings but a little duplication is ok sometimes. @param $val
[ "Explicitly", "filters", "by", "whether", "a", "user", "is", "active", "or", "not", ".", "Does", "this", "by", "setting", "include", "inactive", "users", "to", "true", "THEN", "filtering", "them", "in", "our", "out", ".", "Some", "settings", "here", "are", "redundant", "given", "the", "default", "settings", "but", "a", "little", "duplication", "is", "ok", "sometimes", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/UserList.php#L247-L252
train
concrete5/concrete5
concrete/src/User/UserList.php
UserList.filterByIsValidated
public function filterByIsValidated($isValidated) { $this->includeInactiveUsers(); if (!$isValidated) { $this->includeUnvalidatedUsers(); $this->query->andWhere('u.uIsValidated = :uIsValidated'); $this->query->setParameter('uIsValidated', $isValidated); } }
php
public function filterByIsValidated($isValidated) { $this->includeInactiveUsers(); if (!$isValidated) { $this->includeUnvalidatedUsers(); $this->query->andWhere('u.uIsValidated = :uIsValidated'); $this->query->setParameter('uIsValidated', $isValidated); } }
[ "public", "function", "filterByIsValidated", "(", "$", "isValidated", ")", "{", "$", "this", "->", "includeInactiveUsers", "(", ")", ";", "if", "(", "!", "$", "isValidated", ")", "{", "$", "this", "->", "includeUnvalidatedUsers", "(", ")", ";", "$", "this", "->", "query", "->", "andWhere", "(", "'u.uIsValidated = :uIsValidated'", ")", ";", "$", "this", "->", "query", "->", "setParameter", "(", "'uIsValidated'", ",", "$", "isValidated", ")", ";", "}", "}" ]
Filter list by whether a user is validated or not. @param bool $isValidated
[ "Filter", "list", "by", "whether", "a", "user", "is", "validated", "or", "not", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/UserList.php#L259-L267
train
concrete5/concrete5
concrete/src/User/UserList.php
UserList.filterByFuzzyUserName
public function filterByFuzzyUserName($username) { $this->query->andWhere( $this->query->expr()->like('u.uName', ':uName') ); $this->query->setParameter('uName', $username . '%'); }
php
public function filterByFuzzyUserName($username) { $this->query->andWhere( $this->query->expr()->like('u.uName', ':uName') ); $this->query->setParameter('uName', $username . '%'); }
[ "public", "function", "filterByFuzzyUserName", "(", "$", "username", ")", "{", "$", "this", "->", "query", "->", "andWhere", "(", "$", "this", "->", "query", "->", "expr", "(", ")", "->", "like", "(", "'u.uName'", ",", "':uName'", ")", ")", ";", "$", "this", "->", "query", "->", "setParameter", "(", "'uName'", ",", "$", "username", ".", "'%'", ")", ";", "}" ]
Filter list by user name but as a like parameter. @param $username
[ "Filter", "list", "by", "user", "name", "but", "as", "a", "like", "parameter", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/UserList.php#L291-L297
train
concrete5/concrete5
concrete/src/User/UserList.php
UserList.checkGroupJoin
private function checkGroupJoin() { $query = $this->getQueryObject(); $params = $query->getQueryPart('join'); $isGroupSet = false; $isUserGroupSet = false; // Loop twice as params returns an array of arrays foreach ($params as $param) { foreach ($param as $setTable) if (in_array('ug', $setTable)) { $isUserGroupSet = true; } if (in_array('g', $setTable)) { $isGroupSet = true; } } if ($isUserGroupSet === false) { $query->leftJoin('u', 'UserGroups', 'ug', 'ug.uID = u.uID'); } if ($isGroupSet === false) { $query->leftJoin('ug', $query->getConnection()->getDatabasePlatform()->quoteSingleIdentifier('Groups'),'g', 'ug.gID = g.gID'); } }
php
private function checkGroupJoin() { $query = $this->getQueryObject(); $params = $query->getQueryPart('join'); $isGroupSet = false; $isUserGroupSet = false; // Loop twice as params returns an array of arrays foreach ($params as $param) { foreach ($param as $setTable) if (in_array('ug', $setTable)) { $isUserGroupSet = true; } if (in_array('g', $setTable)) { $isGroupSet = true; } } if ($isUserGroupSet === false) { $query->leftJoin('u', 'UserGroups', 'ug', 'ug.uID = u.uID'); } if ($isGroupSet === false) { $query->leftJoin('ug', $query->getConnection()->getDatabasePlatform()->quoteSingleIdentifier('Groups'),'g', 'ug.gID = g.gID'); } }
[ "private", "function", "checkGroupJoin", "(", ")", "{", "$", "query", "=", "$", "this", "->", "getQueryObject", "(", ")", ";", "$", "params", "=", "$", "query", "->", "getQueryPart", "(", "'join'", ")", ";", "$", "isGroupSet", "=", "false", ";", "$", "isUserGroupSet", "=", "false", ";", "// Loop twice as params returns an array of arrays", "foreach", "(", "$", "params", "as", "$", "param", ")", "{", "foreach", "(", "$", "param", "as", "$", "setTable", ")", "if", "(", "in_array", "(", "'ug'", ",", "$", "setTable", ")", ")", "{", "$", "isUserGroupSet", "=", "true", ";", "}", "if", "(", "in_array", "(", "'g'", ",", "$", "setTable", ")", ")", "{", "$", "isGroupSet", "=", "true", ";", "}", "}", "if", "(", "$", "isUserGroupSet", "===", "false", ")", "{", "$", "query", "->", "leftJoin", "(", "'u'", ",", "'UserGroups'", ",", "'ug'", ",", "'ug.uID = u.uID'", ")", ";", "}", "if", "(", "$", "isGroupSet", "===", "false", ")", "{", "$", "query", "->", "leftJoin", "(", "'ug'", ",", "$", "query", "->", "getConnection", "(", ")", "->", "getDatabasePlatform", "(", ")", "->", "quoteSingleIdentifier", "(", "'Groups'", ")", ",", "'g'", ",", "'ug.gID = g.gID'", ")", ";", "}", "}" ]
Function used to check if a group join has already been set
[ "Function", "used", "to", "check", "if", "a", "group", "join", "has", "already", "been", "set" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/UserList.php#L356-L377
train
concrete5/concrete5
concrete/src/User/UserList.php
UserList.filterByInAnyGroup
public function filterByInAnyGroup($groups, $inGroups = true) { $this->checkGroupJoin(); $groupIDs = []; $orX = $this->getQueryObject()->expr()->orX(); $app = Application::getFacadeApplication(); /** @var $likeBuilder LikeBuilder */ $likeBuilder = $app->make(LikeBuilder::class); $query = $this->getQueryObject()->getConnection()->createQueryBuilder(); foreach ($groups as $group) { if ($group instanceof \Concrete\Core\User\Group\Group) { $orX->add($this->getQueryObject()->expr()->like('g.gPath', ':groupPathChild_'.$group->getGroupID())); $this->getQueryObject()->setParameter('groupPathChild_'.$group->getGroupID(), $likeBuilder->escapeForLike($group->getGroupPath()). '/%'); $groupIDs[] = $group->getGroupID(); } } if (is_array($groups) && count($groups) > 0) { $query->select('u.uID')->from('Users','u') ->leftJoin('u','UserGroups','ug','u.uID=ug.uID') ->leftJoin('ug', $query->getConnection()->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g', 'ug.gID=g.gID'); $orX->add($this->getQueryObject()->expr()->in('g.gID', $groupIDs)); $query->where($orX)->andWhere($this->getQueryObject()->expr()->isNotNull('g.gID')); if ($inGroups) { $this->getQueryObject()->andWhere($this->getQueryObject()->expr()->in('u.uID', $query->getSQL())); } else { $this->getQueryObject()->andWhere($this->getQueryObject()->expr()->notIn('u.uID', $query->getSQL())); $this->getQueryObject()->setParameter('groupIDs',$groupIDs, \Concrete\Core\Database\Connection\Connection::PARAM_INT_ARRAY); } } }
php
public function filterByInAnyGroup($groups, $inGroups = true) { $this->checkGroupJoin(); $groupIDs = []; $orX = $this->getQueryObject()->expr()->orX(); $app = Application::getFacadeApplication(); /** @var $likeBuilder LikeBuilder */ $likeBuilder = $app->make(LikeBuilder::class); $query = $this->getQueryObject()->getConnection()->createQueryBuilder(); foreach ($groups as $group) { if ($group instanceof \Concrete\Core\User\Group\Group) { $orX->add($this->getQueryObject()->expr()->like('g.gPath', ':groupPathChild_'.$group->getGroupID())); $this->getQueryObject()->setParameter('groupPathChild_'.$group->getGroupID(), $likeBuilder->escapeForLike($group->getGroupPath()). '/%'); $groupIDs[] = $group->getGroupID(); } } if (is_array($groups) && count($groups) > 0) { $query->select('u.uID')->from('Users','u') ->leftJoin('u','UserGroups','ug','u.uID=ug.uID') ->leftJoin('ug', $query->getConnection()->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g', 'ug.gID=g.gID'); $orX->add($this->getQueryObject()->expr()->in('g.gID', $groupIDs)); $query->where($orX)->andWhere($this->getQueryObject()->expr()->isNotNull('g.gID')); if ($inGroups) { $this->getQueryObject()->andWhere($this->getQueryObject()->expr()->in('u.uID', $query->getSQL())); } else { $this->getQueryObject()->andWhere($this->getQueryObject()->expr()->notIn('u.uID', $query->getSQL())); $this->getQueryObject()->setParameter('groupIDs',$groupIDs, \Concrete\Core\Database\Connection\Connection::PARAM_INT_ARRAY); } } }
[ "public", "function", "filterByInAnyGroup", "(", "$", "groups", ",", "$", "inGroups", "=", "true", ")", "{", "$", "this", "->", "checkGroupJoin", "(", ")", ";", "$", "groupIDs", "=", "[", "]", ";", "$", "orX", "=", "$", "this", "->", "getQueryObject", "(", ")", "->", "expr", "(", ")", "->", "orX", "(", ")", ";", "$", "app", "=", "Application", "::", "getFacadeApplication", "(", ")", ";", "/** @var $likeBuilder LikeBuilder */", "$", "likeBuilder", "=", "$", "app", "->", "make", "(", "LikeBuilder", "::", "class", ")", ";", "$", "query", "=", "$", "this", "->", "getQueryObject", "(", ")", "->", "getConnection", "(", ")", "->", "createQueryBuilder", "(", ")", ";", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "if", "(", "$", "group", "instanceof", "\\", "Concrete", "\\", "Core", "\\", "User", "\\", "Group", "\\", "Group", ")", "{", "$", "orX", "->", "add", "(", "$", "this", "->", "getQueryObject", "(", ")", "->", "expr", "(", ")", "->", "like", "(", "'g.gPath'", ",", "':groupPathChild_'", ".", "$", "group", "->", "getGroupID", "(", ")", ")", ")", ";", "$", "this", "->", "getQueryObject", "(", ")", "->", "setParameter", "(", "'groupPathChild_'", ".", "$", "group", "->", "getGroupID", "(", ")", ",", "$", "likeBuilder", "->", "escapeForLike", "(", "$", "group", "->", "getGroupPath", "(", ")", ")", ".", "'/%'", ")", ";", "$", "groupIDs", "[", "]", "=", "$", "group", "->", "getGroupID", "(", ")", ";", "}", "}", "if", "(", "is_array", "(", "$", "groups", ")", "&&", "count", "(", "$", "groups", ")", ">", "0", ")", "{", "$", "query", "->", "select", "(", "'u.uID'", ")", "->", "from", "(", "'Users'", ",", "'u'", ")", "->", "leftJoin", "(", "'u'", ",", "'UserGroups'", ",", "'ug'", ",", "'u.uID=ug.uID'", ")", "->", "leftJoin", "(", "'ug'", ",", "$", "query", "->", "getConnection", "(", ")", "->", "getDatabasePlatform", "(", ")", "->", "quoteSingleIdentifier", "(", "'Groups'", ")", ",", "'g'", ",", "'ug.gID=g.gID'", ")", ";", "$", "orX", "->", "add", "(", "$", "this", "->", "getQueryObject", "(", ")", "->", "expr", "(", ")", "->", "in", "(", "'g.gID'", ",", "$", "groupIDs", ")", ")", ";", "$", "query", "->", "where", "(", "$", "orX", ")", "->", "andWhere", "(", "$", "this", "->", "getQueryObject", "(", ")", "->", "expr", "(", ")", "->", "isNotNull", "(", "'g.gID'", ")", ")", ";", "if", "(", "$", "inGroups", ")", "{", "$", "this", "->", "getQueryObject", "(", ")", "->", "andWhere", "(", "$", "this", "->", "getQueryObject", "(", ")", "->", "expr", "(", ")", "->", "in", "(", "'u.uID'", ",", "$", "query", "->", "getSQL", "(", ")", ")", ")", ";", "}", "else", "{", "$", "this", "->", "getQueryObject", "(", ")", "->", "andWhere", "(", "$", "this", "->", "getQueryObject", "(", ")", "->", "expr", "(", ")", "->", "notIn", "(", "'u.uID'", ",", "$", "query", "->", "getSQL", "(", ")", ")", ")", ";", "$", "this", "->", "getQueryObject", "(", ")", "->", "setParameter", "(", "'groupIDs'", ",", "$", "groupIDs", ",", "\\", "Concrete", "\\", "Core", "\\", "Database", "\\", "Connection", "\\", "Connection", "::", "PARAM_INT_ARRAY", ")", ";", "}", "}", "}" ]
Filters the user list for only users within at least one of the provided groups. @param \Concrete\Core\User\Group\Group[]|\Generator $groups @param bool $inGroups Set to true to search users that are in at least in one of the specified groups, false to search users that aren't in any of the specified groups
[ "Filters", "the", "user", "list", "for", "only", "users", "within", "at", "least", "one", "of", "the", "provided", "groups", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/User/UserList.php#L385-L419
train
concrete5/concrete5
concrete/src/Html/Image.php
Image.loadPictureSettingsFromTheme
protected function loadPictureSettingsFromTheme() { $c = Page::getCurrentPage(); if (is_object($c)) { $pt = $c->getPageController()->getTheme(); if (is_object($pt)) { $pt = $pt->getThemeHandle(); } $th = Theme::getByHandle($pt); if (is_object($th)) { $this->theme = $th; $this->usePictureTag = count($th->getThemeResponsiveImageMap()) > 0; } } }
php
protected function loadPictureSettingsFromTheme() { $c = Page::getCurrentPage(); if (is_object($c)) { $pt = $c->getPageController()->getTheme(); if (is_object($pt)) { $pt = $pt->getThemeHandle(); } $th = Theme::getByHandle($pt); if (is_object($th)) { $this->theme = $th; $this->usePictureTag = count($th->getThemeResponsiveImageMap()) > 0; } } }
[ "protected", "function", "loadPictureSettingsFromTheme", "(", ")", "{", "$", "c", "=", "Page", "::", "getCurrentPage", "(", ")", ";", "if", "(", "is_object", "(", "$", "c", ")", ")", "{", "$", "pt", "=", "$", "c", "->", "getPageController", "(", ")", "->", "getTheme", "(", ")", ";", "if", "(", "is_object", "(", "$", "pt", ")", ")", "{", "$", "pt", "=", "$", "pt", "->", "getThemeHandle", "(", ")", ";", "}", "$", "th", "=", "Theme", "::", "getByHandle", "(", "$", "pt", ")", ";", "if", "(", "is_object", "(", "$", "th", ")", ")", "{", "$", "this", "->", "theme", "=", "$", "th", ";", "$", "this", "->", "usePictureTag", "=", "count", "(", "$", "th", "->", "getThemeResponsiveImageMap", "(", ")", ")", ">", "0", ";", "}", "}", "}" ]
Load picture settings from the theme. If the theme uses responsive image maps, the getTag method will return a Picture object.
[ "Load", "picture", "settings", "from", "the", "theme", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Html/Image.php#L95-L109
train
concrete5/concrete5
concrete/src/Page/Search/Index/PageIndex.php
PageIndex.clear
public function clear() { /** @var PageCategory $pageCategory */ $pageCategory = $this->app[PageCategory::class]; /** @var PageKey $key */ foreach ($pageCategory->getList() as $key) { /** @var SearchIndexerInterface $indexer */ $indexer = $key->getSearchIndexer(); // Update the key tables $indexer->updateSearchIndexKeyColumns($pageCategory, $key); } // Truncate the existing search index $database = $this->app['database']->connection(); $database->Execute('truncate table PageSearchIndex'); }
php
public function clear() { /** @var PageCategory $pageCategory */ $pageCategory = $this->app[PageCategory::class]; /** @var PageKey $key */ foreach ($pageCategory->getList() as $key) { /** @var SearchIndexerInterface $indexer */ $indexer = $key->getSearchIndexer(); // Update the key tables $indexer->updateSearchIndexKeyColumns($pageCategory, $key); } // Truncate the existing search index $database = $this->app['database']->connection(); $database->Execute('truncate table PageSearchIndex'); }
[ "public", "function", "clear", "(", ")", "{", "/** @var PageCategory $pageCategory */", "$", "pageCategory", "=", "$", "this", "->", "app", "[", "PageCategory", "::", "class", "]", ";", "/** @var PageKey $key */", "foreach", "(", "$", "pageCategory", "->", "getList", "(", ")", "as", "$", "key", ")", "{", "/** @var SearchIndexerInterface $indexer */", "$", "indexer", "=", "$", "key", "->", "getSearchIndexer", "(", ")", ";", "// Update the key tables", "$", "indexer", "->", "updateSearchIndexKeyColumns", "(", "$", "pageCategory", ",", "$", "key", ")", ";", "}", "// Truncate the existing search index", "$", "database", "=", "$", "this", "->", "app", "[", "'database'", "]", "->", "connection", "(", ")", ";", "$", "database", "->", "Execute", "(", "'truncate table PageSearchIndex'", ")", ";", "}" ]
Clear out all indexed items @return void
[ "Clear", "out", "all", "indexed", "items" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Page/Search/Index/PageIndex.php#L43-L60
train
concrete5/concrete5
concrete/src/Job/QueueableJob.php
QueueableJob.getJobQueueBatchSize
public function getJobQueueBatchSize() { // If there's no batch size set, let's pull the batch size from the config if ($this->jQueueBatchSize === null) { $this->jQueueBatchSize = Config::get('concrete.limits.job_queue_batch'); } return $this->jQueueBatchSize; }
php
public function getJobQueueBatchSize() { // If there's no batch size set, let's pull the batch size from the config if ($this->jQueueBatchSize === null) { $this->jQueueBatchSize = Config::get('concrete.limits.job_queue_batch'); } return $this->jQueueBatchSize; }
[ "public", "function", "getJobQueueBatchSize", "(", ")", "{", "// If there's no batch size set, let's pull the batch size from the config", "if", "(", "$", "this", "->", "jQueueBatchSize", "===", "null", ")", "{", "$", "this", "->", "jQueueBatchSize", "=", "Config", "::", "get", "(", "'concrete.limits.job_queue_batch'", ")", ";", "}", "return", "$", "this", "->", "jQueueBatchSize", ";", "}" ]
Get the size of the queue batches @return int
[ "Get", "the", "size", "of", "the", "queue", "batches" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Job/QueueableJob.php#L63-L71
train
concrete5/concrete5
concrete/src/Job/QueueableJob.php
QueueableJob.getQueueObject
public function getQueueObject() { if ($this->jQueueObject === null) { $this->jQueueObject = Queue::get('job_' . $this->getJobHandle(), array('timeout' => 1)); } return $this->jQueueObject; }
php
public function getQueueObject() { if ($this->jQueueObject === null) { $this->jQueueObject = Queue::get('job_' . $this->getJobHandle(), array('timeout' => 1)); } return $this->jQueueObject; }
[ "public", "function", "getQueueObject", "(", ")", "{", "if", "(", "$", "this", "->", "jQueueObject", "===", "null", ")", "{", "$", "this", "->", "jQueueObject", "=", "Queue", "::", "get", "(", "'job_'", ".", "$", "this", "->", "getJobHandle", "(", ")", ",", "array", "(", "'timeout'", "=>", "1", ")", ")", ";", "}", "return", "$", "this", "->", "jQueueObject", ";", "}" ]
Get the queue object we're going to use to queue @return \ZendQueue\Queue
[ "Get", "the", "queue", "object", "we", "re", "going", "to", "use", "to", "queue" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Job/QueueableJob.php#L77-L84
train
concrete5/concrete5
concrete/src/Job/QueueableJob.php
QueueableJob.markCompleted
public function markCompleted($code = 0, $message = false) { $obj = parent::markCompleted($code, $message); $queue = $this->getQueueObject(); if (!$this->didFail()) { $queue->deleteQueue(); } return $obj; }
php
public function markCompleted($code = 0, $message = false) { $obj = parent::markCompleted($code, $message); $queue = $this->getQueueObject(); if (!$this->didFail()) { $queue->deleteQueue(); } return $obj; }
[ "public", "function", "markCompleted", "(", "$", "code", "=", "0", ",", "$", "message", "=", "false", ")", "{", "$", "obj", "=", "parent", "::", "markCompleted", "(", "$", "code", ",", "$", "message", ")", ";", "$", "queue", "=", "$", "this", "->", "getQueueObject", "(", ")", ";", "if", "(", "!", "$", "this", "->", "didFail", "(", ")", ")", "{", "$", "queue", "->", "deleteQueue", "(", ")", ";", "}", "return", "$", "obj", ";", "}" ]
Mark the queue as having completed @param int $code 0 for success, otherwise the exception error code @param bool $message The message to show @return \Concrete\Core\Job\JobResult
[ "Mark", "the", "queue", "as", "having", "completed" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Job/QueueableJob.php#L111-L120
train
concrete5/concrete5
concrete/src/Job/QueueableJob.php
QueueableJob.executeJob
public function executeJob() { // If the job's already running, don't try to restart it if ($this->getJobStatus() !== 'RUNNING') { $queue = $this->markStarted(); // Prepare the queue for processing $this->start($queue); } else { $queue = $this->getQueueObject(); } try { $batchSize = $this->getJobQueueBatchSize() ?: PHP_INT_MAX; // Loop over queue batches while (($messages = $queue->receive($batchSize)) && $messages->count() > 0) { // Run the batch $this->executeBatch($messages, $queue); } // Mark the queue as finished $output = $this->finish($queue); // Mark the job as completed $result = $this->markCompleted(0, $output); } catch (\Exception $e) { $result = $this->markCompleted(Job::JOB_ERROR_EXCEPTION_GENERAL, $e->getMessage()); $result->message = $result->result; // needed for progressive library. } return $result; }
php
public function executeJob() { // If the job's already running, don't try to restart it if ($this->getJobStatus() !== 'RUNNING') { $queue = $this->markStarted(); // Prepare the queue for processing $this->start($queue); } else { $queue = $this->getQueueObject(); } try { $batchSize = $this->getJobQueueBatchSize() ?: PHP_INT_MAX; // Loop over queue batches while (($messages = $queue->receive($batchSize)) && $messages->count() > 0) { // Run the batch $this->executeBatch($messages, $queue); } // Mark the queue as finished $output = $this->finish($queue); // Mark the job as completed $result = $this->markCompleted(0, $output); } catch (\Exception $e) { $result = $this->markCompleted(Job::JOB_ERROR_EXCEPTION_GENERAL, $e->getMessage()); $result->message = $result->result; // needed for progressive library. } return $result; }
[ "public", "function", "executeJob", "(", ")", "{", "// If the job's already running, don't try to restart it", "if", "(", "$", "this", "->", "getJobStatus", "(", ")", "!==", "'RUNNING'", ")", "{", "$", "queue", "=", "$", "this", "->", "markStarted", "(", ")", ";", "// Prepare the queue for processing", "$", "this", "->", "start", "(", "$", "queue", ")", ";", "}", "else", "{", "$", "queue", "=", "$", "this", "->", "getQueueObject", "(", ")", ";", "}", "try", "{", "$", "batchSize", "=", "$", "this", "->", "getJobQueueBatchSize", "(", ")", "?", ":", "PHP_INT_MAX", ";", "// Loop over queue batches", "while", "(", "(", "$", "messages", "=", "$", "queue", "->", "receive", "(", "$", "batchSize", ")", ")", "&&", "$", "messages", "->", "count", "(", ")", ">", "0", ")", "{", "// Run the batch", "$", "this", "->", "executeBatch", "(", "$", "messages", ",", "$", "queue", ")", ";", "}", "// Mark the queue as finished", "$", "output", "=", "$", "this", "->", "finish", "(", "$", "queue", ")", ";", "// Mark the job as completed", "$", "result", "=", "$", "this", "->", "markCompleted", "(", "0", ",", "$", "output", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "result", "=", "$", "this", "->", "markCompleted", "(", "Job", "::", "JOB_ERROR_EXCEPTION_GENERAL", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "$", "result", "->", "message", "=", "$", "result", "->", "result", ";", "// needed for progressive library.", "}", "return", "$", "result", ";", "}" ]
Executejob for queueable jobs actually starts the queue, runs, and ends all in one function. This happens if we run a job in legacy mode.
[ "Executejob", "for", "queueable", "jobs", "actually", "starts", "the", "queue", "runs", "and", "ends", "all", "in", "one", "function", ".", "This", "happens", "if", "we", "run", "a", "job", "in", "legacy", "mode", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Job/QueueableJob.php#L125-L157
train
concrete5/concrete5
concrete/src/Job/QueueableJob.php
QueueableJob.executeBatch
public function executeBatch($batch, ZendQueue $queue) { foreach ($batch as $item) { $this->processQueueItem($item); $queue->deleteMessage($item); } }
php
public function executeBatch($batch, ZendQueue $queue) { foreach ($batch as $item) { $this->processQueueItem($item); $queue->deleteMessage($item); } }
[ "public", "function", "executeBatch", "(", "$", "batch", ",", "ZendQueue", "$", "queue", ")", "{", "foreach", "(", "$", "batch", "as", "$", "item", ")", "{", "$", "this", "->", "processQueueItem", "(", "$", "item", ")", ";", "$", "queue", "->", "deleteMessage", "(", "$", "item", ")", ";", "}", "}" ]
Process a queue batch @param array|iterator $batch @param \ZendQueue\Queue $queue
[ "Process", "a", "queue", "batch" ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Job/QueueableJob.php#L165-L171
train
concrete5/concrete5
concrete/src/Captcha/Library.php
Library.getActive
public static function getActive() { $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $sclHandle = $db->fetchColumn('select sclHandle from SystemCaptchaLibraries where sclIsActive = 1'); return ($sclHandle === false) ? null : static::getByHandle($sclHandle); }
php
public static function getActive() { $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $sclHandle = $db->fetchColumn('select sclHandle from SystemCaptchaLibraries where sclIsActive = 1'); return ($sclHandle === false) ? null : static::getByHandle($sclHandle); }
[ "public", "static", "function", "getActive", "(", ")", "{", "$", "app", "=", "Facade", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "'database'", ")", "->", "connection", "(", ")", ";", "$", "sclHandle", "=", "$", "db", "->", "fetchColumn", "(", "'select sclHandle from SystemCaptchaLibraries where sclIsActive = 1'", ")", ";", "return", "(", "$", "sclHandle", "===", "false", ")", "?", "null", ":", "static", "::", "getByHandle", "(", "$", "sclHandle", ")", ";", "}" ]
Get the active library. @return static|null
[ "Get", "the", "active", "library", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Captcha/Library.php#L111-L118
train
concrete5/concrete5
concrete/src/Captcha/Library.php
Library.getByHandle
public static function getByHandle($sclHandle) { $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $r = $db->fetchAssoc('select sclHandle, sclIsActive, pkgID, sclName from SystemCaptchaLibraries where sclHandle = ?', [$sclHandle]); if ($r !== false) { $sc = new static(); $sc->setPropertiesFromArray($r); return $sc; } }
php
public static function getByHandle($sclHandle) { $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $r = $db->fetchAssoc('select sclHandle, sclIsActive, pkgID, sclName from SystemCaptchaLibraries where sclHandle = ?', [$sclHandle]); if ($r !== false) { $sc = new static(); $sc->setPropertiesFromArray($r); return $sc; } }
[ "public", "static", "function", "getByHandle", "(", "$", "sclHandle", ")", "{", "$", "app", "=", "Facade", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "'database'", ")", "->", "connection", "(", ")", ";", "$", "r", "=", "$", "db", "->", "fetchAssoc", "(", "'select sclHandle, sclIsActive, pkgID, sclName from SystemCaptchaLibraries where sclHandle = ?'", ",", "[", "$", "sclHandle", "]", ")", ";", "if", "(", "$", "r", "!==", "false", ")", "{", "$", "sc", "=", "new", "static", "(", ")", ";", "$", "sc", "->", "setPropertiesFromArray", "(", "$", "r", ")", ";", "return", "$", "sc", ";", "}", "}" ]
Get a library given its handle. @param string $sclHandle the library handle @return static|null
[ "Get", "a", "library", "given", "its", "handle", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Captcha/Library.php#L127-L138
train
concrete5/concrete5
concrete/src/Captcha/Library.php
Library.add
public static function add($sclHandle, $sclName, $pkg = false) { if (is_object($pkg)) { $pkgID = $pkg->getPackageID(); } else { $pkgID = (int) $pkg; } $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $db->executeQuery('insert into SystemCaptchaLibraries (sclHandle, sclName, pkgID) values (?, ?, ?)', [$sclHandle, $sclName, $pkgID]); return static::getByHandle($sclHandle); }
php
public static function add($sclHandle, $sclName, $pkg = false) { if (is_object($pkg)) { $pkgID = $pkg->getPackageID(); } else { $pkgID = (int) $pkg; } $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $db->executeQuery('insert into SystemCaptchaLibraries (sclHandle, sclName, pkgID) values (?, ?, ?)', [$sclHandle, $sclName, $pkgID]); return static::getByHandle($sclHandle); }
[ "public", "static", "function", "add", "(", "$", "sclHandle", ",", "$", "sclName", ",", "$", "pkg", "=", "false", ")", "{", "if", "(", "is_object", "(", "$", "pkg", ")", ")", "{", "$", "pkgID", "=", "$", "pkg", "->", "getPackageID", "(", ")", ";", "}", "else", "{", "$", "pkgID", "=", "(", "int", ")", "$", "pkg", ";", "}", "$", "app", "=", "Facade", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "'database'", ")", "->", "connection", "(", ")", ";", "$", "db", "->", "executeQuery", "(", "'insert into SystemCaptchaLibraries (sclHandle, sclName, pkgID) values (?, ?, ?)'", ",", "[", "$", "sclHandle", ",", "$", "sclName", ",", "$", "pkgID", "]", ")", ";", "return", "static", "::", "getByHandle", "(", "$", "sclHandle", ")", ";", "}" ]
Add a new library. @param string $sclHandle the library handle @param string $sclName the library name @param \Concrete\Core\Entity\Package|int|false $pkg the package that installs this library @return static
[ "Add", "a", "new", "library", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Captcha/Library.php#L149-L161
train
concrete5/concrete5
concrete/src/Captcha/Library.php
Library.activate
public function activate() { $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $db->executeQuery('update SystemCaptchaLibraries set sclIsActive = 0'); $db->executeQuery('update SystemCaptchaLibraries set sclIsActive = 1 where sclHandle = ?', [$this->sclHandle]); $this->sclIsActive = 1; }
php
public function activate() { $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $db->executeQuery('update SystemCaptchaLibraries set sclIsActive = 0'); $db->executeQuery('update SystemCaptchaLibraries set sclIsActive = 1 where sclHandle = ?', [$this->sclHandle]); $this->sclIsActive = 1; }
[ "public", "function", "activate", "(", ")", "{", "$", "app", "=", "Facade", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "'database'", ")", "->", "connection", "(", ")", ";", "$", "db", "->", "executeQuery", "(", "'update SystemCaptchaLibraries set sclIsActive = 0'", ")", ";", "$", "db", "->", "executeQuery", "(", "'update SystemCaptchaLibraries set sclIsActive = 1 where sclHandle = ?'", ",", "[", "$", "this", "->", "sclHandle", "]", ")", ";", "$", "this", "->", "sclIsActive", "=", "1", ";", "}" ]
Make this library the active one.
[ "Make", "this", "library", "the", "active", "one", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Captcha/Library.php#L182-L189
train
concrete5/concrete5
concrete/src/Captcha/Library.php
Library.getList
public static function getList() { $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $libraries = []; foreach ($db->fetchAll('select sclHandle from SystemCaptchaLibraries order by sclHandle asc') as $row) { $scl = static::getByHandle($row['sclHandle']); $libraries[] = $scl; } return $libraries; }
php
public static function getList() { $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $libraries = []; foreach ($db->fetchAll('select sclHandle from SystemCaptchaLibraries order by sclHandle asc') as $row) { $scl = static::getByHandle($row['sclHandle']); $libraries[] = $scl; } return $libraries; }
[ "public", "static", "function", "getList", "(", ")", "{", "$", "app", "=", "Facade", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "'database'", ")", "->", "connection", "(", ")", ";", "$", "libraries", "=", "[", "]", ";", "foreach", "(", "$", "db", "->", "fetchAll", "(", "'select sclHandle from SystemCaptchaLibraries order by sclHandle asc'", ")", "as", "$", "row", ")", "{", "$", "scl", "=", "static", "::", "getByHandle", "(", "$", "row", "[", "'sclHandle'", "]", ")", ";", "$", "libraries", "[", "]", "=", "$", "scl", ";", "}", "return", "$", "libraries", ";", "}" ]
Retrieve all the installed libraries. @return static[]
[ "Retrieve", "all", "the", "installed", "libraries", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Captcha/Library.php#L196-L207
train
concrete5/concrete5
concrete/src/Captcha/Library.php
Library.getListByPackage
public static function getListByPackage($pkg) { if (is_object($pkg)) { $pkgID = $pkg->getPackageID(); } else { $pkgID = (int) $pkg; } $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $libraries = []; foreach ($db->fetchAll('select sclHandle from SystemCaptchaLibraries where pkgID = ? order by sclHandle asc', [$pkgID]) as $row) { $scl = static::getByHandle($row['sclHandle']); $libraries[] = $scl; } return $libraries; }
php
public static function getListByPackage($pkg) { if (is_object($pkg)) { $pkgID = $pkg->getPackageID(); } else { $pkgID = (int) $pkg; } $app = Facade::getFacadeApplication(); $db = $app->make('database')->connection(); $libraries = []; foreach ($db->fetchAll('select sclHandle from SystemCaptchaLibraries where pkgID = ? order by sclHandle asc', [$pkgID]) as $row) { $scl = static::getByHandle($row['sclHandle']); $libraries[] = $scl; } return $libraries; }
[ "public", "static", "function", "getListByPackage", "(", "$", "pkg", ")", "{", "if", "(", "is_object", "(", "$", "pkg", ")", ")", "{", "$", "pkgID", "=", "$", "pkg", "->", "getPackageID", "(", ")", ";", "}", "else", "{", "$", "pkgID", "=", "(", "int", ")", "$", "pkg", ";", "}", "$", "app", "=", "Facade", "::", "getFacadeApplication", "(", ")", ";", "$", "db", "=", "$", "app", "->", "make", "(", "'database'", ")", "->", "connection", "(", ")", ";", "$", "libraries", "=", "[", "]", ";", "foreach", "(", "$", "db", "->", "fetchAll", "(", "'select sclHandle from SystemCaptchaLibraries where pkgID = ? order by sclHandle asc'", ",", "[", "$", "pkgID", "]", ")", "as", "$", "row", ")", "{", "$", "scl", "=", "static", "::", "getByHandle", "(", "$", "row", "[", "'sclHandle'", "]", ")", ";", "$", "libraries", "[", "]", "=", "$", "scl", ";", "}", "return", "$", "libraries", ";", "}" ]
Retrieve the libraries installed by a package. @param \Concrete\Core\Entity\Package|int $pkg the package instance (or its ID) @return static[]
[ "Retrieve", "the", "libraries", "installed", "by", "a", "package", "." ]
c54c94e4eb6d45696fed85a5b8b415f70ea677b8
https://github.com/concrete5/concrete5/blob/c54c94e4eb6d45696fed85a5b8b415f70ea677b8/concrete/src/Captcha/Library.php#L216-L232
train