sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function createModel($detailed, $action)
{
$model = $this->loader->getModels()->getStaffModel(false);
$model->applyOwnAccountEdit();
return $model;
} | Creates a model for getModel(). Called only for each new $action.
The parameters allow you to easily adapt the model to the current action. The $detailed
parameter was added, because the most common use of action is a split between detailed
and summarized actions.
@param boolean $detailed True when the current action is not in $summarizedActions.
@param string $action The current action.
@return \MUtil_Model_ModelAbstract | entailment |
public function overviewAction()
{
if ($this->overviewSnippets) {
$params = $this->_processParameters($this->overviewParameters);
$this->addSnippets($this->overviewSnippets, $params);
}
} | Show log overview for the current user | entailment |
public function showLogAction()
{
if ($this->showLogSnippets) {
$params = $this->_processParameters($this->showLogParameters);
$this->addSnippets($this->showLogSnippets, $params);
}
} | Show a log item | entailment |
public function twoFactorAction()
{
if ($this->twoFactorSnippets) {
$params = $this->_processParameters($this->twoFactorParameters);
$this->addSnippets($this->twoFactorSnippets, $params);
}
} | Set two factor authentication | entailment |
protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model)
{
$filter[] = $this->db->quoteInto(
"gr2t_id_respondent_track IN (
SELECT gr2t2a_id_respondent_track
FROM gems__respondent2track2appointment
WHERE gr2t2a_id_appointment = ?)",
$this->request->getParam(\Gems_Model::APPOINTMENT_ID)
);
// \MUtil_Model::$verbose = true;
$model->setFilter($filter);
$this->processSortOnly($model);
} | Overrule to implement snippet specific filtering and sorting.
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function exportFieldData(array $data)
{
$replacements = array("\n" => '\\n', "\r" => '\\r', "\t" => '\\t');
foreach ($data as &$item) {
$item = strtr((string) $item, $replacements);
}
fwrite($this->_file, implode("\t", $data) . "\r\n");
} | Write the array to the output to file
@param array $data | entailment |
protected function exportTypeHeader($header, $prependNewline = true)
{
if ($prependNewline) {
fwrite($this->_file, "\r\n");
}
fwrite($this->_file, "$header\r\n");
} | Write the export type to the output
@param array $data With headers as the keys | entailment |
public function setBatch(\MUtil_Task_TaskBatch $batch)
{
parent::setBatch($batch);
$this->_file = $batch->getVariable('file');
return $this;
} | Sets the batch this task belongs to
This method will be called from the \Gems_Task_TaskRunnerBatch upon execution of the
task. It allows the task to communicate with the batch queue.
@param \MUtil_Task_TaskBatch $batch
@return \MUtil_Task_TaskInterface (continuation pattern) | entailment |
protected function translateFieldCode(FieldsDefinition $fields, $fieldId)
{
$field = $fields->getField($fieldId);
if ($field instanceof FieldInterface) {
return '{f' . $field->getOrder() . '}';
}
return $fieldId;
} | Translate a field code to the field order number
@param FieldsDefinition $fields
@param string $fieldId
@return string {order} or original value | entailment |
public function isTwoFactorRequired($ipAddress, $hasKey, Group $group = null)
{
if ($group) {
return $group->isTwoFactorRequired($ipAddress, $hasKey);
}
return false;
} | Should this user be authorized using two factor authentication?
@param string $ipAddress
@param boolean $hasKey
@param Group $group
@return boolean | entailment |
protected function addFormElements(\Zend_Form $form)
{
// Veld inlognaam
$element = $form->createElement('text', 'email');
$element->setLabel($this->_('Your E-Mail address'))
->setAttrib('size', 30)
->setRequired(true)
->addValidator('SimpleEmail');
$form->addElement($element);
return $element;
} | Add the elements to the form
@param \Zend_Form $form | entailment |
protected function saveData()
{
$this->addMessage($this->_('Your e-mail address has been unsubscribed'));
$sql = "SELECT gr2o_patient_nr, gr2o_id_organization, gr2o_id_user, gr2o_mailable FROM gems__respondent2org
WHERE gr2o_email = ? AND gr2o_id_organization = ?";
$row = $this->db->fetchRow($sql, [$this->formData['email'], $this->currentOrganization->getId()]);
if ($row) {
if ($row['gr2o_mailable']) {
$row['gr2o_mailable'] = 0;
$row['gr2o_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
$row['gr2o_changed_by'] = $row['gr2o_id_user'];
$where = $this->db->quoteInto("gr2o_patient_nr = ?", $row['gr2o_patient_nr']) . " AND " .
$this->db->quoteInto("gr2o_id_organization = ?", $row['gr2o_id_organization']);
$this->db->update('gems__respondent2org', $row, $where);
return 1;
} else {
return 0;
}
} else {
return 0;
}
} | Hook containing the actual save code.
@return int The number of "row level" items changed | entailment |
public function checkRegistryRequestsAnswers()
{
$escort = \GemsEscort::getInstance();
//As an upgrade almost always includes executing db patches, make a DatabasePatcher object available
$this->patcher = new \Gems_Util_DatabasePatcher($this->db, 'patches.sql', $escort->getDatabasePaths(), $this->project->databaseFileEncoding);
return parent::checkRegistryRequestsAnswers();
} | Now we have the requests answered, add the DatabasePatcher as it needs the db object
@return boolean | entailment |
public function send(Message $mail): void
{
if ($this->bounceMail !== null) {
// Append this commands cause bounce email
$this->commandArgs = sprintf('-f%s', $this->bounceMail);
}
// Trigger event
$this->onSend($this, $mail);
// Delegate to original mailer
parent::send($mail);
} | Sends email | entailment |
public function execute($errors = null)
{
$batch = $this->getBatch();
foreach ((array) $errors as $error) {
$batch->addToCounter('import_errors');
$batch->addMessage($error);
}
} | 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 addButtons(\Gems_Menu_MenuList $menuList)
{
$menuList->addByController('respondent', 'show', $this->_('Show respondent'))
->addByController('track', 'index', $this->_('Show tracks'))
->addByController('track', 'show-track', $this->_('Show track'))
->addByController('track', 'show', $this->_('Show token'))
->addCurrentSiblings()
->addCurrentChildren();
} | Set the menu items (allows for overruling in subclasses)
@param \Gems_Menu_MenuList $menuList | entailment |
protected function _cleanData($values)
{
$linebreak = $this->getLinebreak();
if (is_array($values)) {
ksort($values);
}
$retVal = '<div class="pre">';
foreach ($values as $key => $value)
{
$key = htmlspecialchars($key);
if (is_numeric($value)) {
$retVal .= $key.' => '.$value.$linebreak;
}
else if (is_string($value)) {
$retVal .= $key.' => \''.htmlspecialchars($value).'\''.$linebreak;
}
else if (is_array($value))
{
$retVal .= $key.' => '.self::_cleanData($value);
}
else if (is_object($value))
{
$retVal .= $key.' => '.get_class($value).' Object()'.$linebreak;
}
else if (is_null($value))
{
$retVal .= $key.' => NULL'.$linebreak;
}
}
return $retVal.'</div>';
} | Transforms data into readable format
@param array $values
@return string | entailment |
public function loadDefaultDecorators()
{
if ($this->loadDefaultDecoratorsIsDisabled()) {
return $this;
}
$decorators = $this->getDecorators();
if (empty($decorators)) {
$this->addDecorator('FormElements');
if (\MUtil_Bootstrap::enabled() !== true) {
$this->addDecorator(array('table' => 'HtmlTag'), array('tag' => 'table', 'class'=>'formTable'));
}
$this->addDecorator(array('tab' => 'HtmlTag'), array('tag' => 'div', 'class' => 'displayGroup'))
->addDecorator('TabPane', array('jQueryParams' => array('containerId' => 'mainForm',
'title' => $this->getAttrib('title')),
'class' => $this->getAttrib('class')));
}
return $this;
} | Load default decorators
@return void | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
$elements[] = new \Zend_Form_Element_Hidden(\MUtil_Model::REQUEST_ID1);
$elements[] = new \Zend_Form_Element_Hidden(\MUtil_Model::REQUEST_ID2);
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 getFixedParams()
{
$neededParams = parent::getFixedParams();
$neededParams[] = \MUtil_Model::REQUEST_ID1;
$neededParams[] = \MUtil_Model::REQUEST_ID2;
return $neededParams;
} | Return the fixed parameters
Normally these are the hidden parameters like ID
@return array | entailment |
public function filterAnswers(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model, array $currentNames)
{
if (! $this->token->isCompleted()) {
return $currentNames;
}
$answers = $this->token->getRawAnswers();
$onTop = array();
// \MUtil_Echo::track($answers);
foreach($answers as $name => $value) {
if ($value === 'Y') {
$onTop[$name] = $name;
} else {
// Split on last underscore instead of first
if ($i = strrpos($name, '_')) {
if (isset($onTop[substr($name, 0, $i)])) {
$onTop[$name] = $name;
}
}
}
}
$currentNames = array_combine($currentNames, $currentNames);
// \MUtil_Echo::track($onTop, $onTop + $currentNames, $currentNames);
return $this->restoreHeaderPositions($model, $onTop + $currentNames);
} | This function is called in addBrowseTableColumns() to filter the names displayed
by AnswerModelSnippetGeneric.
@see \Gems_Tracker_Snippets_AnswerModelSnippetGeneric
@param \MUtil_Model_Bridge_TableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@param array $currentNames The current names in use (allows chaining)
@return array Of the names of labels that should be shown | entailment |
public function beforeDisplay()
{
if ($this->_csrf) {
$this->_csrf->initCsrfToken();
}
$links = $this->getMenuList();
if (\MUtil_Bootstrap::enabled()) {
if ($links) {
$element = $this->_form->createElement('html', 'menuLinks');
$element->setValue($links);
$element->setOrder(999);
$this->_form->addElement($element);
}
} else {
$table = new \MUtil_Html_TableElement(array('class' => $this->class));
$table->setAsFormLayout($this->_form, true, true);
// There is only one row with formLayout, so all in output fields get class.
$table['tbody'][0][0]->appendAttrib('class', $this->labelClass);
if ($links) {
$table->tf(); // Add empty cell, no label
$table->tf($links);
}
}
} | Perform some actions on the form, right before it is displayed but already populated
Here we add the table display to the form.
@return \Zend_Form | entailment |
protected function addBrowseColumn3(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
if (isset($this->searchFilter['grc_success']) && (! $this->searchFilter['grc_success'])) {
$model->set('grc_description', 'label', $this->_('Rejection code'));
$bridge->addSortable('grc_description');
} elseif (! isset($this->searchFilter[\MUtil_Model::REQUEST_ID2])) {
$bridge->addSortable('gr2o_id_organization');
}
} | Add first columns (group) from the model to the bridge that creates the browse table.
You can actually add more than one column in this function, but just call all four functions
with the default columns in each
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 |
protected function addBrowseColumn4(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
if ($model->hasAlias('gems__respondent2track')) {
$br = \MUtil_Html::create('br');
$model->set('gtr_track_name', 'label', $this->_('Track'));
$model->set('gr2t_track_info', 'label', $this->_('Track description'));
$items = $this->findMenuItems('track', 'show-track');
$track = 'gtr_track_name';
if ($items) {
$menuItem = reset($items);
if ($menuItem instanceof \Gems_Menu_MenuAbstract) {
$href = $menuItem->toHRefAttribute(
$this->request,
$bridge,
array('gr2t_id_respondent_track' => $bridge->gr2t_id_respondent_track)
);
$track = array();
$track[0] = \MUtil_Lazy::iif($bridge->gr2t_id_respondent_track,
\MUtil_Html::create()->a(
$href,
$bridge->gtr_track_name,
array('onclick' => "event.cancelBubble = true;")
)
);
$track[1] = $bridge->createSortLink('gtr_track_name');
}
}
$bridge->addMultiSort($track, $br, 'gr2t_track_info');
}
} | Add first columns (group) from the model to the bridge that creates the browse table.
You can actually add more than one column in this function, but just call all four functions
with the default columns in each
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 |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
// make sure search results are highlighted
$this->applyTextMarker();
parent::addBrowseTableColumns($bridge, $model);
$bridge->getTable()->addColumn(null,$this->_('Action'));
$td = $bridge->getTable()->tbody()->getLast()->getLast();
$td->class = 'fileAction';
foreach ($this->getFileIcons($bridge) as $icon => $item) {
if (is_array($item)) {
list($menuItem, $other) = $item;
} else {
$menuItem = $item;
$other = null;
}
$this->addFileImage($td, $bridge, $icon, $menuItem, $other);
}
} | 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 |
protected function addPaginator(\MUtil_Html_TableElement $table, \Zend_Paginator $paginator)
{
$table->tfrow()->pagePanel($paginator, $this->request, $this->translate, array('baseUrl' => $this->baseUrl));
} | Add the paginator panel to the table.
Only called when $this->browse is true. Overrule this function
to define your own method.
$param \Zend_Paginator $paginator | entailment |
protected function getFileIcons(\MUtil_Model_Bridge_TableBridge $bridge)
{
$onDelete = new \MUtil_Html_OnClickArrayAttribute();
$onDelete->addConfirm(\MUtil_Lazy::call(
'sprintf',
$this->_("Are you sure you want to delete '%s'?"),
$bridge->relpath
));
return array(
'process.png' => $this->findMenuItem($this->request->getControllerName(), 'import'),
'download.png' => $this->findMenuItem($this->request->getControllerName(), 'download'),
'eye.png' => $this->findMenuItem($this->request->getControllerName(), 'show'),
'edit.png' => $this->findMenuItem($this->request->getControllerName(), 'edit'),
'delete.png' => array(
$this->findMenuItem($this->request->getControllerName(), 'delete'),
$onDelete,
),
);
} | Get the file icons
@param \MUtil_Model_Bridge_TableBridge $bridge
@return array $icon => $menuItem or array($menuItem, $other) | entailment |
protected function addFillerSelect(array &$elements, $data, $elementId = 'fillerfilter')
{
$elements[] = null;
if (isset($data[$this->trackFieldId]) && !empty($data[$this->trackFieldId])) {
$trackId = (int) $data[$this->trackFieldId];
} else {
$trackId = -1;
}
$sql = $this->db->quoteInto("SELECT ggp_name, ggp_name as label FROM (
SELECT DISTINCT ggp_name
FROM gems__groups INNER JOIN gems__surveys ON ggp_id_group = gsu_id_primary_group
INNER JOIN gems__rounds ON gsu_id_survey = gro_id_survey
INNER JOIN gems__tracks ON gro_id_track = gtr_id_track
WHERE ggp_group_active = 1 AND
gro_active=1 AND
gtr_active=1 AND
gtr_id_track = ?
UNION ALL
SELECT DISTINCT gtf_field_name as ggp_name
FROM gems__track_fields
WHERE gtf_field_type = 'relation' AND
gtf_id_track = ?
) AS tmpTable
ORDER BY ggp_name", $trackId);
$elements[$elementId] = $this->_createSelectElement($elementId, $sql, $this->_('(all fillers)'));
} | Add filler select to the elements array
@param array $elements
@param array $data
@param string $elementId | entailment |
protected function addOrgSelect(array &$elements, $data, $elementId = 'gto_id_organzation')
{
$orgs = $this->currentUser->getRespondentOrganizations();
if (count($orgs) > 1) {
if ($this->orgIsMultiCheckbox) {
$elements[$elementId] = $this->_createMultiCheckBoxElements($elementId, $orgs, ' ');
} else {
$elements[$elementId] = $this->_createSelectElement($elementId, $orgs, $this->_('(all organizations)'));
}
}
} | Add organization select to the elements array
@param array $elements
@param array $data
@param string $elementId | entailment |
protected function addPeriodSelect(array &$elements, $data)
{
$dates = array(
'gr2t_start_date' => $this->_('Track start'),
'gr2t_end_date' => $this->_('Track end'),
'gto_valid_from' => $this->_('Valid from'),
'gto_valid_until' => $this->_('Valid until'),
);
// $dates = 'gto_valid_from';
$this->_addPeriodSelectors($elements, $dates, 'gto_valid_from');
} | Add period select to the elements array
@param array $elements
@param array $data | entailment |
protected function addTrackSelect(array &$elements, $data, $elementId = 'gto_id_track')
{
// Store for use in addFillerSelect
$this->trackFieldId = $elementId;
$orgs = $this->currentUser->getRespondentOrganizations();
$tracks = $this->util->getTrackData()->getTracksForOrgs($orgs);
if (count($tracks) > 1) {
$elements[$elementId] = $this->_createSelectElement($elementId, $tracks, $this->_('(select a track)'));
$elements[$elementId]->setAttrib('onchange', 'this.form.submit();');
}
} | Add track select to the elements array
@param array $elements
@param array $data
@param string $elementId | entailment |
public function getAuthAdapter(\Gems_User_User $user, $password)
{
$config = $this->project->getLdapSettings();
$adapter = new LdapAdapter();
// \MUtil_Echo::track($config);
foreach ($config as $server) {
$adapter->setOptions([$server]);
if (isset($server['accountDomainNameShort'])) {
$userName = $server['accountDomainNameShort'] . '\\' . $user->getLoginName();
} else {
$userName = $user->getLoginName();
}
$adapter->setUsername($userName)
->setPassword($password);
}
return $adapter;
} | Returns an initialized Zend\Authentication\Adapter\AdapterInterface
@param \Gems_User_User $user
@param string $password
@return Zend\Authentication\Adapter\AdapterInterface | entailment |
public function checkRegistryRequestsAnswers()
{
if (isset($this->project->tokens['chars'])) {
$this->tokenChars = $this->project->tokens['chars'];
} else {
throw new \Gems_Exception_Coding('Required project.ini setting "tokens.chars" is missing.');
}
if (isset($this->project->tokens['format'])) {
$this->tokenFormat = $this->project->tokens['format'];
$this->tokenDisplayFormat = str_replace("\t", '\\', str_replace(array('\\\\', '\\'), array("\t", ''), $this->tokenFormat));
} else {
throw new \Gems_Exception_Coding('Required project.ini setting "tokens.format" is missing.');
}
if (isset($this->project->tokens['from'])) {
$this->tokenFrom = $this->project->tokens['from'];
if (isset($this->project->tokens['to'])) {
$this->tokenTo = $this->project->tokens['to'];
} else {
$this->tokenTo = null;
}
if (strlen($this->tokenFrom) != strlen($this->tokenTo)) {
throw new \Gems_Exception_Coding('Project.ini setting "token.from" does not have the same length as argument "token.to".');
}
} else {
$this->tokenFrom = null;
$this->tokenTo = null;
}
if (isset($this->project->tokens['case'])) {
$this->tokenCaseSensitive = $this->project->tokens['case'];
} else {
$this->tokenCaseSensitive = ! ($this->tokenChars === strtolower($this->tokenChars));
}
if (isset($this->project->tokens['reuse'])) {
$this->tokenReuse = intval($this->project->tokens['reuse']);
} else {
$this->tokenReuse = $this->_defaultReuse;
}
return true;
} | 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 createToken(array $tokenData, $userId)
{
$current = new \MUtil_Db_Expr_CurrentTimestamp();
$tokenData['gto_changed'] = $current;
$tokenData['gto_changed_by'] = $userId;
$tokenData['gto_created'] = $current;
$tokenData['gto_created_by'] = $userId;
// Wait till the last nanosecond with creating the token id
$tokenData['gto_id_token'] = $this->createTokenId();
$this->db->insert('gems__tokens', $tokenData);
if (\Gems_Tracker::$verbose) {
\MUtil_Echo::r($tokenData, 'Created token: ' . $tokenData['gto_id_token']);
}
return $tokenData['gto_id_token'];
} | Creates a new token with a new random token Id
@param array $tokenData
@param int $userId Id of the user who takes the action (for logging)
@return string The new token Id | entailment |
protected function createTokenId()
{
$max = strlen($this->tokenChars) - 1;
$len = strlen($this->tokenFormat);
do {
$out = '';
for ($i = 0; $i < $len; $i++) {
if ('\\' == $this->tokenFormat[$i]) {
$i++;
$out .= $this->tokenFormat[$i];
} else {
$out .= $this->tokenChars[mt_rand(0, $max)];
}
}
} while ($this->db->fetchOne('SELECT gto_id_token FROM gems__tokens WHERE gto_id_token = ?', $out));
return $out;
} | Generates a random token and checks for uniqueness
@return string A non-existing token | entailment |
public function filter($token)
{
// Apply replacements
if ($this->tokenFrom) {
$token = strtr($token, $this->tokenFrom, $this->tokenTo);
}
// If not case sensitive, convert to lowercase
if (! $this->tokenCaseSensitive) {
$token = strtolower($token);
}
// Filter out invalid chars
$tokenLength = strlen($token);
$filteredToken = '';
for ($tokenPos = 0; ($tokenPos < $tokenLength); $tokenPos++) {
if (strpos($this->tokenChars, $token[$tokenPos]) !== false) {
$filteredToken .= $token[$tokenPos];
}
}
// Now check against the format for fixed chars
$formatLength = strlen($this->tokenFormat);
$tokenLength = strlen($filteredToken);
$tokenPos = 0;
$resultToken = '';
for ($formatPos = 0; ($formatPos < $formatLength) && ($tokenPos < $tokenLength); $formatPos++) {
if ('\\' == $this->tokenFormat[$formatPos]) {
$formatPos++;
$resultToken .= $this->tokenFormat[$formatPos];
} else {
$resultToken .= $filteredToken[$tokenPos];
$tokenPos++;
}
}
// Separate extra chars with a space and a questionmark
if ($tokenPos < $tokenLength) {
$resultToken .= ' ?' . substr($filteredToken, $tokenPos);
}
return $resultToken;
} | Removes all unacceptable characters from the input token and inserts any fixed characters left out
@param string $token
@return string Reformatted token | entailment |
public function hasHtmlOutput()
{
$model = $this->getModel();
$data = $model->loadFirst();
$roles = $this->currentUser->getAllowedRoles();
//\MUtil_Echo::track($data);
// Perform access check here, before anything has happened!!!
if (isset($data['ggp_role']) && (! isset($roles[$data['ggp_role']]))) {
$this->addMessage($this->_('You do not have sufficient privilege to edit this group.'));
$this->afterSaveRouteUrl = array($this->request->getActionKey() => 'show');
$this->resetRoute = false;
return false;
}
$this->menu->getParameterSource()->offsetSet('ggp_role', $data['ggp_role']);
return parent::hasHtmlOutput();
} | 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 afterLoad()
{
if ($this->_data &&
$this->db instanceof \Zend_Db_Adapter_Abstract &&
!($this->_activities || $this->_procedures)) {
if ($this->_data['gaf_filter_text1']) {
$sqlActivites = "SELECT gaa_id_activity, gaa_id_activity
FROM gems__agenda_activities
WHERE gaa_active = 1 AND gaa_name LIKE '%s'
ORDER BY gaa_id_activity";
$this->_activities = $this->db->fetchPairs(sprintf(
$sqlActivites,
addslashes($this->_data['gaf_filter_text1']))
);
} else {
$this->_activities = true;
}
if ($this->_data['gaf_filter_text2'] || $this->_data['gaf_filter_text3']) {
$sqlProcedures = "SELECT gapr_id_procedure, gapr_id_procedure
FROM gems__agenda_procedures
WHERE gapr_active = 1 ";
if ($this->_data['gaf_filter_text2']) {
$sqlProcedures .= sprintf(
" AND gapr_name LIKE '%s' ",
addslashes($this->_data['gaf_filter_text2'])
);
}
if ($this->_data['gaf_filter_text3']) {
$sqlProcedures .= sprintf(
" AND gapr_name NOT LIKE '%s' ",
addslashes($this->_data['gaf_filter_text3'])
);
}
$sqlProcedures .= "ORDER BY gapr_id_procedure";
$this->_procedures = $this->db->fetchPairs($sqlProcedures);
} else {
$this->_procedures = true;
}
}
} | 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 getSqlAppointmentsWhere()
{
if ($this->_activities && ($this->_activities !== true)) {
$where = 'gap_id_activity IN (' . implode(', ', $this->_activities) . ')';
if ($this->_procedures !== true) {
$where .= ' AND ';
}
} else {
$where = '';
}
if ($this->_procedures && ($this->_procedures !== true)) {
$where .= 'gap_id_procedure IN (' . implode(', ', $this->_procedures) . ')';
} elseif ($where && (! $this->_procedures)) {
$where .= parent::NO_MATCH_SQL;
}
if ($where) {
return "($where)";
} else {
return parent::NO_MATCH_SQL;
}
} | Generate a where statement to filter the appointment model
@return string | entailment |
public function matchAppointment(\Gems_Agenda_Appointment $appointment)
{
if (true !== $this->_activities) {
if (! isset($this->_activities[$appointment->getActivityId()])) {
return false;
}
}
return isset($this->_procedures[$appointment->getProcedureId()]) || (true === $this->_procedures);
} | Check a filter for a match
@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean | entailment |
public function listClasses($classType, $paths, $nameMethod = 'getName')
{
$results = array();
foreach ($paths as $prefix => $path) {
$parts = explode('_', $prefix, 2);
if ($name = reset($parts)) {
$name = ' (' . $name . ')';
}
try {
$globIter = new \GlobIterator($path . DIRECTORY_SEPARATOR . '*.php');
} catch (\RuntimeException $e) {
// We skip invalid dirs
continue;
}
foreach($globIter as $fileinfo) {
$filename = $fileinfo->getFilename();
$className = $prefix . substr($filename, 0, -4);
$classNsName = '\\' . strtr($className, '_', '\\');
// Take care of double definitions
if (isset($results[$className])) {
continue;
}
if (! (class_exists($className, false) || class_exists($classNsName, false))) {
include($path . DIRECTORY_SEPARATOR . $filename);
}
if ((! class_exists($className, false)) && class_exists($classNsName, false)) {
$className = $classNsName;
}
$class = new $className();
if ($class instanceof $classType) {
if ($class instanceof \MUtil_Registry_TargetInterface) {
$this->applySource($class);
}
$results[$className] = trim($class->$nameMethod()) . $name;
}
// \MUtil_Echo::track($eventName);
}
}
natcasesort($results);
return $results;
} | Returns a list of selectable classes with an empty element as the first option.
@param string $classType The class or interface that must me implemented
@param array $paths Array of prefix => path to search
@param string $nameMEthod The method to call to get the name of the class
@return [] array of classname => name | entailment |
public function hasHtmlOutput()
{
return ($this->respondent instanceof \Gems_Tracker_Respondent) &&
$this->respondent->exists &&
(! ($this->multiTracks || ($this->respondentTrack instanceof \Gems_Tracker_RespondentTrack)));
} | 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 setAfterSaveRoute()
{
// Default is just go to the index
if ($this->routeAction && ($this->request->getActionName() !== $this->routeAction)) {
$this->afterSaveRouteUrl = array(
$this->request->getControllerKey() => 'track',
$this->request->getActionKey() => $this->routeAction,
);
if ($this->afterSaveRouteKeys) {
// Set the key identifiers for the route.
//
// Mind you the values may have changed, either because of an edit or
// because a new item was created.
foreach ($this->getModel()->getKeys() as $id => $key) {
if (isset($this->formData[$key])) {
$this->afterSaveRouteUrl[$id] = $this->formData[$key];
}
}
}
}
if (is_array($this->afterSaveRouteUrl)) {
// Make sure controller is set
if (!array_key_exists('controller', $this->afterSaveRouteUrl)) {
$this->afterSaveRouteUrl['controller'] = $this->request->getControllerName();
}
// Search array for menu item
$find['controller'] = $this->afterSaveRouteUrl['controller'];
$find['action'] = $this->afterSaveRouteUrl['action'];
// If not allowed, redirect to index
if (null == $this->menu->find($find)) {
$this->afterSaveRouteUrl['action'] = 'index';
$this->resetRoute = true;
}
}
return $this;
} | Set what to do when the form is 'finished'.
@return \MUtil_Snippets_ModelFormSnippetAbstract (continuation pattern) | entailment |
protected function addStepElementsFor(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model, $step) {
$this->displayHeader($bridge, $this->_('Survey replace'), 'h1');
// If we don't copy answers, we skip step 2
if ($this->formData['copy_answers'] == 0 && $step > 1) {
$step = $step + 1;
}
// To prevent confusion we show a progressbar that jumps from 25% to 50% or 75%
$element = $bridge->getForm()->createElement('html', 'progress');
$bridge->addElement($element);
$element->div(array('class' => 'progress', 'renderClosingTag' => true))->div('', array(
'class' => 'progress-bar',
'style' => 'width: ' . $step / $this->getStepCount() * 100 . '%;',
'renderClosingTag' => true));
switch ($step) {
case 0:
case 1:
$this->addStepElementsForStep1($bridge, $model);
break;
case 2:
$this->addStepElementsForStep2($bridge, $model);
break;
case 3:
$this->addStepElementsForStep3($bridge, $model);
break;
default:
$this->addStepElementsForStep4($bridge, $model);
break;
}
return;
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model
@param int $step The current step | entailment |
protected function addStepElementsForStep1(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model) {
$model->set('source_survey', 'elementClass', 'Select');
$this->addItems($bridge, 'source_survey', 'target_survey');
$this->addItems($bridge, 'track_replace', 'token_update', 'copy_answers');
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepElementsForStep2(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model) {
$element = $bridge->getForm()->createElement('html', 'table');
$bridge->addElement($element);
$table = $element->table(['class' => 'browser table']);
$headers = [
$this->_('Question code'),
$this->_('Source Survey'),
$this->_('Target Survey'),
];
$tableHeader = $table->thead();
$headerRow = $tableHeader->tr();
foreach ($headers as $label) {
$headerRow->th($label);
}
$headerRow = $tableHeader->tr();
$headerRow->th();
$headerRow->th($this->surveys[$this->sourceSurveyId]);
$headerRow->th($this->surveys[$this->targetSurveyId]);
$tableBody = $table->tbody();
$row = $tableBody->tr();
$row->td($this->_('Usage'));
$row->td($this->getSurveyStatistics($this->sourceSurveyId));
$row->td($this->getSurveyStatistics($this->targetSurveyId));
$this->addSurveyCompareForm($tableBody, $this->formData);
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepElementsForStep3(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model) {
//$this->_form->append($this->getSurveyCompareTable());
//$this->addItems($bridge, 'target_survey', 'source_survey');
$element = $bridge->getForm()->createElement('html', 'table');
$bridge->addElement($element);
$element->append($this->getSurveyResults($this->formData));
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepElementsForStep4(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model) {
// Things go really wrong (at the session level) if we run this code
// while the finish button was pressed
if ($this->isFinishedClicked()) {
return;
}
$this->nextDisabled = true;
$batch = $this->getUpdateBatch();
$form = $bridge->getForm();
$batch->setFormId($form->getId());
$batch->autoStart = true;
// \MUtil_Registry_Source::$verbose = true;
if ($batch->run($this->request)) {
exit;
}
$element = $form->createElement('html', $batch->getId());
if ($batch->isFinished()) {
// Keep the filename after $batch->getMessages(true) cleared the previous
$this->addMessage($batch->getMessages(true));
$element->h3($this->_('Survey replaced successfully!'));
$this->nextDisabled = false;
$data = $this->formData;
// Remove unuseful data
unset($data['button_spacer'], $data['current_step'], $data[$this->csrfId], $data['auto_form_focus_tracker'], $data['import_id']);
// Add friendly names
$data['source_survey_name'] = $this->getSurveyName($this->sourceSurveyId);
$data['target_survey_name'] = $this->getSurveyName($this->targetSurveyId);
$this->accesslog->logChange($this->request, null, array_filter($data));
} else {
$element->setValue($batch->getPanel($this->view, $batch->getProgressPercentage() . '%'));
}
$form->activateJQuery();
$form->addElement($element);
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
public function addSurveyCompareForm($tableBody, $post) {
if ($this->sourceSurveyId && $this->targetSurveyId) {
$sourceSurveyData = $this->getSurveyData($this->sourceSurveyId);
$targetSurveyData = $this->getSurveyData($this->targetSurveyId);
$surveyCompare = $this->getSurveyCompare($sourceSurveyData, $targetSurveyData, $post);
$icon = \MUtil_Html::create()->i(['class' => 'fa fa-exclamation-triangle', 'style' => 'color: #d43f3a; margin: 1em;', 'renderClosingTag' => true]);
foreach ($surveyCompare as $question) {
if ($question['status'] == 'missing') {
continue;
}
$rowMessage = false;
$statusClass = '';
if (isset($this->questionStatusClasses[$question['status']])) {
$statusClass = $this->questionStatusClasses[$question['status']];
}
if ($question['status'] == 'type-difference') {
$rowMessage = $this->_('Question type is not the same. Check compatibility!');
} elseif ($question['status'] == 'new') {
$rowMessage = $this->_('Question could not be found in source. Is this a new question?');
} /*elseif ($question['status'] == 'missing') {
$rowMessage = $this->_('Warning! Question not found in target survey. Data will be lost on transfer');
}*/
$row = $tableBody->tr(['class' => $statusClass]);
$row->td($question['target']);
// Source column
$row->td($this->getSurveyQuestionSelect($sourceSurveyData, $question['source'], $question['target']));
// Target column
if (isset($targetSurveyData[$question['target']])) {
$row->td($targetSurveyData[$question['target']]['question']);
} else {
$row->td();
}
if ($rowMessage) {
$tableBody->tr(['class' => $statusClass])->td(['colspan' => 3])->append($icon, $rowMessage);
}
}
}
} | Adds the survey compare form to the current table, showing the matches between different surveys
@param $tableBody \MUtil_Html Table object
@param $post array List of Post data | entailment |
public function calculateTrackUsage($surveyId) {
$select = $this->db->select();
$select->from('gems__tracks', array('gtr_track_name'));
$select->joinLeft('gems__rounds', 'gro_id_track = gtr_id_track', array('useCnt' => 'COUNT(*)'))
->where('gro_id_survey = ?', $surveyId)
->group('gtr_track_name');
$usage = $this->db->fetchPairs($select);
if ($usage) {
$seq = new \MUtil_Html_Sequence();
$seq->setGlue(\MUtil_Html::create('br'));
foreach ($usage as $track => $count) {
$seq[] = sprintf($this->plural(
'Used %d time in %s track.',
'Used %d times in %s track.',
$count), $count, $track);
}
return $seq;
} else {
return $this->_('Not used in any track.');
}
} | Gets how many times a survey is used in tracks
@param $surveyId int Gems Survey ID
@return array|\MUtil_Html_Sequence translated string with track usage | entailment |
protected function getCategorizedResults($post, $sourceSurveyData, $targetSurveyData) {
$surveyCompare = $this->getSurveyCompare($sourceSurveyData, $targetSurveyData, $post);
$categorizedResults = [];
foreach (array_keys($this->questionStatusClasses) as $status) {
$categorizedResults[$status] = [];
}
foreach ($surveyCompare as $result) {
if (isset($result['status'])) {
if ($result['status'] == 'missing') {
$categorizedResults[$result['status']][$result['source']] = $result;
} else {
$categorizedResults[$result['status']][$result['target']] = $result;
}
} else {
$categorizedResults['other'][] = $result;
}
}
return $categorizedResults;
} | Function to get Survey compare results sorted by status
@param $post Post request data
@param $sourceSurveyData array with source survey data
@param $targetSurveyData array with target survey data
@return array compare results sorted by status | entailment |
public function getComments() {
$comments = false;
$table = \MUtil_Html::create()->table(['class' => 'browser table', 'style' => 'width: auto']);
$targetSurveyAnswers = $this->getNumberOfAnswers($this->targetSurveyId);
if ($targetSurveyAnswers > 0) {
$comments = true;
$table
->tr(['class' => 'warning'])
->td(
sprintf(
$this->_('Target survey already has %d answers. Is this expected?'),
$targetSurveyAnswers
)
);
}
if ($comments) {
return $table;
}
return false;
} | Creates a table with warnings about the survey answer transfer
@return bool|\MUtil_Html Table with information | entailment |
protected function getCompareResultSummary($post, $sourceSurveyData, $targetSurveyData) {
$categorizedResults = $this->getCategorizedResults($post, $sourceSurveyData, $targetSurveyData);
$table = \MUtil_Html::create()->table(['class' => 'browser table', 'style' => 'width: auto']);
$row = $table->tr(['class' => $this->questionStatusClasses['new']]);
$row->td(sprintf($this->_('%d new questions'), count($categorizedResults['new'])));
$row->td(join(', ', array_keys($categorizedResults['new'])));
$row = $table->tr(['class' => $this->questionStatusClasses['same']]);
$row->td(sprintf($this->_('%d questions without warnings '), count($categorizedResults['same'])));
$row->td(join(', ', array_keys($categorizedResults['same'])));
$row = $table->tr(['class' => $this->questionStatusClasses['missing']]);
$row->td(sprintf($this->_('%d missing questions'), count($categorizedResults['missing'])));
$row->td(join(', ', array_keys($categorizedResults['missing'])));
$row = $table->tr(['class' => $this->questionStatusClasses['type-difference']]);
$row->td(sprintf($this->_('%d questions where the question type has changed'), count($categorizedResults['type-difference'])));
$row->td(join(', ', array_keys($categorizedResults['type-difference'])));
return $table;
} | Creates a table with comparison summary
@param $post array List of post values
@param $sourceSurveyData array list of survey structure
@param $targetSurveyData
@return mixed | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view) {
$form = parent::getHtmlOutput($view);
$html = \MUtil_Html::create()->div(['id' => 'survey-compare']);
$html->append($form);
return $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 getNumberOfAnswers($surveyId) {
$fields['tokenCount'] = 'COUNT(DISTINCT gto_id_token)';
$select = $this->loader->getTracker()->getTokenSelect($fields)->andReceptionCodes([]);
$select->forSurveyId($surveyId)
->onlySucces()
->onlyCompleted();
$row = $select->fetchRow();
return sprintf($this->_('Answered surveys: %d.'), $row['tokenCount']);
} | Gets the number of answers in a survey
@param $surveyId int Gems Survey ID
@return string translated string with number of answers | entailment |
public function getSourceSurveyId($surveyId) {
$tracker = $this->loader->getTracker();
$survey = $tracker->getSurvey($surveyId);
return $survey->getSourceSurveyId();
} | Get the survey ID in the survey source
@param $surveyId int Gems survey ID
@return int source survey ID | entailment |
public function getSurveyCompare($sourceSurveyData, $targetSurveyData, $post) {
$surveyCompareArray = [];
$missingSourceSurveyTitles = $sourceSurveyData;
// show all questions that can be send to the target survey
foreach ($targetSurveyData as $questionCode => $questionData) {
$currentQuestionCode = $questionCode;
if (isset($post['target']) && isset($post['target'][$currentQuestionCode])) {
$currentQuestionCode = $post['target'][$currentQuestionCode];
}
$questionCompare = [
'target' => $questionCode,
'source' => $currentQuestionCode,
];
if (isset($sourceSurveyData[$currentQuestionCode])) {
if ($questionData['type'] === $sourceSurveyData[$currentQuestionCode]['type']) {
$questionCompare['status'] = 'same';
} else {
$questionCompare['status'] = 'type-difference';
}
unset($missingSourceSurveyTitles[$currentQuestionCode]);
} else {
$questionCompare['status'] = 'new';
}
$surveyCompareArray[] = $questionCompare;
}
// show all questions that are missing in the target survey
foreach ($missingSourceSurveyTitles as $questionId => $questionData) {
$surveyCompareArray[] = [
'target' => null,
'source' => $questionId,
'status' => 'missing',
];
}
return $surveyCompareArray;
} | create an array with statusses of survey questions and how they're matched in the form
@param $sourceSurveyData array with source survey data
@param $targetSurveyData array with target survey data
@param $post array List of POST data
@return array status array | entailment |
public function getSurveyCompareTable($bridge) {
$post = $this->formData;
$element = $bridge->getForm()->createElement('html', 'table');
$table = $element->table(['class' => 'browser table']);
$bridge->addElement($element);
$headers = [
$this->_('Question code'),
$this->_('Source Survey'),
$this->_('Target Survey'),
];
$tableHeader = $table->thead()->tr();
foreach ($headers as $label) {
$tableHeader->th($label);
}
$tableBody = $table->tbody();
if ($this->sourceSurveyId && $this->targetSurveyId) {
$row = $tableBody->tr();
$row->td($this->_('Usage'));
$row->td($this->getSurveyStatistics($this->sourceSurveyId));
$row->td($this->getSurveyStatistics($this->targetSurveyId));
$this->addSurveyCompareForm($tableBody, $post);
}
} | Get the complete comparison table
@return \MUtil_Html Form nodes | entailment |
public function getSurveyData($surveyId) {
$tracker = $this->loader->getTracker();
$survey = $tracker->getSurvey($surveyId);
$surveyInfo = $survey->getQuestionInformation($this->locale);
$filteredSurveyInfo = $surveyInfo;
foreach ($surveyInfo as $questionCode => $questionInfo) {
if ($questionInfo['class'] == 'question_sub') {
$parentCode = $questionInfo['title'];
$parent = $surveyInfo[$parentCode];
$filteredSurveyInfo[$questionCode]['question'] = $parent['question'] . ' | ' . $questionInfo['question'];
if (isset($filteredSurveyInfo[$parentCode])) {
unset($filteredSurveyInfo[$parentCode]);
}
}
}
return $filteredSurveyInfo;
} | Gets question information about the survey structure from a specific survey and makes the result readable
@param $surveyId int ID of the survey
@return array List of survey information | entailment |
public function getSurveyName($surveyId) {
$tracker = $this->loader->getTracker();
$survey = $tracker->getSurvey($surveyId);
return $survey->getName();
} | Get Survey name from Id
@param $surveyId
@return string Survey name | entailment |
public function getSurveyQuestionSelect($surveyData, $currentQuestionCode, $targetQuestionCode) {
$name = 'target[' . $targetQuestionCode . ']';
if ($targetQuestionCode === null) {
$name = 'notfound[]';
}
$select = \MUtil_Html::create()->select(['name' => $name]);
$select->class = 'form-control';
$empty = $this->util->getTranslated()->getEmptyDropdownArray();
$select->option(reset($empty), ['value' => '']);
foreach ($surveyData as $questionCode => $questionData) {
$attributes = ['value' => $questionCode];
if ($currentQuestionCode === $questionCode) {
$attributes['selected'] = 'selected';
}
$select->option($questionData['question'], $attributes);
}
return $select;
} | Get the form select with all the questions in the survey and the current selected one
@param $surveyData array List of survey data
@param $currentQuestionCode string Current selected question code
@param $targetQuestionCode string the target question code used in the name field of the select
@return \MUtil_Html Select object | entailment |
public function getSurveyResults($post) {
$comments = $this->getComments();
$table = \MUtil_Html::create()->table(['class' => 'browser table']);
$header = $table->thead()->tr();
$header->th($this->_('Source Survey'));
$header->th($this->_('Target Survey'));
$header = $table->thead()->tr();
$header->th($this->surveys[$this->sourceSurveyId]);
$header->th($this->surveys[$this->targetSurveyId]);
$tableBody = $table->tbody();
$row = $tableBody->tr();
$row->td($this->getSurveyStatistics($this->sourceSurveyId));
$row->td($this->getSurveyStatistics($this->targetSurveyId));
$tableBody->tr()->td(['colspan' => 2]);
if ($this->formData['copy_answers'] == 1) {
$sourceSurveyData = $this->getSurveyData($this->sourceSurveyId);
$targetSurveyData = $this->getSurveyData($this->targetSurveyId);
$compareResultSummary = $this->getCompareResultSummary($post, $sourceSurveyData, $targetSurveyData);
$tableBody->tr()->th($this->_('Summary'), ['colspan' => 2]);
$tableBody->tr()->td($compareResultSummary, ['colspan' => 2]);
}
if ($comments) {
$tableBody->tr()->th($this->_('Comments'), ['colspan' => 2]);
$tableBody->tr()->td($comments, ['colspan' => 2]);
}
return $table;
} | Creates a table showing the results of the survey compare
@param $post array List of POST data
@return \MUtil_Html Table | entailment |
public function getSurveySelect($name, $post) {
$surveys = $this->surveys;
$select = \MUtil_Html::create()->select(['name' => $name]);
$empty = $this->util->getTranslated()->getEmptyDropdownArray();
$select->option(reset($empty), ['value' => '']);
return $select;
} | Create a select element node with all available surveys
@param $name string name of the survey select
@return mixed \MUtil_Html node | entailment |
public function getSurveyStatistics($surveyId) {
$seq = new \MUtil_Html_Sequence();
$seq->setGlue(\MUtil_Html::create('br'));
$seq[] = $this->getNumberOfAnswers($surveyId);
$seq[] = $this->calculateTrackUsage($surveyId);
return $seq;
} | Creates a small html block of number of answers and usage in tracks of surveys
@param $surveyId int id of the survey
@return \MUtil_Html_Sequence | entailment |
public function getSurveys() {
if (!$this->surveys) {
$dbLookup = $this->util->getDbLookup();
$this->surveys = $dbLookup->getSurveysWithSid();
}
return $this->surveys;
} | Get all available surveys
@return array Survey Id => Survey name of available surveys | entailment |
protected function loadFormData() {
if ($this->request->isPost()) {
$this->formData = $this->request->getPost() + $this->formData;
} else {
foreach ($this->model->getColNames('default') as $name) {
if (!(isset($this->formData[$name]) && $this->formData[$name])) {
$this->formData[$name] = $this->model->get($name, 'default');
}
}
}
if (!(isset($this->formData['import_id']) && $this->formData['import_id'])) {
$this->formData['import_id'] = mt_rand(10000, 99999) . time();
}
if (array_key_exists('source_survey', $this->formData) && $this->formData['source_survey']) {
$this->sourceSurveyId = $this->formData['source_survey'];
}
if (array_key_exists('target_survey', $this->formData) && $this->formData['target_survey']) {
$this->targetSurveyId = $this->formData['target_survey'];
}
$this->_session = new \Zend_Session_Namespace(__CLASS__ . '-' . $this->formData['import_id']);
if (array_key_exists('target', $this->formData)) {
$this->_session->target = $this->formData['target'];
} else {
if (isset($this->_session->target)) {
$this->formData['target'] = $this->_session->target;
}
}
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
protected function createModel()
{
if (! $this->model instanceof LogModel) {
$this->model = $this->loader->getModels()->createLogModel();
$this->model->applyBrowseSettings();
}
return $this->model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function loadFormData()
{
parent::loadFormData();
if (isset($this->formData['gor_id_organization']) && $this->formData['gor_id_organization']) {
$model = $this->getModel();
// Strip self from list of organizations
$multiOptions = $model->get('gor_accessible_by', 'multiOptions');
unset($multiOptions[$this->formData['gor_id_organization']]);
$model->set('gor_accessible_by', 'multiOptions', $multiOptions);
// Show allowed organizations
$org = $this->loader->getOrganization($this->formData['gor_id_organization']);
$allowedOrgs = $org->getAllowedOrganizations();
//Strip self
unset($allowedOrgs[$this->formData['gor_id_organization']]);
$display = join(', ', $allowedOrgs);
if (! $display) {
$display = \MUtil_Html::create('em', $this->_('No access to other organizations.'));
}
$this->formData['allowed'] = $display;
$model->set('allowed', 'value', $display);
}
// MultiOption null is ''.
if (! isset($this->formData['gor_respondent_edit'])) {
$this->formData['gor_respondent_edit'] = '';
}
if (! isset($this->formData['gor_respondent_show'])) {
$this->formData['gor_respondent_show'] = '';
}
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
public function createModel($detailed, $action)
{
$rcLib = $this->util->getReceptionCodeLibrary();
$yesNo = $this->util->getTranslated()->getYesNo();
$model = new \MUtil_Model_TableModel('gems__reception_codes');
$model->copyKeys(); // The user can edit the keys.
$model->set('grc_id_reception_code', 'label', $this->_('Code'), 'size', '10');
$model->set('grc_description', 'label', $this->_('Description'), 'size', '30');
$model->set('grc_success', 'label', $this->_('Is success code'),
'multiOptions', $yesNo ,
'elementClass', 'CheckBox',
'description', $this->_('This reception code is a success code.'));
$model->set('grc_active', 'label', $this->_('Active'),
'multiOptions', $yesNo,
'elementClass', 'CheckBox',
'description', $this->_('Only active codes can be selected.'));
if ($detailed) {
$model->set('desc1', 'elementClass', 'Html',
'label', ' ',
'value', \MUtil_Html::create('h4', $this->_('Can be assigned to'))
);
}
$model->set('grc_for_respondents', 'label', $this->_('Respondents'),
'multiOptions', $yesNo,
'elementClass', 'CheckBox',
'description', $this->_('This reception code can be assigned to a respondent.'));
$model->set('grc_for_tracks', 'label', $this->_('Tracks'),
'multiOptions', $yesNo,
'elementClass', 'CheckBox',
'description', $this->_('This reception code can be assigned to a track.'));
$model->set('grc_for_surveys', 'label', $this->_('Tokens'),
'multiOptions', $rcLib->getSurveyApplicationValues(),
'description', $this->_('This reception code can be assigned to a token.'));
if ($detailed) {
$model->set('desc2', 'elementClass', 'Html',
'label', ' ',
'value', \MUtil_Html::create('h4', $this->_('Additional actions'))
);
}
$model->set('grc_redo_survey', 'label', $this->_('Redo survey'),
'multiOptions', $rcLib->getRedoValues(),
'description', $this->_('Redo a survey on this reception code.'));
$model->set('grc_overwrite_answers', 'label', $this->_('Overwrite existing consents'),
'multiOptions', $yesNo,
'elementClass', 'CheckBox',
'description', $this->_('Remove the consent from already answered surveys.'));
if ($detailed) {
$model->set('grc_id_reception_code', 'validator', $model->createUniqueValidator('grc_id_reception_code'));
$model->set('grc_description', 'validator', $model->createUniqueValidator('grc_description'));
}
if ($this->project->multiLocale) {
$model->set('grc_description', 'description', 'ENGLISH please! Use translation file to translate.');
}
\Gems_Model::setChangeFieldsByPrefix($model, 'grc');
return $model;
} | Creates a model for getModel(). Called only for each new $action.
The parameters allow you to easily adapt the model to the current action. The $detailed
parameter was added, because the most common use of action is a split between detailed
and summarized actions.
@param boolean $detailed True when the current action is not in $summarizedActions.
@param string $action The current action.
@return \MUtil_Model_ModelAbstract | entailment |
protected function createModel()
{
$model = parent::createModel();
foreach ($model->getItemNames() as $name) {
if (! $model->has($name, 'label')) {
$model->set($name, 'label', ' ');
}
}
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function bbToHtml($bbcode)
{
if (empty($bbcode)) {
$em = \MUtil_Html::create('em');
$em->raw($this->_('«empty»'));
return $em;
}
$text = \MUtil_Markup::render($bbcode, 'Bbcode', 'Html');
$div = \MUtil_Html::create('div', array('class' => 'mailpreview'));
$div->raw($text);
return $div;
} | Display a template body
@param string $bbcode
@return \MUtil_Html_HtmlElement | entailment |
public function createModel($detailed, $action)
{
$allLanguages = $this->util->getLocalized()->getLanguages();
$currentLanguage = $this->locale->getLanguage();
$markEmptyCall = array($this->util->getTranslated(), 'markEmpty');
ksort($allLanguages);
$model = $this->loader->getModels()->getCommtemplateModel($currentLanguage);
$commTargets = $this->loader->getMailTargets();
$model->set('gct_name', 'label', $this->_('Name'), 'size', 50);
$model->set('gct_target', 'label', $this->_('Mail Target'),
'multiOptions', $commTargets,
'formatFunction', array($this, '_')
);
// If the token target is available, use it as a default
if (array_key_exists('token', $commTargets)) {
$model->set('gct_target', 'default', 'token');
}
$model->set('gct_code', 'label', $this->_('Template code'),
'description', $this->_('Optional code name to link the template to program code.'),
'formatFunction', $markEmptyCall,
'size', 50
);
// SUB TRANSLATION MODEL
$translationModel = new \MUtil_Model_TableModel('gems__comm_template_translations', 'gctt');
$translationModel->set('gctt_lang', 'multiOptions', $allLanguages);
if ($action === 'index') {
$translationModel->set('gctt', 'label', $this->_('Subject'),
'size', 50,
'formatFunction', array($this, 'displayMultipleSubjects')
);
} else {
$translationModel->set('gctt_subject', 'label', $this->_('Subject'),
'size', 100,
'formatFunction', $markEmptyCall
);
}
if ($detailed) {
$translationModel->set('gctt_body', 'label', $this->_('Message'),
'cols', 60,
'decorators', array('CKEditor'),
'elementClass', 'textarea',
'formatFunction', array($this, 'bbToHtml'),
'rows', 8
);
}
if ($this->project->getEmailMultiLanguage()) {
$requiredRows = array();
foreach($allLanguages as $code=>$language) {
$requiredRows[]['gctt_lang'] = $code;
}
} else {
$defaultLanguage = $this->project->getLocaleDefault();
$requiredRows[]['gctt_lang'] = $defaultLanguage;
$translationModel->setFilter(array('gctt_lang' => $defaultLanguage));
}
$transformer = new \MUtil_Model_Transform_RequiredRowsTransformer();
$transformer->setRequiredRows($requiredRows);
$translationModel->addTransformer($transformer);
$model->addModel($translationModel, array('gct_id_template' => 'gctt_id_template'), 'gctt');
return $model;
} | Creates a model for getModel(). Called only for each new $action.
The parameters allow you to easily adapt the model to the current action. The $detailed
parameter was added, because the most common use of action is a split between detailed
and summarized actions.
@param boolean $detailed True when the current action is not in $summarizedActions.
@param string $action The current action.
@return \MUtil_Model_ModelAbstract | entailment |
public function execute($sourceId = null, $userId = null)
{
$now = new \MUtil_Db_Expr_CurrentTimestamp();
$values = array('gso_last_synch' => $now, 'gso_changed' => $now, 'gso_changed_by' => $userId);
$where = $this->db->quoteInto('gso_id_source = ?', $sourceId);
$this->db->update('gems__sources', $values, $where);
} | 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 |
public function getChanges(array $context, $new)
{
$conditions = $this->loader->getConditions();
if (isset($context['gro_condition']) && !empty($context['gro_condition'])) {
$condition = $conditions->loadCondition($context['gro_condition']);
$callback = [$condition, 'isValid'];
$validator = new \Zend_Validate_Callback($callback);
$validator->setMessage($condition->getNotValidReason($context['gro_condition'], $context), $validator::INVALID_VALUE);
return [
'condition_display' => [
'elementClass' => 'Exhibitor',
'value' => $condition->getRoundDisplay($context['gro_id_track'], $context['gro_id_round'])
],
'gro_condition' => [
'validator' => $validator
]
];
}
return [
'condition_display' => [
'elementClass' => 'Hidden',
'value' => null
]
];
} | 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 |
private function _loadPatches($minimumLevel, $maximumLevel)
{
if (! $this->_loaded_patches) {
$this->_loaded_patches = array();
foreach ($this->patch_sources as $file => $location) {
$this->_loadPatchFile($file, $location, $minimumLevel, $maximumLevel);
}
}
} | Load all patches from all patch files with the range
@param int $minimumLevel
@param int $maximumLevel | entailment |
private function _loadPatchFile($file, $location, $minimumLevel, $maximumLevel)
{
if ($sql = file_get_contents($file)) {
if ($this->encoding && ($this->encoding !== mb_internal_encoding())) {
$sql = mb_convert_encoding($sql, mb_internal_encoding(), $this->encoding);
}
$levels = preg_split('/--\s*(GEMS\s+)?VERSION:?\s*/', $sql);
// SQL before first -- VERSION: is ignored.
array_shift($levels);
foreach ($levels as $level) {
list($levelnrtext, $leveltext) = explode("\n", $level, 2);
// no loading of unused patches
$levelnr = intval($levelnrtext);
if ($levelnr && ($levelnr >= $minimumLevel) && ($levelnr <= $maximumLevel)) {
$patches = preg_split('/--\s*PATCH:?\s*/', $leveltext);
// SQL before first -- PATCH: is ignored.
array_shift($patches);
foreach ($patches as $patch) {
// First line now contains patch name
list($name, $statements) = explode("\n", $patch, 2);
$name = substr(trim($name), 0, 30);
// \MUtil_Echo::r($statements, $name);
foreach (\MUtil_Parser_Sql_WordsParser::splitStatements($statements, false) as $i => $statement) {
$this->_loaded_patches[] = array(
'gpa_level' => $levelnr,
'gpa_location' => $location,
'gpa_name' => $name,
'gpa_order' => $i,
'gpa_sql' => $statement,
);
}
}
}
}
}
} | Load all patches from a single patch file
@param string $file Full filename
@param string $location Location description
@param int $minimumLevel
@param int $maximumLevel | entailment |
public function getPatchDatabase($location)
{
if (isset($this->patch_databases[$location])) {
return $this->patch_databases[$location];
}
return $this->db;
} | Get the database for a location
@param string $location
@return \Zend_Db_Adapter_Abstract | entailment |
public function loadPatchBatch($patchLevel, $ignoreCompleted, $ignoreExecuted, \MUtil_Task_TaskBatch $batch)
{
$select = $this->db->select();
$select->from('gems__patches', array('gpa_id_patch', 'gpa_sql', 'gpa_location', 'gpa_completed'))
->where('gpa_level = ?', $patchLevel)
->order('gpa_level')
->order('gpa_location')
->order('gpa_id_patch');
if ($ignoreCompleted) {
$select->where('gpa_completed = 0');
}
if ($ignoreExecuted) {
$select->where('gpa_executed = 0');
}
// \MUtil_Echo::track($ignoreCompleted, $ignoreExecuted, $select);
$executed = 0;
$patches = $select->query()->fetchAll();
if ($patches) {
foreach ($patches as $patch) {
$batch->addTask(
'Db_ExecuteOnePatch',
$patch['gpa_location'],
$patch['gpa_sql'],
$patch['gpa_completed'],
$patch['gpa_id_patch']
);
}
$batch->addTask('Db_UpdatePatchLevel', $patchLevel);
$batch->addTask('CleanCache');
}
return $batch;
} | Loads execution of selected db patches for the given $patchLevel into a TaskBatch.
@param int $patchLevel Only execute patches for this patchlevel
@param boolean $ignoreCompleted Set to yes to skip patches that where already completed
@param boolean $ignoreExecuted Set to yes to skip patches that where already executed
(this includes the ones that are executed but not completed)
@param \MUtil_Task_TaskBatch $batch Optional batch, otherwise one is created
@return \MUtil_Task_TaskBatch The batch | entailment |
public function uploadPatches($applicationLevel)
{
// Load current
$select = $this->db->select();
$select->from(
'gems__patches',
array('gpa_level', 'gpa_location', 'gpa_name', 'gpa_order', 'gpa_sql', 'gpa_id_patch')
);
try {
$existing = $select->query()->fetchAll();
} catch (exception $e) {
return -1;
}
// Change into a nested tree for easy access
$tree = \MUtil_Ra_Nested::toTree($existing, 'gpa_level', 'gpa_location', 'gpa_name', 'gpa_order');
$changed = 0;
$current = new \MUtil_Db_Expr_CurrentTimestamp();
$this->_loadPatches($this->getMinimumPatchLevel(), $applicationLevel);
// \MUtil_Echo::track($this->_loaded_patches);
foreach ($this->_loaded_patches as $patch) {
$level = $patch['gpa_level'];
$location = $patch['gpa_location'];
$name = $patch['gpa_name'];
$order = $patch['gpa_order'];
// Does it exist?
if (isset($tree[$level][$location][$name][$order])) {
$sql = $patch['gpa_sql'];
if ($sql != $tree[$level][$location][$name][$order]['gpa_sql']) {
$values['gpa_sql'] = $sql;
$values['gpa_executed'] = 0;
$values['gpa_completed'] = 0;
$values['gpa_changed'] = $current;
$where = $this->db->quoteInto(
'gpa_id_patch = ?',
$tree[$level][$location][$name][$order]['gpa_id_patch']
);
// \MUtil_Echo::track($values, $where);
$this->db->update('gems__patches', $values, $where);
$changed++;
}
} else {
$patch['gpa_changed'] = $current;
$patch['gpa_created'] = $current;
$this->db->insert('gems__patches', $patch);
$changed++;
}
} // */
return $changed;
} | Load all (new and changed) patches from all patch files into permanent storage in the database
@param int $applicationLevel Highest level of patches to load (no loading of future patches) | entailment |
public function loadConfiguration(): void
{
$builder = $this->getContainerBuilder();
$config = $this->config;
if ($config->mailer === null) {
throw new InvalidStateException(sprintf('"%s" must be configured.', $this->prefix('mailer')));
}
$builder->addFactoryDefinition($this->prefix('messageFactory'))
->setImplement(IMessageFactory::class);
// Wrap original mailer by TraceableMailer
if ($config->debug === true) {
$mailer = $builder->addDefinition($this->prefix('mailer.original'))
->setAutowired(false);
$this->loadDefinitionsFromConfig(['mailer.original' => $config->mailer]);
$traceableMailer = $builder->addDefinition($this->prefix('mailer'))
->setType(TraceableMailer::class)
->setArguments([$mailer]);
// Mail panel for tracy
$builder->addDefinition($this->prefix('panel'))
->setFactory(MailPanel::class)
->addSetup('setTraceableMailer', [$traceableMailer]);
} else {
// Load mailer
$this->loadDefinitionsFromConfig(['mailer' => $config->mailer]);
}
} | Register services | entailment |
public function beforeCompile(): void
{
$builder = $this->getContainerBuilder();
$config = $this->config;
// Handle nette/mail configuration
if ($this->name === 'mail') {
return;
}
if ($config->mode === self::MODE_STANDALONE) {
// Disable autowiring of nette.mailer
if ($builder->hasDefinition('mail.mailer')) {
$builder->getDefinition('mail.mailer')
->setAutowired(false);
}
} elseif ($config->mode === self::MODE_OVERRIDE) {
// Remove nette.mailer and replace with our mailer
$builder->removeDefinition('mail.mailer');
$builder->addAlias('mail.mailer', $this->prefix('mailer'));
}
} | Decorate services | entailment |
public function afterCompile(ClassType $class): void
{
$config = $this->config;
if ($config->debug === true) {
$initialize = $class->getMethod('initialize');
$initialize->addBody(
'$this->getService(?)->addPanel($this->getService(?));',
['tracy.bar', $this->prefix('panel')]
);
}
} | Show mail panel in tracy | entailment |
public function execute($location = null, $sql = null, $completed = null, $patchId = null)
{
$batch = $this->getBatch();
$db = $this->patcher->getPatchDatabase($location);
$data['gpa_executed'] = 1;
$data['gpa_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
try {
$stmt = $db->query($sql);
if ($rows = $stmt->rowCount()) {
// No translation to avoid conflicting translations
$data['gpa_result'] = 'OK: ' . $rows . ' changed';
} else {
$data['gpa_result'] = 'OK';
}
$data['gpa_completed'] = 1;
} catch (\Zend_Db_Statement_Exception $e) {
$message = $e->getMessage();
// Make sure these do not remain uncompleted
if (\MUtil_String::contains($message, 'Duplicate column name')) {
$data['gpa_result'] = 'Column exists in table';
$data['gpa_completed'] = 1;
} elseif (\MUtil_String::contains($message, "DROP") &&
\MUtil_String::contains($message, 'check that column/key exists')) {
$data['gpa_result'] = 'Column does not exists in table';
$data['gpa_completed'] = 1;
} else {
$data['gpa_result'] = substr($message, 0, 254);
$data['gpa_completed'] = $completed ? $completed : 0;
}
$batch->addMessage($data['gpa_result']);
}
// $this->db, not the database the patch was executed on
$this->db->update('gems__patches', $data, $this->db->quoteInto('gpa_id_patch = ?', $patchId));
// \MUtil_Echo::track($data, $patchId);
$batch->addToCounter('executed');
$batch->setMessage('executed', sprintf($this->_('%d patch(es) executed.'), $batch->getCounter('executed')));
} | 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
@param string $location
@param string $sql
@param int $completed
@param int $patchId | entailment |
protected function createLoginForm($showToken = null, $showPasswordLost = null)
{
$args = \MUtil_Ra::args(func_get_args(),
array(
'showToken' => 'is_boolean',
'showPasswordLost' => 'is_boolean',
),
array(
'showToken' => $this->showTokenButton,
'showPasswordLost' => $this->showPasswordLostButton,
'labelWidthFactor' => $this->labelWidthFactor,
'organizationMaxLines' => $this->organizationMaxLines,
));
\Gems_Html::init();
if ($this->layeredLogin === true) {
// Allow to set labels without modifying the form by overriding the below methods
$args['topOrganizationDescription'] = $this->getTopOrganizationDescription();
$args['childOrganizationDescription'] = $this->getChildOrganizationDescription();
return $this->loader->getUserLoader()->getLayeredLoginForm($args);
} else {
return $this->loader->getUserLoader()->getLoginForm($args);
}
} | Returns a login form
@param boolean $showToken Optional, show 'Ask token' button, $this->showTokenButton is used when not specified
@param boolean $showPasswordLost Optional, show 'Lost password' button, $this->showPasswordLostButton is used when not specified
@return \Gems_User_Form_LoginForm | entailment |
protected function createResetRequestForm()
{
$args = \MUtil_Ra::args(func_get_args(),
array(),
array(
'labelWidthFactor' => $this->labelWidthFactor,
));
$this->initHtml();
return $this->loader->getUserLoader()->getResetRequestForm($args);
} | Gets a reset password form.
@return \Gems_User_Form_ResetForm | entailment |
protected function displayLoginForm(\Gems_User_Form_LoginForm $form)
{
$this->setCurrentOrganizationTo($form->getUser());
$this->view->form = $form;
} | Function for overruling the display of the login form.
@param \Gems_User_Form_LoginForm $form
@deprecated since version 1.8.4 no longer in use with 2FA login | entailment |
protected function displayResetForm(\Gems_Form_AutoLoadFormAbstract $form, $errors)
{
if ($form instanceof \Gems_User_Validate_GetUserInterface) {
$user = $form->getUser();
}
if ($form instanceof \Gems_User_Form_ResetRequestForm) {
$this->html->h3($this->_('Request password reset'));
$p = $this->html->pInfo();
if ($form->getOrganizationIsVisible()) {
$p->append($this->_('Please enter your organization and your username or e-mail address. '));
} else {
$p->append($this->_('Please enter your username or e-mail address. '));
}
$this->html->p($this->_('We will then send you an e-mail with a link. The link will bring you to a page where you can set a new password of your choice.'));
} elseif ($form instanceof \Gems_User_Form_ChangePasswordForm) {
$this->setCurrentOrganizationTo($user);
if ($user->hasPassword()) {
$this->html->h3($this->_('Execute password reset'));
$p = $this->html->pInfo($this->_('We received your password reset request.'));
} else {
// New user
$this->html->h3(sprintf($this->_('Welcome to %s'), $this->project->getName()));
$p = $this->html->pInfo($this->_('Welcome to this website.'));
}
$p->append(' ');
$p->append($this->_('Please enter your password of choice twice.'));
}
if ($errors) {
$this->addMessage($errors);
}
if (isset($user)) {
$this->setCurrentOrganizationTo($user);
}
$formContainer = \MUtil_Html::create('div', array('class' => 'resetPassword'), $form);
$this->html->append($formContainer);
} | Function for overruling the display of the reset form.
@param \Gems_Form_AutoLoadFormAbstract $form Rset password or reset request form
@param mixed $errors | entailment |
public function loginAction()
{
if ($this->loginSnippets && $this->useHtmlView) {
$params = $this->_processParameters($this->loginParameters + $this->_loginDefaultParameters);
$sparams['request'] = $this->getRequest();
$sparams['resetParam'] = $params['resetParam'];
$sparams['snippetList'] = $this->loginSnippets;
$sparams['snippetLoader'] = $this->getSnippetLoader();
$sparams['snippetParameters'] = $params;
$this->addSnippets('SequenceSnippet', $sparams);
return;
}
$request = $this->getRequest();
$form = $this->createLoginForm();
// Retrieve these before the session is reset
$staticSession = \GemsEscort::getInstance()->getStaticSession();
$previousRequestParameters = $staticSession->previousRequestParameters;
$previousRequestMode = $staticSession->previousRequestMode;
if ($form->wasSubmitted()) {
if ($form->isValid($request->getPost(), false)) {
$user = $form->getUser();
$user->setAsCurrentUser();
if ($messages = $user->reportPasswordWeakness($request->getParam($form->passwordFieldName))) {
$user->setPasswordResetRequired(true);
$this->addMessage($this->_('Your password must be changed.'));
foreach ($messages as &$message) {
$message = ucfirst($message) . '.';
}
$this->addMessage($messages);
}
/**
* Fix current locale in cookies
*/
\Gems_Cookies::setLocale($user->getLocale(), $this->basepath->getBasePath());
/**
* Ready
*/
$this->addMessage(sprintf($this->_('Login successful, welcome %s.'), $user->getFullName()), 'success');
/**
* Log the login
*/
$this->accesslog->logChange($request);
if ($previousRequestParameters) {
$this->_reroute(array('controller' => $previousRequestParameters['controller'], 'action' => $previousRequestParameters['action']), false);
} else {
// This reroutes to the first available menu page after login.
//
// Do not user $user->gotoStartPage() as the menu is still set
// for no login.
$this->_reroute(array('controller' => null, 'action' => null), true);
}
return;
} else {
$errors = \MUtil_Ra::flatten($form->getMessages());
// \MUtil_Echo::track($errors);
//Also log the error to the log table
//when the project has logging enabled
$logErrors = join(' - ', $errors);
$msg = sprintf('Failed login for : %s (%s) - %s', $request->getParam($form->usernameFieldName), $request->getParam($form->organizationFieldName), $logErrors);
$this->accesslog->logChange($request, $msg);
} // */
} else {
if ($request->isPost()) {
$form->populate($request->getPost());
}
}
// Check job monitors
$this->util->getMonitor()->checkMonitors();
$this->displayLoginForm($form);
} | Default login page | entailment |
public function logoffAction()
{
$this->addMessage(sprintf($this->_('Good bye: %s.'), $this->currentUser->getFullName()));
$this->accesslog->logChange($this->getRequest());
$this->currentUser->unsetAsCurrentUser();
\Zend_Session::destroy();
$this->_reroute(array('action' => 'index'), true);
} | Default logoff action | entailment |
public function resetpasswordAction()
{
$errors = array();
$form = $this->createResetRequestForm();
$request = $this->getRequest();
if ($key = $this->_getParam('key')) {
$user = $this->loader->getUserLoader()->getUserByResetKey($key);
if ($user->hasValidResetKey()) {
// Signal the reqset required so the maxage check is disabled while validating
$user->setPasswordResetRequired(true);
$form = $user->getChangePasswordForm(array('askOld' => false, 'askCheck' => true, 'labelWidthFactor' => $this->labelWidthFactor));
$result = $user->authenticate(null, false);
if (! $result->isValid()) {
$this->addMessage($result->getMessages());
$this->addMessage($this->_('For that reason you cannot reset your password.'));
return;
}
if (! $request->isPost()) {
$this->accesslog->logChange($request, sprintf("User %s opened valid reset link.", $user->getLoginName()));
}
} else {
if (! $request->isPost()) {
if ($user->getLoginName()) {
$message = sprintf("User %s used old reset key.", $user->getLoginName());
} else {
$message = sprintf("Someone used a non existent reset key.", $user->getLoginName());
}
$this->accesslog->logChange($request, $message);
if ($user->hasPassword() || (! $user->isActive())) {
$errors[] = $this->_('Your password reset request is no longer valid, please request a new link.');
} else {
$errors[] = $this->_('Your password input request is no longer valid, please request a new link.');
}
}
if ($user->isActive()) {
$form->getUserNameElement()->setValue($user->getLoginName());
$form->getOrganizationElement()->setValue($user->getBaseOrganizationId());
}
}
}
if ($request->isPost() && $form->isValid($request->getPost())) {
if ($form instanceof \Gems_User_Form_ResetRequestForm) {
$user = $form->getUser();
$result = $user->authenticate(null, false);
if (! $result->isValid()) {
$this->addMessage($result->getMessages());
$this->addMessage($this->_('For that reason you cannot request a password reset.'));
return;
}
$errors = $this->sendUserResetEMail($user);
if ($errors) {
$this->accesslog->logChange(
$request,
sprintf(
"User %s requested reset password but got %d error(s). %s",
$form->getUserNameElement()->getValue(),
count($errors),
implode(' ', $errors)
)
);
} else {
// Everything went OK!
$this->addMessage($this->_(
'We sent you an e-mail with a reset link. Click on the link in the e-mail.'
));
$this->accesslog->logChange($request);
if ($this->returnToLoginAfterReset) {
$this->setCurrentOrganizationTo($user);
$this->currentUser->gotoStartPage($this->menu, $request);
}
}
} elseif ($form instanceof \Gems_User_Form_ChangePasswordForm) {
$this->addMessage($this->_('New password is active.'));
// User set before this form was initiated
$user->setAsCurrentUser();
/**
* Log the login
*/
$this->accesslog->logChange($request, $this->_("User logged in through reset password."));
$user->gotoStartPage($this->menu, $this->getRequest());
return;
}
}
$form->populate($request->getParams());
$this->displayResetForm($form, $errors);
} | Reset password page. | entailment |
public function sendUserResetEMail(\Gems_User_User $user)
{
$subjectTemplate = $this->_('Password reset requested');
// Multi line strings did not come through correctly in poEdit
$bbBodyTemplate = $this->_("Dear {greeting},\n\n\nA new password was requested for your [b]{organization}[/b] account on the [b]{project}[/b] site, please click within {reset_in_hours} hours on [url={reset_url}]this link[/url] to enter the password of your choice.\n\n\n{organization_signature}\n\n[url={reset_url}]{reset_url}[/url]\n"); // */
//$bbBodyTemplate = $this->_("To set a new password for the [b]{organization}[/b] site [b]{project}[/b], please click on this link:\n{reset_url}");
return $user->sendMail($subjectTemplate, $bbBodyTemplate, true);
} | Send the user an e-mail with a link for password reset
@param \Gems_User_User $user
@return mixed string or array of Errors or null when successful. | entailment |
protected function setCurrentOrganizationTo(\Gems_User_User $user)
{
if ($this->currentUser !== $user) {
$this->currentUser->setCurrentOrganization($user->getCurrentOrganization());
}
} | Helper function to safely switch org during login
@param \Gems_User_User $user | entailment |
public static function generate($length = 128, $type = 'alnum', $caseSensitive = true)
{
$characters = self::$characters;
// Provided characters
if (is_array($type)) {
$characters = $type;
} // Hexa decimal
elseif ($type === 'hexa') {
$characters = array_merge(array_slice(self::$characters, 52), array_slice(self::$characters, 26, 6));
} // Case insensitive alpha numeric
elseif ($type === 'alnum' && $caseSensitive === false) {
$characters = array_slice(self::$characters, 26);
} // Alphabet only
elseif ($type === 'alpha') {
$characters = array_slice(self::$characters, 0, 26);
} // Numbers only
elseif ($type === 'digit' || $type === 'numeric') {
$characters = array_slice(self::$characters, 52);
}
return self::make($characters, $length);
} | Generate a random string
@param int $length
@param mixed $type
@param bool $caseSensitive
@return string | entailment |
private static function make($characters, $length)
{
$token = '';
do {
$token .= $characters[random_int(0, count($characters) - 1)];
} while (strlen($token) < $length);
return $token;
} | Make the random string
@param string $characters
@param int $length
@return string | entailment |
protected function _cascadedDirs(array $dirs, $cascade, $fullClassnameFallback = true)
{
// Allow the use of the full class name instead of just the plugin part of the
// name during load.
if ($fullClassnameFallback) {
$newdirs = array('' =>'');
} else {
$newdirs = array();
}
$cascadePath = '/' . strtr($cascade, '_\\', '//');
$cascadeCls = '_' . strtr($cascade, '/\\', '__');
foreach ($dirs as $prefix => $path) {
// Do not cascade a full classname fallback
if ($prefix) {
$newdirs[$prefix . $cascadeCls] = $path . $cascadePath;
}
}
return $newdirs;
} | Add a subdirectory / sub name to a list of class load paths
@param array $dirs prefix => path
@param string $cascade The sub directories to cascade to
@param boolean $fullClassnameFallback Allows full class name specification instead of just plugin name part
@return array prefix => path | entailment |
protected function _getClass($name, $className = null, array $arguments = array())
{
if (! isset($this->$name)) {
if (null === $className) {
$className = $name;
}
$this->$name = $this->_loadClass($className, true, $arguments);
}
return $this->$name;
} | Returns $this->$name, creating the item if it does not yet exist.
@param string $name The $name of the variable to store this object in.
@param string $className Class name or null if the same as $name, prepending $this->_dirs.
@param array $arguments Class initialization arguments.
@return mixed Instance of $className | entailment |
protected function _loadClass($name, $create = false, array $arguments = array())
{
if ($this->_loader instanceof Zalt\Loader\ProjectOverloader) {
$className = $this->_loader->find($name);
} else {
$className = $this->_loader->load($name);
}
// \MUtil_Echo::track($className);
if (is_subclass_of($className, __CLASS__)) {
$create = true;
$arguments = array();
if (isset($this->_containers[0])) {
$arguments[] = $this->_containers[0];
} else {
$arguments[] = null;
}
$arguments[] = $this->_dirs;
if ($this->_loader instanceof Zalt\Loader\ProjectOverloader) {
$arguments[] = $this->_loader;
}
} elseif (is_subclass_of($className, 'MUtil_Registry_TargetInterface')) {
$create = true;
}
if (! $create) {
return new \MUtil_Lazy_StaticCall($className);
}
if ($this->_loader instanceof Zalt\Loader\ProjectOverloader) {
$mergedArguments = array_merge(['className' => $className], $arguments);
$obj = call_user_func_array([$this->_loader, 'create'], $mergedArguments);
} else {
$obj = $this->_loader->createClass($className, $arguments);
}
if ($obj instanceof \MUtil_Registry_TargetInterface) {
if ((! $this->applySource($obj)) && parent::$verbose) {
\MUtil_Echo::r("Source apply to object of type $name failed.", __CLASS__ . '->' . __FUNCTION__);
}
}
return $obj;
} | Create or loads the class. When only loading, this function returns a StaticCall object that
can be invoked lazely.
@see \MUtil_Lazy_StaticCall
@see \MUtil_Registry_TargetInterface
@param string $name The class name, minus the part in $this->_dirs.
@param boolean $create Create the object, or only when an \MUtil_Registry_TargetInterface instance.
@param array $arguments Class initialization arguments.
@return mixed A class instance or a \MUtil_Lazy_StaticCall object | entailment |
public function addPrefixPath($prefix, $path, $prepend = true)
{
if ($this->cascade) {
$newPrefix = $prefix . '_' . $this->cascade;
$newPath = $path . '/' . strtr($this->cascade, '_', '/');
} else {
$newPrefix = $prefix;
$newPath = $path;
}
if ($prepend) {
$this->_dirs = array($newPrefix => $newPath) + $this->_dirs;
} else {
$this->_dirs[$newPrefix] = $newPath;
}
$this->_loader->addPrefixPath($newPrefix, $newPath, $prepend);
if (\MUtil_Registry_Source::$verbose) {
\MUtil_Echo::r($this->_dirs, '$this->_dirs in ' . get_class($this) . '->' . __FUNCTION__ . '():');
}
return $this;
} | Add prefixed paths to the registry of paths
@param string $prefix
@param mixed $paths String or an array of strings
@param boolean $prepend Put path at the beginning of the stack (has no effect when prefix / dir already set)
@return \Gems_Loader_LoaderAbstract (continuation pattern) | entailment |
private function _getActionsDb()
{
try {
$rows = $this->_db->fetchAssoc("SELECT * FROM gems__log_setup ORDER BY gls_name");
} catch (\Exception $exc) {
$rows = array();
$this->_warn();
}
$output = array();
foreach ((array) $rows as $row) {
$output[$row['gls_name']] = $row;
}
// \MUtil_Echo::track($output);
$this->_cache->save($output, $this->_cacheId, array('accesslog_actions'));
return $output;
} | Load the actions into memory from the database (and cache them) | entailment |
private function _storeLogEntry(\Zend_Controller_Request_Abstract $request, array $row, $force)
{
if (! $force) {
if (isset($this->_sessionStore->last) && ($row === $this->_sessionStore->last)) {
return false;
}
// Now save the variables to the session to prevent duplicates if needed
//
// We skip $force as they are always saved and this prevents double logging in case of
// e.g. a show => edit => show cycle
$this->_sessionStore->last = $row;
}
try {
$this->_db->insert('gems__log_activity', $row);
return true;
} catch (\Exception $exc) {
\Gems_Log::getLogger()->logError($exc, $request);
$this->_warn();
return false;
}
} | Stores the current log entry
@param \Zend_Controller_Request_Abstract $request
@param array $row
@param boolean $force Should we force the logentry to be inserted or should we try to skip duplicates?
@return boolean True when a log entry was stored | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.