sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function _initTranslate()
{
$this->bootstrap('locale');
$language = $this->locale->getLanguage();
/*
* Scan for files with -<languagecode> and disable notices when the requested
* language is not found
*/
$options = array( 'adapter' => 'gettext',
'content' => GEMS_LIBRARY_DIR . '/languages/',
'disableNotices' => true,
'scan' => \Zend_Translate::LOCALE_FILENAME);
$translate = new \Zend_Translate($options);
// If we don't find the needed language, use a fake translator to disable notices
if (! $translate->isAvailable($language)) {
$translate = \MUtil_Translate_Adapter_Potemkin::create();
}
//Now if we have a project specific language file, add it
$projectLanguageDir = APPLICATION_PATH . '/languages/';
if (file_exists($projectLanguageDir)) {
$options['content'] = $projectLanguageDir;
$options['disableNotices'] = true;
$projectTranslations = new \Zend_Translate($options);
//But only when it has the requested language
if ($projectTranslations->isAvailable($language)) {
$translate->addTranslation(array('content' => $projectTranslations));
}
unset($projectTranslations); //Save some memory
}
$translate->setLocale($language);
\Zend_Registry::set('Zend_Translate', $translate);
// Fix for _init resource being case insensitive
$container = $this->getContainer();
$adapter = $translate->getAdapter();
$container->translateAdapter = $adapter;
$this->translateAdapter = $adapter;
return $translate;
} | Initialize the translate component.
Scans the application and project dirs for available translations
Use $this->translate to access afterwards
Also sets $this->translateAdapter to access afterwards
@return \Zend_Translate | entailment |
protected function _initView()
{
$this->bootstrap('project');
// Initialize view
$view = new \Zend_View();
$view->addHelperPath('MUtil/View/Helper', 'MUtil_View_Helper');
$view->addHelperPath('MUtil/Less/View/Helper', 'MUtil_Less_View_Helper');
$view->addHelperPath('Gems/View/Helper', 'Gems_View_Helper');
$view->addScriptPath(GEMS_LIBRARY_DIR . '/views/scripts');
$view->headTitle($this->project->getName());
$view->setEncoding('UTF-8');
$metas = $this->project->getMetaHeaders();
$headMeta = $view->headMeta();
foreach ($metas as $httpEquiv => $content) {
$headMeta->appendHttpEquiv($httpEquiv, $content);
}
if ($this->useHtml5) {
$view->doctype(\Zend_View_Helper_Doctype::HTML5);
} else {
$view->doctype(\Zend_View_Helper_Doctype::XHTML1_STRICT);
}
// Add it to the ViewRenderer
$viewRenderer = \Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($view);
// Return it, so that it can be stored by the bootstrap
return $view;
} | Initialize the view component and sets some project specific values.
Actions taken here can take advantage that the full framework has
been activated by now, including session data, etc.
Use $this->view to access afterwards
@return \Zend_View | entailment |
protected function _initCurrentUser()
{
$this->bootstrap(array('acl', 'basepath', 'cache', 'db', 'loader', 'project', 'session', 'translate', 'util'));
// Fix for _init resourcea being case insensitive
$container = $this->getContainer();
$user = $this->loader->getCurrentUser();
$container->currentUser = $user;
return $user;
} | Initialize the currentUser component.
You can overrule this function to specify your own project translation method / file.
Use $this->currentUser to access afterwards
@return \Gems_User_User | entailment |
protected function _initZFDebug()
{
if ((APPLICATION_ENV === 'production') || (APPLICATION_ENV === 'acceptance') || Zend_Session::$_unitTestEnabled ) {
// Never on on production systems
return;
}
$debug = $this->getOption('zfdebug');
if (! isset($debug['activate']) || ('1' !== $debug['activate'])) {
// Only turn on when activated
return;
}
# Instantiate the database adapter and cache
$this->bootstrap('db');
$db = $this->getPluginResource('db');
$this->bootstrap('cache');
$cache = $this->cache;
$options = array(
'plugins' => array('Variables',
'Database' => array('adapter' => $db->getDbAdapter()),
'File' => array('basePath' => GEMS_ROOT_DIR),
'Cache' => array('backend' => $cache->getBackend()),
'Exception')
);
$debugPlugin = new \ZFDebug_Controller_Plugin_Debug($options);
$this->bootstrap('frontController');
$frontController = $this->getResource('frontController');
$frontController->registerPlugin($debugPlugin);
} | Add ZFDebug info to the page output.
@return void | entailment |
protected function _layoutContact(array $args = null)
{
if ($this->menu instanceof \Gems_Menu) {
$menuItem = $this->menu->find(array('controller' => 'contact', 'action' => 'index'));
if ($menuItem) {
$contactDiv = \MUtil_Html::create()->div(
$args,
array('id' => 'contact')
); // tooltip
$contactDiv->a($menuItem->toHRefAttribute(), $menuItem->get('label'));
// List may be empty
if ($ul = $menuItem->toUl()) {
$ul->class = 'dropdownContent tooltip';
$contactDiv->append($ul);
}
return $contactDiv;
}
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutCrumbs(array $args = null)
{
// Must be called after _layoutNavigation()
if ($this->menu && $this->menu->isVisible()) {
$path = $this->menu->getActivePath($this->request);
$last = array_pop($path);
// Only display when there is a path of more than one step or always is on
if ($path || (isset($args['always']) && $args['always'])) {
// Never needed from now on
unset($args['always']);
if (isset($args['tag'])) {
$tag = $args['tag'];
unset($args['tag']);
} else {
$tag = 'div';
}
$source = array($this->menu->getParameterSource(), $this->request);
if ($this->useBootstrap && !isset($args['tag'])) {
$div = \MUtil_Html::create('ol', $args + array('id' => 'crumbs', 'class' => 'breadcrumb'));
foreach ($path as $menuItem) {
$div->li()->a($menuItem->toHRefAttribute($source), $menuItem->get('label'));
}
if ($last) {
$div->li(array('class' => 'active'))->append($last->get('label'));
}
} else {
$div = \MUtil_Html::create($tag, $args + array('id' => 'crumbs'));
$content = $div->seq();
$content->setGlue(\MUtil_Html::raw($this->_(' > ')));
// Add request to existing menu parameter sources
foreach ($path as $menuItem) {
$content->a($menuItem->toHRefAttribute($source), $menuItem->get('label'));
}
if ($last) {
$content->append($last->get('label'));
}
}
return $div;
}
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutCss()
{
// Set CSS stylescheet(s)
$projectCss = isset($this->project->css) ? (array) $this->project->css : [];
$projectCss = array_reverse($projectCss);
foreach ($projectCss as $css) {
if (is_array($css)) {
$media = $css['media'];
$url = $css['url'];
} else {
$url = $css;
$media = 'all';
}
// When exporting to pdf, we need full urls
if (substr($url,0,4) == 'http') {
$this->view->headLink()->prependStylesheet($url, $media);
} else {
$this->view->headLink()->prependStylesheet($this->view->serverUrl() . $this->basepath->getBasePath() . '/' . $url, $media);
}
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutFavicon()
{
// FAVICON
$icon = isset($this->project->favicon) ? $this->project->favicon : 'favicon.ico';
if (file_exists(GEMS_WEB_DIR . '/' . $icon)) {
$this->view->headLink(
array(
'rel' => 'shortcut icon',
'href' => $this->basepath->getBasePath() . '/' . $icon,
'type' => 'image/x-icon'
),
\Zend_View_Helper_Placeholder_Container_Abstract::PREPEND
);
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutGroupSwitcher(array $args = null)
{
if ($this->currentUser->isActive() && $this->currentUser->hasPrivilege('pr.group.switch', false)) {
$groups = $this->currentUser->getAllowedStaffGroups(false);
if (count($groups) > 1) {
// Group switcher
return $this->getUiSwitcher($groups, $this->currentUser->getGroupId(), 'groups', 'group', 'group', $args);
}
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutJQuery()
{
// JQUERY
if (\MUtil_JQuery::usesJQuery($this->view)) {
$jquery = $this->view->jQuery();
$jquery->uiEnable(); // enable user interface
$jqueryCss = isset($this->project->jquerycss) ? (array) $this->project->jquerycss : [];
foreach ($jqueryCss as $css) {
$jquery->addStylesheet($this->basepath->getBasePath() . '/' . $css);
}
return true;
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutLocaleSet(array $args = null)
{
// LOCALE
$currentUri = base64_encode($this->view->url());
$localeDiv = \MUtil_Html::create('div', $args, array('id' => 'languages'));
// There will always be a localeDiv, but it can be empty
if (isset($this->project->locales)) {
foreach ($this->project->locales as $locale) {
if ($locale == $this->view->locale) {
$localeDiv->span(strtoupper($locale), array('class' => 'language ' . $locale));
} else {
$localeDiv->a(
array(
'controller' => 'language',
'action' => 'change-ui',
'language' => urlencode($locale),
'current_uri' => $currentUri,
'class' => ''
),
strtoupper($locale),
array(
'class' => 'language ' . $locale,
'rel' => 'nofollow'
)
);
}
$localeDiv[] = ' ';
}
}
return $localeDiv;
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutLogin(array $args = null)
{
// During error reporting the user or menu are not always known.
if ($this->currentUser && $this->menu) {
$div = \MUtil_Html::create('div', array('id' => 'login'), $args);
$p = $div->p();
if ($this->currentUser->isActive()) {
$p->append(sprintf($this->_('You are logged in as %s'), $this->currentUser->getFullName()));
$item = $this->menu->findController('index', 'logoff');
$p->a($item->toHRefAttribute(), $this->_('Logoff'), array('class' => 'logout'));
$item->set('visible', false);
} else {
$item = $this->menu->findController('index', 'login');
$p->a($item->toHRefAttribute(), $this->_('You are not logged in'), array('class' => 'logout'));
}
return $div;
}
} | Display either a link to the login screen or displays the name of the current user
and a logoff link.
Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutMenuHtml()
{
// ACL && Menu
if ($this->menu && $this->menu->isVisible()) {
// Make sure the actual $request and $controller in use at the end
// of the dispatchloop is used and make \Zend_Navigation object
return $this->menu->render($this->view);
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutNavigation()
{
// ACL && Menu
if ($this->menu && $this->menu->isVisible()) {
// Make sure the actual $request and $controller in use at the end
// of the dispatchloop is used and make \Zend_Navigation object
$nav = $this->menu->toZendNavigation($this->request, $this->controller);
// Set the navigation object
\Zend_Registry::set('Zend_Navigation', $nav);
$zendNav = $this->view->navigation();
// $zendNav->setAcl($this->acl); // Not needed with \Gems_Menu
// $zendNav->setRole($this->session->user_role); // is set to nologin when no user
$zendNav->setUseTranslator(false);
// Other options
// $zendNav->breadcrumbs()->setLinkLast(true);
// $zendNav->breadcrumbs()->setMaxDepth(1);
// $zendNav->menu()->setOnlyActiveBranch(true);
return true;
}
return false;
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutOrganizationSwitcher(array $args = null)
{
if ($this->currentUser->isActive() && ($orgs = $this->currentUser->getAllowedOrganizations())) {
if (count($orgs) > 1) {
// Organization switcher
return $this->getUiSwitcher($orgs, $this->currentUser->getCurrentOrganizationId(), 'organizations', 'org', 'organization', $args);
}
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutProjectName(array $args = null)
{
if (isset($args['tagName'])) {
$tagName = $args['tagName'];
unset($args['tagName']);
} else {
$tagName = 'h1';
}
return \MUtil_Html::create($tagName, $this->project->name, $args);
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutTitle(array $args = null)
{
if (is_array($args) && array_key_exists('separator', $args)) {
$separator = $args['separator'];
} else {
$separator = ' - ';
}
if ($this->controller instanceof \MUtil_Controller_Action) {
if ($title = $this->controller->getTitle($separator)) {
$this->view->headTitle($separator . $title);
}
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutUser(array $args = null)
{
if ($this->currentUser->isActive()) {
return \MUtil_Html::create()->div(
sprintf($this->_('User: %s'), $this->currentUser->getFullName()),
$args,
array('id' => 'username')
);
}
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _layoutVersion(array $args = null)
{
$div = \MUtil_Html::create()->div($args, array('id' => 'version'));
if ($this->currentUser->isActive()) {
$version = $this->loader->getVersions()->getVersion();
} else {
$version = $this->loader->getVersions()->getMainVersion();
}
if (($this->menu instanceof \Gems_Menu) &&
($item = $this->menu->findController('project-information', 'changelog')->toHRefAttribute())) {
$link = \MUtil_Html::create()->a($version, $item);
} else {
$link = $version;
}
$this->view->currentVersion = $this->loader->getVersions()->getProjectVersion();
$div->spaced($this->project->description, $this->translateAdapter->_('version'), $link);
return $div;
} | Function called if specified in the Project.ini layoutPrepare section before
the layout is drawn, but after the rest of the program has run it's course.
@return mixed If null nothing is set, otherwise the name of
the function is used as \Zend_View variable name. | entailment |
protected function _updateVariable($name)
{
if (!$this->_copyDestinations) {
return;
}
$names = (array) $name;
foreach ($this->_copyDestinations as $object) {
foreach ($names as $key) {
$object->$key = $this->_container->$key;
}
}
} | Function to maintain uniformity of access to variables from the bootstrap object.
Updates selected variable(s) to the objects targeted in _copyVariables.
Do this when an object is created or when a non-object variable has changed.
You do not need to call this method for changes to objects .
@param String|Array $name A property name or array of property names to copy from this
object to the previous copy targets.
@return void | entailment |
public function addMessage()
{
$messages = \MUtil_Ra::flatten(func_get_args());
$messenger = $this->getMessenger();
foreach ($messages as $message) {
$messenger->addMessage($message);
}
return $this;
} | Adds one or more messages to the session based message store.
@param mixed ...$messages Can be an array or multiple argements. Each sub element is a single message string
@return \MUtil_Controller_Action | entailment |
public function controllerBeforeAction(\Zend_Controller_Action $actionController = null)
{
// Test for Zend_Session::$_unitTestEnabled: db is not yet loaded in tests
if (method_exists($actionController, 'getRespondent') && (!\Zend_Session::$_unitTestEnabled)) {
$this->accesslog->logRequest($this->request, array(), null, $actionController->getRespondent());
} else {
$this->accesslog->logRequest($this->request, array());
}
} | Hook 10: Called before the $controller->preDispatch() and $controller->{name}Action
methods have been called.
Here you can change or check all values set in $controller->init(). All output echoed
here is captured for the output.
Previous hook: controllerInit()
Actions since: $controller->init(); ob_start(); $controller->dispatch()
Actions after: $controller->preDispatch(); $controller->{name}Action(); $controller->postDispatch()
Next hook: controllerAfterAction()
@param \Zend_Controller_Action $actionController
@return void | entailment |
public function controllerInit(\Zend_Controller_Action $actionController = null)
{
$this->_copyVariables($actionController ? $actionController : $this->controllerAfterAction);
$this->prepareController();
$imgUrl = $this->getUtil()->getImageUri('datepicker.png');
$jstUrl = $this->basepath->getBasePath() . '/gems/js';
// Now set some defaults
$dateFormOptions['dateFormat'] = 'dd-MM-yyyy';
$dateFormOptions['description'] = $this->_('dd-mm-yyyy');
$dateFormOptions['size'] = 10;
if ($this->useBootstrap == true) {
// Do not use a buttonImage, since we will use bootstrap add-on
$basicOptions = array();
} else {
$basicOptions = array(
'buttonImage' => $imgUrl,
'showOn' => 'button'
);
}
$dateFormOptions['jQueryParams'] = $basicOptions + array(
'changeMonth' => true,
'changeYear' => true,
'duration' => 'fast',
);
$datetimeFormOptions['dateFormat'] = 'dd-MM-yyyy HH:mm';
$datetimeFormOptions['description'] = $this->_('dd-mm-yyyy hh:mm');
$datetimeFormOptions['size'] = 16;
$datetimeFormOptions['jQueryParams'] = $basicOptions + array(
'changeMonth' => true,
'changeYear' => true,
'duration' => 'fast',
'stepMinute' => 5,
'size' => 8,
'timeJsUrl' => $jstUrl,
);
$timeFormOptions['dateFormat'] = 'HH:mm';
$timeFormOptions['description'] = $this->_('hh:mm');
$timeFormOptions['jQueryParams'] = $basicOptions + array(
'duration' => 'fast',
'stepMinute' => 5,
'size' => 8,
'timeJsUrl' => $jstUrl,
);
\MUtil_Model_Bridge_FormBridge::setFixedOptions(array(
'date' => $dateFormOptions,
'datetime' => $datetimeFormOptions,
'time' => $timeFormOptions,
));
} | Hook 9: During action controller initialization.
This hook is called in the constructor of the controller. Nothing is done and
$controller->init has not been called, so this is a good moment to change settings
that should influence $controller->init().
Previous hook: preDispatch()
Actions since: $dispatcher->dispatch(); $controller->__construct()
Actions after: $controller->init(); ob_start(); $controller->dispatch()
Next hook: controllerBeforeAction()
@param \Zend_Controller_Action $actionController
@return void | entailment |
protected function createProjectClass($className)
{
$arguments = func_get_args();
array_shift($arguments);
return $this->_projectLoader->createClass($className, $arguments);
} | Creates an object of the specified className seareching the loader dirs path
@param string $className
@param mixed ...$arguments Optional parameters
@return object | entailment |
public function dispatchLoopStartup(\Zend_Controller_Request_Abstract $request)
{
// Check the installation
if (! isset($this->db)) {
$this->setException(new \Gems_Exception_Coding(
'No database registered in ' . GEMS_PROJECT_NAME . 'Application.ini for key resources.db.')
);
}
if (($request instanceof \Zend_Controller_Request_Http) && $request->isPost()) {
$posts = $request->getPost();
} else {
$posts = [];
}
$this->_checkParameters($request->getParams(), $posts);
// Empty params are filtered from request, only saved when using special router
$router = Zend_Controller_Front::getInstance()->getRouter();
if ($router instanceof Rewrite) {
$this->_checkParameters($router->getAllParams(), $posts);
}
} | Hook 7: Called before \Zend_Controller_Front enters its dispatch loop.
This events enables you to adjust the request after the routing has been done.
This is the final hook before the dispatchLoop starts. All the hooks in the dispatchLoop
can be executed more then once.
Not yet initialized is the $controller object - as the $controller can change during
the dispatchLoop.
Previous hook: routeShutdown()
Actions since: nothing, but the route consisting of controller, action and module should now be fixed
Actions after: dispatch loop started
Next hook: preDispatch()
@param \Zend_Controller_Request_Abstract $request
@return void | entailment |
public function getDatabasePaths()
{
$path = APPLICATION_PATH . '/configs/db';
if (file_exists($path)) {
$paths[] = array(
'path' => $path,
'name' => GEMS_PROJECT_NAME,
'db' => $this->db,
);
}
$path = GEMS_LIBRARY_DIR . '/configs/db';
if (file_exists($path)) {
$paths[] = array(
'path' => $path,
'name' => 'gems',
'db' => $this->db,
);
}
if ($this->project->hasResponseDatabase()) {
$path = GEMS_LIBRARY_DIR . '/configs/db_response_data';
if (file_exists($path)) {
$paths[] = array(
'path' => $path,
'name' => 'gemsdata',
'db' => $this->project->getResponseDatabase(),
);
}
}
return $paths;
} | Return the directories where the Database Administrator Model (DbaModel)
should look for sql creation files.
@return array Of index => array('path' =>, 'name' =>, 'db' =>,) | entailment |
public function getMessenger()
{
if (! isset($this->view->messenger)) {
$this->view->messenger = $this->loader->getMessenger();
}
return $this->view->messenger;
} | Retrieves / sets the messenger
@return \Zend_Controller_Action_Helper_FlashMessenger | entailment |
public function hasPrivilege($privilege, $role = null)
{
if (is_null($role)) $role = $this->session->user_role;
return (! $this->acl) || $this->acl->isAllowed($role, null, $privilege);
} | Returns true if the given role or role of the current user has the given privilege
@param string $privilege
@param string $role
@return bool
@deprecated Since 1.7.2 Replaced by $this->currentUser->hasPrivilege(); | entailment |
protected function includeFile($fileName)
{
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
if (! $extension) {
$extension = $this->findExtension($fileName, array('inc', 'ini', 'php', 'xml'));
$fileName .= '.' . $extension;
}
if (file_exists($fileName)) {
switch ($extension) {
case 'ini':
$config = new \Zend_Config_Ini($fileName, APPLICATION_ENV);
break;
case 'xml':
$config = new \Zend_Config_Xml($fileName, APPLICATION_ENV);
break;
case 'php':
case 'inc':
// Exclude all variables not needed
unset($extension);
// All variables from this Escort file can be changed in the include file.
return include($fileName);
break;
default:
throw new \Zend_Application_Exception(
'Invalid configuration file provided; unknown config type ' . $extension
);
}
return $config->toArray();
}
// If the file does not exists it is up to the calling function to do something about it.
return false;
} | Searches and loads ini, xml, php or inc file
When no extension is specified the system looks for a file with the right extension,
in the order: .ini, .php, .xml, .inc.
.php and .inc files run within the context of this object and thus can access all
$this-> variables and functions.
@param string $fileName A filename in the include path
@return mixed false if nothing was returned | entailment |
public function isAllowedHost($fullHost)
{
$host = \MUtil_String::stripToHost($fullHost);
$request = $this->request;
if ($request instanceof \Zend_Controller_Request_Http) {
if ($host == \MUtil_String::stripToHost($request->getServer('HTTP_HOST'))) {
return true;
}
}
if (isset($this->project)) {
foreach ($this->project->getAllowedHosts() as $allowedHost) {
if ($host == \MUtil_String::stripToHost($allowedHost)) {
return true;
}
}
}
$loader = $this->getLoader();
foreach ($loader->getUserLoader()->getOrganizationUrls() as $url => $orgId) {
if ($host == \MUtil_String::stripToHost($url)) {
return true;
}
}
return false;
} | Is the host name one allowed by the system
@param string $fullHost
@return boolean | entailment |
public function passwordHash($value, $isNew = false, $name = null, array $context = array())
{
return $this->project->getValueHash($value);
} | Return a hashed version of the input value.
@deprecated Since 1.5
@param string $value The value to hash.
@param boolean $new Optional is new, is here for ModelAbstract setOnSave compatibility
@param string $name Optional name, is here for ModelAbstract setOnSave compatibility
@param array $context Optional, the other values being saved
@return string The salted hash as a 32-character hexadecimal number. | entailment |
public function getRandomPassword()
{
$salt = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789";
$pass = "";
srand((double)microtime()*1000000);
$i = 0;
while ($i <= 7)
{
$num = rand() % strlen($salt);
$tmp = substr($salt, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
} | Generate random password
@return string | entailment |
public function postDispatch(\Zend_Controller_Request_Abstract $request)
{
if ($request->isDispatched()) {
$headers = $this->project->getResponseHeaders();
foreach ($headers as $name => $value) {
$this->response->setHeader($name, $value, true);
}
// Only when we need to render the layout, we run the layout prepare
if (\Zend_Controller_Action_HelperBroker::hasHelper('layout') &&
\Zend_Controller_Action_HelperBroker::getExistingHelper('layout')->isEnabled()) {
// Per project layout preparation
$layoutFuncs = isset($this->project->layoutPrepare) ? $this->project->layoutPrepare : [];
$layoutArgs = isset($this->project->layoutPrepareArgs) ? $this->project->layoutPrepareArgs : [];
$this->prepareLayout($layoutFuncs, $layoutArgs);
}
// For AJAX calls we sometimes need to add JQuery onload scripts since otherwise they won't get rendered:
// We expect JQuery to be loaded in the master page, since the call is probably made using JQuery
if ($request instanceof \Zend_Controller_Request_Http && $request->isXmlHttpRequest()) {
\MUtil_JQuery::enableView($this->view);
$scripts = $this->view->jQuery()->getOnLoadActions();
$content = '';
foreach($scripts as $script) {
$content .= "<script type='text/javascript'>$script</script>\n";
}
$content .= $this->view->inlineScript();
// Now cleanup the rendered content (just to make sure)
$this->view->jQuery()->clearOnLoadActions();
$this->view->inlineScript()->exchangeArray(array());
if (!empty($content)) {
$this->response->appendBody($content);
}
}
}
} | Hook 12: Called after an action is dispatched by \Zend_Controller_Dispatcher.
This callback allows for proxy or filter behavior. By altering the
request and resetting its dispatched flag (via {@link
\Zend_Controller_Request_Abstract::setDispatched() setDispatched(false)}),
a new action may be specified for dispatching.
\Zend_Layout_Controller_Plugin_Layout uses this event to change the output
of the $response with the rendering of the layout. As the Layout plugin
has a priority of 99, this Escort event will take place before the layout
is rendered, unless $this->run() was called with a stackIndex lower than zero.
Previous hook: controllerAfterAction()
Actions since: ob_get_clean(); $response->appendBody()
Actions after: while (! Request->isDispatched()) or back to Hook 8 preDispatch()
Next hook: dispatchLoopShutdown()
@param \Zend_Controller_Request_Abstract $request
@return void | entailment |
public function preDispatch(\Zend_Controller_Request_Abstract $request)
{
if ($request instanceof \Zend_Controller_Request_Http && $request->isXmlHttpRequest()) {
$mvc = \Zend_Layout::getMvcInstance();
if ($mvc instanceof \Zend_Layout) {
$mvc->disableLayout();
}
}
$staticSession = $this->getStaticSession();
if ($this->session->user_id && $previousRequestParameters = $staticSession->previousRequestParameters) {
unset($previousRequestParameters['save_button']);
unset($previousRequestParameters['userlogin']);
unset($previousRequestParameters['password']);
// fake POST
if ($staticSession->previousRequestMode == 'POST') {
$this->addMessage($this->_('Take note: your session has expired, your inputs were not saved. Please check the input data and try again'));
$_POST = $previousRequestParameters;
$_SERVER['REQUEST_METHOD'] = $staticSession->previousRequestMode;
$staticSession->previousRequestMode = null;
}
$staticSession->previousRequestParameters = null;
}
$this->setControllerDirectory($request);
} | Hook 8: Start of dispatchLoop. Called before an action is dispatched
by \Zend_Controller_Dispatcher.
This callback allows for proxy or filter behavior. By altering the request
and resetting its dispatched flag (via {@link \Zend_Controller_Request_Abstract::setDispatched()
setDispatched(false)}), the current action may be skipped.
Not yet initialized is the $controller object - as the $controller can change during
the dispatchLoop.
Previous hook: dispatchLoopStartup() or new loop
Actions since: dispatch loop started
Actions after: $dispatcher->dispatch(); $controller->__construct()
Next hook: controllerInit()
@param \Zend_Controller_Request_Abstract $request
@return void | entailment |
public function prepareController()
{
// Do the layout switch here, when view is set the layout can still be changed, but
// Bootstrap can no longer be switched on/off
if ($this instanceof \Gems_Project_Layout_MultiLayoutInterface) {
$this->layoutSwitch();
}
if ($this->useBootstrap) {
$bootstrap = \MUtil_Bootstrap::bootstrap(array('fontawesome' => true));
\MUtil_Bootstrap::enableView($this->view);
}
if (\MUtil_Console::isConsole()) {
/* @var $layout \Zend_Layout */
$layout = $this->view->layout();
$layout->setLayoutPath(GEMS_LIBRARY_DIR . "/layouts/scripts");
$layout->setLayout('cli');
}
} | Hook function called during controllerInit
return @void | entailment |
public function requestChanged(\Zend_Controller_Request_Abstract $request)
{
if ($this->project->isMultiLocale()) {
// Get the choosen language
$localeId = \Gems_Cookies::getLocale($request);
// Change when $localeId exists and is different from session
if ($localeId && ($this->locale->getLanguage() !== $localeId)) {
// \MUtil_Echo::r('On cookie ' . $localeId . ' <> ' . $this->locale->getLanguage());
// Does the locale exist?
if (isset($this->project->locales[$localeId])) {
// Add and implement the choosen locale
$this->session->user_locale = $localeId;
$this->locale->setLocale($localeId);
if (! $this->translate->isAvailable($localeId)) {
$languageFilename = APPLICATION_PATH . '/languages/default-' . $localeId . '.mo';
if (file_exists($languageFilename)) {
$this->translate->addTranslation($languageFilename, $localeId);
}
}
$this->translate->setLocale($localeId);
$this->translateAdapter = $this->translate->getAdapter();
}
}
}
// Set the base path, the route is now fixed
$this->basepath->setBasePath($request->getBasePath());
// Set the jQuery version and other information needed
// by classes using jQuery
$jquery = \MUtil_JQuery::jQuery();
$jqueryVersion = '1.11.1';
$jqueryUiVersion = '1.11.1';
$jquery->setVersion($jqueryVersion);
$jquery->setUiVersion($jqueryUiVersion);
if ($this->project->isJQueryLocal()) {
$jqueryDir = $request->getBasePath() . $this->project->getJQueryLocal();
$jquery->setLocalPath($jqueryDir . 'jquery-' . $jqueryVersion . '.js');
$jquery->setUiLocalPath($jqueryDir . 'jquery-ui-' . $jqueryUiVersion . '.js');
} else {
if (\MUtil_Https::on()) {
$jquery->setCdnSsl(true);
}
}
if (\MUtil_Bootstrap::enabled() && $this->project->isBootstrapLocal()) {
$bootstrap = \MUtil_Bootstrap::bootstrap();
$basePath = $request->getBasePath();
$bootstrap->setBootstrapScriptPath($basePath.'/bootstrap/js/bootstrap.min.js');
$bootstrap->setBootstrapStylePath($basePath.'/bootstrap/css/bootstrap.min.css');
$bootstrap->setFontAwesomeStylePath($basePath.'/bootstrap/css/font-awesome.min.css');
}
} | Hook 3: Called in $this->setRequest.
All resources have been loaded and the $request object is created.
Theoretically this event can be triggered multiple times, but this does
not happen in a standard Zend application.
Not initialized are the $response and $controller objects.
Previous hook: beforeRun()
Actions since: $this->request object created
Actions after: $this->response object created
Next hook: responseChanged()
@param \Zend_Controller_Request_Abstract $request
@return void | entailment |
public function routeShutdown(\Zend_Controller_Request_Abstract $request)
{
$loader = $this->getLoader();
// Load the menu. As building the menu can depend on all resources and the request, we do it here.
//
// PS: The REQUEST is needed because otherwise the locale for translate is not certain.
$menu = $loader->createMenu($this);
$source = $menu->getParameterSource();
$user = $this->_container->currentUser;
$user->setRequest($request);
$action = $request->getActionName();
$controller = $request->getControllerName();
$organization = $user->getCurrentOrganization();
$organization->applyToMenuSource($source);
$this->_container->currentOrganization = $organization;
$this->_container->menu = $menu;
$this->_updateVariable(array('currentOrganization', 'menu'));
// Now is a good time to check for required values
// Moved down here to prevent unit test from failing on missing salt
$this->project->checkRequiredValues();
/**
* Check if we are in maintenance mode or not. This is triggeren by a file in the var/settings
* directory with the name lock.txt
*/
if ($this->getUtil()->getMaintenanceLock()->isLocked()) {
if ($user->hasPrivilege('pr.maintenance.maintenance-mode', false)) {
\MUtil_Echo::r($this->_('System is in maintenance mode'));
} elseif (! (isset($this->maintenanceAccessiblePages[$controller]) &&
is_array($this->maintenanceAccessiblePages[$controller]) &&
in_array($action, $this->maintenanceAccessiblePages[$controller]))) {
$this->addMessage($this->_('The page you requested is currently inaccessible.'));
$this->setError($this->_('Please check back later.'), 401);
$user->unsetAsCurrentUser();
}
$this->addMessage($this->_('System is in maintenance mode'));
}
// Gems does not use index/index
if (('index' == $controller) &&
(('index' == $action) || ($user->isActive() && ('login' == $action)))) {
// Instead Gems routes to the first available menu item when this is the request target
if (! $user->gotoStartPage($menu, $request)) {
$this->setError(
$this->_('No access to site.'),
401,
$this->_('You have no access to this site.'),
true);
return;
}
} else {
//find first allowed item in the menu
$menuItem = $menu->find(['action' => $action, 'controller' => $controller]);
// Display error when not having the right priviliges
if (! ($menuItem && $menuItem->get('allowed'))) {
// When logged in
if ($user->getUserId()) {
$this->setError(
$this->_('No access to page'),
403,
sprintf($this->_('Access to the %s/%s page is not allowed for your current group: %s.'),
$controller,
$action,
$user->getGroup()->getName()),
true);
} else { // No longer logged in
if (\MUtil_Console::isConsole()) {
$this->setError(
'No access to page.',
401,
sprintf('Controller "%s" action "%s" is not accessible.', $controller, $action),
true);
return;
}
if ($action == 'autofilter') {
// Throw an exception + HTTP 401 when an autofilter is called
throw new \Gems_Exception("Session expired", 401);
}
$menuItem = $menu->findFirst(['allowed' => true, 'visible' => true]);
if ($menuItem) {
// Do not store previous request & show message when the intended action is logoff
if (! ($controller == 'index' && $action == 'logoff')) {
$this->addMessage($this->_('You are no longer logged in.'));
$this->addMessage($this->_('You must login to access this page.'));
if (! \MUtil_String::contains($controller . $action, '.')) {
// save original request, we will redirect back once the user succesfully logs in
$staticSession = $this->getStaticSession();
$staticSession->previousRequestParameters = $request->getParams();
$staticSession->previousRequestMode = ($request->isPost() ? "POST" : "GET");
}
}
$redirector = \Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->gotoRoute($menuItem->toRouteUrl($request));
} else {
$this->setError(
$this->_('You are no longer logged in.'),
401,
$this->_('You have no access to this site.'),
true);
return;
}
}
}
}
if (isset($menuItem)) {
$menuItem->applyHiddenParameters($request, $source);
$menu->setCurrent($menuItem);
}
if ($request instanceof \Zend_Controller_Request_Http) {
if ($request->isPost()) {
$incoming = $request->getServer('HTTP_ORIGIN', $request->getServer('HTTP_REFERER', false));
if ($incoming) {
if (! $this->isAllowedHost($incoming)) {
throw new \Gems_Exception(
sprintf("Invalid source host, possible CSRF attack. Used host: %s", $incoming),
403
);
}
}
}
}
} | Hook 6: Called after \Zend_Controller_Router has determined the route set by the request.
This events enables you to adjust the route after the routing has run it's course.
Not initialized is the $controller object.
Previous hook: routeStartup()
Actions since: $router->route()
Actions after: nothing, but the route consisting of controller, action and module should now be fixed
Next hook: dispatchLoopStartup()
Also sets $this->currentOrganization and $this->menu to access afterwards
@param \Zend_Controller_Request_Abstract $request
@return void | entailment |
public function setError($message, $code = 200, $info = null, $isSecurity = false)
{
if ($isSecurity) {
$e = new \Gems_Exception_Security($message, $code, null, $info);
} else {
$e = new \Gems_Exception($message, $code, null, $info);
}
$this->setException($e);
} | Create an exception for the error, depending on processing position we either
set the response exception or throw the exception if the response is
@param string $message
@param int $code
@param string $info
@param boolean $isSecurity
@throws exception | entailment |
public function setException(exception $e)
{
if (isset($this->response)) {
$this->response->setException($e);
} else {
throw $e;
}
} | Handle the exception depending on processing position we either
set the response exception or throw the exception if the response is
@param exception $e
@throws exception | entailment |
public function processTokenData(\Gems_Tracker_Token $token)
{
$tokenAnswers = $token->getRawAnswers();
if (isset($tokenAnswers['LENGTH'], $tokenAnswers['WEIGHT']) && $tokenAnswers['LENGTH'] && $tokenAnswers['WEIGHT']) {
$length = $tokenAnswers['LENGTH'] / 100;
$newValue = round($tokenAnswers['WEIGHT'] / ($length * $length), 2);
if ($newValue !== $tokenAnswers['BMI']) {
return array('BMI' => $newValue);
}
}
return false;
} | Process the data and return the answers that should be changed.
Storing the changed values is handled by the calling function.
@param \Gems_Tracker_Token $token Gems token object
@return array Containing the changed values | entailment |
protected function _getOrganizationsList()
{
$html = new \MUtil_Html_Sequence();
$sql = '
SELECT *
FROM gems__organizations
WHERE gor_active=1 AND gor_url IS NOT NULL AND gor_task IS NOT NULL
ORDER BY gor_name';
// $organizations = array();
// $organizations = array(key($organizations) => reset($organizations));
$organizations = $this->db->fetchAll($sql);
$orgCount = count($organizations);
switch ($orgCount) {
case 0:
return $html->pInfo(sprintf($this->_('%s is still under development.'), $this->project->getName()));
case 1:
$organization = reset($organizations);
$p = $html->pInfo(sprintf($this->_('%s is run by: '), $this->project->getName()));
$p->a($organization['gor_url'], $organization['gor_name']);
$p->append('.');
$html->pInfo()->sprintf(
$this->_('Please contact the %s if you have any questions regarding %s.'),
$organization['gor_name'],
$this->project->getName()
);
return $html;
default:
$p = $html->pInfo(sprintf(
$this->_('%s is a collaboration of these organizations:'),
$this->project->getName()
));
$data = \MUtil_Lazy::repeat($organizations);
$ul = $p->ul($data, array('class' => 'indent'));
$li = $ul->li();
$li->a($data->gor_url->call($this, '_'), $data->gor_name, array('rel' => 'external'));
$li->append(' (');
$li->append($data->gor_task->call(array($this, '_')));
$li->append(')');
$html->pInfo()->sprintf(
$this->_('You can contact any of these organizations if you have questions regarding %s.'),
$this->project->getName()
);
return $html;
}
} | A list of all participating organizations.
@return \MUtil_Html_HtmlElement | entailment |
public function aboutAction()
{
$this->initHtml();
$this->html->h3()->sprintf($this->_('About %s'), $this->project->getName());
$this->html->pInfo(\MUtil_Html_Raw::raw($this->project->getLongDescription($this->locale->getLanguage())));
$this->html->append($this->_getOrganizationsList());
} | Shows an about page | entailment |
public function gemsAction()
{
$this->initHtml();
$this->html->h3()->sprintf($this->_('About %s'), $this->_('GemsTracker'));
$this->html->pInfo($this->_(
'GemsTracker (GEneric Medical Survey Tracker) is a software package for (complex) distribution of questionnaires and forms during clinical research and for quality registration in healthcare.'));
$this->html->pInfo()->sprintf(
$this->_('%s is a project built using GemsTracker as a foundation.'),
$this->project->getName());
$this->html->pInfo()->sprintf($this->_('GemsTracker is an open source project hosted on %s.'))
->a(
'https://github.com/GemsTracker/gemstracker-library',
'GitHub',
array('rel' => 'external', 'target' => 'sourceforge')
);
$this->html->pInfo()->sprintf($this->_('More information about GemsTracker is available on the %s website.'))
->a(
'http://gemstracker.org/',
'GemsTracker.org',
array('rel' => 'external', 'target' => 'gemstracker')
);
} | Show screen telling people about gems | entailment |
public function indexAction()
{
$this->initHtml();
$this->html->h3($this->_('Contact'));
$this->html->h4(sprintf($this->_('The %s project'), $this->project->getName()));
$this->html->append($this->_getOrganizationsList());
$this->html->h4($this->_('Information on this application'));
$this->html->pInfo($this->_('Links concerning this web application:'));
$menuItem = $this->menu->getCurrent();
$ul = $menuItem->toUl($this->getRequest());
$ul->class = 'indent';
$this->html[] = $ul;
} | General contact page | entailment |
public function supportAction()
{
$this->initHtml();
$this->html->h3($this->_('Support'));
$this->html->pInfo()->sprintf(
$this->_('There is more than one way to get support for %s.'),
$this->project->getName()
);
if ($url = $this->project->getDocumentationUrl()) {
$this->html->h4($this->_('Documentation'));
$this->html->pInfo()->sprintf($this->_('All available documentation is gathered at: %s'))
->a($url, array('rel' => 'external', 'target' => 'documentation'));
}
if ($url = $this->project->getManualUrl()) {
$this->html->h4($this->_('Manual'));
$this->html->pInfo()->sprintf($this->_('The manual is available here: %s'))
->a($url, array('rel' => 'external', 'target' => 'manual'));
}
if ($url = $this->project->getForumUrl()) {
$this->html->h4($this->_('The forum'));
$this->html->pInfo()->sprintf($this->_(
'You will find questions asked by other users and ask new questions at our forum site: %s'
))->a($url, array('rel' => 'external', 'target' => 'forum'));
}
if ($url = $this->project->getSupportUrl()) {
$this->html->h4($this->_('Support site'));
$this->html->pInfo()->sprintf($this->_('Check our support site at %s.'))
->a($url, array('rel' => 'external', 'target' => 'support'));
}
$this->html->h4($this->_('Or contact'));
$this->html->append($this->_getOrganizationsList());
} | Shows a support page | entailment |
public function isValid($value, $context = array())
{
if (parent::isValid($value, $context)) {
$value .= '/admin/lsrc.server.php';
if (parent::isValid($value, $context)) {
return true;
}
$this->_setValue($value);
$this->_messageTemplates[self::ERROR_NO_LS_SOAP] = 'No Lime Survey SOAP connection on URL.';
$this->_error(self::ERROR_NO_LS_SOAP);
}
return false;
} | Returns true if and only if $value meets the validation requirements
If $value fails validation, then this method returns false, and
getMessages() will return an array of messages that explain why the
validation failed.
@param mixed $value
@return boolean
@throws \Zend_Valid_Exception If validation of $value is impossible | entailment |
protected function getTabs()
{
$user = $this->loader->getCurrentUser();
$sql = "SELECT gr2o_id_organization, gr2o_patient_nr FROM gems__respondent2org WHERE gr2o_id_user = ?";
$this->defaultTab = $user->getCurrentOrganizationId();
$this->currentTab = $this->request->getParam(\MUtil_Model::REQUEST_ID2);
$allowedOrgs = $user->getRespondentOrganizations();
$existingOrgs = $this->db->fetchPairs($sql, $this->respondent->getId());
$tabs = array();
foreach ($allowedOrgs as $orgId => $name) {
if (isset($existingOrgs[$orgId])) {
$tabs[$orgId] = $name;
$this->hrefs[$orgId] = array(
\MUtil_Model::REQUEST_ID1 => $existingOrgs[$orgId],
\MUtil_Model::REQUEST_ID2 => $orgId,
'RouteReset' => true,
);
}
}
return $tabs;
} | Function used to fill the tab bar
@return array tabId => label | entailment |
public function render($content)
{
$form = $this->getElement();
$view = $form->getView();
/*
* Check if this is a form that should autosubmit. If so, add script to head and onload
*/
if ($form->isAutoSubmit()) {
$form->addScript($this->localScriptFiles);
//\ZendX_JQuery::enableForm($form);
$jquery = $view->jQuery();
$jquery->enable(); //Just to make sure
$params = $form->getAutoSubmit();
if (($view instanceof \Zend_View_Abstract) && ($params['submitUrl'] instanceof \MUtil_Html_HtmlInterface)) {
$params['submitUrl'] = $params['submitUrl']->render($view);
}
$js = sprintf(
'%s("#%s").%s(%s);',
\ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(),
$form->getId(),
$this->localScriptName,
\ZendX_JQuery::encodeJson($params)
);
$jquery->addOnLoad($js);
}
$scripts = $form->getScripts();
$css = $form->getCss();
if (!is_null($scripts) && is_array($scripts)) {
$baseUrl = $view->serverUrl() . $view->baseUrl();
$headscript = $view->headScript();
foreach ($scripts as $script) {
$headscript->appendFile($baseUrl . $script);
}
}
if (!is_null($css) && is_array($css)) {
$baseUrl = $view->serverUrl() . $view->baseUrl();
$headLink = $view->headLink();
foreach($css as $cssFile => $media) {
$headLink->appendStylesheet($baseUrl . $cssFile, $media);
}
}
$content = parent::render($content);
return $content;
} | Render a form
Replaces $content entirely from currently set element.
@param string $content
@return string | entailment |
public function checkHasRespondents($userId, $check = false)
{
$sql = "CASE
WHEN EXISTS (SELECT * FROM gems__respondent2org WHERE gr2o_id_organization = gor_id_organization)
THEN 1
ELSE 0
END";
$values['gor_has_respondents'] = new \Zend_Db_Expr($sql);
$values['gor_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
$values['gor_changed_by'] = $userId;
$where = $this->db->quoteInto('gor_id_organization = ?', $this->_id);
if ($this->db->update('gems__organizations', $values, $where)) {
$this->loadData($this->_id);
}
return $this;
} | Check whether the organization still has at least one respondent attached to it.
Does nothing if this is already known.
@param int $userId The current user
@return \Gems_User_Organization (continuation pattern) | entailment |
public function getAllowedUserClasses()
{
$output = $this->_allowedProjectUserClasses;
if (\Gems_User_UserLoader::USER_RADIUS !== $this->_get('gor_user_class')) {
unset($output[\Gems_User_UserLoader::USER_RADIUS]);
}
return $output;
} | Get the available user class for new users in this organization
@return array Of type class name => class label | entailment |
public function getMailFields()
{
$result['organization'] = $this->getName();
$result['organization_location'] = $this->_get('gor_location');
$result['organization_login_url'] = $this->getLoginUrl();
$result['organization_reply_name'] = $this->_get('gor_contact_name');
$result['organization_reply_to'] = $this->_get('gor_contact_email');
$result['organization_signature'] = $this->getSignature();
$result['organization_url'] = $this->_get('gor_url');
$result['organization_welcome'] = $this->getWelcome();
if ((APPLICATION_ENV === 'production') &&
preg_match('#^http(s)?://localhost#', $result['organization_login_url'])) {
throw new \Gems_Exception("Use of 'localhost' as url not permitted on production system.");
}
return $result;
} | Array of field name => values for sending E-Mail
@return array | entailment |
protected function loadData($id)
{
if (\Gems_User_UserLoader::SYSTEM_NO_ORG === $id) {
$data = false;
} else {
try {
$sql = "SELECT * FROM gems__organizations WHERE gor_id_organization = ? LIMIT 1";
$data = $this->db->fetchRow($sql, intval($id));
} catch (\Exception $e) {
$data = false;
}
}
if ($data) {
try {
$dbOrgId = $this->db->quote($id, \Zend_Db::INT_TYPE);
$sql = "SELECT gor_id_organization, gor_name
FROM gems__organizations
WHERE gor_active = 1 AND
(
gor_id_organization = $dbOrgId OR
gor_accessible_by LIKE '%:$dbOrgId:%'
)
ORDER BY gor_name";
$data['can_access'] = $this->db->fetchPairs($sql);
natsort($data['can_access']);
} catch (\Exception $e) {
$data['can_access'] = array();
}
// \MUtil_Echo::track($sql, $data['can_access']);
if (array_key_exists('gor_url_base', $data) && $baseUrls = explode(' ', $data['gor_url_base'])) {
$data['base_url'] = reset($baseUrls);
}
} else {
$data = $this->_noOrganization;
$data['gor_id_organization'] = $id;
}
return $data;
} | Load the data when the cache is empty.
@param mixed $id
@return array The array of data values | entailment |
public function setAsCurrentOrganization()
{
$organizationId = $this->getId();
if ($organizationId && (! \Gems_Cookies::setOrganization($organizationId, $this->basepath->getBasePath()))) {
throw new \Exception('Cookies must be enabled for this site.');
}
$escort = \GemsEscort::getInstance();
if ($escort instanceof \Gems_Project_Layout_MultiLayoutInterface) {
$escort->layoutSwitch($this->getStyle());
}
return $this;
} | Set this organization as the one currently active
@return \Gems_User_Organization (continuation pattern) | entailment |
public function setHasRespondents($userId)
{
if (! $this->_get('gor_has_respondents')) {
$values['gor_has_respondents'] = 1;
$values['gor_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
$values['gor_changed_by'] = $userId;
$where = $this->db->quoteInto('gor_id_organization = ?', $this->_id);
$this->db->update('gems__organizations', $values, $where);
// Invalidate cache / change value
$this->_set('gor_has_respondents', 1);
}
return $this;
} | Tell the organization there is at least one respondent attached to it.
Does nothing if this is already known.
@param int $userId The current user
@return \Gems_User_Organization (continuation pattern) | entailment |
private function _checkUserId($userId = null)
{
if (empty($userId) && $this->currentUser instanceof \Gems_User_User) {
$userId = $this->currentUser->getUserId();
if (0 === $userId) {
$userId = null;
}
}
return $userId;
} | Replaces a null or empty userId with that of the current user
@param int $userId
@return int | entailment |
public function createToken(array $tokenData, $userId = null)
{
$userId = $this->_checkUserId($userId);
return $this->getTokenLibrary()->createToken($tokenData, $userId);
} | Creates a new token with a new random token Id
@param array $tokenData The other new data for the token
@param int $userId Id of the user who takes the action (for logging)
@return string | entailment |
public function filterChangesOnly(array $oldValues, array &$newValues)
{
if ($newValues && $oldValues) {
// \MUtil_Echo::track($newValues);
// Remove up unchanged values
foreach ($newValues as $name => $value) {
if (array_key_exists($name, $oldValues)) {
/*
* Token->setValidFrom will convert to a string representation
* but values read from database will be Date objects. Make
* sure we compare string with strings
*/
if ($value instanceof \Zend_Date) {
$value = $value->toString(\Gems_Tracker::DB_DATETIME_FORMAT);
}
if ($oldValues[$name] instanceof \Zend_Date) {
$oldValues[$name] = $oldValues[$name]->toString(\Gems_Tracker::DB_DATETIME_FORMAT);
}
// Extra condition for empty time in date values
if (($value === $oldValues[$name]) || ($value === $oldValues[$name] . ' 00:00:00')) {
unset($newValues[$name]);
}
}
}
}
return $newValues;
} | Utility function for detecting unchanged values.
@param array $oldValues
@param array $newValues
@return array | entailment |
public function getAllCodeFields()
{
static $fields = false; // Using static so it will be refreshed once per request
if ($fields === false) {
$fields = array();
$model = $this->createTrackClass('Model\\FieldMaintenanceModel');
$rows = $model->load(array('gtf_field_code IS NOT NULL'), array('gtf_field_code' => SORT_ASC));
if ($rows) {
foreach ($rows as $row) {
$key = FieldsDefinition::makeKey($row['sub'], $row['gtf_id_field']);
$fields[$key] = $row['gtf_field_code'];
}
}
}
return $fields;
} | Returns an array of all field id's for all tracks that have a code id
@return array id => code | entailment |
public function getRespondentTracks($respondentId, $organizationId, $order = array('gr2t_start_date'))
{
$select = $this->db->select()
->from('gems__respondent2track')
->joinInner('gems__tracks', 'gr2t_id_track = gtr_id_track')
->joinInner('gems__reception_codes', 'gr2t_reception_code = grc_id_reception_code')
->where('gr2t_id_user = ? AND gr2t_id_organization = ?');
if (!is_null($order)) {
$select->order($order);
}
$rows = $this->db->fetchAll($select, array($respondentId, $organizationId));
$tracks = array();
foreach ($rows as $row) {
$tracks[$row['gr2t_id_respondent_track']] = $this->getRespondentTrack($row);
}
return $tracks;
} | Get all tracks for a respondent
Specify the optional $order to sort other than on start date
@param int $respondentId
@param int $organizationId
@param mixed $order The column(s) and direction to order by
@return \Gems_Tracker_RespondentTrack[] | entailment |
public function getSource($sourceData)
{
if (is_array($sourceData)) {
$sourceId = $sourceData['gso_id_source'];
} else {
$sourceId = $sourceData;
$sourceData = false;
}
if (! isset($this->_sources[$sourceId])) {
if (! $sourceData) {
$sourceData = $this->db->fetchRow("SELECT * FROM gems__sources WHERE gso_id_source = ?", $sourceId);
}
if (! isset($sourceData['gso_ls_class'])) {
throw new \Gems_Exception_Coding('Missing source class for source ID: ' . $sourceId);
}
$this->_sources[$sourceId] = $this->_loadClass('source_' . $sourceData['gso_ls_class'], true, array($sourceData, $this->db));
}
return $this->_sources[$sourceId];
} | Retrieve a SourceInterface with a given id
Should only be called by \Gems_Tracker, \Gems_Tracker_Survey or \Gems_Tracker_Token (or should
this one use \Gems_Tracker_Survey instead?)
@param mixed $sourceData Gems source id or array containing gems source data
@return \Gems_Tracker_Source_SourceInterface | entailment |
public function getTokenLibrary()
{
if (! $this->_tokenLibrary) {
$this->_tokenLibrary = $this->_loadClass('Token_TokenLibrary', true);
}
return $this->_tokenLibrary;
} | Use this function only within \Gems_Tracker!!
@return \Gems_Tracker_Token_TokenLibrary | entailment |
public function getTokenModel($modelClass = 'StandardTokenModel')
{
if (! isset($this->_tokenModels[$modelClass])) {
$this->_tokenModels[$modelClass] = $this->_loadClass('Model_' . $modelClass, true);
$this->_tokenModels[$modelClass]->applyFormatting();
}
return $this->_tokenModels[$modelClass];
} | Returns a token model of the specified class with full display information
@param string $modelClass Optional class to use instead of StandardTokenModel. Must be subclass.
@return \Gems_Tracker_Model_StandardTokenModel | entailment |
public function getTokenSelect($fields = '*')
{
return $this->_loadClass('Token_TokenSelect', true, array($this->db, $fields, $this->loader->getUtil()));
} | Create a select statement on the token table
@return \Gems_Tracker_Token_TokenSelect | entailment |
public function getTrackDisplayGroups()
{
return array(
'tracks' => $this->translate->_('Tracks'),
'respondents' => $this->translate->_('Respondent'),
'staff' => $this->translate->_('Staff'),
);
} | Get the allowed display groups for tracks in this project.
@return array | entailment |
public function getTrackEngineClasses()
{
static $dummyClasses;
if (! $dummyClasses) {
$dummyTrackData['gtr_id_track'] = 0;
foreach ($this->getTrackEngineClassNames() as $className) {
$dummyClasses[$className] = $this->_loadClass('Engine_' . $className, true, array($dummyTrackData));
}
}
return $dummyClasses;
} | Returns dummy objects for all registered track engines class names
Instead of creating another object layer all classes defined by
getTrackEngineClassNames() are loaded with dummy data so that the
TrackEngineInterface functions containing general class information
can be used.
@see getTrackEngineClassNames()
@static $dummyClasses Cache array
@return \Gems_Tracker_Engine_TrackEngineInterface[] | entailment |
public function getTrackEngineList($extended = false, $userCreatableOnly = false)
{
$results = array();
$dummyTrackData['gtr_id_track'] = 0;
foreach ($this->getTrackEngineClasses() as $className => $cls) {
if ((! $userCreatableOnly) || $cls->isUserCreatable()) {
if ($extended) {
$results[$className] = \MUtil_Html::raw(sprintf('<strong>%s</strong> %s', $cls->getName(), $cls->getDescription()));
} else {
$results[$className] = $cls->getName();
}
}
}
return $results;
} | Returns all registered track engines classes for use in drop down lists.
@param boolean $extended When true return a longer name.
@param boolean $userCreatableOnly Return only the classes that can be created by the user interface
@return array Of classname => description | entailment |
public function loadCompletedTokensBatch(\Gems_Task_TaskRunnerBatch $batch, $respondentId = null, $userId = null, $orgId = null, $quickCheck = false)
{
$userId = $this->_checkUserId($userId);
$tokenSelect = $this->getTokenSelect(array('gto_id_token'));
$tokenSelect->onlyActive($quickCheck)
->forRespondent($respondentId)
->andSurveys(array('gsu_surveyor_id'))
->forWhere('gsu_surveyor_active = 1')
->order('gsu_surveyor_id');
if (null !== $orgId) {
$tokenSelect->forWhere('gto_id_organization = ?', $orgId);
}
$statement = $tokenSelect->getSelect()->query();
//Process one row at a time to prevent out of memory errors for really big resultsets
$tokens = array();
$tokencount = 0;
$activeId = 0;
$maxCount = 100; // Arbitrary value, change as needed
while ($tokenData = $statement->fetch()) {
$tokenId = $tokenData['gto_id_token'];
$surveyorId = $tokenData['gsu_surveyor_id'];
if ($activeId <> $surveyorId || count($tokens) > $maxCount) {
// Flush
if (count($tokens)> 0) {
$batch->addTask('Tracker_BulkCheckTokenCompletion', $tokens, $userId);
}
$activeId = $surveyorId;
$tokens = array();
}
$tokens[] = $tokenId;
$batch->addToCounter('tokens');
}
if (count($tokens)> 0) {
$batch->addTask('Tracker_BulkCheckTokenCompletion', $tokens, $userId);
}
} | Checks the token table to see if there are any answered surveys to be processed and loads those tasks
If the survey was started (and the token was forwarded to limesurvey) we need to check
if is was completed. If so, we might want to check the track the survey is in to enable
or disable future rounds
Does not reflect changes to tracks or rounds.
@param \Gems_Task_TaskRunnerBatch $batch The batch to load
@param int $respondentId Id of the respondent to check for or NULL
@param int $userId Id of the user who takes the action (for logging)
@param int $orgId Optional Id of the organization to check for
@param boolean $quickCheck Check only tokens with recent gto_start_time's
@return bool Did we find new answers? | entailment |
public function processCompletedTokens($respondentId, $userId = null, $orgId = null, $quickCheck = false)
{
$batch = $this->loader->getTaskRunnerBatch('completed');
if (! $batch->isLoaded()) {
$this->loadCompletedTokensBatch($batch, $respondentId, $userId, $orgId, $quickCheck);
}
$batch->runAll();
if ($batch->getCounter('resultDataChanges') > 0 || $batch->getCounter('surveyCompletionChanges')>0) {
$changed = true;
} else {
$changed = false;
}
$batch->reset();
return $changed;
} | Checks the token table to see if there are any answered surveys to be processed
If the survey was started (and the token was forwarded to limesurvey) we need to check
if is was completed. If so, we might want to check the track the survey is in to enable
or disable future rounds
Does not reflect changes to tracks or rounds.
@param int $respondentId Id of the respondent to check for or NULL
@param int $userId Id of the user who takes the action (for logging)
@param int $orgId Optional Id of the organization to check for
@param boolean $quickCheck Check only tokens with recent gto_start_time's
@return bool Did we find new answers? | entailment |
protected function processTokensBatch($batch_id, \Gems_Tracker_Token_TokenSelect $tokenSelect, $userId)
{
$where = implode(' ', $tokenSelect->getSelect()->getPart(\Zend_Db_Select::WHERE));
$batch = $this->loader->getTaskRunnerBatch($batch_id);
//Now set the step duration
$batch->minimalStepDurationMs = 3000;
if (! $batch->isLoaded()) {
$statement = $tokenSelect->getSelect()->query();
//Process one row at a time to prevent out of memory errors for really big resultsets
while ($tokenData = $statement->fetch()) {
$tokenId = $tokenData['gto_id_token'];
$batch->setTask('Tracker_CheckTokenCompletion', 'tokchk-' . $tokenId, $tokenId, $userId);
$batch->addToCounter('tokens');
}
}
return $batch;
} | Checks the token table to see if there are any answered surveys to be processed
If the survey was started (and the token was forwarded to limesurvey) we need to check
if is was completed. If so, we might want to check the track the survey is in to enable
or disable future rounds
Does not reflect changes to tracks or rounds.
@param string $batch_id A unique identifier for the current batch
@param \Gems_Tracker_Token_TokenSelect Select statements selecting tokens
@param int $userId Id of the user who takes the action (for logging)
@return \Gems_Task_TaskRunnerBatch A batch to process the changes | entailment |
public function recalculateTokens($batch_id, $userId = null, $cond = null)
{
$userId = $this->_checkUserId($userId);
$tokenSelect = $this->getTokenSelect(array('gto_id_token'));
$tokenSelect->andReceptionCodes(array())
->andRespondents(array())
->andRespondentOrganizations(array())
->andConsents(array());
if ($cond) {
$tokenSelect->forWhere($cond);
}
//Only select surveys that are active in the source (so we can recalculate inactive in Gems)
$tokenSelect->andSurveys(array());
$tokenSelect->forWhere('gsu_surveyor_active = 1');
self::$verbose = true;
return $this->processTokensBatch($batch_id, $tokenSelect, $userId);
} | Recalculates all token dates, timing and results
and outputs text messages.
Does not reflect changes to tracks or rounds.
@param string $batch_id A unique identifier for the current batch
@param int $userId Id of the user who takes the action (for logging)
@param string $cond
@return \Gems_Task_TaskRunnerBatch A batch to process the changes | entailment |
public function recalcTrackFields($batchId, $cond = null)
{
$respTrackSelect = $this->db->select();
$respTrackSelect->from('gems__respondent2track', array('gr2t_id_respondent_track'));
$respTrackSelect->join('gems__reception_codes', 'gr2t_reception_code = grc_id_reception_code', array());
$respTrackSelect->join('gems__tracks', 'gr2t_id_track = gtr_id_track', array());
if ($cond) {
$respTrackSelect->where($cond);
}
$respTrackSelect->where('gr2t_active = 1');
$respTrackSelect->where('grc_success = 1');
$respTrackSelect->where('gtr_active = 1');
// Also recaclulate when track was completed: there may be new rounds!
// $respTrackSelect->where('gr2t_count != gr2t_completed');
$batch = $this->loader->getTaskRunnerBatch($batchId);
//Now set the step duration
$batch->minimalStepDurationMs = 3000;
if (! $batch->isLoaded()) {
$statement = $respTrackSelect->query();
//Process one item at a time to prevent out of memory errors for really big resultsets
while ($respTrackData = $statement->fetch()) {
$respTrackId = $respTrackData['gr2t_id_respondent_track'];
$batch->setTask('Tracker_RecalculateFields', 'trkfcalc-' . $respTrackId, $respTrackId);
$batch->addToCounter('resptracks');
}
}
return $batch;
} | Recalculates the fields in tracks.
Does recalculate changed tracks
@param string $batchId A unique identifier for the current batch
@param string $cond Optional where statement for selecting tracks
@return \Gems_Task_TaskRunnerBatch A batch to process the changes | entailment |
public function refreshTokenAttributes($batch_id, $cond = null)
{
$batch = $this->loader->getTaskRunnerBatch($batch_id);
if (! $batch->isLoaded()) {
$tokenSelect = $this->getTokenSelect(array('gto_id_token'));
$tokenSelect->andSurveys(array())
->forWhere('gsu_surveyor_active = 1')
->forWhere('gto_in_source = 1');
if ($cond) {
// Add all connections for filtering, but select only surveys that are active in the source
$tokenSelect->andReceptionCodes(array())
->andRespondents(array())
->andRespondentOrganizations(array())
->andConsents(array())
->forWhere($cond);
}
foreach ($this->db->fetchCol($tokenSelect->getSelect()) as $token) {
$batch->addTask('Tracker_RefreshTokenAttributes', $token);
}
}
self::$verbose = true;
return $batch;
} | Refreshes the tokens in the source
@param string $batch_id A unique identifier for the current batch
@param string $cond An optional where statement
@return \Gems_Task_TaskRunnerBatch A batch to process the changes | entailment |
public function removeToken($token)
{
if ($token instanceof \Gems_Tracker_Token) {
$tokenId = $token->getTokenId();
} else {
$tokenId = $token;
}
unset($this->_tokens[$tokenId]);
return $this;
} | Remove token from cache for saving memory
@param string|\Gems_Tracker_Token $token
@return \Gems_Tracker (continuation pattern) | entailment |
public function synchronizeSources($sourceId = null, $userId = null)
{
$batch_id = 'source_synch' . ($sourceId ? '_' . $sourceId : '');
$batch = $this->loader->getTaskRunnerBatch($batch_id);
if (! $batch->isLoaded()) {
if ($sourceId) {
$sources = array($sourceId);
} else {
$select = $this->db->select();
$select->from('gems__sources', array('gso_id_source'))
->where('gso_active = 1');
$sources = $this->db->fetchCol($select);
}
foreach ($sources as $source) {
$batch->addTask('Tracker_SourceSyncSurveys', $source, $userId);
// Reset cache after basic synch
$batch->addTask('CleanCache');
// Reset cache after field synch
$batch->addTask('AddTask', 'CleanCache');
$batch->addTask('AddTask', 'Tracker\\UpdateSyncDate', $source, $userId);
}
}
return $batch;
} | Recalculates all token dates, timing and results
and outputs text messages.
Does not reflect changes to tracks or rounds.
@param int $sourceId A source identifier
@param int $userId Id of the user who takes the action (for logging)
@return \Gems_Task_TaskRunnerBatch A batch to process the synchronization | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$this->contentTitle = sprintf($this->_('Rounds in %s track'), $this->trackEngine->getTrackName());
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function checkRegistryRequestsAnswers()
{
return $this->db instanceof \Zend_Db_Adapter_Abstract &&
$this->logger instanceof \Gems_Log &&
$this->project instanceof \Gems_Project_ProjectSettings &&
$this->tracker instanceof \Gems_Tracker_TrackerInterface &&
$this->translate instanceof \Zend_Translate;
} | Should be called after answering the request to allow the Target
to check if all required registry values have been set correctly.
@return boolean False if required values are missing. | entailment |
public function isValid($value)
{
if ($throttleSettings = $this->project->getAskThrottleSettings()) {
// Prune the database for (very) old attempts
$where = $this->db->quoteInto(
"gta_datetime < DATE_SUB(NOW(), INTERVAL ? second) AND gta_activated = 0",
$throttleSettings['period'] * 20)
;
$this->db->delete('gems__token_attempts', $where);
// Retrieve the number of failed attempts that occurred within the specified window
$select = $this->db->select();
$select->from('gems__token_attempts', array(
new \Zend_Db_Expr('COUNT(*) AS attempts'),
new \Zend_Db_Expr('UNIX_TIMESTAMP(MAX(gta_datetime)) - UNIX_TIMESTAMP() AS last'),
))
->where('gta_datetime > DATE_SUB(NOW(), INTERVAL ? second)', $throttleSettings['period']);
$attemptData = $this->db->fetchRow($select);
$remainingDelay = ($attemptData['last'] + $throttleSettings['delay']);
// \MUtil_Echo::track($throttleSettings, $attemptData, $remainingDelay, $select->getPart(\Zend_Db_Select::WHERE));
if ($attemptData['attempts'] > $throttleSettings['threshold'] && $remainingDelay > 0) {
$this->logger->log("Possible token brute force attack, throttling for $remainingDelay seconds", \Zend_Log::ERR);
$this->_messages = $this->translate->_('The server is currently busy, please wait a while and try again.');
$this->db->update(
'gems__token_attempts',
['gta_activated' => 1],
implode(' AND ', $select->getPart(\Zend_Db_Select::WHERE))
);
return false;
}
}
// The pure token check
if ($this->isValidToken($value)) {
return true;
}
$max_length = $this->tracker->getTokenLibrary()->getLength();
$this->db->insert('gems__token_attempts',
array(
'gta_id_token' => substr($value, 0, $max_length),
'gta_ip_address' => $this->getRequest()->getClientIp()
)
);
return false;
} | Returns true if and only if $value meets the validation requirements
If $value fails validation, then this method returns false, and
getMessages() will return an array of messages that explain why the
validation failed.
@param mixed $value
@return boolean
@throws \Zend_Valid_Exception If validation of $value is impossible | entailment |
protected function isValidToken($value)
{
// Make sure the value has the right format
$value = $this->tracker->filterToken($value);
$library = $this->tracker->getTokenLibrary();
$format = $library->getFormat();
$reuse = $library->hasReuse() ? $library->getReuse() : -1;
if (strlen($value) !== strlen($format)) {
$this->_messages = sprintf($this->translate->_('Not a valid token. The format for valid tokens is: %s.'), $format);
return false;
}
$token = $this->tracker->getToken($value);
if ($token && $token->exists && $token->getReceptionCode()->isSuccess()) {
$currentDate = new \MUtil_Date();
if ($completionTime = $token->getCompletionTime()) {
// Reuse means a user can use an old token to check for new surveys
if ($reuse >= 0) {
// Oldest date AFTER completiondate. Oldest date is today minus reuse time
if ($currentDate->diffDays($completionTime) <= $reuse) {
// It is completed and may still be used to look
// up other valid tokens.
return true;
}
}
$this->_messages = $this->translate->_('This token is no longer valid.');
return false;
}
$fromDate = $token->getValidFrom();
if ((null === $fromDate) || $currentDate->isEarlier($fromDate)) {
// Current date is BEFORE from date
$this->_messages = $this->translate->_('This token cannot (yet) be used.');
return false;
}
if ($untilDate = $token->getValidUntil()) {
if ($currentDate->isLater($untilDate)) {
//Current date is AFTER until date
$this->_messages = $this->translate->_('This token is no longer valid.');
return false;
}
}
return true;
} else {
$this->_messages = $this->translate->_('Unknown token.');
return false;
}
} | Seperate the incorrect tokens from the right tokens
@param mixed $value
@return boolean | entailment |
public function formatDetailed($value)
{
//\MUtil_Echo::track($value);
if (is_array($value)) {
$group = $this->currentUser->getGroup();
if ($group) {
$value = $group->applyGroupToData($value);
}
}
return parent::formatDetailed($value);
} | Displays the content
@param string $value
@return string | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
$elements = $elements + $this->getExportTypeElements($data);
$elements[] = null;
return $elements;
} | Creates the form itself
@param array $options
@return \Gems_Form
/
protected function createForm($options = null)
{
$form = parent::createForm($options);
$form->setAction($this->basepath->getBasePath() . '/' .
$this->request->getControllerName() . '/' .
$this->request->getActionName() .
'/step/batch');
return $form;
}
Returns a text element for autosearch. Can be overruled.
The form / html elements to search on. Elements can be grouped by inserting null's between them.
That creates a distinct group of elements
@param array $data The $form field values (can be usefull, but no need to set them)
@return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks. | entailment |
protected function getExportTypeElements(array $data)
{
$export = $this->loader->getExport();
$exportTypes = $export->getExportClasses();
if (isset($data['type'])) {
$currentType = $data['type'];
} else {
reset($exportTypes);
$currentType = key($exportTypes);
}
$elements['type_label'] = $this->_('Export to');
$elements['type'] = $this->_createSelectElement( 'type', $exportTypes);
$elements['type']->setAttrib('onchange', 'this.form.submit();');
// $elements['step'] = $this->form->createElement('hidden', 'step');;
$exportClass = $export->getExport($currentType);
$exportName = $exportClass->getName();
$exportFormElements = $exportClass->getFormElements($this->form, $data);
if ($exportFormElements) {
$elements['firstCheck'] = $this->form->createElement('hidden', $currentType);
foreach ($exportFormElements as $key => $formElement) {
$elements['type_br_' . $key] = \MUtil_Html::create('br');
$elements['type_el_' . $key] = $formElement;
}
}
// if (!isset($data[$currentType])) {
// $data[$exportName] = $exportClass->getDefaultFormValues();
// }
return $elements;
} | Returns export field elements for auto search.
The form / html elements to search on. Elements can be grouped by inserting null's between them.
That creates a distinct group of elements
@param array $data The $form field values (can be usefull, but no need to set them)
@return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks. | entailment |
protected function getSurveySelectElements(array $data)
{
$dbLookup = $this->util->getDbLookup();
$translated = $this->util->getTranslated();
// $noRound = array(self::NoRound => $this->_('No round description'));
// $empty = $translated->getEmptyDropdownArray();
// get the current selections
$roundDescr = isset($data['gto_round_description']) ? $data['gto_round_description'] : null;
// $surveyIds = isset($data['gto_id_survey']) ? $data['gto_id_survey'] : null;
$trackId = isset($data['gto_id_track']) ? $data['gto_id_track'] : null;
// Get the selection data
$rounds = $dbLookup->getRoundsForExport($trackId);
$tracks = $this->util->getTrackData()->getTracksForOrgs($this->currentUser->getRespondentOrganizations());
$surveys = $dbLookup->getSurveysForExport($trackId, $roundDescr, true);
$elements['gto_id_track'] = $this->_createSelectElement(
'gto_id_track',
$tracks,
$this->_('(any track)')
);
$elements['gto_id_track']->setAttrib('onchange', 'this.form.submit();');
$elements[] = \MUtil_Html::create('br');
$elements['gto_round_description'] = $this->_createSelectElement(
'gto_round_description',
[self::NoRound => $this->_('No round description')] + $rounds,
$this->_('(any round)')
);
$elements['gto_round_description']->setAttrib('onchange', 'this.form.submit();');
$elements[] = \MUtil_Html::create('br');
$elements[] = $this->_createMultiCheckBoxElements('gto_id_survey', $surveys);
return $elements;
} | Returns start elements for auto search.
The form / html elements to search on. Elements can be grouped by inserting null's between them.
That creates a distinct group of elements
@param array $data The $form field values (can be usefull, but no need to set them)
@return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks. | entailment |
public function init()
{
parent::init();
/**
* If not in the index action, add the following to the head section
* <meta name="robots" content="noindex">
*/
$action = $this->getRequest()->getActionName();
if ($action !== 'index') {
$view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');
$this->view->getHelper('headMeta')->appendName('robots', 'noindex, nofollow');
}
} | Leave on top, so we won't miss this | entailment |
protected function _initToken()
{
if ($this->tracker) {
return $this->token && $this->token->exists;
}
$this->tracker = $this->loader->getTracker();
$this->tokenId = $this->tracker->filterToken($this->_getParam(\MUtil_Model::REQUEST_ID));
// Now check if the token is valid
$validator = $this->tracker->getTokenValidator();
if (! $this->tokenId || $validator->isValid($this->tokenId) === false) {
return false;
}
$this->token = $this->tracker->getToken($this->tokenId);
if (! $this->token->exists) {
return false;
}
if (! ($this->currentUser->isActive() || $this->token->getSurvey()->isTakenByStaff())) {
$tokenLang = strtolower($this->token->getRespondentLanguage());
// \MUtil_Echo::track($tokenLang, $this->locale->getLanguage());
if ($tokenLang != $this->locale->getLanguage()) {
$this->currentUser->switchLocale($tokenLang);
}
$currentOrg = $this->loader->getOrganization();
$tokenOrgId = $this->token->getOrganizationId();
if ($tokenOrgId != $currentOrg->getId()) {
$this->loader->getOrganization($tokenOrgId)
->setAsCurrentOrganization();
}
}
return true;
} | Common handler utility to initialize tokens from parameters
@return boolean True if there is a real token specified in the request | entailment |
protected function displayTokenForm(\Gems_Tracker_Form_AskTokenForm $form)
{
$form->setDescription(sprintf($this->_('Enter your %s token'), $this->project->name));
$this->html->h3($form->getDescription());
$this->html[] = $form;
$this->html->pInfo($this->_('Tokens identify a survey that was assigned to you personally.') . ' ' . $this->_('Entering the token and pressing OK will open that survey.'));
if ($this->currentUser->isActive()) {
if ($this->currentUser->isLogoutOnSurvey()) {
$this->html->pInfo($this->_('After answering the survey you will be logged off automatically.'));
}
}
$this->html->pInfo(
$this->_('A token consists of two groups of four letters and numbers, separated by an optional hyphen. Tokens are case insensitive.'), ' ',
$this->_('The number zero and the letter O are treated as the same; the same goes for the number one and the letter L.')
);
} | Function for overruling the display of the login form.
@param \Gems_Tracker_Form_AskTokenForm $form | entailment |
public function forwardAction()
{
/**************
* Find token *
**************/
if (! $this->_initToken()) {
if ($this->tokenId) {
// There is a token but is incorrect
$this->addMessage(sprintf(
$this->_('The token %s does not exist (any more).'),
strtoupper($this->tokenId)
));
}
$this->_forward('index');
return;
}
if ($this->util->getMaintenanceLock()->isLocked()) {
$this->addSnippet($this->maintenanceModeSnippets, ['token' => $this->token]);
return;
}
/****************************
* Update open tokens first *
****************************/
$this->tracker->processCompletedTokens(
$this->token->getRespondentId(),
$this->token->getChangedBy(),
$this->token->getOrganizationId()
);
$screen = $this->token->getOrganization()->getTokenAskScreen();
if ($screen) {
$params = $screen->getParameters($this->token);
$snippets = $screen->getSnippets($this->token);
if (false !== $snippets) {
$this->forwardSnippets = $snippets;
}
}
$params['token'] = $this->token;
// Display token when possible
if ($this->html->snippet($this->forwardSnippets, $params)) {
return;
}
// Snippet had nothing to display, because of an answer
if ($this->getRequest()->getActionName() == 'return') {
$this->addMessage(sprintf(
$this->_('Thank you for answering. At the moment we have no further surveys for you to take.'),
strtoupper($this->tokenId)
));
} else {
$this->addMessage(sprintf(
$this->_('The survey for token %s has been answered and no further surveys are open.'),
strtoupper($this->tokenId)
));
}
// Do not enter a loop!! Reroute!
$this->_reroute(array('controller' => 'ask', 'action' => 'index'), true);
} | Show the user a screen with token information and a button to take at least one survey
@return void | entailment |
public function indexAction()
{
if ($this->util->getMaintenanceLock()->isLocked()) {
$this->addSnippet($this->maintenanceModeSnippets);
return;
}
// Make sure to return to the forward screen
$this->currentUser->setSurveyReturn();
$request = $this->getRequest();
$tracker = $this->loader->getTracker();
$form = $tracker->getAskTokenForm(array(
'displayOrder' => array('element', 'description', 'errors'),
'labelWidthFactor' => 0.8
));
if ($request->isPost() && $form->isValid($request->getParams())) {
$this->_forward('forward');
return;
}
$form->populate($request->getParams());
$this->displayTokenForm($form);
} | Ask the user for a token
@return void | entailment |
public function returnAction()
{
if (! $this->_initToken()) {
// In all other cases: the action that generates meaningfull warnings and is reachable for everyone
$this->_forward('forward');
return;
}
if ($url = $this->token->getReturnUrl()) {
// Check for completed tokens
$this->tracker->processCompletedTokens(
$this->token->getRespondentId(),
$this->token->getChangedBy(),
$this->token->getOrganizationId()
);
// Redirect at once, might be another site url
header('Location: ' . $url);
exit();
}
// No return? Check for old style user based return
if (! $this->currentUser->isActive()) {
$this->_forward('forward');
return;
}
// Check for completed tokens
$this->tracker->processCompletedTokens($this->token->getRespondentId(), $this->currentUser->getUserId());
// Get return route parameters
$parameters = $this->currentUser->getSurveyReturn();
if (! $parameters) {
// Default fallback for the fallback
$request = $this->getRequest();
$parameters[$request->getControllerKey()] = 'respondent';
$parameters[$request->getActionKey()] = 'show';
$parameters[\MUtil_Model::REQUEST_ID] = $this->token->getPatientNumber();
}
$this->_reroute($parameters, true);
} | The action where survey sources should return to after survey completion | entailment |
public function toSurveyAction()
{
if (! $this->_initToken()) {
// Default option
$this->_forward('index');
return;
}
$language = $this->locale->getLanguage();
try {
$url = $this->token->getUrl(
$language,
$this->currentUser->getUserId() ? $this->currentUser->getUserId() : $this->token->getRespondentId()
);
/************************
* Optional user logout *
************************/
if ($this->currentUser->isLogoutOnSurvey()) {
$this->currentUser->unsetAsCurrentUser();
}
// Redirect at once
header('Location: ' . $url);
exit();
} catch (\Gems_Tracker_Source_SurveyNotFoundException $e) {
$this->addMessage(sprintf(
$this->_('The survey for token %s is no longer active.'),
strtoupper($this->tokenId)
));
// Default option
$this->_forward('index');
}
} | Go directly to url | entailment |
protected function addEscortReport()
{
$this->html->h3('Project and escort class report');
$escortClass = get_class($this->escort);
$foundNone = true;
$projectName = $this->project->getName();
$oldInterfaces = array(
'Gems_Project_Log_LogRespondentAccessInterface',
'Gems_Project_Organization_MultiOrganizationInterface',
'Gems_Project_Organization_SingleOrganizationInterface',
'Gems_Project_Tracks_FixedTracksInterface',
'Gems_Project_Tracks_StandAloneSurveysInterface',
'Gems_Project_Tracks_TracksOnlyInterface',
);
foreach ($oldInterfaces as $interface) {
if ($this->escort instanceof $interface) {
$foundNone = false;
$this->html->pInfo(sprintf(
'%s implements the deprecated %s interface. Remove this interface.',
$escortClass,
$interface
));
}
}
$snippetsDir = APPLICATION_PATH . '\snippets';
if (file_exists($snippetsDir)) {
$foundNone = false;
$this->html->pInfo(sprintf(
'%s still uses the deprecated %s directory for snippets. This directory is deprecated and will be removed in 1.7.2.',
$projectName,
$snippetsDir
));
}
if ($foundNone) {
$this->html->pInfo(sprintf('%s and %s are up to date.', $projectName, $escortClass));
}
} | A specific report on the escort class | entailment |
protected function addFileReport(\SplFileInfo $fileinfo)
{
// $extension = strtolower($fileinfo->getExtension());
$extension = strtolower(pathinfo($fileinfo, PATHINFO_EXTENSION));
if (('php' !== $extension) && ('phtml' !== $extension)) {
return false;
}
$content = file_get_contents($fileinfo);
$messages = array();
if (preg_match('/Single.*Survey/', $fileinfo->getFilename())) {
$messages[] = "This seems to be a file for (obsolete) SingleSurveys. This file can probably be removed.";
}
$this->_checkCodingChanged($fileinfo, $content, $messages);
if (\MUtil_String::endsWith($fileinfo->getPath(), 'controllers')) {
$this->_checkControllersChanged($fileinfo, $content, $messages);
} else {
$this->_checkSnippetsChanged($fileinfo, $content, $messages);
}
$this->_checkTablesChanged($fileinfo, $content, $messages);
$this->_checkVariablesChanged($fileinfo, $content, $messages);
$this->_checkDepreciations($fileinfo, $content, $messages);
if (! $messages) {
return false;
}
$this->html->h3(sprintf('Report on file %s', substr($fileinfo->getPathname(), strlen(GEMS_ROOT_DIR) + 1)));
foreach ($messages as $message) {
$this->html->pInfo($message);
}
return true;
} | A specific report on a code file
@param \SplFileInfo $filename
@return boolean | entailment |
protected function addFileReports()
{
$sCode = $this->html->sequence();
$output = false;
$filenames = $this->_getFilenames();
foreach ($filenames as $filename) {
$output = $this->addFileReport($filename) || $output;
}
if ($this->appNamespaceError) {
$sCode->h3('Code change issues found');
$sCode->pInfo('The application code has code change issues. You can try to fix them by running this phing script:');
$sCode->pre(
'cd ' . APPLICATION_PATH . "\n" .
'phing -f ' . GEMS_LIBRARY_DIR . DIRECTORY_SEPARATOR . 'scripts' . DIRECTORY_SEPARATOR . 'namespacer.xml'
);
$p = $sCode->pInfo('To use this script you have to install ');
$p->a('https://www.phing.info/', 'Phing');
$p->append('. Then run the script and check again for issues not fixed by the script.');
} elseif (! $output) {
$this->html->h3('Code change report');
$this->html->pInfo('No compatibility issues found in the code for this project.');
}
} | A reports on code files | entailment |
protected function addProjectIniReport()
{
$h3 = $this->html->h3();
$issues = false;
if (! $this->project->offsetExists('headers')) {
$this->html->pInfo('No headers section found.');
$issues = true;
}
if (!$this->project->offsetExists('meta')) {
$this->html->pInfo('No meta headers section found.');
$issues = true;
} else {
if (isset($this->project['meta']['Content-Security-Policy'])) {
$this->html->pInfo('meta.Content-Security-Policy should be moved to headers section');
$issues = true;
}
if (isset($this->project['meta']['Strict-Transport-Security'])) {
$this->html->pInfo('meta.Strict-Transport-Security should be moved to headers section');
$issues = true;
}
}
if (isset($this->project['headers']['Content-Security-Policy']) &&
preg_match('/img-src\s.*?data:.*?;/', $this->project['headers']['Content-Security-Policy']) !== 1) {
$this->html->pInfo('The headers.Content-Security-Policy setting img-src should have data: for Two Factor Authentication.');
$issues = true;
}
if ($this->project->offsetExists('jquerycss')) {
$this->html->pInfo('Separate JQuery CSS no longer in use. Remove jquerycss setting.');
$issues = true;
}
if (! isset($this->project['security'], $this->project['security']['methods'])) {
$this->html->pInfo('No OpenSSL cipher methods defined in security.methods.');
$issues = true;
}
if ($issues) {
$h3->append('Project.ini issues found');
$this->html->pInfo()->strong('See project.example.ini for examples of fixes.');
} else {
$h3->append('Project.ini report');
$this->html->pInfo('No compatibility issues found in project.ini.');
}
} | A reports on the project ini | entailment |
public function afterRegistry()
{
$this->codeVersion = $this->loader->getVersions()->getBuild();
foreach ($this->escort->getLoaderDirs() as $prefix => $dir) {
$this->projectDirs[$prefix . '_'] = $prefix;
}
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
protected function getRecursiveDirectoryIterator($dir)
{
return new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir, \FilesystemIterator::CURRENT_AS_FILEINFO),
\RecursiveIteratorIterator::SELF_FIRST,
\RecursiveIteratorIterator::CATCH_GET_CHILD
);
} | Iterator for looping thorugh all files in a directory and i's sub directories
@param string $dir
@return \RecursiveIteratorIterator | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$this->html = $this->getHtmlSequence();
$versions = $this->loader->getVersions();
$this->html->h2(sprintf(
'Upgrade compatibility report for GemsTracker %s, build %d',
$versions->getGemsVersion(),
$versions->getBuild()
));
$this->addEscortReport();
$this->addProjectIniReport();
$this->addFileReports();
return $this->html;
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
public function render($content)
{
$useBootstrap = \MUtil_Bootstrap::enabled();
if ((null === ($element = $this->getElement())) ||
(null === ($view = $element->getView()))) {
return $content;
}
$cellDecorators = $this->getCellDecorators();
$containerDiv = \MUtil_Html::create()->div(array('id' => 'tabElement'));
if ($element instanceof \MUtil_Form_Element_Table) {
$containerDiv->appendAttrib('class', $element->getAttrib('class'));
$subforms = $element->getSubForms();
} elseif ($element instanceof \Zend_Form) {
$cellDecorators = null;
$subforms = array($element);
}
if ($subforms) {
$activeTabs = false;
if (count($subforms) > 1) {
$activeTabs = true;
if (!$useBootstrap) {
$jquery = $view->jQuery();
$js = sprintf('%1$s("#tabElement").tabs();', \ZendX_JQuery_View_Helper_JQuery::getJQueryHandler());
if ($selectedTabElement = $this->getOption('selectedTabElement')) {
$js .= sprintf('%1$s("#tabElement").on("tabsactivate", function(event, ui) { console.log(ui.newTab.text()); %1$s("#%2$s").val(ui.newTab.text()) });', \ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(), $selectedTabElement);
}
$jquery->addOnLoad($js);
} else {
$jquery = $view->jQuery();
if ($selectedTabElement = $this->getOption('selectedTabElement')) {
$js = sprintf('%1$s(\'a[data-toggle="tab"]\').on(\'shown.bs.tab\', function (e) {
var tabtext = $(e.target).text();
%1$s("#%2$s").val(tabtext);
})', \ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(), $selectedTabElement);
$jquery->addOnLoad($js);
}
}
$list = $containerDiv->ul(array('class' => 'nav nav-tabs', 'role' => 'tablist'));
}
$tabNumber = 0;
$tabContainerDiv = $containerDiv->div(array('class' => 'tab-content'));//\MUtil_Html::create()->div(array('class' => 'tab-content'));
$active = $this->getOption('active');
foreach($subforms as $subform) {
if ($activeTabs) {
if ($tabcolumn = $this->getOption('tabcolumn')) {
$tabName = $subform->getElement($tabcolumn)->getValue();
} else {
$elements = $subform->getElements();
$element = reset($elements);
$tabName = $element->getValue();
}
$tabId = $tabName.'-tab';
$liOptions = array();
$tabPaneOptions = array('id' => $tabId,'class' => 'tab-pane');
if ($active && $active == $tabName) {
// If a tab is active, select it
if (!$useBootstrap) {
$js = sprintf('%1$s("#tabElement").tabs({ selected: %2$d});', \ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(), $tabNumber);
$jquery->addOnLoad($js);
} else {
$js = sprintf('%1$s(\'a[data-toggle="tab"]\').eq(%2$d).tab(\'show\');', \ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(), $tabNumber);
$jquery->addOnLoad($js);
}
$liOptions['class'] = 'active';
$tabPaneOptions['class'] .= ' active';
}
$tabNumber++;
$list->li($liOptions)->a('#'.$tabId, $tabName, array('role' => 'tab', 'data-toggle' => 'tab'));
if ($useBootstrap) {
$subContainer = $tabContainerDiv->div($tabPaneOptions);
} else {
$subContainer = $tabContainerDiv->div($tabPaneOptions)->table(array('class' => 'formTable'));
}
} else {
if($useBootstrap) {
$subContainer = $tabContainerDiv;
} else {
$subContainer = $tabContainerDiv->table(array('class' => 'formTable'));
}
}
foreach ($subform->getElements() as $subelement) {
if ($subelement instanceof \Zend_Form_Element_Hidden) {
$this->applyDecorators($subelement, array(array('ViewHelper')));
$subContainer[] = $subelement;
} else {
if ($useBootstrap) {
$subgroup = $subContainer->div(array('class' => 'form-group'));
$label = $subgroup->div(array('class' => 'label-container'))->label(array('for' => $subelement->getId()));
$label[] = $subelement->getLabel();
$divContainer = $subgroup->div(array('class' => 'element-container'));
$divContainer[] = $subelement;
} else {
$row = $subContainer->tr();
$label = $row->td()->label(array('for' => $subelement->getId()));
$label[] = $subelement->getLabel();
$column = $row->td();
$column[] = $subelement;
}
}
}
}
}
$containerDiv->view = $view;
$html = $containerDiv;
return $html;
} | Render the element
@param string $content Content to decorate
@return string | entailment |
public function setOption($key, $value)
{
switch ($key) {
case 'cellDecorator':
$value = $this->getCellDecorators() + array($value);
case 'cellDecorators':
$this->_cellDecorators = $value;
break;
default:
$this->_options[$key] = $value;
break;
}
return $this;
} | Set a single option
@param string $key
@param mixed $value
@return \Zend_Form_Decorator_Interface | entailment |
public function getChanges(array $context, $new)
{
$conditions = $this->loader->getConditions();
if (isset($context['gcon_type'],$context['gcon_class']) && !empty($context['gcon_class'])) {
$condition = $conditions->loadConditionForType($context['gcon_type'],$context['gcon_class']);
$changes = [
'condition_help' => ['value' => \MUtil_Html::raw('<pre>' . $condition->getHelp() . '</pre>')],
] + $condition->getModelFields($context, $new);
return $changes;
}
return [];
} | Returns the changes that must be made in an array consisting of
<code>
array(
field1 => array(setting1 => $value1, setting2 => $value2, ...),
field2 => array(setting3 => $value3, setting4 => $value4, ...),
</code>
By using [] array notation in the setting name you can append to existing
values.
Use the setting 'value' to change a value in the original data.
When a 'model' setting is set, the workings cascade.
@param array $context The current data this object is dependent on
@param boolean $new True when the item is a new record not yet saved
@return array name => array(setting => value) | entailment |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$bridge->tr()->class = $bridge->row_class;
if ($showMenuItem = $this->getShowMenuItem()) {
$bridge->addItemLink($showMenuItem->toActionLinkLower($this->request, $bridge));
}
// make sure search results are highlighted
$this->applyTextMarker();
$br = \MUtil_Html::create()->br();
$orgName[] = \MUtil_Lazy::iff($bridge->gor_url,
\MUtil_Html_AElement::a($bridge->gor_name, array('href' => $bridge->gor_url, 'target' => '_blank', 'class' => 'globe')),
$bridge->gor_name);
$orgName[] = $bridge->createSortLink('gor_name');
$mailName[] = \MUtil_Lazy::iff($bridge->gor_contact_email,
\MUtil_Html_AElement::email(\MUtil_Lazy::first($bridge->gor_contact_name, $bridge->gor_contact_email), array('href' => array('mailto:', $bridge->gor_contact_email))),
$bridge->gor_contact_name);
$mailName[] = $bridge->createSortLink('gor_contact_name');
$bridge->addMultiSort($orgName, $br, 'gor_task', $br, 'gor_location');
$bridge->addMultiSort($mailName, $br, 'gor_active', $br, 'gor_has_login');
if ($model->has('gor_respondent_group', 'label')) {
$bridge->addMultiSort('gor_add_respondents', $br, 'gor_has_respondents', $br, 'gor_respondent_group');
} else {
$bridge->addMultiSort('gor_add_respondents', $br, 'gor_has_respondents');
}
$bridge->add('gor_accessible_by');
if ($editMenuItem = $this->getEditMenuItem()) {
$bridge->addItemLink($editMenuItem->toActionLinkLower($this->request, $bridge));
}
} | Adds columns from the model to the bridge that creates the browse table.
Overrule this function to add different columns to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_TableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@return void | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.