sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function authorizeIp() { //In unit test REMOTE_ADDR is not available and will return null $request = $this->getRequest(); // E.g. command line user if (! $request instanceof \Zend_Controller_Request_Http) { return true; } $remoteIp = $request->getServer('REMOTE_ADDR'); if ($this->util->isAllowedIP($remoteIp, $this->getAllowedIPRanges())) { return true; } return $this->_('You are not allowed to login from this location.'); }
Checks if the user is allowed to login using the current IP address according to the group he is in An adapter authorizes and if the end resultis boolean, string or array it is converted into a Zend\Authenticate\Result. @return mixed Zend\Authentication\Adapter\AdapterInterface|Zend\Authenticate\Result|boolean|string|array
entailment
protected function authorizeOrgIp() { //special case: project user should have no restriction if ($this->project->getSuperAdminName() == $this->getLoginName()) { return true; } //In unit test REMOTE_ADDR is not available and will return null $request = $this->getRequest(); // E.g. command line user if (! $request instanceof \Zend_Controller_Request_Http) { return true; } $remoteIp = $request->getServer('REMOTE_ADDR'); if ($this->util->isAllowedIP($remoteIp, $this->getBaseOrganization()->getAllowedIpRanges())) { return true; } return $this->_('You are not allowed to login from this location.'); }
Checks if the user is allowed to login using the current IP address according to his BASE organization An adapter authorizes and if the end resultis boolean, string or array it is converted into a Zend\Authenticate\Result. @return mixed Zend\Authentication\Adapter\AdapterInterface|Zend\Authenticate\Result|boolean|string|array
entailment
public function canLoginHere() { if (! $this->_hasVar('can_login_here')) { $this->_setVar('can_login_here', true); if ($orgId = $this->userLoader->getOrganizationIdByUrl()) { if (! $this->isAllowedOrganization($orgId)) { $this->_setVar('can_login_here', false);; } } } return $this->_getVar('can_login_here'); }
True when the current url is one where this user is allowed to login. If the url is a fixed organization url and the user is not allowed to access this organization, then this function returns false. @return boolean
entailment
public function checkRegistryRequestsAnswers() { if (! (($this->db instanceof \Zend_Db_Adapter_Abstract) && ($this->session instanceof \Zend_Session_Namespace))) { return false; } // Checks if this is the current user if (! $this->_vars instanceof \Zend_Session_Namespace) { $sessionStore = $this->session; $notCurrent = true; foreach (array('user_id', 'user_organization_id') as $key) { if ($sessionStore->__isset($key) && $this->_vars->offsetExists($key)) { $notCurrent = $sessionStore->__get($key) != $this->_vars->offsetGet($key); } else { $notCurrent = $sessionStore->__isset($key) || $this->_vars->offsetExists($key); } if ($notCurrent) { break; } } if (! $notCurrent) { // When this is the case, use the \Zend_Session_Namespace object with the current set values // This way changes to this user object are reflected in the CurrentUser object and vice versa. $this->setAsCurrentUser(); } } // Change a numeric role id to it's string value $this->_getRole('user_role'); if ($this->_hasVar('current_user_role')) { $this->_getRole('current_user_role'); } return (boolean) $this->acl && $this->userLoader; }
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 clearTwoFactorKey() { $this->_setVar('user_two_factor_key', null); $this->definition->setTwoFactorKey($this, null); return $this; }
Clear the two factor authentication key @return $this
entailment
public function getAllowedRoles() { $userRole = $this->getRole(); if ($userRole === 'master') { $output = $this->acl->getRoles(); return array_combine($output, $output); } $output = array($userRole => $userRole); foreach ($this->acl->getRoles() as $role) { if (! $this->acl->inheritsRole($role, $userRole, true)) { $output[$role] = $role; } } unset($output['master']); return $output; }
Returns the current roles a user may set. NOTE! A user can set a role, unless it <em>requires a higher role level</em>. I.e. an admin is not allowed to set a super role as super inherits and expands admin. But it is allowed to set the nologin and respondent roles that are not inherited by the admin as they are in a different hierarchy. An exception is the role master as it is set by the system. You gotta be a master to set the master role. @return array With identical keys and values roleId => roleId
entailment
public function getAllowedStaffGroups($current = true) { // Always refresh because these values are otherwise not responsive to change $dbLookup = $this->util->getDbLookup(); $groupId = $this->getGroupId($current); $groups = $dbLookup->getActiveStaffGroups(); if ('master' === $this->getRole($current)) { $groups[-1] = $this->_('Project \'master\''); return $groups; } try { $setGroups = $this->db->fetchOne( "SELECT ggp_may_set_groups FROM gems__groups WHERE ggp_id_group = ?", $groupId ); $groupsAllowed = explode(',', $setGroups); } catch (\Zend_Db_Exception $e) { // The database might not be updated $groupsAllowed = []; } $result = array(); foreach ($groups as $id => $label) { if ((in_array($id, $groupsAllowed))) { $result[$id] = $groups[$id]; } } natsort($result); return $result; }
Retrieve an array of groups the user is allowed to assign: his own group and all groups he/she inherits rights from @param boolean $current Return the current list or the original list when true @return array
entailment
public function getChangePasswordForm($args_array = null) { if (! $this->canSetPassword()) { return; } $args = \MUtil_Ra::args(func_get_args()); if (isset($args['askCheck']) && $args['askCheck']) { $args['checkFields'] = $this->loadResetPasswordCheckFields(); } return $this->userLoader->getChangePasswordForm($this, $args); }
Returns a form to change the possword for this user. @param boolean $askOld Ask for the old password, calculated when not set. @return \Gems_Form
entailment
public function getCurrentOrganizationId() { $orgId = $this->_getVar('user_organization_id'); //If not set, read it from the cookie if ($this->isCurrentUser() && ((null === $orgId) || (\Gems_User_UserLoader::SYSTEM_NO_ORG === $orgId))) { $request = $this->getRequest(); if ($request) { $orgId = \Gems_Cookies::getOrganization($this->getRequest()); } if (! $orgId) { $orgId = 0; } $this->_setVar('user_organization_id', $orgId); } return $orgId; }
Returns the organization id that is currently used by this user. @return int
entailment
public function getFrom() { // Gather possible sources of a from address $sources[] = $this->getBaseOrganization(); if ($this->getBaseOrganizationId() != $this->getCurrentOrganizationId()) { $sources[] = $this->getCurrentOrganization(); } $sources[] = $this->project; foreach ($sources as $source) { if ($from = $source->getFrom()) { return $from; } } // We really don't like it, but sometimes the only way to get a from address. return $this->getEmailAddress(); }
Returns the from address @return string E-Mail address
entailment
public function getFullName() { if (! $this->_getVar('user_name')) { $name = ltrim($this->_getVar('user_first_name') . ' ') . ltrim($this->_getVar('user_surname_prefix') . ' ') . $this->_getVar('user_last_name'); if (! $name) { // Use obfuscated login name $name = $this->getLoginName(); $name = substr($name, 0, 3) . str_repeat('*', max(5, strlen($name) - 2)); } $this->_setVar('user_name', $name); // \MUtil_Echo::track($name); } return $this->_getVar('user_name'); }
Returns the full user name (first, prefix, last). @return string
entailment
protected function getGenderGreeting($locale = null) { $greetings = $this->util->getTranslated()->getGenderGreeting($locale); if (isset($greetings[$this->_getVar('user_gender')])) { return $greetings[$this->_getVar('user_gender')]; } }
Returns the gender for use as part of a sentence, e.g. Dear Mr/Mrs In practice: starts lowercase @param string $locale @return array gender => string
entailment
public function getGreeting($locale = null) { if (! $this->_getVar('user_greeting')) { $greeting[] = $this->getGenderGreeting($locale); if ($this->_getVar('user_last_name')) { $greeting[] = $this->_getVar('user_surname_prefix'); $greeting[] = $this->_getVar('user_last_name'); } else { $name = $this->getLoginName(); if ($name) { $name = substr($name, 0, 3) . str_repeat('*', strlen($name) - 2); $greeting[] = $name; } } array_filter($greeting); $this->_setVar('user_greeting', implode(' ', $greeting)); } return $this->_getVar('user_greeting'); }
Returns a standard greeting for the current user. @param string $locale @return int
entailment
public function getGroup() { if (! $this->_group) { $this->_group = $this->userLoader->getGroup($this->getGroupId()); } return $this->_group; }
Returns the group of this user. @return \Gems\User\Group
entailment
public function getGroupId($current = true) { if ($current && $this->_hasVar('current_user_group')) { return $this->_getVar('current_user_group'); } return $this->_getVar('user_group'); }
Returns the group number of this user. @param boolean $current Checks value for current role (when false for normal role); @return int
entailment
public function getMailFields($locale = null) { $org = $this->getBaseOrganization(); $orgResults = $org->getMailFields(); $projResults = $this->project->getMailFields(); $result['bcc'] = $projResults['project_bcc']; $result['email'] = $this->getEmailAddress(); $result['first_name'] = $this->_getVar('user_first_name'); $result['from'] = $this->getFrom(); $result['full_name'] = trim($this->getGenderHello($locale) . ' ' . $this->getFullName()); $result['greeting'] = $this->getGreeting($locale); $result['last_name'] = ltrim($this->_getVar('user_surname_prefix') . ' ') . $this->_getVar('user_last_name'); $result['login_url'] = $orgResults['organization_login_url']; $result['name'] = $this->getFullName(); $result['login_name'] = $this->getLoginName(); $result = $result + $orgResults + $projResults; $result['reset_ask'] = $orgResults['organization_login_url'] . '/index/resetpassword'; $result['reset_in_hours'] = $this->definition->getResetKeyDurationInHours(); $result['reply_to'] = $result['from']; $result['to'] = $result['email']; return $result; }
Array of field name => values for sending E-Mail @param string $locale @return array
entailment
public function getPasswordAge() { $date = \MUtil_Date::ifDate( $this->_getVar('user_password_last_changed'), array(\Gems_Tracker::DB_DATETIME_FORMAT, \Gems_Tracker::DB_DATE_FORMAT, \Zend_Date::ISO_8601) ); if ($date instanceof \MUtil_Date) { return abs($date->diffDays()); } else { return 0; } }
Return the number of days since last change of password @return int
entailment
public function getRequest() { if (! $this->request) { $this->request = \Zend_Controller_Front::getInstance()->getRequest(); } return $this->request; }
Return the Request object @return \Zend_Controller_Request_Abstract
entailment
public function getResetPasswordMailFields($locale = null) { $result['reset_key'] = $this->getPasswordResetKey(); $result['reset_url'] = $this->getBaseOrganization()->getLoginUrl() . '/index/resetpassword/key/' . $result['reset_key']; $result['reset_in_hours'] = $this->definition->getResetKeyDurationInHours(); return $result + $this->getMailFields($locale); }
Array of field name => values for sending a reset password E-Mail @param string $locale @return array
entailment
public function getRespondentOrganizations() { if (! $this->_hasVar('__allowedRespOrgs')) { $availableOrganizations = $this->util->getDbLookup()->getOrganizationsWithRespondents(); $allowedOrganizations = $this->getAllowedOrganizations(); $this->_setVar('__allowedRespOrgs', array_intersect($availableOrganizations, $allowedOrganizations)); } // \MUtil_Echo::track($this->_getVar('__allowedOrgs')); return $this->_getVar('__allowedRespOrgs'); }
Get an array of OrgId => Org Name for all allowed organizations that can have respondents for the current logged in user @return array
entailment
public function getRole($current = true) { if ($current && $this->_hasVar('current_user_role')) { return $this->_getRole('current_user_role'); } return $this->_getRole('user_role'); }
Returns the current user role. @param boolean $current Checks value for current role (when false for normal role); @return string
entailment
public function gotoStartPage(\Gems_Menu $menu, \Zend_Controller_Request_Abstract $request) { if (false && $this->isPasswordResetRequired()) { // Set menu OFF // This code may be obsolete from 1.8.4 $menu->setVisible(false); $menuItem = $menu->findController('option', 'change-password'); // This may not yet be true, but is needed for the redirect. $menuItem->set('allowed', true); $menuItem->set('visible', true); } else { $menuItem = $menu->findFirst(array('allowed' => true, 'visible' => true)); } if ($menuItem) { // Prevent redirecting to the current page. if (! ($menuItem->is('controller', $request->getControllerName()) && $menuItem->is('action', $request->getActionName()))) { if (!$menuItem->has('controller')) { //This is a container, try to find first active child $item = $menuItem; foreach ($item->sortByOrder()->getChildren() as $menuItem) { if ($menuItem->isAllowed() && $menuItem->has('controller')) { break; } $menuItem = null; } } if ($menuItem) { $redirector = \Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); $redirector->gotoRoute($menuItem->toRouteUrl($request), null, true); } } } return $menuItem; }
Redirects the user to his/her start page. @param \Gems_Menu $menu @param \Zend_Controller_Request_Abstract $request @return \Gems_Menu_SubMenuItem
entailment
public function hasPrivilege($privilege, $current = true) { if (! $this->acl) { return true; } $role = $this->getRole($current); return $this->acl->isAllowed($role, null, $privilege); }
Returns true if the role of the current user has the given privilege @param string $privilege @param boolean $current Checks value for current role (when false for normal role); @return bool
entailment
public function inAllowedGroup() { if ($this->isCurrentUser() || (! $this->isStaff())) { // Always allow editing of non-staff user // for the time being return true; } $group = $this->getGroupId(); $groups = $this->util->getDbLookup()->getActiveStaffGroups(); if (! isset($groups[$group])) { // Allow editing when the group does not exist or is no longer active. return true; } $allowedGroups = $this->userLoader->getCurrentUser()->getAllowedStaffGroups(); if ($allowedGroups) { return (boolean) isset($allowedGroups[$group]); } else { return false; } }
Return true if this user has a role that is accessible by the current user, i.e. is the current user allowed to change this specific user @return boolean
entailment
public function isAllowedOrganization($organizationId) { $orgs = $this->getAllowedOrganizations(); return isset($orgs[$organizationId]) || (\Gems_User_UserLoader::SYSTEM_NO_ORG == $organizationId); }
Is this organization in the list of currently allowed organizations? @param int $organizationId @return boolean
entailment
public function isTwoFactorRequired($ipAddress) { return $this->definition->isTwoFactorRequired($ipAddress, $this->isTwoFactorEnabled(), $this->getGroup()); }
Should this user be authorized using two factor authentication? @param string $ipAddress @return boolean
entailment
protected function loadAuthorizers($password, $testPassword = true) { if ($this->isBlockable()) { $auths['block'] = array($this, 'authorizeBlock'); } // organization ip restriction $auths['orgip'] = array($this, 'authorizeOrgIp'); // group ip restriction $auths['ip'] = array($this, 'authorizeIp'); if ($testPassword) { if ($this->isActive()) { $auths['pwd'] = $this->definition->getAuthAdapter($this, $password); } else { $auths['pwd'] = false; } } return $auths; }
Load the callables | results needed to authenticate/authorize this user A callable will be called, then an adapter authorizes and if the end result is boolean, string or array it is converted into a Zend\Authenticate\Result. @param string $password @param boolean $testPassword Set to false to test on the non-password checks only @return array Of Callable|Zend\Authentication\Adapter\AdapterInterface|Zend\Authenticate\Result|boolean|string|array
entailment
protected function loadResetPasswordCheckFields() { // CHECK ON SOMEONES BIRTHDAY // Birthdays are usually not defined for staff but they do exist for respondents if ($value = $this->_getVar('user_birthday')) { $label = $this->_('Your birthday'); $birthdayElem = new \Gems_JQuery_Form_Element_DatePicker('birthday'); $birthdayElem->setLabel($label) ->setOptions(\MUtil_Model_Bridge_FormBridge::getFixedOptions('date')) ->setRequired(true) ->setStorageFormat('yyyy-MM-dd'); if ($format = $birthdayElem->getDateFormat()) { $valueFormatted = \MUtil_Date::format($value, $format, $birthdayElem->getStorageFormat()); } else { $valueFormatted = $value; } $validator = new \Zend_Validate_Identical($valueFormatted); $validator->setMessage(sprintf($this->_('%s is not correct.'), $label), \Zend_Validate_Identical::NOT_SAME); $birthdayElem->addValidator($validator); return array($label => $birthdayElem); } // CHECK ON SOMEONES ZIP // Zips are usually not defined for staff but they do exist for respondents if ($value = $this->_getVar('user_zip')) { $label = $this->_('Your zipcode'); $zipElem = new Text('zipcode'); $zipElem->setLabel($label) ->setRequired(true); $validator = new \Zend_Validate_Identical($value); $validator->setMessage(sprintf($this->_('%s is not correct.'), $label), \Zend_Validate_Identical::NOT_SAME); $zipElem->addValidator($validator); return array($label => $zipElem); } return array($this->_('Username') => $this->getLoginName()); }
Returns an array of elements for check fields during password reset and/or 'label name' => 'required value' pairs. For asking extra questions before allowing a password change. Default is asking for the username but you can e.g. ask for someones birthday. @return array Of 'label name' => 'required values' or \Zend_Form_Element elements
entailment
public function refreshAllowedOrganizations() { // Privilege overrules organizational settings if ($this->hasPrivilege('pr.organization-switch')) { $orgs = $this->util->getDbLookup()->getOrganizations(); } else { $org = $this->getBaseOrganization(); $orgs = array($org->getId() => $org->getName()) + $org->getAllowedOrganizations(); } // \MUtil_Echo::track($orgs); $this->_setVar('__allowedOrgs', $orgs); // Clean this cache $this->_unsetVar('__allowedRespOrgs'); return $this; }
Allowes a refresh of the existing list of organizations for this user. @return \Gems_User_User (continuation pattern)
entailment
public function reportPasswordWeakness($password = null, $skipAge = false) { if ($this->canSetPassword()) { $checker = $this->userLoader->getPasswordChecker(); $codes[] = $this->getCurrentOrganization()->getCode(); $codes[] = $this->getRoles(); $codes[] = $this->_getVar('__user_definition'); if ($this->isStaff()) { $codes[] = 'staff'; } return $checker->reportPasswordWeakness($this, $password, \MUtil_Ra::flatten($codes), $skipAge); } }
Check for password weakness. @param string $password Or null when you want a report on all the rules for this password. @param boolean $skipAge When setting a new password, we should not check for age @return mixed String or array of strings containing warning messages or nothing
entailment
public function sendMail($subjectTemplate, $bbBodyTemplate, $useResetFields = false, $locale = null) { if ($useResetFields && (! $this->canResetPassword())) { return $this->_('Trying to send a password reset to a user that cannot be reset.'); } $mail = $this->loader->getMail(); $mail->setTemplateStyle($this->getBaseOrganization()->getStyle()); $mail->setFrom($this->getFrom()); $mail->addTo($this->getEmailAddress(), $this->getFullName(), $this->project->getStaffBounce()); if ($bcc = $this->project->getEmailBcc()) { $mail->addBcc($bcc); } if ($useResetFields) { $fields = $this->getResetPasswordMailFields($locale); } else { $fields = $this->getMailFields($locale); } // \MUtil_Echo::track($fields, $bbBodyTemplate); $fields = \MUtil_Ra::braceKeys($fields, '{', '}'); $mail->setSubject(strtr($subjectTemplate, $fields)); $mail->setBodyBBCode(strtr($bbBodyTemplate, $fields)); try { $mail->send(); return null; } catch (\Exception $e) { return array( $this->_('Unable to send e-mail.'), $e->getMessage()); } }
Send an e-mail to this user @param string $subjectTemplate A subject template in which {fields} are replaced @param string $bbBodyTemplate A BB Code body template in which {fields} are replaced @param boolean $useResetFields When true get a reset key for this user @param string $locale Optional locale @return mixed String or array of warnings when something went wrong
entailment
public function setAsCurrentUser($signalLoader = true, $resetSessionId = true) { // Get the current variables $oldStore = $this->_getVariableStore(); // When $oldStore is a \Zend_Session_Namespace, then this user is already the current user. if (! $this->isCurrentUser()) { $this->userLoader->unsetCurrentUser(); if ($resetSessionId) { \Zend_Session::regenerateId(); } $this->_vars = $this->session; foreach ($oldStore as $name => $value) { $this->_vars->__set($name, $value); } // Perform the interface switch $this->switchLocale(); if ($signalLoader) { $this->userLoader->setCurrentUser($this); } } $this->getCurrentOrganization()->setAsCurrentOrganization(); return $this; }
Set this user as the current user. This means that the data about this user will be stored in a session. @param boolean $signalLoader Do not set, except from UserLoader @param boolean $resetSessionId Should the session be reset? @return \Gems_User_User (continuation pattern)
entailment
public function setCurrentOrganization($organization) { if (!($organization instanceof \Gems_User_Organization)) { $organization = $this->userLoader->getOrganization($organization); } $organizationId = $organization->getId(); $oldOrganizationId = $this->getCurrentOrganizationId(); if ($organizationId != $oldOrganizationId) { $this->_setVar('user_organization_id', $organizationId); if ($this->isCurrentUser()) { $this->getCurrentOrganization()->setAsCurrentOrganization(); if ($organization->canHaveRespondents()) { $usedOrganizationId = $organizationId; } else { $usedOrganizationId = null; } // Now update the requestcache to change the oldOrgId to the new orgId // Don't do it when the oldOrgId doesn't match $keysArray = array_flip($this->possibleOrgIds); $requestCache = $this->session->requestCache; if ($requestCache) { foreach ($requestCache as $key => &$elements) { $elements = $this->_changeIds($elements, $oldOrganizationId, $usedOrganizationId, $keysArray); } $this->session->requestCache = $requestCache; } // $searchSession &= $_SESSION['ModelSnippetActionAbstract_getSearchData']; $searchSession = new \Zend_Session_Namespace('ModelSnippetActionAbstract_getSearchData'); foreach ($searchSession as $id => $data) { $searchSession->$id = $this->_changeIds($data, $oldOrganizationId, $usedOrganizationId, $keysArray); } } } return $this; }
Set the currently selected organization for this user @param mixed $organization \Gems_User_Organization or an organization id. @return \Gems_User_User (continuation pattern)
entailment
public function setGroupTemp($groupId) { if ($groupId == $this->_getVar('user_group')) { $this->_unsetVar('current_user_group'); $this->_unsetVar('current_user_role'); } else { $groups = $this->getAllowedStaffGroups(false); $group = $this->userLoader->getGroup($groupId); if (isset($groups[$groupId])) { $this->_setVar('current_user_group', $groupId); $this->_setVar('current_user_role', $group->getRole()); } elseif ($group->isActive()) { throw new \Gems_Exception($this->_('No access to group'), 403, null, sprintf( $this->_('You are not allowed to switch to the %s group.'), $group->getName() )); } else { throw new \Gems_Exception($this->_('No access to group'), 403, null, sprintf( $this->_('You cannot switch to an inactive or non-existing group.') )); } } return $this; }
(Temporarily) the group of the current user. @param int $groupId @return self
entailment
public function setPassword($password) { $this->definition->setPassword($this, $password); $this->setPasswordResetRequired(false); $this->refresh(); // force refresh return $this; }
Set the password, if allowed for this user type. @param string $password @return \Gems_User_User (continuation pattern)
entailment
public function setSurveyReturn($return = null) { if (null === $return) { $this->_unsetVar('surveyReturn'); return $this; } if ($return instanceof \Zend_Controller_Request_Abstract) { $return = $return->getParams(); } elseif (! is_array($return)) { $return = \MUtil_Ra::to($return); } if ('autofilter' == $return['action']) { $return['action'] = 'index'; } $return = array_filter($return); // \MUtil_Echo::track($return); $this->_setVar('surveyReturn', $return); return $this; }
Set the parameters where the survey should return to @param mixed $return \Zend_Controller_Request_Abstract, array of something that can be turned into one. @return \Gems_User_User
entailment
public function switchLocale($locale = null) { if (null === $locale) { $locale = $this->getLocale(); } elseif ($this->getLocale() != $locale) { $this->setLocale($locale); } $this->locale->setLocale($locale); $this->translateAdapter->setLocale($locale); return \Gems_Cookies::setLocale($locale, $this->basepath->getBasePath()); }
Switch to new locale @param string $locale Current if omitted @return boolean true if cookie was set
entailment
public function unsetAsCurrentUser($signalLoader = true) { // When $oldStore is a \Zend_Session_Namespace, then this user is already the current user. if ($this->isCurrentUser()) { // Get the current variables $oldStore = $this->_vars; $this->_vars = new \ArrayObject(); $this->_vars->setFlags(\ArrayObject::STD_PROP_LIST); foreach ($oldStore as $name => $value) { $this->_vars->offsetSet($name, $value); } // Clean up what is there now in the session. $oldStore->unsetAll(); if ($signalLoader) { // Signal the loader $this->userLoader->unsetCurrentUser(); } } return $this; }
Unsets this user as the current user. This means that the data about this user will no longer be stored in a session. @param boolean $signalLoader Do not set, except from UserLoader @return \Gems_User_User (continuation pattern)
entailment
public function afterRegistry() { parent::afterRegistry(); $allowedGroups = $this->loader->getCurrentUser()->getAllowedStaffGroups(); if ($allowedGroups) { $expr = new \Zend_Db_Expr(sprintf( "CASE WHEN gsf_id_primary_group IN (%s) THEN 1 ELSE 0 END", implode(", ", array_keys($allowedGroups)) )); } else { $expr = new \Zend_Db_Expr('0'); } $this->addColumn($expr, 'accessible_role'); $this->set('accessible_role', 'default', 1); }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
public function save(array $newValues, array $filter = null, array $saveTables = null) { //First perform a save $savedValues = parent::save($newValues, $filter, $saveTables); //Now check if we need to set the password if(isset($newValues['fld_password']) && !empty($newValues['fld_password'])) { if ($this->getChanged()<1) { $this->setChanged(1); } //Now load the userclass and save the password use the $savedValues as for a new //user we might not have the id in the $newValues $user = $this->loader->getUserLoader()->getUserByStaffId($savedValues['gsf_id_user']); if ($user->canSetPassword()) { $user->setPassword($newValues['fld_password']); } } return $savedValues; }
Save a single model item. Makes sure the password is saved too using the userclass @param array $newValues The values to store for a single model item. @param array $filter If the filter contains old key values these are used to decide on update versus insert. @param array $saveTables Optional array containing the table names to save, otherwise the tables set to save at model level will be saved. @return array The values as they are after saving (they may change).
entailment
public function matchEpisode(EpisodeOfCare $episode) { foreach ($episode->getAppointments() as $appointment) { if ($appointment instanceof \Gems_Agenda_Appointment) { if ($this->matchAppointment($appointment)) { return true; } } } return false; }
Check a filter for a match @param \Gems\Agenda\EpisodeOfCare $episode @return boolean
entailment
public function getUserData($login_name, $organization) { $orgs = null; try { $orgs = $this->db->fetchPairs("SELECT gor_id_organization, gor_name FROM gems__organizations WHERE gor_active = 1 ORDER BY gor_name"); natsort($orgs); } catch (\Zend_Db_Exception $zde) { } if (! $orgs) { // Table might not exist or be empty, so do something failsafe $orgs = array($organization => 'create db first'); } return array( 'user_id' => \Gems_User_UserLoader::SYSTEM_USER_ID, 'user_login' => $login_name, 'user_name' => $login_name, 'user_group' => 800, 'user_role' => $this->project->getConsoleRole(), 'user_style' => 'gems', 'user_base_org_id' => $organization, 'user_allowed_ip_ranges' => null, 'user_blockable' => false, '__allowedOrgs' => $orgs ); }
Returns the data for a user object. It may be empty if the user is unknown. @param string $login_name @param int $organization @return array Of data to fill the user with.
entailment
protected function getRespondentMailfields() { if ($this->respondent) { $result = array(); $result['bcc'] = $this->mailFields['project_bcc']; $result['email'] = $this->respondent->getEmailAddress(); $result['from'] = ''; $result['first_name'] = $this->respondent->getFirstName(); $result['full_name'] = $this->respondent->getFullName(); $result['greeting'] = $this->respondent->getGreeting(); $result['last_name'] = $this->respondent->getLastName(); $result['name'] = $this->respondent->getName(); } else { $result = array( 'email' => '', 'from' => '', 'first_name'=> '', 'full_name' => '', 'greeting' => '', 'last_name' => '', 'name' => '' ); } $result['reply_to'] = $result['from']; $result['to'] = $result['email']; $result['reset_ask'] = ''; if ($this->mailFields['organization_login_url']) { $result['reset_ask'] = $this->mailFields['organization_login_url'] . '/index/resetpassword'; } return $result; }
Get the respondent mailfields @return array
entailment
protected function afterLoad() { if ($this->_data && $this->agenda instanceof \Gems_Agenda && ! $this->_subFilters) { // Flexible determination of filters to load. Save for future expansion of number of fields $i = 1; $field = 'gaf_filter_text' . $i; $filterIds = array(); while (array_key_exists($field, $this->_data)) { if ($this->_data[$field]) { $filterIds[] = intval($this->_data[$field]); } $i++; $field = 'gaf_filter_text' . $i; } if ($filterIds) { $preferAppBalance = 0; $filterObjects = $this->agenda->getFilters("SELECT * FROM gems__appointment_filters WHERE gaf_id IN (" . implode(', ', $filterIds) . ") ORDER BY gaf_id_order"); // The order we get the filters may not be the same as the one in which they are specified foreach ($filterIds as $id) { foreach ($filterObjects as $filterObject) { if ($filterObject instanceof AppointmentFilterInterface) { if ($filterObject->getFilterId() == $id) { $this->_subFilters[$id] = $filterObject; $preferAppBalance += $filterObject->preferAppointmentSql() ? 1 : -1; } } } } $this->_preferAppointments = $preferAppBalance >= 0; } } }
Override this function when you need to perform any actions when the data is loaded. Test for the availability of variables as these objects can be loaded data first after deserialization or registry variables first after normal instantiation. That is why this function called both at the end of afterRegistry() and after exchangeArray(), but NOT after unserialize(). After this the object should be ready for serialization
entailment
public function getTab() { // $this->_logger->zflog('test'); $tab = " Log"; if ($this->_writer->getErrorCount()) { $tab .= " (".$this->_writer->getErrorCount().")"; $_COOKIE['ZFDebugCollapsed'] = 'ZFDebug_'.$this->getIdentifier(); } return $tab; }
Has to return html code for the menu tab @return string
entailment
public function getPanel() { $request = Zend_Controller_Front::getInstance()->getRequest(); $module = $request->getModuleName(); if ('default' !== $module) { $module = " ($module module)"; } else { $module = ''; } $controller = $request->getControllerName(); $action = $request->getActionName(); $panel = "<h4>Event log for {$controller}Controller->{$action}Action() {$module}</h4>"; $panel .= '<table cellpadding="0" cellspacing="0">'.implode('', $this->_writer->getMessages()).'</table>'; return $panel; }
Has to return html code for the content panel @return string
entailment
public function mark($name, $logFirst = false) { if (isset($this->_marks[$name])) { $this->_marks[$name]['time'] = round((microtime(true)-$_SERVER['REQUEST_TIME'])*1000-$this->_marks[$name]['time']).'ms'; if (function_exists('memory_get_usage')) { $this->_marks[$name]['memory'] = round((memory_get_usage()-$this->_marks[$name]['memory'])/1024) . 'K'; } else { $this->_marks[$name]['memory'] = 'N/A'; } $this->_logger->zflog( array('time' => $this->_marks[$name]['time'], 'memory' => $this->_marks[$name]['memory'], 'message' => $name ) ); } else { $this->_marks[$name]['time'] = (microtime(true)-$_SERVER['REQUEST_TIME'])*1000; if (function_exists('memory_get_usage')) { $this->_marks[$name]['memory'] = memory_get_usage(); } else { $this->_marks[$name]['memory'] = 'N/A'; } if ($logFirst) { $this->_logger->zflog( array('time' => round($this->_marks[$name]['time']).'ms', 'memory' => round($this->_marks[$name]['memory']/1024).'K', 'message' => $name ) ); } } }
Sets a time mark identified with $name @param string $name
entailment
public function addField(FieldInterface $field) { $key = $field->getFieldKey(); $this->addDependsOn($field->getDataModelDependsOn()); $this->addEffected($key, $field->getDataModelEffecteds()); $this->_fields[$key] = $field; return $this; }
Add a field to this dependency @param FieldInterface $field @return \Gems\Tracker\Model\FieldDataDependency
entailment
public function getChanges(array $context, $new) { $output = array(); foreach ($this->_fields as $key => $field) { if ($field instanceof FieldInterface) { $changes = $field->getDataModelDependyChanges($context, $new); if ($changes) { $output[$field->getFieldKey()] = $changes; } } } return $output; }
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
public function calculateFieldInfo($currentValue, array $fieldData) { if (! $currentValue) { return $currentValue; } $agenda = $this->loader->getAgenda(); $appointment = $agenda->getAppointment($currentValue); if ($appointment && $appointment->isActive()) { $time = $appointment->getAdmissionTime(); if ($time) { return $time->toString($this->appointmentTimeFormat); } } return null; }
Calculation the field info display for this type @param array $currentValue The current value @param array $fieldData The other values loaded so far @return mixed the new value
entailment
public function calculateFieldValue($currentValue, array $fieldData, array $trackData) { if ($currentValue || isset($this->_fieldDefinition['gtf_filter_id'])) { $agenda = $this->loader->getAgenda(); if ($this->_lastActiveKey && isset($this->_fieldDefinition['gtf_filter_id'])) { $fromDate = false; $lastActive = self::$_lastActiveAppointment[$this->_lastActiveKey]; if (($lastActive instanceof \Gems_Agenda_Appointment) && $lastActive->isActive()) { $fromDate = $lastActive->getAdmissionTime(); } if ((! $fromDate) && isset($trackData['gr2t_start_date']) && $trackData['gr2t_start_date']) { if ($trackData['gr2t_start_date'] instanceof \Zend_Date) { $fromDate = $trackData['gr2t_start_date']; } else { $fromDate = new \MUtil_Date($trackData['gr2t_start_date'], \Gems_Tracker::DB_DATETIME_FORMAT); } // Always use start of the day for start date comparisons $fromDate->setTime('00:00:00'); } if ($fromDate instanceof \MUtil_Date) { $select = $agenda->createAppointmentSelect(array('gap_id_appointment')); $select->onlyActive() ->forFilterId($this->_fieldDefinition['gtf_filter_id']) ->forRespondent($trackData['gr2t_id_user'], $trackData['gr2t_id_organization']); $minDate = Period::applyPeriod( $fromDate, $this->_fieldDefinition['gtf_min_diff_unit'], $this->_fieldDefinition['gtf_min_diff_length'] ); if ($this->_fieldDefinition['gtf_max_diff_exists']) { $maxDate = Period::applyPeriod( $fromDate, $this->_fieldDefinition['gtf_max_diff_unit'], $this->_fieldDefinition['gtf_max_diff_length'] ); } else { $maxDate = null; } if ($this->_fieldDefinition['gtf_min_diff_length'] > 0) { $select->forPeriod($minDate, $maxDate, true); } else { $select->forPeriod($maxDate, $minDate, false); } if ($this->_fieldDefinition['gtf_uniqueness']) { switch ($this->_fieldDefinition['gtf_uniqueness']) { case 1: // Track instances may link only once to an appointment $select->uniqueInTrackInstance( self::$_lastActiveAppointmentIds[$this->_lastActiveKey] ); break; case 2: // Tracks of this type may link only once to an appointment if (isset($trackData['gr2t_id_respondent_track'])) { $respTrackId = $trackData['gr2t_id_respondent_track']; } else { $respTrackId = null; } $select->uniqueForTrackId( $this->_trackId, $respTrackId, self::$_lastActiveAppointmentIds[$this->_lastActiveKey] ); break; // default: } } // Query ready // echo "\n" . $select->getSelect()->__toString() . "\n"; $newValue = $select->fetchOne(); if ($newValue) { $currentValue = $newValue; } } } if ($this->_lastActiveKey && $currentValue) { $appointment = $agenda->getAppointment($currentValue); if ($appointment->isActive()) { self::$_lastActiveAppointment[$this->_lastActiveKey] = $appointment; self::$_lastActiveAppointmentIds[$this->_lastActiveKey][$currentValue] = $currentValue; } } } return $currentValue; }
Calculate the field value using the current values @param array $currentValue The current value @param array $fieldData The other known field values @param array $trackData The currently available track data (track id may be empty) @return mixed the new value
entailment
public function calculationStart(array $trackData) { if (isset($trackData['gr2t_id_respondent_track'])) { $this->_lastActiveKey = $trackData['gr2t_id_respondent_track']; } elseif (isset($trackData['gr2t_id_user'], $trackData['gr2t_id_organization'])) { $this->_lastActiveKey = $trackData['gr2t_id_user'] . '__' . $trackData['gr2t_id_organization']; } else { $this->_lastActiveKey = false; } if ($this->_lastActiveKey) { self::$_lastActiveAppointment[$this->_lastActiveKey] = null; self::$_lastActiveAppointmentIds[$this->_lastActiveKey] = array(); } return $this; }
Signal the start of a new calculation round (for all fields) @param array $trackData The currently available track data (track id may be empty) @return \Gems\Tracker\Field\FieldAbstract
entailment
public function getDataModelDependyChanges(array $context, $new) { if ($this->isReadOnly()) { return null; } $agenda = $this->loader->getAgenda(); $empty = $this->util->getTranslated()->getEmptyDropdownArray(); $output['multiOptions'] = $empty + $agenda->getActiveAppointments( $context['gr2t_id_user'], $context['gr2t_id_organization'] ); return $output; }
Returns the changes to the model for this field that must be made in an array consisting of <code> array(setting1 => $value1, setting2 => $value2, ...), </code> By using [] array notation in the setting array key 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 (setting => value)
entailment
public function showAppointment($value) { if (! $value) { return $this->_('Unknown'); } if ($value instanceof \Gems_Agenda_Appointment) { $appointment = $value; } else { $appointment = $this->loader->getAgenda()->getAppointment($value); } if ($appointment instanceof \Gems_Agenda_Appointment) { if (! $this->menu instanceof \Gems_Menu) { $this->menu = $this->loader->getMenu(); } $menuItem = $this->menu->findAllowedController('appointment', 'show'); if ($menuItem) { if (! $this->request) { $this->request = \Zend_Controller_Front::getInstance()->getRequest(); } $href = $menuItem->toHRefAttribute( array('gap_id_appointment' => $appointment->getId()), $this->request ); if ($href) { return \MUtil_Html::create('a', $href, $appointment->getDisplayString()); } } return $appointment->getDisplayString(); } return $value; }
Dispaly an appoitment as text @param value $value @return string
entailment
public function commJob() { $batch = $this->loader->getMailLoader()->getCronBatch(); $batch->autoStart = true; $this->_helper->BatchRunner($batch, $this->_('Executing all cron jobs'), $this->accesslog); // $this->html->br(); }
Perform automatic job mail
entailment
public function cronLockAction() { // Switch lock $this->util->getCronJobLock()->reverse(); // Redirect $request = $this->getRequest(); $this->_reroute($this->menu->getCurrentParent()->toRouteUrl()); }
Action that switches the cron job lock on or off.
entailment
public function indexAction() { $this->initHtml(); if ($this->util->getMaintenanceLock()->isLocked()) { $this->addMessage($this->_('Cannot run cron job in maintenance mode.')); } elseif ($this->util->getCronJobLock()->isLocked()) { $this->addMessage($this->_('Cron jobs turned off.')); } else { $this->commJob(); } $this->util->getMonitor()->startCronMailMonitor(); }
The general "do the jobs" action
entailment
public function execute() { $batch = $this->getBatch(); $import = $batch->getVariable('import'); if (! (isset($import['trackId']) && $import['trackId'])) { // Do nothing return; } $tracker = $this->loader->getTracker(); $trackEngine = $tracker->getTrackEngine($import['trackId']); $trackEngine->updateRoundCount($this->currentUser->getUserLoginId()); // Now cleanup the cache $this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('tracks')); }
Should handle execution of the task, taking as much (optional) parameters as needed The parameters should be optional and failing to provide them should be handled by the task
entailment
protected function getAutoSearchElements(array $data) { // Search text $elements = parent::getAutoSearchElements($data); $this->_addPeriodSelectors($elements, array('grco_created' => $this->_('Date sent'))); $br = \MUtil_Html::create()->br(); $elements[] = null; $dbLookup = $this->util->getDbLookup(); $elements[] = $this->_createSelectElement( 'gto_id_track', $this->util->getTrackData()->getAllTracks(), $this->_('(select a track)') ); $elements[] = $this->_createSelectElement( 'gto_id_survey', $this->util->getTrackData()->getAllSurveys(), $this->_('(all surveys)') ); $elements[] = $this->_createSelectElement( 'grco_organization', $this->loader->getCurrentUser()->getRespondentOrganizations(), $this->_('(all organizations)') ); return $elements; }
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 addFormElements(\Zend_Form $form) { $this->saveLabel = $this->_('Save Two Factor Setup'); $this->authenticator->addSetupFormElements($form, $this->user, $this->formData); if ($this->user->canSaveTwoFactorKey()) { $options = [ 'label' => $this->_('Enabled'), ]; $keyElement = $form->createElement('Checkbox', 'twoFactorEnabled', $options); $form->addElement($keyElement); } }
Add the elements to the form @param \Zend_Form $form
entailment
protected function getDefaultFormValues() { if ($this->formData) { return $this->formData; } if ($this->user->hasTwoFactor()) { $authKey = $this->user->getTwoFactorKey(); } else { $authKey = null; } if (! $authKey) { $authKey = $this->authenticator->createSecret(); $this->addMessage(sprintf( $this->_('A new random two factor key was saved for %s.'), $this->user->getFullName() )); $this->addMessage($this->_('Click save to enable two factor authentication.')); $this->user->setTwoFactorKey($this->authenticator, $authKey, false); // Set on save $output['twoFactorEnabled'] = 1; } else { $output['twoFactorEnabled'] = $this->user->isTwoFactorEnabled() ? 1 : 0; if (! $output['twoFactorEnabled']) { $this->addMessage($this->_('Two factor authentication not active!')); } } $output['twoFactorKey'] = $authKey; return $output; }
Return the default values for the form @return array
entailment
public function hasHtmlOutput() { if (! ($this->user->hasTwoFactor() || $this->user->canSaveTwoFactorKey())) { $this->addMessage(sprintf( $this->_('A two factor key cannot be set for %s.'), $this->user->getFullName() )); return false; } if (parent::hasHtmlOutput()) { return $this->processForm(); } }
The place to check if the data set in the snippet is valid to generate the snippet. When invalid data should result in an error, you can throw it here but you can also perform the check in the checkRegistryRequestsAnswers() function from the {@see MUtil_Registry_TargetInterface}. @return boolean
entailment
protected function saveData() { $newKey = $this->formData['twoFactorKey']; if ($newKey) { if ($this->user->canSaveTwoFactorKey()) { $enabled = $this->formData['twoFactorEnabled'] ? 1 : 0; } else { $enabled = null; } $this->user->setTwoFactorKey($this->authenticator, $newKey, $enabled); $this->addMessage($this->_('Two factor authentication setting saved.')); } return 0; }
Hook containing the actual save code. @return int The number of "row level" items changed
entailment
protected function createModel() { $groupby['period_1'] = new \Zend_Db_Expr("YEAR($this->dateFrom)"); $date = new \MUtil_Date(); switch ($this->dateType) { case 'D': $keyCount = 1; $groupby['period_1'] = new \Zend_Db_Expr("CONVERT($this->dateFrom, DATE)"); $date->setTime(0); $date->addDay($this->dateFactor - $this->dateRange); $start = $date->getIso(); for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) { if (0 == $i) { $this->dateCurrentStart = clone $date; $this->dateCurrentEnd = clone $date; $this->dateCurrentEnd->setTimeToDayEnd(); } $values = array(); $values['period_1'] = $date->get('yyyy-MM-dd'); $values['range'] = $i; $requiredRows[$i] = $values; $date->addDay(1); } $date->subSecond(1); $end = $date->getIso(); break; case 'W': $keyCount = 2; // Use MONDAY as start of week $groupby['period_1'] = new \Zend_Db_Expr("substr(YEARWEEK(gto_valid_from, 3),1,4)"); //$groupby['period_1'] = new \Zend_Db_Expr("YEAR($this->dateFrom) - CASE WHEN WEEK($this->dateFrom, 1) = 0 THEN 1 ELSE 0 END"); $groupby['period_2'] = new \Zend_Db_Expr("WEEK($this->dateFrom, 3)"); $date->setWeekday(1); $date->setTime(0); $date->addWeek($this->dateFactor - $this->dateRange); $start = $date->getIso(); for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) { if (0 == $i) { $this->dateCurrentStart = clone $date; $this->dateCurrentEnd = clone $date; $this->dateCurrentEnd->addWeek(1)->subSecond(1); } $values = array(); $values['period_1'] = $date->get(\Zend_Date::YEAR); $values['period_2'] = (int) $date->get(\Zend_Date::WEEK); // Use constant but drop leading zero // When monday is in the previous year, add one to the year if ($date->get(\Zend_Date::DAY_OF_YEAR)>14 && $date->get(\Zend_Date::WEEK) == 1) { $values['period_1'] = $values['period_1'] + 1; } $values['range'] = $i; $requiredRows[$i] = $values; $date->addWeek(1); } $date->subSecond(1); $end = $date->getIso(); break; case 'M': $keyCount = 2; $groupby['period_2'] = new \Zend_Db_Expr("MONTH($this->dateFrom)"); $date->setDay(1); $date->setTime(0); $date->addMonth($this->dateFactor - $this->dateRange); $start = $date->getIso(); for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) { if (0 == $i) { $this->dateCurrentStart = clone $date; $this->dateCurrentEnd = clone $date; $this->dateCurrentEnd->addMonth(1)->subSecond(1); } $values = array(); $values['period_1'] = $date->get(\Zend_Date::YEAR); $values['period_2'] = $date->get(\Zend_Date::MONTH); $values['range'] = $i; $requiredRows[$i] = $values; $date->addMonth(1); } $date->subSecond(1); $end = $date->getIso(); break; case 'Y': $keyCount = 1; $date->setDay(1); $date->setMonth(1); $date->setTime(0); $date->addYear($this->dateFactor - $this->dateRange); $start = $date->getIso(); for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) { if (0 == $i) { $this->dateCurrentStart = clone $date; $this->dateCurrentEnd = clone $date; $this->dateCurrentEnd->addYear(1)->subSecond(1); } $values = array(); $values['period_1'] = $date->get(\Zend_Date::YEAR); $values['range'] = $i; $requiredRows[$i] = $values; $date->addYear(1); } $date->subSecond(1); $end = $date->getIso(); break; default: throw new \Gems_Exception_Coding('Incorrect date_type value: ' . $this->dateType); } $where = "$this->dateFrom BETWEEN '$start' AND '$end'"; for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) { $requiredRows[$i]['date_factor'] = $this->dateFactor + $i; $requiredRows[$i]['df_link'] = null; $requiredRows[$i]['df_label'] = null; } if ($this->dateRange > 0) { $requiredRows[-$this->dateRange]['df_link'] = $this->dateFactor - ($this->dateRange * 2); $requiredRows[-$this->dateRange]['df_label'] = $this->_('<<'); $requiredRows[ $this->dateRange]['df_link'] = $this->dateFactor + ($this->dateRange * 2); $requiredRows[ $this->dateRange]['df_label'] = $this->_('>>'); if ($this->dateRange > 1) { $i = intval($this->dateRange / 2); $requiredRows[-$i]['df_link'] = $this->dateFactor - 1; $requiredRows[-$i]['df_label'] = $this->_('<'); $requiredRows[ $i]['df_link'] = $this->dateFactor + 1; $requiredRows[ $i]['df_label'] = $this->_('>'); } $requiredRows[ 0]['df_link'] = $this->dateFactor ? '0' : null; $requiredRows[ 0]['df_label'] = $this->_('Now!'); } if ($this->dateFactor) { $today = new \MUtil_Date(); $this->dateFactorChanges['D'] = $this->dateCurrentStart->diffDays($today); $this->dateFactorChanges['W'] = $this->dateCurrentStart->diffWeeks($today); $this->dateFactorChanges['M'] = $this->dateCurrentStart->diffMonths($today); $this->dateFactorChanges['Y'] = $this->dateCurrentStart->diffYears($today); } else { $this->dateFactorChanges = array_fill_keys(array('D', 'W', 'M', 'Y'), 0); } // \MUtil_Echo::track($requiredRows); // \MUtil_Echo::rs($start, $end, $where); $select = new \Zend_Db_Select($this->db); $select->from($this->dataTableName, $groupby + $this->getDbFields()); $select->where($where); $select->group($groupby); $this->processSelect($select); // \MUtil_Echo::r((string) $select); $model = new \MUtil_Model_SelectModel($select, $this->dataTableName); // Display by column cannot use formatFunction as it is a simple repeater // $model->set('duration_avg', 'formatFunction', $this->util->getLocalized()->formatNumber); $transformer = new \MUtil_Model_Transform_RequiredRowsTransformer(); $transformer->setDefaultRow($this->getDefaultRow()); $transformer->setRequiredRows($requiredRows); $transformer->setKeyItemCount($keyCount); $model->addTransformer($transformer); return $model; }
Creates the base model. @return \MUtil_Model_SelectModel
entailment
protected function getDefaultRow() { $results = array(); foreach ($this->getFields() as $name => $field) { $results[$name] = $field->getDefault(); } return $results; }
Returns defaults for all field values. Can be overruled. @return array An array with appropriate default values for use in \MUtil_Model_Transform_RequiredRowsTransformer
entailment
public function getFilter(\Zend_Controller_Request_Abstract $request, array $filter = array(), $dateField = null) { $this->_actionKey = $request->getActionKey(); // \MUtil_Echo::r($filter, __CLASS__ . '->' . __FUNCTION__ .' 1'); $filter = $this->processFilter($request, $filter); if ($filter) { $model = $this->getModel(); $model->addFilter($filter); } // \MUtil_Echo::r($filter, __CLASS__ . '->' . __FUNCTION__ . ' 2'); $newfilter = $filter; if ($this->dateCurrentStart && $this->dateCurrentEnd) { if (null === $dateField) { $dateField = $this->dateFrom; } $start = $this->dateCurrentStart->getIso(); $end = $this->dateCurrentEnd->getIso(); $newfilter[] = "$dateField BETWEEN '$start' AND '$end'"; } if ($this->dateGroup) { $fields = $this->getFields(); if (isset($fields[$this->dateGroup])) { if ($groupfilter = $fields[$this->dateGroup]->getFilter()) { $newfilter[] = $groupfilter; } } } return $newfilter; }
Prcesses the filter for the date selector and return the filter to use instead @param \Zend_Controller_Request_Abstract $request @param array $filter @param string $dateField @return array The new complete filter to use
entailment
protected function processFilter(\Zend_Controller_Request_Abstract $request, array $filter) { $defaults = $this->getDefaultSearchData(); $this->dateFactor = $this->processFilterName(self::DATE_FACTOR, $request, $filter, $defaults); $this->dateGroup = $this->processFilterName(self::DATE_GROUP, $request, $filter, $defaults); $this->dateType = $this->processFilterName(self::DATE_TYPE, $request, $filter, $defaults); unset($filter[self::DATE_FACTOR], $filter[self::DATE_GROUP], $filter[self::DATE_TYPE]); $model = $this->getModel(); return $filter; }
Processing of filter, can be overriden. @param \Zend_Controller_Request_Abstract $request @param array $filter @return array
entailment
public function checkRegistryRequestsAnswers() { $this->escort = \GemsEscort::getInstance(); //Load the dbaModel $model = new \Gems_Model_DbaModel($this->db, $this->escort->getDatabasePaths()); if ($this->project->databaseFileEncoding) { $model->setFileEncoding($this->project->databaseFileEncoding); } $this->dbaModel = $model; return true; }
Now we have the requests answered, add the DatabasePatcher as it needs the db object @return boolean
entailment
protected function _getPasswordRules(array $current, array $codes, array &$rules) { foreach ($current as $key => $value) { if (is_array($value)) { // Only act when this is in the set of key values if (isset($codes[strtolower($key)])) { $this->_getPasswordRules($value, $codes, $rules); } } else { $rules[$key] = $value; } } }
Add recursively the rules active for this specific set of codes. @param array $current The current (part)sub) array of $this->passwords to check @param array $codes An array of code names that identify rules that should be used only for those codes. @param array $rules The array that stores the activated rules. @return void
entailment
public function checkRequiredValues() { $missing = array(); foreach ($this->requiredKeys as $key => $names) { if (is_array($names)) { if (! ($this->offsetExists($key) && $this->offsetGet($key))) { $subarray = array(); } else { $subarray = $this->offsetGet($key); } foreach ($names as $name) { if (! isset($subarray[$name])) { $missing[] = $key . '.' . $name; } } } else { if (! ($this->offsetExists($names) && $this->offsetGet($names))) { $missing[] = $names; } } } // Chek for https if (!\MUtil_Https::on()) { if ($this->isHttpsRequired()) { \MUtil_Https::enforce(); } } if ($missing) { if (count($missing) == 1) { $error = sprintf("Missing required project setting: '%s'.", reset($missing)); } else { $error = sprintf("Missing required project settings: '%s'.", implode("', '", $missing)); } throw new \Gems_Exception_Coding($error); } $superPassword = $this->getSuperAdminPassword(); if (('production' === APPLICATION_ENV || 'acceptance' === APPLICATION_ENV) && $this->getSuperAdminName() && $superPassword) { if (strlen($superPassword) < $this->minimumSuperPasswordLength) { $error = sprintf("Project setting 'admin.pwd' is shorter than %d characters. That is not allowed.", $this->minimumSuperPasswordLength); throw new \Gems_Exception_Coding($error); } } }
This function checks for the required project settings. Overrule this function or the $requiredParameters to add extra required settings. @see $requiredParameters @return void
entailment
public function decrypt($input) { if (! $input) { return $input; } $methods = $this->getEncryptionMethods(); if (':' == $input[0]) { list($empty, $mkey, $base64) = explode(':', $input, 3); if (! isset($methods[$mkey])) { $error = sprintf("Encryption method '%s' not defined in projec.ini.", $mkey); throw new \Gems_Exception_Coding($error); } $method = $methods[$mkey]; } else { $mkey = 'mcrypt'; $base64 = $input; $method = $mkey; } $decoded = base64_decode($base64); if ('mcrypt' == $method) { $output = $this->decryptMcrypt($decoded); } elseif ('null' == $method) { $output = $base64; } else { $output = $this->decryptOpenSsl($decoded, $method); } if (false === $output) { return $input; } else { return $output; } }
Decrypt a string encrypted with encrypt() @param string $input String to decrypt @return decrypted string
entailment
protected function decryptMcrypt($input) { $ivlen = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); $iv = substr($input, 0, $ivlen); $key = md5($this->offsetExists('salt') ? $this->offsetGet('salt') : 'vadf2646fakjndkjn24656452vqk'); // Remove trailing zero bytes! return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, substr($input, $ivlen), MCRYPT_MODE_CBC, $iv), "\0"); }
Decrypt a string encrypted with encrypt() @param string $input String to decrypt @return string decrypted string of false
entailment
protected function decryptOpenSsl($input, $method) { $ivlen = openssl_cipher_iv_length($method); $iv = substr($input, 0, $ivlen); $key = $this->getEncryptionSaltKey(); return openssl_decrypt(substr($input, $ivlen), $method, $key, 0, $iv); }
Reversibly encrypt a string @param string $input String to decrypt @param string $method The cipher method, one of openssl_get_cipher_methods(). @return string decrypted string of false
entailment
public function encrypt($input) { if (! $input) { return $input; } $methods = $this->getEncryptionMethods(); $method = reset($methods); $mkey = key($methods); if ('mcrypt' == $method) { $result = $this->encryptMcrypt($input); } elseif ('null' == $method) { $result = $input; } else { $result = $this->encryptOpenSsl($input, $method); } return ":$mkey:" . base64_encode($result); }
Reversibly encrypt a string @param string $input String to decrypt @return encrypted string
entailment
protected function encryptMcrypt($input) { $ivlen = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($ivlen, MCRYPT_RAND); $key = $this->getEncryptionSaltKey(); return $iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $input, MCRYPT_MODE_CBC, $iv); }
Reversibly encrypt a string @param string $input String to encrypt @return encrypted string
entailment
protected function encryptOpenSsl($input, $method) { $ivlen = openssl_cipher_iv_length($method); $iv = openssl_random_pseudo_bytes($ivlen); $key = $this->getEncryptionSaltKey(); return $iv . openssl_encrypt($input, $method, $key, 0, $iv); }
Reversibly encrypt a string @param string $input String to encrypt @param string $method The cipher method, one of openssl_get_cipher_methods(). @return encrypted string
entailment
public function getAskDelay(\Zend_Controller_Request_Abstract $request, $wasAnswered) { if ($request->getParam('delay_cancelled', false)) { return -1; } $delay = $request->getParam('delay', null); if (null != $delay) { return $delay; } if ($wasAnswered) { if ($this->offsetExists('askNextDelay')) { return $this->offsetGet('askNextDelay'); } } else { if ($this->offsetExists('askDelay')) { return $this->offsetGet('askDelay'); } } return -1; }
Calculate the delay between surveys being asked for this request. Zero means forward at once, a negative value means wait forever. @param \Zend_Controller_Request_Abstract $request @param boolean $wasAnswered When true use the ask delay @return int -1 means waiting indefinitely
entailment
public function getConsoleRole() { if ($this->offsetExists('console')) { $cons = $this->offsetGet('console'); if (isset($cons['role'])) { return $cons['role']; } } return false; }
Get the specified role for the console user from the project setttings. If the role is not defined (or does not exist) running GemsTracker in console mode requires the users login name, organization and password to be specified on the command line. @return string
entailment
public function getCronLogfile() { if (! ($this->offsetExists('cron') && isset($this->cron['logfile']))) { return null; } $file = trim($this->cron['logfile']); if (\MUtil_File::isRootPath($file)) { return $file; } return GEMS_ROOT_DIR . '/var/logs/' . $file; }
The logfile for cron jobs @return string
entailment
public function getEmailBounce() { if ($this->offsetExists('email') && isset($this->email['bounce'])) { return (boolean) $this->email['bounce']; } return false; }
Should all mail be bounced to the sender? @return boolean
entailment
public function getEmailCreateAccount() { if ($this->offsetExists('email') && isset($this->email['createAccountTemplate'])) { return (string) $this->email['createAccountTemplate']; } return false; }
The default Email Template for Create Account @return string Template Code
entailment
public function getEmailMultiLanguage() { if ($this->offsetExists('email') && isset($this->email['multiLanguage'])) { return (boolean) $this->email['multiLanguage']; } else { return true; } }
Check if multiple language mail templates is supported @return boolean
entailment
public function getEmailResetPassword() { if ($this->offsetExists('email') && isset($this->email['resetPasswordTemplate'])) { return (string) $this->email['resetPasswordTemplate']; } return false; }
The default Email template for Reset password @return string Template Code
entailment
public function getLogLevel() { if (isset($this['logLevel'])) { $logLevel = $this['logLevel']; } else { $logLevel = $this->getLogLevelDefault(); } return (int) $logLevel; }
Get the logLevel to use with the \Gems_Log Default settings is for development and testing environment to use \Zend_Log::DEBUG and for all other environments to use the \Zend_Log::ERR level. This can be overruled by specifying a logLevel in the project.ini Using a level higher than \Zend_Log::ERR will output full error messages, traces and request info to the logfile. Please be aware that this might introduce a security risk as passwords might be written to the logfile in plain text. @return int The loglevel to use
entailment
public function getLogLevelDefault() { if ('development' == APPLICATION_ENV || 'testing' == APPLICATION_ENV) { $logLevel = \Zend_Log::DEBUG; } else { $logLevel = \Zend_Log::ERR; } return $logLevel; }
Return the default logLevel to use with the \Gems_Log Default settings is for development and testing environment to use \Zend_Log::DEBUG and for all other environments to use the \Zend_Log::ERR level. This can be overruled by specifying a logLevel in the project.ini @return int The loglevel to use
entailment
public function getLongDescription($language) { if (isset($this['longDescr' . ucfirst($language)])) { return $this['longDescr' . ucfirst($language)]; } if (isset($this['longDescr'])) { return $this['longDescr']; } }
Return a long description, in the correct language if available @param string $language Iso code languahe @return string
entailment
public function getMailFields() { $result['project'] = $this->getName(); $result['project_bcc'] = $this->getEmailBcc(); $result['project_description'] = $this->getDescription(); $result['project_from'] = $this->getFrom(); return $result; }
Array of field name => values for sending E-Mail @return array
entailment
public function getMonitorFrom($name = null) { if ($name) { if (isset($this['monitor'], $this['monitor'][$name], $this['monitor'][$name]['from']) && trim($this['monitor'][$name]['from'])) { return $this['monitor'][$name]['from']; } } if (isset($this['monitor'], $this['monitor']['default'], $this['monitor']['default']['from']) && trim($this['monitor']['default']['from'])) { return $this['monitor']['default']['from']; } $email = $this->getSiteEmail(); if ($email) { return $email; } return '[email protected]'; }
Get the form address for monitor messages @param string $name Optional section name @return string
entailment
public function getMonitorPeriod($name = null) { if ($name) { if (isset($this['monitor'], $this['monitor'][$name], $this['monitor'][$name]['period']) && strlen(trim($this['monitor'][$name]['period']))) { return $this['monitor'][$name]['period']; } } if (isset($this['monitor'], $this['monitor']['default'], $this['monitor']['default']['period']) && strlen(trim($this['monitor']['default']['period']))) { return $this['monitor']['default']['period']; } return '25h'; }
Get the period for monitor messages, optionally for a name @param string $name Optional section name @return string
entailment
public function getMonitorTo($name = null) { if ($name) { if (isset($this['monitor'], $this['monitor'][$name], $this['monitor'][$name]['to']) && trim($this['monitor'][$name]['to'])) { return $this['monitor'][$name]['to']; } } if (isset($this['monitor'], $this['monitor']['default'], $this['monitor']['default']['to']) && trim($this['monitor']['default']['to'])) { return $this['monitor']['default']['to']; } return null; }
Get the to addresses for monitor messages, optionally for a name @param string $name Optional section name @return string
entailment
public function getPasswordRules(array $codes) { // Process the codes array to a format better used for filtering $codes = array_change_key_case(array_flip(array_filter($codes))); // \MUtil_Echo::track($codes); $rules = array(); if ($this->offsetExists('passwords') && is_array($this->passwords)) { $this->_getPasswordRules($this->passwords, $codes, $rules); } return $rules; }
Get the rules active for this specific set of codes. @param array $codes An array of code names that identify rules that should be used only for those codes. @return array
entailment
public function getMetaHeaders() { if ($this->offsetExists('meta') && is_array($this->meta)) { $meta = $this->meta; } else { $meta = []; } if (!array_key_exists('Content-Type', $meta)) { $meta['Content-Type'] = 'text/html;charset=UTF-8'; } // Remove null/empty values, this allow you to remove the Content-Type by making it empty. return array_filter($meta); }
Get additional meta headers @return array Of http-equiv => content values for meta tags
entailment
public function getResponseDatabase() { if ((!$this->_responsesDb) && $this->hasResponseDatabase()) { $adapter = $this['responses']['adapter']; if (isset($this['responses'], $this['responses']['params'])) { $options = $this['responses']['params']; if (! isset( $options['charset'], $options['host'], $options['dbname'], $options['username'], $options['password'] )) { $db = \Zend_Registry::get('db'); if ($db instanceof \Zend_Db_Adapter_Abstract) { $options = $options + $db->getConfig(); } } $this->_responsesDb = \Zend_Db::factory($adapter, $options); } else { $db = \Zend_Registry::get('db'); if ($db instanceof \Zend_Db_Adapter_Abstract) { $this->_responsesDb = $db; } } } return $this->_responsesDb; }
The response database with a table with one row for each token answer. @return \Zend_Db_Adapter_Abstract
entailment
public function getResponseHeaders() { if ($this->offsetExists('headers') && is_array($this->headers)) { $headers = $this->headers; } else { $headers = []; } if (!array_key_exists('X-UA-Compatible', $headers)) { $headers['X-UA-Compatible'] = 'IE=edge,chrome=1'; } // Remove null/empty values, this allow you to remove the X-UA-Compatible by making it empty. return array_filter($headers); }
Get additional response headers @return array Of name => value for HTTP response headers
entailment
public function getSessionTimeOut() { if ($this->offsetExists('session') && isset($this->session['idleTimeout'])) { return $this->session['idleTimeout']; } else { return $this->defaultSessionTimeout; } }
Timeout for sessions in seconds. @return int
entailment
public function getStaffBounce() { if ($this->offsetExists('email') && isset($this->email['staffBounce'])) { return (boolean) $this->email['staffBounce']; } return $this->getEmailBounce(); }
Should staff mail be bounced to the sender? @return boolean
entailment
public function getSuperAdminTwoFactorIpExclude() { if ($this->offsetExists('admin') && isset($this->admin['2fa'], $this->admin['2fa']['exclude'])) { return trim($this->admin['2fa']['exclude']); } }
Get the super admin two factor authentication ip exclude range @return string
entailment
public function getSuperAdminTwoFactorKey() { if ($this->offsetExists('admin') && isset($this->admin['2fa'], $this->admin['2fa']['key'])) { return trim($this->admin['2fa']['key']); } }
Get the super admin two factor authentication key @return string
entailment
public function getValueHash($value, $algorithm = null) { $salt = $this->offsetExists('salt') ? $this->offsetGet('salt') : ''; if (false === strpos($salt, '%s')) { $salted = $salt . $value; } else { $salted = sprintf($salt, $value); } // \MUtil_Echo::track($value, md5($salted)); if (null == $algorithm) { return md5($salted, false); } return hash($algorithm, $value, false); }
Returns a salted hash optionally using the specified hash algorithm @param string $value The value to hash @param string $algoritm Optional, hash() algorithm; uses md5() otherwise @return string The salted hexadecimal hash, length depending on the algorithm (32 for md5, 128 for sha512.
entailment
public function hasAnySupportUrl() { return isset($this['contact']) && ( isset($this['contact']['docsUrl']) || isset($this['contact']['forumUrl']) || isset($this['contact']['manualUrl']) || isset($this['contact']['supportUrl']) ); }
True at least one support url exists. @return boolean @deprecated Since 1.8.2 No longer in use
entailment