sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function getUserClassSelect($login_name, $organization) { $select = $this->db->select(); /** * tolerance field: * 1 - login and organization match * 2 - login found in an organization with access to the requested organization * 3 - login found in another organization without rights to the requested organiation * (could be allowed due to privilege with rights to ALL organizations) */ $select->from('gems__user_logins', array("gul_user_class", 'gul_id_organization', 'gul_login')) ->where('gul_can_login = 1'); if ($this->allowLoginOnWithoutOrganization && !$organization) { $select->columns(new \Zend_Db_Expr('1 AS tolerance')); } else { $select->from('gems__organizations', array()) ->columns(new \Zend_Db_Expr( "CASE WHEN gor_id_organization = gul_id_organization THEN 1 WHEN gor_accessible_by LIKE CONCAT('%:', gul_id_organization, ':%') THEN 2 ELSE 3 END AS tolerance")) ->where('gor_active = 1') ->where('gor_id_organization = ?', $organization) ->order('tolerance'); } $wheres[] = $this->db->quoteInto('gul_login = ?', $login_name); $isEmail = \MUtil_String::contains($login_name, '@'); if ($isEmail && $this->allowStaffEmailLogin) { $rows = $this->db->fetchAll( "SELECT gsf_login, gsf_id_organization FROM gems__staff WHERE gsf_email = ?", $login_name ); if ($rows) { foreach ($rows as $row) { $wheres[] = $this->db->quoteInto('gul_login = ? AND ', $row['gsf_login']) . $this->db->quoteInto('gul_id_organization = ?', $row['gsf_id_organization']); } } } if ($isEmail && $this->allowRespondentEmailLogin) { $rows = $this->db->fetchAll( "SELECT gr2o_patient_nr, gr2o_id_organization FROM gems__respondent2org " . "INNER JOIN gems__respondents WHERE gr2o_id_user = grs_id_user AND gr2o_email = ?", $login_name ); if ($rows) { foreach ($rows as $row) { $wheres[] = $this->db->quoteInto('gul_login = ? AND ', $row['gr2o_patient_nr']) . $this->db->quoteInto('gul_id_organization = ?', $row['gr2o_id_organization']); } } } // Add search fields $select->where(new \Zend_Db_Expr('(' . implode(') OR (', $wheres) . ')')); // \MUtil_Echo::track($select->__toString()); return $select; }
Returns a select statement to find a corresponding user. @param string $login_name @param int $organization @return \Zend_Db_Select
entailment
protected function loadUser($defName, $userOrganization, $userName) { $definition = $this->getUserDefinition($defName); $values = $definition->getUserData($userName, $userOrganization); // \MUtil_Echo::track($defName, $login_name, $userOrganization, $values); $values = $this->ensureDefaultUserValues($values, $definition, $defName); // \MUtil_Echo::track($values, $userName, $userOrganization, $defName); return $this->_loadClass('User', true, array($values, $definition)); }
Returns a loaded user object @param string $defName @param int $userOrganization @param string $userName @return \Gems_User_User But ! ->isActive when the user does not exist
entailment
public function setCurrentUser(\Gems_User_User $user) { if ($user !== self::$currentUser) { $this->unsetCurrentUser(); self::$currentUser = $user; // Update the escort variable used by loader if ($escort = GemsEscort::getInstance()) { $escort->currentUser = $user; } // Double check in case this function was used as original // start for setting the user. if (! $user->isCurrentUser()) { $user->setAsCurrentUser(true); } } return $this; }
Sets a new user as the current user. @param \Gems_User_User $user @return \Gems_User_UserLoader (continuation pattern)
entailment
public function unsetCurrentUser() { // Remove if the currentUser still sees itself as the current user. if ((self::$currentUser instanceof \Gems_User_User) && self::$currentUser->isCurrentUser()) { self::$currentUser->unsetAsCurrentUser(false); } self::$currentUser = null; return $this; }
Removes the current user @return \Gems_User_UserLoader (continuation pattern)
entailment
public function afterRegistry() { parent::afterRegistry(); // Load the pdf class from the project settings if available if (isset($this->project->export) && isset($this->project->export['pdfExportCommand'])) { $this->_pdfExportCommand = $this->project->export['pdfExportCommand']; } }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
protected function addTokenToDocument(\Zend_Pdf $pdf, $tokenId, $surveyId) { $token = strtoupper($tokenId); foreach (array('Title', 'Subject', 'Keywords') as $name) { if (isset($pdf->properties[$name])) { $orgValue = $pdf->properties[$name]; if (mb_detect_encoding($orgValue) === false) { // Assume UTF-16 mb_convert_encoding($orgValue, mb_internal_encoding(), 'UTF-16'); } $value = rtrim($orgValue) . ' ' . $token; } else { $value = $token; } $pdf->properties[$name] = $value; } // Acrobat defined date format D:YYYYMMDDHHmmSSOHH'mm $pdf->properties['ModDate'] = 'D:' . str_replace(':', "'", date('YmdHisP')) . "'"; $pdf->properties['Producer'] = $this->project->getName(); // Avoid warning on Word with a (R) symbol $pdf->properties['Creator'] = $this->project->getName(); // Avoid warning on Word with a (R) symbol $pdf->properties['Author'] = $this->project->getName(); // Avoid warning on Word with a (R) symbol }
Add the token to every page of a pdf @param \Zend_Pdf $pdf @param string $tokenId @param int $surveyId
entailment
protected function addTokenToPage(\Zend_Pdf_Page $page, $tokenId) { // Set $this->pageFont to false to prevent drawing of tokens on page. if ($this->pageFont) { $font = \Zend_Pdf_Font::fontWithName($this->pageFont); if ($this->pageXfromLeft) { $x = $this->pageX; } else { $x = $page->getWidth() - $this->pageX; } if ($this->pageYfromTop) { $y = $page->getHeight() - $this->pageY; } else { $y = $this->pageY; } $page->setFont($font, $this->pageFontSize); $page->drawText(strtoupper($tokenId), $x, $y, 'UTF-8'); } }
Add the token to a pdf page @param \Zend_Pdf_Page $page @param string $tokenId
entailment
protected function echoPdf(\Zend_Pdf $pdf, $filename, $download = false, $exit = true) { $content = $pdf->render(); $this->echoPdfContent($content, $filename, $download); if ($exit) { // No further output exit; } }
Echos the pdf as output with the specified filename. When download is true the file is returned as a download link, otherwise the pdf is shown in the browser. @param \Zend_Pdf $pdf @param string $filename @param boolean $download @param boolean $exit Should the application stop running after output
entailment
public function echoPdfContent($content, $filename, $download = false) { // \MUtil_Echo::track($filename); if ($download) { // Download & save header('Content-Type: application/x-download'); } else { //We send to a browser header('Content-Type: application/pdf'); } header('Content-Length: '.strlen($content)); header('Content-Disposition: inline; filename="'.$filename.'"'); header('Cache-Control: private, max-age=0, must-revalidate'); header('Pragma: public'); echo $content; }
Output the pdf with the right headers. @param string $content The content to echo @param string $filename The filename as reported to the downloader @param boolean $download Download to file or when false: show in browser
entailment
public function echoPdfBySurveyId($surveyId) { $pdf = $this->getSurveyPdf($surveyId); $this->echoPdf($pdf, $surveyId . '.pdf'); }
Reads the survey pdf and outputs the result (without token id's etc.. @param string $tokenId
entailment
public function echoPdfByTokenId($tokenId) { $surveyId = $this->db->fetchOne('SELECT gto_id_survey FROM gems__tokens WHERE gto_id_token = ?', $tokenId); $pdf = $this->getSurveyPdf($surveyId); $this->addTokenToDocument($pdf, $tokenId, $surveyId); foreach ($pdf->pages as $page) { $this->addTokenToPage($page, $tokenId); } $this->echoPdf($pdf, $tokenId . '.pdf'); }
Reads the survey pdf belonging to this token, puts the token id on de pages and outputs the result. @param string $tokenId
entailment
public function getUploadDir($subdir = null) { $dir = GEMS_ROOT_DIR . '/var/uploads'; if ($subdir) { if (($subdir[0] == '/') || ($subdir[0] == '\\') || (substr($subdir, 1, 2) == ':\\')) { $dir = rtrim($subdir, '\//'); } else { $dir .= DIRECTORY_SEPARATOR . rtrim($subdir, '\//'); } } if (! is_dir($dir)) { $oldmask = umask(0777); if (! @mkdir($dir, 0777, true)) { $this->throwLastError(sprintf($this->translate->_("Could not create '%s' directory."), $dir)); } umask($oldmask); } return $dir; }
Return upload directory, optionally with specified sub directory. You can overrule this function to specify your own directory. @param string $subdir Optional sub-directory, when starting with / or x:\ only $subdir is used. Function creates subdirectory if it does not exist. @return string
entailment
protected function throwLastError($msg) { if ($last = \MUtil_Error::getLastPhpErrorMessage()) { $msg .= sprintf($this->translate->_(' The error message is: %s'), $last); } throw new \Gems_Exception_Coding($msg); }
Helper function for error handling @param string $msg @throws \Gems_Exception_Coding
entailment
public function convertFromHtml($content) { \MUtil_File::ensureDir(GEMS_ROOT_DIR . '/var/tmp'); $tempInputFilename = GEMS_ROOT_DIR . '/var/tmp/export-' . md5(time() . rand()) . '.html'; $tempOutputFilename = GEMS_ROOT_DIR . '/var/tmp/export-' . md5(time() . rand()) . '.pdf'; if (\MUtil_File::isOnWindows()) { // Running on Windows, remove drive letter as that will not work with some // html to pdf converters. $tempInputFilename = strtr(\MUtil_File::removeWindowsDriveLetter($tempInputFilename), '\\', '/'); $tempOutputFilename = strtr(\MUtil_File::removeWindowsDriveLetter($tempOutputFilename), '\\', '/'); } file_put_contents($tempInputFilename, $content); if (!file_exists($tempInputFilename)) { throw new \Exception("Unable to create temporary file '{$tempInputFilename}'"); } $command = sprintf($this->_pdfExportCommand, escapeshellarg($tempInputFilename), escapeshellarg($tempOutputFilename)); // error_log($command); $lastLine = exec($command, $outputLines, $return); if ($return > 0) { @unlink($tempInputFilename); @unlink($tempOutputFilename); throw new \Exception(sprintf($this->translate->_('Unable to run PDF conversion (%s): "%s"'), $command, $lastLine)); } $pdfContents = file_get_contents($tempOutputFilename); @unlink($tempInputFilename); @unlink($tempOutputFilename); if ($pdfContents == '') { throw new \Exception(sprintf($this->translate->_('Unable to run PDF conversion (%s): "%s"'), $command, $lastLine)); } return $pdfContents; }
Calls the PDF convertor (wkhtmltopdf / phantom.js) to convert HTML to PDF @param string $content The HTML source @return string The converted PDF file @throws \Exception
entailment
public function addMessage($message, $status=null) { $messenger = $this->getMessenger(); $messenger->addMessage($message, $status); return $this; }
Adds one or more messages to the session based message store. @param mixed $message_args Can be an array or multiple argemuents. Each sub element is a single message string @return \MUtil_Controller_Action
entailment
public function transformLoad(\MUtil_Model_ModelAbstract $model, array $data, $new = false, $isPostData = false) { foreach($data as $tokenId=>$row) { if (isset($row['gto_id_respondent_track'])) { if (!isset($this->trackFieldsByRespondentTrack[$row['gto_id_respondent_track']])) { $trackData = array_filter($row, function($key) { return strpos($key, 'gtr_') === 0; }, ARRAY_FILTER_USE_KEY); $this->trackFieldsByRespondentTrack[$row['gto_id_respondent_track']] = $this->getTrackFields($trackData, $row['gto_id_respondent_track']); } $newData = $this->trackFieldsByRespondentTrack[$row['gto_id_respondent_track']]; $data[$tokenId] = array_merge($data[$tokenId], $newData); } } return $data; }
The transform function performs the actual transformation of the data and is called after the loading of the data in the source model. @param \MUtil_Model_ModelAbstract $model The parent model @param array $data Nested array @param boolean $new True when loading a new item @param boolean $isPostData With post data, unselected multiOptions values are not set so should be added @return array Nested array containing (optionally) transformed data
entailment
private function _applyParameterFilter(\Gems_Menu_ParameterCollector $source, $raiseConditions, &$condition) { foreach ($this->_parameterFilter as $name => $testValue) { $paramValue = $source->getMenuParameter($name); $testValue = (array) $testValue; if ($paramValue instanceof \MUtil_Lazy_LazyInterface) { if (!$raiseConditions) { $newCondition = new \MUtil_Lazy_Call('in_array', array($paramValue, $testValue)); if ($condition instanceof \MUtil_Lazy_LazyInterface) { if ($condition instanceof \MUtil_Lazy_LazyAnd) { $condition->add($newCondition); } else { $condition = new \MUtil_Lazy_LazyAnd($condition, $newCondition); } } else { $condition = $newCondition; } continue; } $paramValue = \MUtil_Lazy::rise($paramValue); } if (!in_array($paramValue, $testValue)) { if (\Gems_Menu::$verbose) { // Mutil_Echo::backtrace(); \MUtil_Echo::r($name . ' => ' . print_r($testValue,true) . ' !== ' . $paramValue, $this->get('label') . ' (' . $this->get('controller') . '/' . $this->get('action') . ')'); } return true; } } return false; }
Return true when then $source does NOT contain all items in the parameterFilter @param \Gems_Menu_ParameterCollector $source @param boolean $raiseConditions @param mixed $condition @return boolean
entailment
private function _applyParameterSources(\Gems_Menu_ParameterCollector $source, array &$parameters, $raiseConditions) { // \Gems_Menu::$verbose = true; // \MUtil_Echo::r($this->get('label')); $condition = true; if ($this->_applyParameterFilter($source, $raiseConditions, $condition)) { return false; } $this->_applyParameterSource($source, $parameters); // Test required parameters foreach ($this->_requiredParameters as $param => $name) { if (! isset($parameters[$param])) { if (\Gems_Menu::$verbose) { // \MUtil_Echo::backtrace(); \MUtil_Echo::r('<b>Not found:</b> ' . $param . '/' . $name, $this->get('label') . ' (' . $this->get('controller') . '/' . $this->get('action') . ')'); } return false; } } if ($this->_hiddenOrgId && $raiseConditions) { // Remove org paramter that should remain hidden when conditions have been raised. if (isset($parameters[\MUtil_Model::REQUEST_ID1], $parameters[\MUtil_Model::REQUEST_ID2]) && ($parameters[\MUtil_Model::REQUEST_ID2] == $this->_hiddenOrgId)) { $parameters[\MUtil_Model::REQUEST_ID] = $parameters[\MUtil_Model::REQUEST_ID1]; unset($parameters[\MUtil_Model::REQUEST_ID1], $parameters[\MUtil_Model::REQUEST_ID2]); } } return $condition; }
A function that determines the parameters that this menu item should have using these paramter sources. @param \Gems_Menu_ParameterCollector $source A source of parameter values @param array $parameters A usually empty array of parameters that is filled from the sources @param boolean $raiseConditions When true, no lazyness is returned @return boolean Or lazy condition. When true menu item is enabled otherwise false
entailment
private function _toHRef(\Gems_Menu_ParameterCollector $source, &$condition) { if ($this->get('allowed')) { $parameters = array(); if ($condition = $this->_applyParameterSources($source, $parameters, ! $condition)) { if ($this->_hiddenOrgId) { $url = new \Gems_Menu_HiddenOrganizationHrefAttribute($parameters); $url->setHiddenOrgId($this->_hiddenOrgId); } else { $url = new \MUtil_Html_HrefArrayAttribute($parameters); } $url->setRouteReset($this->get('reset_param', true)); foreach (array('module', 'controller', 'action', 'route') as $name) { if ($this->has($name)) { $url->add($name, $this->get($name)); // \MUtil_Echo::r($name . '-' . $this->get($name)); // } else { // \MUtil_Echo::r($name); } } return $url; } } }
Generate a hrf attribute using these sources @param \Gems_Menu_ParameterCollector $source A parameter source collection @param boolean $condition When true the system may create a Lazy condition for the url @return \MUtil_Html_HrefArrayAttribute
entailment
protected function _toNavigationArray(\Gems_Menu_ParameterCollector $source) { $result = $this->_itemOptions; if ($result['visible']) { $parameters = array(); if ($this->_applyParameterSources($source, $parameters, true)) { $result['params'] = $parameters; } else { $result['visible'] = false; } } if ($this->hasChildren()) { $result['pages'] = parent::_toNavigationArray($source); } return $result; }
Returns a \Zend_Navigation creation array for this menu item, with sub menu items in 'pages' @param \Gems_Menu_ParameterCollector $source @return array
entailment
public function addAction($label, $privilege = null, $action = 'index', array $other = array()) { $other['label'] = $label; $other['controller'] = $this->get('controller'); $other['action'] = $action; if (null === $privilege) { $privilege = $this->get('privilege'); } if (null !== $privilege) { $other['privilege'] = $privilege; } return $this->add($other); }
Add an action to the current subMenuItem @param string $label The label to display for the menu item @param string $privilege The privilege for the item @param string $action The name of the action @param array $other Array of extra options for this item, e.g. 'visible', 'allowed', 'class', 'icon', 'target', 'type', 'button_only' @return \Gems_Menu_SubMenuItem
entailment
public function addActionButton($label, $privilege = null, $action = 'index', array $other = array()) { $other['button_only'] = true; return $this->addAction($label, $privilege, $action, $other); }
Add a button only action to the current subMenuItem @param string $label The label to display for the menu item @param string $privilege The privilege for the item @param string $action The name of the action @param array $other Array of extra options for this item, e.g. 'visible', 'allowed', 'class', 'icon', 'target', 'type', 'button_only' @return \Gems_Menu_SubMenuItem
entailment
public function addCreateAction($privilege = null, array $other = array()) { if (isset($other['label'])) { $label = $other['label']; unset($other['label']); } else { $label = $this->_('New'); } if (null === $privilege) { $privilege = $this->get('privilege') . '.create'; } return $this->addAction($label, $privilege, 'create', $other); }
Add an "Create new" action to the current subMenuItem @param string $privilege The privilege for the item, defaults to parent + .create when not specified @param array $other Array of extra options for this item, e.g. 'visible', 'allowed', 'class', 'icon', 'target', 'type', 'button_only' @return \Gems_Menu_SubMenuItem
entailment
public function addDeReactivateAction($checkField, $deactivateOn = 1, $reactivateOn = 1, array $otherDeact = array(), array $otherReact = array()) { $pages = array(); if (null !== $deactivateOn) { if (isset($otherDeact['privilege'])) { $privilege = $otherDeact['privilege']; } else { $privilege = $this->get('privilege') . '.deactivate'; } $deactivate = $this->addAction($this->_('Deactivate'), $privilege, 'deactivate', $otherDeact); $deactivate->setModelParameters(1) ->addParameterFilter($checkField, $deactivateOn); $pages['deactivate'] = $deactivate; } if (null !== $reactivateOn) { if (isset($otherReact['privilege'])) { $privilege = $otherReact['privilege']; } else { $privilege = $this->get('privilege') . '.reactivate'; } $reactivate = $this->addAction($this->_('Reactivate'), $privilege, 'reactivate', $otherReact); $reactivate->setModelParameters(1) ->addParameterFilter($checkField, $reactivateOn); $pages['reactivate'] = $reactivate; } return $pages; }
Add a standard deactivate action and optional reactivate action to the current menu item @param string $checkField The name of the field to filter on for deactivation @param string $deactivateOn The value to check against for deactivation, no menu item when null @param string $reactivateOn The value to check against for reactivation, no menu item when null @param array $otherDeact Array of extra options for deactivate item, e.g. 'visible', 'allowed', 'class', 'icon', 'privilege', 'target', 'type', 'button_only'. @param array $otherReact Array of extra options for reactivate item, e.g. 'visible', 'allowed', 'class', 'icon', 'privilege', 'target', 'type', 'button_only'. @return \Gems_Menu_SubmenuItem[]
entailment
public function addEditAction($privilege = null, array $other = array()) { if (isset($other['label'])) { $label = $other['label']; unset($other['label']); } else { $label = $this->_('Edit'); } if (null === $privilege) { $privilege = $this->get('privilege') . '.edit'; } $menu = $this->addAction($label, $privilege, 'edit', $other); $menu->setModelParameters(1); return $menu; }
Add a standard edit action to the current menu item @param string $privilege A privilege name, defaults to parent + .edit when not specified @param array $other Array of extra options for this item, e.g. 'visible', 'allowed', 'class', 'icon', 'target', 'type', 'button_only' @return \Gems_Menu_SubmenuItem
entailment
public function addExcelAction() { $options = array( 'class' => 'excel', //'rel' => 'external', 'target' => null, 'title' => $this->_('Export the current data set to Excel'), //'type' => 'application/vnd.ms-excel', ); return $this->addActionButton($this->_('Excel export'), $this->get('privilege') . '.excel', 'excel', $options); }
Add a standard edit action to the current menu item @deprecated Since 1.8.1 @return \Gems_Menu_SubmenuItem
entailment
public function addExportAction() { $options = array( 'class' => 'model-export', 'target' => null, 'title' => $this->_('Export the current data set'), ); return $this->addActionButton($this->_('Export'), $this->get('privilege') . '.export', 'export', $options); }
Add a standard edit action to the current menu item @return \Gems_Menu_SubmenuItem
entailment
public function addHiddenParameter($name, $value = null) { if (null === $value) { unset($this->_hiddenParameters[$name]); } else { $this->_hiddenParameters[$name] = $value; } return $this; }
Add parameter values that should not show in the url but that must be added to the request when this menu item is current. @see applyHiddenParameters @param string $name Name of parameter @param mixed $value @return \Gems_Menu_SubMenuItem (continuation pattern
entailment
public function addImportAction($privilege = null, array $other = array()) { if (isset($other['label'])) { $label = $other['label']; unset($other['label']); } else { $label = $this->_('Import'); } if (null === $privilege) { $privilege = $this->get('privilege') . '.import'; } $menu = $this->addAction($label, $privilege, 'import', $other); return $menu; }
Add a standard import action to the current menu item @param string $privilege A privilege name, defaults to parent + .import when not specified @param array $other Array of extra options for this item, e.g. 'visible', 'allowed', 'class', 'icon', 'target', 'type', 'button_only' @return \Gems_Menu_SubmenuItem
entailment
public function addNamedParameters($arrayOrKey1 = null, $altName1 = null) { $params = \MUtil_Ra::pairs(func_get_args()); foreach ($params as $param => $name) { if (is_int($param)) { $param = $name; } $this->_requiredParameters[$param] = $name; $this->_parameters[$param] = $name; } return $this; }
Add required parameters - shown in the url - for this menu item. Numeric array keys are changed into the same string as the array value. @param mixed $arrayOrKey1 \MUtil_Ra::pairs named array @param mixed $key2 @return \Gems_Menu_SubMenuItem (continuation pattern)
entailment
public function addShowAction($privilege = null, array $other = array()) { if (isset($other['label'])) { $label = $other['label']; unset($other['label']); } else { $label = $this->_('Show'); } $menu = $this->addAction($label, $privilege, 'show', $other); $menu->setModelParameters(1); return $menu; }
Add a standard show action to the current menu item @param string $privilege A privilege name, defaults to parent + .show when not specified @param array $other Array of extra options for this item, e.g. 'visible', 'allowed', 'class', 'icon', 'target', 'type', 'button_only' @return \Gems_Menu_SubmenuItem
entailment
public function checkParameterFilter($arrayOrKey1, $value1 = null) { $checks = \MUtil_Ra::pairs(func_get_args()); foreach($checks as $name => $value) { // \MUtil_Echo::track($name, $value, $this->_parameterFilter[$name]); if (null === $value) { if (isset($this->_parameterFilter[$name])) { return false; } } else { if (isset($this->_parameterFilter[$name])) { if ($this->_parameterFilter[$name] != $value) { return false; } } else { return false; } } } return true; }
Check if a menu item contains these parameter settings @param mixed $arrayOrKey1 \MUtil_Ra:pairs() name => value argument pairs @param mixed $value1 The value should be identical or when null, should not exist or be null @return boolean True if all values where set
entailment
public function setModelParameters($idCount) { $params = array(); if (1 == $idCount) { $params[\MUtil_Model::REQUEST_ID] = \MUtil_Model::REQUEST_ID; } else { for ($idx = 1; $idx <= $idCount; $idx++) { $params[\MUtil_Model::REQUEST_ID . $idx] = \MUtil_Model::REQUEST_ID . $idx; } } $this->setNamedParameters($params); return $this; }
Defines the number of named parameters using the model naming convention: id=x or id1=x id2=y @see setNamedParamenters() @param int $idCount The number of parameters to define @return \Gems_Menu_SubMenuItem (continuation pattern)
entailment
public function setNamedParameters($arrayOrKey1 = null, $key2 = null) { $params = \MUtil_Ra::pairs(func_get_args()); $this->removeParameters(); $this->addNamedParameters($params); return $this; }
Set the required parameters - shown in the url - for this menu item. Numeric array keys are changed into the same string as the array value. @param mixed $arrayOrKey1 \MUtil_Ra::pairs named array @param mixed $key2 @return \Gems_Menu_SubMenuItem (continuation pattern)
entailment
protected function addModelSettings(array &$settings) { $empty = []; if (!$this->_fieldDefinition['gtf_required'] || $this->_fieldDefinition['gtf_field_default'] === null) { $empty = $this->util->getTranslated()->getEmptyDropdownArray(); } $multi = explode(parent::FIELD_SEP, $this->_fieldDefinition['gtf_field_values']); $settings['elementClass'] = 'Select'; $settings['multiOptions'] = $empty + array_combine($multi, $multi); }
Add the model settings like the elementClass for this field. elementClass is overwritten when this field is read only, unless you override it again in getDataModelSettings() @param array $settings The settings set so far
entailment
public function execute($lineNr = null, $roundData = null) { $batch = $this->getBatch(); $events = $this->loader->getEvents(); $import = $batch->getVariable('import'); if (isset($roundData['gro_id_order']) && $roundData['gro_id_order']) { $import['roundOrder'][$roundData['gro_id_order']] = false; } else { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('No gro_id_order specified for round at line %d.'), $lineNr )); } if (isset($roundData['survey_export_code']) && $roundData['survey_export_code']) { if (! (isset($import['surveyCodes']) && array_key_exists($roundData['survey_export_code'], $import['surveyCodes']))) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown survey export code "%s" specified for round on line %d.'), $roundData['survey_export_code'], $lineNr )); } } else { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('No survey export code specified for round on line %d.'), $lineNr )); } if (isset($roundData['gro_changed_event']) && $roundData['gro_changed_event']) { try { $events->loadRoundChangedEvent($roundData['gro_changed_event']); } catch (\Gems_Exception_Coding $ex) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown or invalid round changed event "%s" specified on line %d.'), $roundData['gro_changed_event'], $lineNr )); } } if (isset($roundData['gro_display_event']) && $roundData['gro_display_event']) { try { $events->loadSurveyDisplayEvent($roundData['gro_display_event']); } catch (\Gems_Exception_Coding $ex) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown or invalid round display event "%s" specified on line %d.'), $roundData['gro_display_event'], $lineNr )); } } }
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 writeRespondent(\Gems_Communication_RespondentContainer $respondent, &$userId) { $parameters = $this->_model->applyParameters( array( 'grs_ssn' => $respondent->getBsn(), 'gr2o_reception_code' => \GemsEscort::RECEPTION_OK, 'gr2o_patient_nr' => $respondent->getPatientId() ) ); $data = $this->_model->loadFirst(); $isNew = false; if (empty($data)) { $isNew = true; $data = $this->_model->loadNew(); } unset($data['gr2o_email']); $data['gr2o_patient_nr'] = $respondent->getPatientId(); $data['grs_first_name'] = $respondent->getFirstName(); $data['grs_last_name'] = $respondent->getLastName(); $data['grs_surname_prefix'] = $respondent->getSurnamePrefix(); $data['grs_ssn'] = $respondent->getBsn(); $data['grs_gender'] = $respondent->getGender(); $data['grs_birthday'] = $respondent->getBirthday(); $data = $this->_model->save($data); $userId = $data['grs_id_user']; return $isNew; }
- Fetches respondent based on bsn / reception code and patient nr - Creates the respondent if it does not exist, updates otherwise @see \Gems_Model_RespondentModel @see \Gems_Communication_RespondentWriter::writeRespondent() @param \Gems_Communication_RespondentContainer $respondent @param int $userId @return boolean True if a new respondent was added, false if one was updated
entailment
public function itemToString(\stdClass $item) { $attributes = (array) $item; if (isset($attributes['type']) && (($attributes['type'] == 'text/css') || ($attributes['type'] == 'text/less'))) { // This is a stylesheet, consider extension and compile .less to .css if (($attributes['type'] == 'text/less') || \MUtil_String::endsWith($attributes['href'], '.less', true)) { $this->compile($this->view, $attributes['href'], false); // Modify object, not the derived array $item->type = 'text/css'; $item->href = substr($attributes['href'], 0, -4) . 'css'; } } if (isset($this->view->currentVersion)) { $version = $this->view->currentVersion; if (property_exists($item, 'href')) { $item->href = $item->href . '?' . $version; } } return \Zend_View_Helper_HeadLink::itemToString($item); }
Create HTML link element from data item @param \stdClass $item @return string
entailment
public function calcultateName($value, $isNew = false, $name = null, array $context = array()) { $fields = $this->agenda->getFieldLabels(); $output = array(); if (isset($context['gaf_filter_text1'], $fields[$context['gaf_filter_text1']], $context['gaf_filter_text2']) && $context['gaf_filter_text1'] && $context['gaf_filter_text2']) { $output[] = sprintf($this->_('%s like "%s"'), $fields[$context['gaf_filter_text1']], $context['gaf_filter_text2']); } if (isset($context['gaf_filter_text3'], $fields[$context['gaf_filter_text3']], $context['gaf_filter_text4']) && $context['gaf_filter_text3'] && $context['gaf_filter_text4']) { $output[] = sprintf($this->_('%s like "%s"'), $fields[$context['gaf_filter_text3']], $context['gaf_filter_text4']); } if ($output) { return ucfirst(implode($this->_(', '), $output)); } else { return $this->_('empty filter'); } }
A ModelAbstract->setOnSave() function that returns the input date as a valid date. @see \MUtil_Model_ModelAbstract @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @return string
entailment
public function getFieldLabels() { $output = array( 'gap_id_organization' => $this->_('Organization'), 'gap_source' => $this->_('Source of appointment'), 'gap_id_attended_by' => $this->_('With'), 'gap_id_referred_by' => $this->_('Referrer'), 'gap_id_activity' => $this->_('Activity'), 'gap_id_procedure' => $this->_('Procedure'), 'gap_id_location' => $this->_('Location'), 'gap_subject' => $this->_('Subject'), ); asort($output); return $output; }
Get the field names in appontments with their labels as the value @return array fieldname => label
entailment
public function getTextSettings() { $fields = $this->agenda->getFieldLabels(); $description = sprintf($this->_( "Use the %%-sign to search for zero or more random characters and an _ for a single random character." )); return array( 'gaf_filter_text1' => array( 'label' => $this->_('Field 1'), 'multiOptions' => $fields, 'required' => true, ), 'gaf_filter_text2' => array( 'label' => $this->_('Search text 1'), 'description' => $description, 'required' => true, ), 'gaf_filter_text3' => array( 'label' => $this->_('Field 2'), 'multiOptions' => $this->util->getTranslated()->getEmptyDropdownArray() + $fields, ), 'gaf_filter_text4' => array( 'label' => $this->_('Search text 2'), 'description' => sprintf($this->_("Required when filled - use %%-sign as well.")), ), ); }
Get the settings for the gaf_filter_textN fields Fields not in this array are not shown in any way @return array gaf_filter_textN => array(modelFieldName => fieldValue)
entailment
public function processChangedRespondent(\Gems_Tracker_Respondent $respondent) { $changes = 0; $tracker = $this->loader->getTracker(); $respTracks = $tracker->getRespondentTracks($respondent->getId(), $respondent->getOrganizationId()); $userId = $this->currentUser->getUserId(); foreach($respTracks as $respondentTrack) { if ($respondentTrack instanceof \Gems_Tracker_RespondentTrack) { $changes += $respondentTrack->checkTrackTokens($userId); } } // \MUtil_Echo::track('Hi there! ' . $changes); return (boolean) $changes; }
Process the respondent and return true when data has changed. The event has to handle the actual storage of the changes. @param \Gems_Tracker_Respondent $respondent @param int $userId The current user @return boolean True when something changed
entailment
public function addPrefixPath($prefix, $path, $prepend = true) { if ($prepend) { $this->_dirs = array($prefix => $path) + $this->_dirs; } else { $this->_dirs[$prefix] = $path; } if ($this->_loader instanceof Zalt\Loader\ProjectOverloader) { $this->_loader->addOverloaders([$prefix]); } else { $this->_loader->addPrefixPath($prefix, $path, $prepend); } return $this; }
Add prefixed paths to the registry of paths @param string $prefix @param string $path @param boolean $prepend @return \MUtil_Snippets_SnippetLoaderInterface
entailment
public function getSnippet($filename, array $extraSourceParameters = null) { try { $this->addRegistryContainer($extraSourceParameters, 'tmpContainer'); $snippet = $this->_loadClass($filename, true); $this->removeRegistryContainer('tmpContainer'); if (self::$verbose) { \MUtil_Echo::r('Loading snippet ' . $filename . '<br/>' . 'Using snippet: ' . get_class($snippet)); } } catch (\Exception $exc) { if (self::$verbose) { \MUtil_Echo::r($exc->getMessage(), __CLASS__ . '->' . __FUNCTION__ . '(' . $filename . ')'); } throw $exc; } return $snippet; }
Searches and loads a .php snippet file. @param string $filename The name of the snippet @param array $extraSourceParameters name/value pairs to add to the source for this snippet @return \MUtil_Snippets_SnippetInterface The snippet
entailment
public function removePrefixPath($prefix, $path = null) { $this->_loader->removePrefixPath($prefix, $path); return $this; }
Remove a prefix (or prefixed-path) from the registry @param string $prefix @param string $path OPTIONAL @return \MUtil_Snippets_SnippetLoaderInterface
entailment
private function _enableAutoSubmitElement($element) { if ($element instanceof \Zend_Form || $element instanceof \Zend_Form_DisplayGroup) { foreach ($element->getElements() as $sub) { $this->_enableAutoSubmitElement($sub); } } elseif ($element instanceof \Gems_Form_AutosubmitElementInterface) { $element->enableAutoSubmit($this->_autosubmit); } }
Change all elements into an autosubmit element Call only when $_autoSubmit is set @param mixed $element
entailment
public function activateJQuery() { if ($this->_no_jquery) { parent::activateJQuery(); $this->addPrefixPath('Gems_JQuery_Form_Decorator', 'Gems/JQuery/Form/Decorator/', \Zend_Form::DECORATOR); $this->addPrefixPath('Gems_JQuery_Form_Element', 'Gems/JQuery/Form/Element/', \Zend_Form::ELEMENT); } return $this; }
Activate JQuery for this form @return \MUtil_Form (continuation pattern)
entailment
public function addElement($element, $name = null, $options = null) { parent::addElement($element, $name, $options); if ($this->isAutoSubmit()) { if (null !== $name) { $element = $this->getElement($name); } $this->_enableAutoSubmitElement($element); } return $this; }
Add a new element $element may be either a string element type, or an object of type \Zend_Form_Element. If a string element type is provided, $name must be provided, and $options may be optionally provided for configuring the element. If a \Zend_Form_Element is provided, $name may be optionally provided, and any provided $options will be ignored. @param string|\Zend_Form_Element $element @param string $name @param array|\Zend_Config $options @throws \Zend_Form_Exception on invalid element @return \Zend_Form (continuation pattern)
entailment
public function setAutoSubmit($submitUrl, $targetId, $selective = false) { // Filter out elements passed by type $args = \MUtil_Ra::args(func_get_args(), array( 'submitUrl' => array('MUtil_Html_UrlArrayAttribute', 'is_array', 'is_string'), 'targetId' => array('MUtil_Html_ElementInterface', 'is_string'), ), null, \MUtil_Ra::STRICT); if (isset($args['targetId'])) { if ($args['targetId'] instanceof \MUtil_Html_ElementInterface) { if (isset($args['targetId']->id)) { $args['targetId'] = '#' . $args['targetId']->id; } elseif (isset($args['targetId']->class)) { $args['targetId'] = '.' . $args['targetId']->class; } else { $args['targetId'] = $args['targetId']->getTagName(); } } else { $args['targetId'] = '#' . $args['targetId']; } } if ($selective) { $args['selective'] = true; } $this->_autosubmit = $args; $this->_enableAutoSubmitElement($this); $this->activateJQuery(); }
Change the form into an autosubmit form @param mixed $submitUrl Url as \MUtil_Html_UrlArrayAttribute, array or string @param mixed $targetId Id of html element whose content is replaced by the submit result: \MUtil_Html_ElementInterface or string @param boolean $selective When true autosubmit is applied only to elements with the CSS class autosubmit
entailment
public function getRedirectRoute() { // Clean up $this->loginStatusTracker->destroySession(); return [ $this->request->getControllerKey() => null, $this->request->getActionKey() => null, ]; }
When hasHtmlOutput() is false a snippet code user should check for a redirectRoute. Otherwise the redirect calling render() will execute the redirect. This function should never return a value when the snippet does not redirect. Also when hasHtmlOutput() is true this function should not be called. @see \Zend_Controller_Action_Helper_Redirector @return mixed Nothing or either an array or a string that is acceptable for Redector->gotoRoute()
entailment
protected function addBrowseColumn3(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { if ($model->hasAlias('gems__respondent2track')) { parent::addBrowseColumn3($bridge, $model); } }
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
public function addSeparator($token) { $this->row->addGenerator($this->generator); $this->generator = $this->documentGenerator->getInlineGenerator($this->generatorName); $this->wikiContent .= $this->wikiContentArr[$this->separatorCount]; ++$this->separatorCount; $this->currentSeparator = $token; $this->wikiContent .= $token; $this->contents[$this->separatorCount] = ''; $this->wikiContentArr[$this->separatorCount] = ''; }
called by the inline parser, when it found a separator. @param string $token
entailment
public function createModel($detailed, $action) { $model = parent::createModel($detailed, $action); $model->set('grs_birthday', 'label', $this->_('Birthday')); $model->set('grs_city', 'label', $this->_('City')); $model->addColumn("CONCAT(gr2t_completed, '" . $this->_(' of ') . "', gr2t_count)", 'progress'); $model->set('progress', 'label', $this->_('Progress')); 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 _filterData($data, array $filters) { $limit = false; if (isset($filters['limit'])) { $limit = $filters['limit']; unset($filters['limit']); } $filteredData = parent::_filterData($data, $filters); if ($limit) { if (is_array($limit)) { $filteredData = array_slice($filteredData, $limit[1], $limit[0]); } elseif (is_numeric($limit)) { $filteredData = array_slice($filteredData, 0, $limit); } } return $filteredData; }
Filters the data array using a model filter @param \Traversable $data @param array $filters @return \Traversable
entailment
public function getItemCount($filter = true, $sort = true) { $data = $this->_loadAllTraversable(); if ($filter) { $data = $this->_filterData($data, $filter); } return count($data); }
Calculates the total number of items in a model result with certain filters @param array $filter Filter array, num keys contain fixed expresions, text keys are equal or one of filters @param array $sort Sort array field name => sort type @return integer number of total items in model result @throws Zend_Db_Select_Exception
entailment
protected function _addDefaultFieldsToExportModel(\MUtil_Model_ModelAbstract $model, array $data, array &$prefixes) { if (!$model->checkJoinExists('gems__respondent2org.gr2o_id_user', 'gems__tokens.gto_id_respondent')) { $model->addTable('gems__respondent2org', array( 'gems__respondent2org.gr2o_id_user' => 'gems__tokens.gto_id_respondent', 'gems__respondent2org.gr2o_id_organization' => 'gems__tokens.gto_id_organization'), 'gr2o' ); } if (!$model->checkJoinExists('gems__respondent2track.gr2t_id_respondent_track', 'gems__tokens.gto_id_respondent_track')) { $model->addTable('gems__respondent2track', array('gems__respondent2track.gr2t_id_respondent_track' => 'gems__tokens.gto_id_respondent_track'), 'gr2t'); } if (!$model->checkJoinExists('gems__tracks.gtr_id_track', 'gems__tokens.gto_id_track')) { $model->addTable('gems__tracks', array('gems__tracks.gtr_id_track' => 'gems__tokens.gto_id_track'), 'gtr'); } if (!$model->checkJoinExists('gems__consents.gco_description', 'gems__respondent2org.gr2o_consent')) { $model->addTable('gems__consents', array('gems__consents.gco_description' => 'gems__respondent2org.gr2o_consent'), 'gco'); } $model->set('respondentid', 'label', $this->_('Respondent ID'), 'type', \MUtil_Model::TYPE_NUMERIC); $model->set('organizationid', 'label', $this->_('Organization'), 'type', \MUtil_Model::TYPE_NUMERIC, 'multiOptions', $this->currentUser->getAllowedOrganizations() ); // Add relation fields $model->set('gto_id_relation', 'label', $this->_('Relation ID'), 'type', \MUtil_Model::TYPE_NUMERIC); $model->set('forgroup', 'label', $this->_('Filler'), 'type', \MUtil_Model::TYPE_STRING); // Add Consent $model->set('consentcode', 'label', $this->_('Consent'), 'type', \MUtil_Model::TYPE_STRING); $model->set('resptrackid', 'label', $this->_('Respondent track ID'), 'type', \MUtil_Model::TYPE_NUMERIC); $model->set('gto_round_order', 'label', $this->_('Round order')); $model->set('gto_round_description', 'label', $this->_('Round description')); $model->set('gtr_track_name', 'label', $this->_('Track name')); $model->set('gr2t_track_info', 'label', $this->_('Track description')); // These are limesurvey fields, replace them with GemsTracker fields //$model->set('submitdate', 'label', $this->_('Submit date')); //$model->set('startdate', 'label', $this->_('Start date')); //$model->set('datestamp', 'label', $this->_('Datestamp')); $model->set('gto_completion_time', 'label', $this->_('Completion date')); $model->set('gto_start_time', 'label', $this->_('Start time')); $model->set('gto_valid_from', 'label', $this->_('Valid from')); $model->set('gto_valid_until', 'label', $this->_('Valid until')); $model->set('startlanguage', 'label', $this->_('Start language')); $model->set('lastpage', 'label', $this->_('Last page')); $model->set('gto_id_token', 'label', $this->_('Token')); }
Add the default fields and optionally joins to the model @param MUtil_Model_ModelAbstract $model @param array $data @param array $prefixes
entailment
protected function _addExtraDataToExportModel(\MUtil_Model_ModelAbstract $model, array $data, array &$prefixes) { $this->_addExtraTrackFields($model, $data, $prefixes); // Create the first 'P' fields after this $this->_addExtraRespondentNumber($model, $data, $prefixes); $this->_addExtraGenderAge($model, $data, $prefixes); $this->_addExtraTokenReceptionCode($model, $data, $prefixes); $this->_addExtraTrackReceptionCode($model, $data, $prefixes); $this->_addExtraTrackFieldsByCode($model, $data, $prefixes); }
Extensible function for added project specific data extensions @param \MUtil_Model_ModelAbstract $model @param array $data @param array $prefixes
entailment
protected function _addNestedFieldsToExportModel(\MUtil_Model_ModelAbstract $model, array $data, array &$prefixes) { // Set labels in the main model for the submodel fields if ($model->getMeta('nested', false)) { $nestedNames = $model->getMeta('nestedNames'); foreach($nestedNames as $nestedName) { $nestedModel = $model->get($nestedName, 'model'); $nestedLabels = $nestedModel->getcolNames('label'); foreach($nestedLabels as $colName) { $label = $nestedModel->get($colName, 'label'); $model->set($colName, 'label', $label); } $model->remove($nestedName, 'label'); } } }
Add nested model fields to the export model @param MUtil_Model_ModelAbstract $model @param array $data @param array $prefixes
entailment
protected function _addSurveyAnswersToExportModel(\MUtil_Model_ModelAbstract $model, \Gems_Tracker_Survey $survey, array $data, array &$prefixes) { $prefixes['A'] = []; $language = $this->locale->getLanguage(); $questions = $survey->getQuestionList($language); $questionInformation = $survey->getQuestionInformation($language); foreach($questions as $questionName => $label) { if ($parent = $model->get($questionName, 'parent_question')) { if ($model->get($parent, 'type') === \MUtil_Model::TYPE_NOVALUE) { if (isset($data['subquestions']) && $data['subquestions'] == 'prefix_child') { $cleanLabel = strip_tags($label); $model->set($questionName, 'label', $cleanLabel); } if (isset($data['subquestions']) && $data['subquestions'] == 'show_parent') { if (!in_array($parent, $prefixes['A'])) { $prefixes['A'][] = $parent; if (isset($questionInformation[$parent], $questionInformation[$parent]['question'])) { $cleanLabel = strip_tags($questionInformation[$parent]['question']); $model->set($parent, 'label', $cleanLabel); } } } else { $model->remove($parent, 'label'); } } } if ($question = $model->get($questionName, 'survey_question') && $model->get($questionName, 'label') == null) { $model->set($questionName, 'label', $questionName); if (isset($questionInformation[$questionName], $questionInformation[$questionName]['question'])) { $cleanLabel = strip_tags($questionInformation[$questionName]['question']); $model->set($questionName, 'label', $cleanLabel); } } $prefixes['A'][] = $questionName; } }
Add all survey answers to the export model @param MUtil_Model_ModelAbstract $model @param Gems_Tracker_Survey $survey @param array $data @param array $prefixes
entailment
protected function _addSurveySourceAttributesToExportModel(\MUtil_Model_ModelAbstract $model, \Gems_Tracker_Survey $survey, array $data, array &$prefixes) { $source = $survey->getSource(); $attributes = $source->getAttributes(); $preExistingFields = $model->getColNames('label'); $attributes = array_diff($attributes, $preExistingFields); foreach($attributes as $attribute) { $model->set($attribute, 'label', $attribute); } }
Add the survey source attributes to the export model that have not yet been set. @param MUtil_Model_ModelAbstract $model @param Gems_Tracker_Survey $survey @param array $data @param array $prefixes @throws Gems_Exception
entailment
public function getExtraDataFormElements(\Gems_Form $form, $data) { $this->form = $form; $elements = []; if (isset($data['gto_id_track']) && $data['gto_id_track']) { $elements['add_track_fields'] = $this->_createCheckboxElement( 'add_track_fields', $this->_('Track fields'), $this->_('Add track fields to export') ); } if ($this->currentUser->hasPrivilege('pr.export.add-resp-nr')) { $elements['export_resp_nr'] = $this->_createCheckboxElement( 'export_resp_nr', $this->getRespondentModel()->get('gr2o_patient_nr', 'label'), $this->_('Add respondent nr to export') ); } if ($this->currentUser->hasPrivilege('pr.export.gender-age')) { $elements['export_resp_gender'] = $this->_createCheckboxElement( 'export_resp_gender', $this->_('Respondent gender'), $this->_('Add respondent gender to export') ); $elements['export_birth_year'] = $this->_createCheckboxElement( 'export_birth_year', $this->_('Respondent birth year'), $this->_('Add respondent birth year to export') ); $elements['export_birth_month'] = $this->_createCheckboxElement( 'export_birth_month', $this->_('Respondent birth month'), $this->_('Add respondent birth month to export') ); } $elements['export_track_reception_code'] = $this->_createCheckboxElement( 'export_track_reception_code', $this->_('Track reception code'), $this->_('Add reception code of track') ); $elements['export_token_reception_code'] = $this->_createCheckboxElement( 'export_token_reception_code', $this->_('Token reception code'), $this->_('Add reception code of token') ); return $elements; }
Get form elements for the specific Export @param \Gems_Form $form existing form type @param array data existing options set in the form @return array of form elements
entailment
public function getModel($filter = array(), $data = array()) { if ($filter !== $this->filter || !$this->model) { $this->filter = $filter; $surveyId = $filter['gto_id_survey']; $language = $this->locale->getLanguage(); $survey = $this->loader->getTracker()->getSurvey($surveyId); $model = $survey->getAnswerModel($language); // Reset labels and order foreach($model->getItemNames() as $itemName) { $model->remove($itemName, 'label'); } $model->resetOrder(); $prefixes = []; $this->_addDefaultFieldsToExportModel($model, $data, $prefixes); $this->_addSurveyAnswersToExportModel($model, $survey, $data, $prefixes); $this->_addNestedFieldsToExportModel($model, $data, $prefixes); $this->_addSurveySourceAttributesToExportModel($model, $survey, $data, $prefixes); $prefixes['D'] = array_diff($model->getColNames('label'), $prefixes['A'], $model->getItemsFor('table', 'gems__respondent2org')); $this->_addExtraDataToExportModel($model, $data, $prefixes); if (isset($data['column_identifiers']) && $data['column_identifiers'] == 1) { foreach ($prefixes as $prefix => $prefixCategory) { foreach($prefixCategory as $columnName) { if ($label = $model->get($columnName, 'label')) { $model->set($columnName, 'label', '(' . $prefix . ') ' . $label); } } } } $this->model = $model; // Exclude external fields from sorting foreach($this->model->getItemsUsed() as $item) { if (!$this->model->get($item, 'table', 'column_expression')) { $this->model->set($item, 'noSort', true); } } } return $this->model; }
Get the model to export @param array $filter Filter for the model @param array $data Data from the form options @return \MUtil_Model_ModelAbstract
entailment
public function subscribeAction() { $orgId = urldecode($this->getRequest()->getParam('org')); if ($orgId && ($orgId != $this->currentUser->getCurrentOrganizationId())) { $allowedOrganizations = $this->currentUser->getAllowedOrganizations(); if ((! $this->currentUser->isActive()) || isset($allowedOrganizations[$orgId])) { $this->currentUser->setCurrentOrganization($orgId); } } $this->html->h1($this->_('Subscribe')); $screen = $this->currentUser->getCurrentOrganization()->getSubscribeScreen(); if ($screen instanceof SubscribeScreenInterface) { $params = $screen->getSubscribeParameters(); $snippets = $screen->getSubscribeSnippets(); } else { $list = $this->_getScreenOrgs('gor_respondent_subscribe'); if ($list) { $params = [ 'action' => 'subscribe', 'info' => $this->_('Select an organization to subscribe to:'), 'orgs' => $list, ]; $snippets = ['Organization\\ChooseListedOrganizationSnippet']; } else { $params = []; $snippets = ['Subscribe\\NoSubscriptionsSnippet']; } } $this->addSnippets($snippets, $params); }
Ask the user which organization to participate with @return void
entailment
public function unsubscribeAction() { $orgId = urldecode($this->getRequest()->getParam('org')); if ($orgId && ($orgId != $this->currentUser->getCurrentOrganizationId())) { $allowedOrganizations = $this->currentUser->getAllowedOrganizations(); if ((! $this->currentUser->isActive()) || isset($allowedOrganizations[$orgId])) { $this->currentUser->setCurrentOrganization($orgId); } } $this->html->h1($this->_('Unsubscribe')); $screen = $this->currentUser->getCurrentOrganization()->getUnsubscribeScreen(); if ($screen instanceof UnsubscribeScreenInterface) { $params = $screen->getUnsubscribeParameters(); $snippets = $screen->getUnsubscribeSnippets(); } else { $list = $this->_getScreenOrgs('gor_respondent_unsubscribe'); if ($list) { $params = [ 'action' => 'unsubscribe', 'info' => $this->_('Select an organization to unsubscribe from:'), 'orgs' => $list, ]; $snippets = ['Organization\\ChooseListedOrganizationSnippet']; } else { $params = []; $snippets = ['Unsubscribe\\NoUnsubscriptionsSnippet']; } } $this->addSnippets($snippets, $params); }
Ask the user which organization to unsubscribe from @return void
entailment
public function unsubscribeToOrgAction() { $request = $this->getRequest(); $orgId = urldecode($request->getParam('org')); $allowedOrganizations = $this->currentUser->getAllowedOrganizations(); if ((! $this->currentUser->isActive()) || isset($allowedOrganizations[$orgId])) { $this->currentUser->setCurrentOrganization($orgId); } $this->forward('unsubscribe'); }
Ask the user which organization to participate with @return void
entailment
public function removesessionAction() { $success = false; $request = $this->getEvent()->getRequest(); if ($request instanceof Request && $request->isPost()) { $containerName = $request->getPost('containerName', 'Default'); $keysession = $request->getPost('keysession', ''); $success = $this->sessionManager ->sessionSetting($containerName, $keysession); } return new JsonModel([ 'success' => $success, ]); }
Remove Session by Container and its key.
entailment
public function reloadsessionAction() { $sessionData = $this->sessionManager->getSessionData(false); $renderedContent = $this->viewRenderer ->render('zend-developer-tools/toolbar/session-data-list', ['sessionData' => $sessionData]); return new JsonModel([ 'san_sessiontoolbar_data_renderedContent' => $renderedContent, ]); }
Reload Session data.
entailment
public function clearsessionAction() { $request = $this->getEvent()->getRequest(); if ($request instanceof Request && $request->isPost()) { $this->sessionManager->clearSession($request->getPost('byContainer')); } $sessionData = $this->sessionManager->getSessionData(); $renderedContent = $this->viewRenderer ->render('zend-developer-tools/toolbar/session-data-list', ['sessionData' => $sessionData]); return new JsonModel([ 'san_sessiontoolbar_data_renderedContent' => $renderedContent, ]); }
Clear Session data.
entailment
public function savesessionAction() { $processSetOrAddSessionData = ['success' => false, 'errorMessage' => '']; $request = $this->getEvent()->getRequest(); if ($request instanceof Request && $request->isPost()) { $processSetOrAddSessionData = $this->setOrAddSession($request); } $sessionData = $this->sessionManager->getSessionData(); $renderedContent = $this->viewRenderer ->render('zend-developer-tools/toolbar/session-data-list', ['sessionData' => $sessionData]); return new JsonModel([ 'success' => $processSetOrAddSessionData['success'], 'errorMessage' => $processSetOrAddSessionData['errorMessage'], 'san_sessiontoolbar_data_renderedContent' => $renderedContent, ]); }
Save Session by Container and its key.
entailment
private function setOrAddSession(Request $request) { $containerName = $request->getPost('containerName', 'Default'); $keysession = $request->getPost('keysession', ''); $sessionValue = $request->getPost('sessionvalue', ''); $new = (bool) $request->getPost('new', false); $notEmptyValidator = new NotEmpty(); if ($notEmptyValidator->isValid($keysession) && $notEmptyValidator->isValid($sessionValue)) { $success = $this->sessionManager ->sessionSetting($containerName, $keysession, $sessionValue, ['set' => true, 'new' => $new]); return ['success' => $success, 'errorMessage' => '']; } return ['success' => false, 'errorMessage' => 'Value is required and can\'t be empty']; }
Set or Add Session Data Process. @param Request $request @return array
entailment
public function calculateFieldValue($currentValue, array $fieldData, array $trackData) { if (null === $currentValue && isset($this->_fieldDefinition['gtf_field_default'])) { return $this->_fieldDefinition['gtf_field_default']; } 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 getCalculationFields(array $fieldData) { $output = array(); // Perform automatic calculation if (isset($this->_fieldDefinition['gtf_calculate_using'])) { $sources = explode(self::FIELD_SEP, $this->_fieldDefinition['gtf_calculate_using']); foreach ($sources as $source) { if (isset($fieldData[$source]) && $fieldData[$source]) { $output[$source] = $fieldData[$source]; } else { $output[$source] = null; } } } return array_reverse($output, true); }
Get the fields that should be used for calculation, first field to use first. I.e. the last selected field in field maintenance is the first field in the output array. @param array $fieldData The fields being saved @return array [fieldKey => fieldValue]
entailment
protected function _getSelectForm() { $form = new \Gems_Form(array('name' => 'autosubmit', 'class' => 'form-inline', 'role' => 'form')); $form->setHtml('div'); $div = $form->getHtml(); $div->class = 'search'; $span = $div->div(array('class' => 'panel panel-default'))->div(array('class' => 'inputgroup panel-body')); $element = $form->createElement('select', 'gpa_level', array( 'multiOptions' => $this->patchLevels, 'onchange' => 'this.form.submit();', 'onkeyup' => 'this.form.submit();', )); $element->setValue($this->getPatchLevel()); $span->input($element); $form->addElement($element); $submit = $form->createElement('submit', 'search', array( 'label' => $this->_('Search'), 'class' => 'button small', )); $span->input($submit); $form->addElement($submit); return $form; }
The form for selecting the patch level @return \Gems_Form
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { if (! $this->patchLevels) { $this->addMessage($this->_('This new project has no structural changes to show.')); return; } $patchLevel = $this->getPatchLevel(); $seq = $this->getHtmlSequence(); $seq->append($this->_getSelectForm()); $div = $seq->div(array('id' => 'autofilter_target')); $div->h2(sprintf($this->_('Structural changes in patch level %d'), $patchLevel)); $div->pInfo($this->_('Download: ')) ->a( array('download' => 1, 'gpa_level' => $patchLevel), sprintf('patchlevel.%d.sql', $patchLevel), array('type' => 'application/download') ); $lastLocation = ''; $lastName = ''; $noOutput = true; foreach ($this->getStructuralPatches($patchLevel) as $patch) { if ($patch['gpa_location'] != $lastLocation) { $div->h3(sprintf($this->_('Group %s'), $patch['gpa_location'])); $lastLocation = $patch['gpa_location']; } if ($patch['gpa_name'] != $lastName) { $div->h4(sprintf($this->_('Patch %s'), $patch['gpa_name'])); $lastName = $patch['gpa_name']; } $div->pre(wordwrap($patch['gpa_sql'], 80, "\n ")); $noOutput = false; } if ($noOutput) { $div->pInfo(sprintf($this->_('No structural changes in patchlevel %d'), $patchLevel)); } return $seq; }
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 getStructuralPatches($patchLevel) { $patches = $this->db->fetchAll( "SELECT * FROM gems__patches WHERE gpa_level = ? ORDER BY gpa_location, gpa_name, gpa_order", $patchLevel ); foreach ($patches as $patchId => $patch) { if (\MUtil_String::startsWith(trim($patch['gpa_sql']), 'INSERT', true) || \MUtil_String::startsWith(trim($patch['gpa_sql']), 'UPDATE', true) || \MUtil_String::startsWith(trim($patch['gpa_sql']), 'DELETE', true)) { unset($patches[$patchId]); } } return $patches; }
Get the structural patches for the given patch level @param int $patchLevel @return array
entailment
public function getTextOutput() { $patchLevel = $this->getPatchLevel(); $commands = array(sprintf('-- Patch level %d structural changes', $patchLevel)); $lastLocation = ''; $lastName = ''; $noOutput = true; foreach ($this->getStructuralPatches($patchLevel) as $patch) { if ($patch['gpa_location'] != $lastLocation) { $commands[] = sprintf("\n-- DATABASE LOCATION: %s", $patch['gpa_location']); $lastLocation = $patch['gpa_location']; } if ($patch['gpa_name'] != $lastName) { $commands[] = sprintf("\n-- PATCH: %s", $patch['gpa_name']); $lastName = $patch['gpa_name']; } $commands[] = $patch['gpa_sql'] . ';'; $noOutput = false; } if ($noOutput) { $commands[] = sprintf("\n-- No structural changes in patchlevel %d", $patchLevel); } $commands[] = ''; return implode("\n", $commands); }
Get the content as text @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment
protected function getPatchLevel() { if (isset($this->searchData['gpa_level']) && $this->searchData['gpa_level']) { return $this->searchData['gpa_level']; } return reset($this->patchLevels); }
Current patch level @return int
entailment
public function loadDefaultDecorators() { if ($this->loadDefaultDecoratorsIsDisabled()) { return; } $decorators = $this->getDecorators(); if (empty($decorators)) { $this->addDecorator('Tabs', $this->_decoratorOptions) ->addDecorator('Label'); } }
Load default decorators @return void
entailment
protected function addFormElements(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model) { if (! $this->createData) { $bridge->addHidden('gtr_id_track'); } $bridge->addText('gtr_track_name'); // gtr_track_class if ($this->trackEngine) { $options = $model->get('gtr_track_class', 'multiOptions'); $alternatives = $this->trackEngine->getConversionTargets($options); if (count($alternatives) > 1) { $options = $alternatives; $bridge->addHidden($this->_oldClassName); if (! isset($this->formData[$this->_oldClassName])) { $this->formData[$this->_oldClassName] = $this->formData['gtr_track_class']; } $classEdit = true; } else { $classEdit = false; } } else { $tracker = $this->loader->getTracker(); $options = $tracker->getTrackEngineList(true, true); $classEdit = true; } $model->set('gtr_track_class', 'multiOptions', $options, 'escape', false); if ($classEdit) { $bridge->addRadio( 'gtr_track_class'); } else { $bridge->addExhibitor('gtr_track_class'); } $bridge->addDate('gtr_date_start'); $bridge->addDate('gtr_date_until'); if (! $this->createData) { $bridge->addCheckbox('gtr_active'); } if ($model->has('gtr_code')) { $bridge->addText('gtr_code'); } if ($model->has('gtr_calculation_event', 'label')) { $bridge->add('gtr_calculation_event'); } if ($model->has('gtr_completed_event', 'label')) { $bridge->add('gtr_completed_event'); } if ($model->has('gtr_beforefieldupdate_event', 'label')) { $bridge->add('gtr_beforefieldupdate_event'); } if ($model->has('gtr_fieldupdate_event', 'label')) { $bridge->add('gtr_fieldupdate_event'); } $bridge->add('gtr_organizations'); if (\MUtil_Bootstrap::enabled()) { $element = new \MUtil_Bootstrap_Form_Element_ToggleCheckboxes('toggleOrg', array('selector'=>'input[name^=gtr_organizations]')); } else { $element = new \Gems_JQuery_Form_Element_ToggleCheckboxes('toggleOrg', array('selector'=>'input[name^=gtr_organizations]')); } $element->setLabel($this->_('Toggle')); $bridge->addElement($element); }
Adds elements from the model to the bridge that creates the form. Overrule this function to add different elements to the browse table, without having to recode the core table building code. @param \MUtil_Model_Bridge_FormBridgeInterface $bridge @param \MUtil_Model_ModelAbstract $model
entailment
protected function createModel() { $model = $this->loader->getTracker()->getTrackModel(); $model->applyFormatting(true, true); return $model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function hasHtmlOutput() { if ($this->trackEngine && (! $this->trackId)) { $this->trackId = $this->trackEngine->getTrackId(); } if ($this->trackId) { // We are updating $this->createData = false; // Try to get $this->trackEngine filled if (! $this->trackEngine) { // Set the engine used $this->trackEngine = $this->loader->getTracker()->getTrackEngine($this->trackId); } } else { // We are inserting $this->createData = true; $this->saveLabel = $this->_($this->_('Add new track')); } 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 loadFormData() { parent::loadFormData(); // feature request #200 if (isset($this->formData['gtr_organizations']) && (! is_array($this->formData['gtr_organizations']))) { $this->formData['gtr_organizations'] = explode('|', trim($this->formData['gtr_organizations'], '|')); } }
Hook that loads the form data from $_POST or the model Or from whatever other source you specify here.
entailment
protected function saveData() { // feature request #200 if (isset($this->formData['gtr_organizations']) && is_array($this->formData['gtr_organizations'])) { $this->formData['gtr_organizations'] = '|' . implode('|', $this->formData['gtr_organizations']) . '|'; } if ($this->trackEngine) { $this->formData['gtr_survey_rounds'] = $this->trackEngine->calculateRoundCount(); } else { $this->formData['gtr_survey_rounds'] = 0; } parent::saveData(); // Check for creation if ($this->createData) { if (isset($this->formData['gtr_id_track'])) { $this->trackId = $this->formData['gtr_id_track']; } } elseif ($this->trackEngine && isset($this->formData[$this->_oldClassName], $this->formData['gtr_track_class']) && $this->formData[$this->_oldClassName] != $this->formData['gtr_track_class']) { // Track conversion $this->trackEngine->convertTo($this->formData['gtr_track_class']); } }
Hook containing the actual save code. Call's afterSave() for user interaction. @see afterSave()
entailment
public function execute($tokenData = null, $userId = null) { $batch = $this->getBatch(); $tracker = $this->loader->getTracker(); $token = $tracker->getToken($tokenData); if ($token->isCompleted()) { $respTrack = $token->getRespondentTrack(); $userId = $userId ? $userId : $this->loader->getCurrentUser()->getUserId(); if ($result = $respTrack->handleRoundCompletion($token, $userId)) { $a = $batch->addToCounter('roundCompletionCauses'); $b = $batch->addToCounter('roundCompletionChanges', $result); $batch->setMessage('roundCompletionChanges', sprintf($this->_('%d token round completion events caused changed to %d tokens.'), $a, $b) ); } $trackId = $respTrack->getRespondentTrackId(); $batch->setTask('Tracker_CheckTrackTokens', 'chktrck-' . $trackId, $trackId, $userId); } // Free memory $tracker->removeToken($token); }
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 getAnswerDisplaySnippets(\Gems_Tracker_Token $token) { $this->token = $token; $snippets = (array) $token->getTrackEngine()->getAnswerSnippetNames(); $snippets['answerFilter'] = $this; return $snippets; }
Function that returns the snippets to use for this display. @param \Gems_Tracker_Token $token The token to get the snippets for @return array of Snippet names or nothing
entailment
protected function getHeaders(\MUtil_Model_ModelAbstract $model, array $currentNames) { $lastParent = null; $results = array(); foreach ($currentNames as $name) { if ($model->is($name, 'type', \MUtil_Model::TYPE_NOVALUE)) { $results[$name] = $name; } elseif ($parent = $model->get($name, 'parent_question')) { // Insert parent header on name if it was not shown before $results[$parent] = $parent; } } return $results; }
Returns only the headers @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
protected function restoreHeaderPositions(\MUtil_Model_ModelAbstract $model, array $currentNames) { $lastParent = null; $results = array(); foreach ($currentNames as $name) { if ($model->is($name, 'type', \MUtil_Model::TYPE_NOVALUE)) { // Skip header types that contain no value continue; } if ($parent = $model->get($name, 'parent_question')) { // Check for change of parent if ($lastParent !== $parent) { if (isset($results[$parent])) { // Add another copy of the parent to the array $results[] = $parent; } else { // Insert parent header on name if it was not shown before $results[$parent] = $parent; } $lastParent = $parent; } } else { // Make sure a question (without parent) is picked up as parent too $lastParent = $name; } // If already set (as a $parent) this will not // redisplay the $parent as $result[$name] does // not change position $results[$name] = $name; } return $results; }
Restores the header position of question before their corresponding question_sub When sub-questions with the same parent are shown continuous the parent is shown once before them. When the sub-questions are displayed in seperate groups the parent is shown once at their start. Stand alone headers without any corresponding value are removed. When they do have a value of their own they are still shown, but their position may change according to their sub-questions position. (NOTE: As in LimeSurvey their are no question headers with values we leave it at this for the moment.) @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
protected function getControllerTargetModel($controller) { switch ($controller) { case 'respondent': $model = $this->loader->getModels()->getRespondentModel(true); $model->applyEditSettings(); return $model; case 'calendar': $model = $this->loader->getModels()->createAppointmentModel(); $this->applySource($model); $model->applyEditSettings(); return $model; default: return null; } }
The model to use with a controller @param string $controller Name of controller (or other id) @return \MUtil_Model_ModelAbstract or null when not found
entailment
public function getFilenameController($filename) { $filename = strtolower(basename($filename)); if (preg_match('/^respondent/', $filename)) { return 'respondent'; } if (preg_match('/^appointment/', $filename)) { return 'calendar'; } return false; }
Get the controller that should be linked to the filename @param string $filename Name of file to import @return string or false if none found.
entailment
public function getOrganizationCode() { if (! $this->_orgCode) { $this->_orgCode = $this->currentOrganization->getCode(); if (! $this->_orgCode) { $this->_orgCode = \MUtil_File::cleanupName($this->currentOrganization->getName()); } } return $this->_orgCode; }
Get the organization name/code used by the long term filename @return string
entailment
public function getLongtermFileName($controller, $dateValue = null) { if ($dateValue instanceof \Zend_Date) { $date = $dateValue; } else { $date = new \MUtil_Date($dateValue); } $name[] = $controller; $name[] = $date->toString('YYYY-MM-ddTHH-mm-ss'); $name[] = preg_replace('/[^a-zA-Z0-9_]/', '', $this->currentUser->getLoginName()); $name[] = $this->getOrganizationCode(); return implode('.', array_filter($name)); }
The file name to use for final storage, minus the extension @param string $controller Name of controller (or other id) @param mixed $dateValue Optional date item to use in filename, timestamp, or DateObject or MUtil_Date @return string
entailment
public function getTranslators($controller, $filename = null) { $translator = $this->getTranslateAdapter(); switch ($controller) { case 'answers': $output['default'] = new \Gems_Model_Translator_TokenAnswerTranslator( $translator->_('Link by token id') ); $output['resp'] = new \Gems_Model_Translator_RespondentAnswerTranslator( $translator->_('Link by patient id') ); $output['date'] = new \Gems_Model_Translator_DateAnswerTranslator( $translator->_('Link by patient id and completion date') ); break; case 'calendar': $output['default'] = new \Gems_Model_Translator_AppointmentTranslator($translator->_('Direct import')); break; case 'respondent': $output['default'] = new \Gems_Model_Translator_RespondentTranslator($translator->_('Direct import')); break; case 'staff': $output['default'] = new \Gems_Model_Translator_StaffTranslator($translator->_('Direct import')); break; default: $output['default'] = new \Gems_Model_Translator_StraightTranslator($translator->_('Direct import')); break; } foreach ($output as $trs) { $this->applySource($trs); } return $output; }
Get the possible translators for the import snippet. @param string $controller Name of controller (or other id) @param string $filename Optional, name of file to import @return \MUtil_Model_ModelTranslatorInterface[]
entailment
public static function addWhenChanged($name, $value, array &$results, array $tokenAnswers) { if ($value != $tokenAnswers[$name]) { $results[$name] = $value; return true; } else { return false; } }
Adds value to $results when it is different from the value in $tokenAnswers. @param string $name The name of the values @param mixed $value The value to compare to @param array $results The results to add to @param array $tokenAnswers The answers to compare to @return boolean True when the value changed.
entailment
private static function _arrayFindName(array $tokenAnswers, $fieldNames) { $results = array(); foreach ($tokenAnswers as $fieldName => $value) { if (strpos($fieldName, $fieldNames) !== false) { $results[] = $fieldName; } } // \MUtil_Echo::track($results); return $results; }
Finds those tokenAnswers array keys that contain "fieldNames" in their key. @param array $tokenAnswers @param string $fieldNames @return array
entailment
public static function averageInt(array $tokenAnswers, $fieldNames) { if (is_string($fieldNames)) { $fieldNames = self::_arrayFindName($tokenAnswers, $fieldNames); } $count = 0; $sum = 0; foreach ($fieldNames as $name) { if (isset($tokenAnswers[$name]) && (is_int($tokenAnswers[$name]) || (string) intval($tokenAnswers[$name]) === $tokenAnswers[$name])) { $count++; $sum += intval($tokenAnswers[$name]); } } return $count ? $sum / $count : null; }
Returns the avarage over those $fieldNames values that exist in $tokenAnswers and are integers. @param array $tokenAnswers Array containing the answers @param mixed $fieldNames An array of those names that should be used or a string that should occur in all names that have to be selected. @return float
entailment
public static function checkFloatChanged(array $values, array $tokenAnswers) { $results = array(); foreach($values as $name => $result) { if (! ((null === $result) && (null === $tokenAnswers[$name]))) { $result = round(floatval($result), 13); if (((string) $tokenAnswers[$name] != (string) $result) || (null === $tokenAnswers[$name])) { // Round to a number the LS database can hold $results[$name] = $result; } } } return $results; }
Checks all $values for a change against $tokenAnswers as floats @param array $values @param array $tokenAnswers @return array Those values that were changed.
entailment
public static function checkIntegerChanged(array $values, array $tokenAnswers) { $results = array(); foreach($values as $name => $result) { $result = intval($result); if (($tokenAnswers[$name] != $result) || ($tokenAnswers[$name] === null)) { $results[$name] = $result; } } return $results; }
Checks all $values for a change against $tokenAnswers as integer @param array $values @param array $tokenAnswers @return array Those values that were changed.
entailment
public static function roundFixed($value, $decimals = 2) { $value = round($value, $decimals); $pos = strpos($value, '.'); if ($pos === false) { $value .= '.' . str_repeat('0', $decimals); } else { $extra = $decimals - strlen($value) + $pos + 1; if ($extra > 0) { $value .= str_repeat('0', $extra); } } return $value; }
Rounds the value with a fixed number of decimals, padding zeros when required. @param numeric $value @param int $decimals @return string
entailment
public static function sumInt(array $tokenAnswers, $fieldNames) { if (is_string($fieldNames)) { $fieldNames = self::_arrayFindName($tokenAnswers, $fieldNames); } $sum = 0; foreach ($fieldNames as $name) { if (isset($tokenAnswers[$name]) && (is_int($tokenAnswers[$name]) || (string) intval($tokenAnswers[$name]) === $tokenAnswers[$name])) { $sum += intval($tokenAnswers[$name]); } } return $sum; }
Returns the sum over those $fieldNames values that exist in $tokenAnswers and are integers @param array $tokenAnswers Array containing the answers @param mixed $fieldNames An array of those names that should be used or a string that should occur in all names that have to be selected. @return int
entailment
public function getPanel() { $this->_request = Zend_Controller_Front::getInstance()->getRequest(); $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); if ($viewRenderer->view && method_exists($viewRenderer->view, 'getVars')) { $viewVars = $this->_cleanData($viewRenderer->view->getVars()); } else { $viewVars = "No 'getVars()' method in view class"; } $vars = '<div style="width:50%;float:left;">'; $vars .= '<h4>View variables</h4>' . '<div id="ZFDebug_vars" style="margin-left:-22px">' . $viewVars . '</div>' . '<h4>Request parameters</h4>' . '<div id="ZFDebug_requests" style="margin-left:-22px">' . $this->_cleanData($this->_request->getParams()) . '</div>'; $vars .= '</div><div style="width:45%;float:left;">'; if ($this->_request->isPost()) { $vars .= '<h4>Post variables</h4>' . '<div id="ZFDebug_post" style="margin-left:-22px">' . $this->_cleanData($this->_request->getPost()) . '</div>'; } $vars .= '<h4>Constants</h4>'; $constants = get_defined_constants(true); ksort($constants['user']); $vars .= '<div id="ZFDebug_constants" style="margin-left:-22px">' . $this->_cleanData($constants['user']) . '</div>'; $registry = Zend_Registry::getInstance(); $vars .= '<h4>Zend Registry</h4>'; $registry->ksort(); $vars .= '<div id="ZFDebug_registry" style="margin-left:-22px">' . $this->_cleanData($registry) . '</div>'; $cookies = $this->_request->getCookie(); $vars .= '<h4>Cookies</h4>' . '<div id="ZFDebug_cookie" style="margin-left:-22px">' . $this->_cleanData($cookies) . '</div>'; $vars .= '</div><div style="clear:both">&nbsp;</div>'; return $vars; }
Gets content panel for the Debugbar @return string
entailment