Пример #1
0
 /**
  * Allows the loader to set resources.
  *
  * @param string $name Name of resource to set
  * @param mixed $resource The resource.
  * @return boolean True if $resource was OK
  */
 public function answerRegistryRequest($name, $resource)
 {
     if (\MUtil_Registry_Source::$verbose) {
         \MUtil_Echo::r('Resource set: ' . get_class($this) . '->' . __FUNCTION__ . '("' . $name . '", ' . (is_object($resource) ? get_class($resource) : gettype($resource)) . ')');
     }
     $this->{$name} = $resource;
     return true;
 }
Пример #2
0
 /**
  * Instantiate a new class using the arguments array for initiation
  *
  * @param string $className
  * @param array $arguments Instanciation arguments
  * @return className
  */
 public function createClass($className, array $arguments = array())
 {
     $object = parent::createClass($className, $arguments);
     if ($object instanceof \MUtil_Registry_TargetInterface) {
         if ($this->_source instanceof \MUtil_Registry_SourceInterface) {
             $this->_source->applySource($object);
         } elseif (self::$verbose) {
             \MUtil_Echo::r("Loading target class {$className}, but source not set.");
         }
     }
     return $object;
 }
Пример #3
0
 /**
  * Returns a value for $name
  *
  * @param string $name A name indentifying a value in this stack.
  * @return A value for $name
  */
 public function lazyGet($name)
 {
     if (property_exists($this->_object, $name)) {
         return $this->_object->{$name};
     }
     if ($this->_throwOnMiss) {
         throw new \MUtil_Lazy_LazyException("No lazy stack variable defined for '{$name}' parameter.");
     }
     if (\MUtil_Lazy::$verbose) {
         $class = get_class($this->_object);
         \MUtil_Echo::header("No lazy stack variable defined for '{$name}' parameter using a '{$class}' object.");
     }
     return null;
 }
Пример #4
0
 /**
  * Returns a value for $name
  *
  * @param string $name A name indentifying a value in this stack.
  * @return A value for $name
  */
 public function lazyGet($name)
 {
     // \MUtil_Echo::track($name, $this->offsetExists($name), $this->offsetGet($name), $this->getArrayCopy());
     if ($this->offsetExists($name)) {
         return $this->offsetGet($name);
     }
     if ($this->_throwOnMiss) {
         throw new \MUtil_Lazy_LazyException("No lazy stack variable defined for '{$name}' parameter.");
     }
     if (\MUtil_Lazy::$verbose) {
         \MUtil_Echo::header("No lazy stack variable defined for '{$name}' parameter.");
     }
     return null;
 }
 /**
  *
  * @param \MUtil_Batch_BatchAbstract $batch
  * @param string $title
  * @param \Gems_AccessLog $accessLog
  */
 public function direct(\MUtil_Batch_BatchAbstract $batch, $title, $accessLog = null)
 {
     if ($batch->isConsole()) {
         $batch->runContinuous();
         $messages = array_values($batch->getMessages(true));
         echo implode("\n", $messages) . "\n";
         $echo = array_filter(array_map('trim', preg_split('/<[^>]+>/', \MUtil_Echo::out())));
         if ($echo) {
             echo "\n\n================================================================\nECHO OUTPUT:\n\n";
             echo implode("\n", $echo);
         }
         if ($accessLog instanceof \Gems_AccessLog) {
             $accessLog->logChange($this->getRequest(), $messages, $echo);
         }
         exit;
     } elseif ($batch->run($this->getRequest())) {
         exit;
     } else {
         $controller = $this->getActionController();
         $batchContainer = $controller->html->div(array('class' => 'batch-container'));
         $batchContainer->h3($title);
         if ($batch->isFinished()) {
             $controller->addMessage($batch->getMessages(true), 'info');
             $batchContainer->pInfo($batch->getRestartButton($controller->_('Prepare recheck'), array('class' => 'actionlink')));
             if ($accessLog instanceof \Gems_AccessLog) {
                 $echo = array_filter(array_map('trim', preg_split('/<[^>]+>/', \MUtil_Echo::getOutput())));
                 $accessLog->logChange($this->getRequest(), null, $echo);
             }
         } else {
             if ($batch->count()) {
                 $batchContainer->pInfo($batch->getStartButton(sprintf($controller->_('Start %s jobs'), $batch->count())));
                 $batchContainer->append($batch->getPanel($controller->view, $batch->getProgressPercentage() . '%'));
             } else {
                 $batchContainer->pInfo($controller->_('Nothing to do.'));
             }
         }
     }
 }
 /**
  * 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
  */
 public function execute($lineNr = null, $fieldId = null, $fieldSub = null, $fieldCalc = null)
 {
     $batch = $this->getBatch();
     $import = $batch->getVariable('import');
     if (!(isset($import['trackId']) && $import['trackId'] && $fieldId)) {
         // Do nothing
         return;
     }
     $tracker = $this->loader->getTracker();
     $trackEngine = $tracker->getTrackEngine($import['trackId']);
     $fieldCodes = $import['fieldCodes'];
     $fieldModel = $trackEngine->getFieldsMaintenanceModel(true, 'edit');
     $roundOrders = $import['roundOrders'];
     $saveData['gtf_id_field'] = $fieldId;
     $saveData['sub'] = $fieldSub;
     $saveData['gtf_id_track'] = $import['trackId'];
     $calcFields = is_array($fieldCalc) ? $fieldCalc : explode('|', trim($fieldCalc, '|'));
     if (!$calcFields) {
         return;
     }
     foreach ($calcFields as $field) {
         if (isset($fieldCodes[$field]) && $fieldCodes[$field]) {
             $saveData['gtf_calculate_using'][] = $fieldCodes[$field];
         } else {
             // Actually this code currently is PULSE specific
             if (\MUtil_String::startsWith($field, '{r')) {
                 $roundOrder = substr($field, 2, -1);
                 if (isset($roundOrders[$roundOrder]) && $roundOrders[$roundOrder]) {
                     $saveData['gtf_calculate_using'][] = $roundOrders[$roundOrder];
                 } else {
                     $saveData['gtf_calculate_using'][] = $field;
                 }
             }
         }
     }
     \MUtil_Echo::track($saveData, $fieldId);
     $fieldModel->save($saveData);
 }
 /**
  * Stores the fields that can be used for sorting or filtering in the
  * sort / filter objects attached to this model.
  *
  * @param array $parameters
  * @param boolean $includeNumericFilters When true numeric filter keys (0, 1, 2...) are added to the filter as well
  * @return array The $parameters minus the sort & textsearch keys
  */
 public function applyParameters(array $parameters, $includeNumericFilters = false)
 {
     if ($parameters) {
         // Allow use when passed only an ID value
         if (isset($parameters[\MUtil_Model::REQUEST_ID]) && !isset($parameters[\MUtil_Model::REQUEST_ID1], $parameters[\MUtil_Model::REQUEST_ID2])) {
             $id = $parameters[\MUtil_Model::REQUEST_ID];
             $keys = $this->getKeys();
             $field = array_shift($keys);
             $parameters[$field] = $id;
             if ($field2 = array_shift($keys)) {
                 $parameters[$field2] = $this->getCurrentOrganization();
                 \MUtil_Echo::r('Still using old HiddenModel parameters.', 'DEPRECIATION WARNING');
                 \MUtil_Echo::r($parameters);
             }
             unset($parameters[\MUtil_Model::REQUEST_ID]);
         }
         if (isset($parameters[\MUtil_Model::REQUEST_ID2]) && !array_key_exists($parameters[\MUtil_Model::REQUEST_ID2], $this->currentUser->getAllowedOrganizations())) {
             $this->initTranslateable();
             throw new \Gems_Exception($this->_('Inaccessible or unknown organization'), 403, null, sprintf($this->_('Access to this page is not allowed for current role: %s.'), $this->currentUser->getRole()));
         }
         return parent::applyParameters($parameters, $includeNumericFilters);
     }
     return array();
 }
Пример #8
0
 /**
  * Adds which settings are effected by a value
  *
  * Overrule this function, e.g. when a sub class changed a fixed setting,
  * but for diverse fields.
  *
  * @param string $effectedField A field name
  * @param mixed $effectedSettings A single setting or an array of settings
  * @return \MUtil\Model\Dependency\DependencyAbstract (continuation pattern)
  */
 public function addEffected($effectedField, $effectedSettings)
 {
     foreach ((array) $effectedSettings as $setting) {
         if (is_array($setting)) {
             \MUtil_Echo::track($setting);
         }
         $this->_effecteds[$effectedField][$setting] = $setting;
     }
     return $this;
 }
Пример #9
0
 /**
  * Compile a less file
  *
  * @param \Zend_View $view
  * @param string $href The less file
  * @param boolean $always Always compile
  * @return boolean True when changed
  */
 public function compile(\Zend_View $view, $href, $always = false)
 {
     if (\MUtil_String::startsWith($href, 'http', true)) {
         // When a local url, strip the serverUrl and basepath
         $base = $view->serverUrl() . $view->baseUrl();
         if (\MUtil_String::startsWith($href, $base, true)) {
             // Only strip when urls match
             $href = substr($href, strlen($base));
         }
     }
     // Add full path to the webdir
     $inFile = $this->_webroot . '/' . $href;
     $outFile = substr($inFile, 0, -strlen(pathinfo($inFile, PATHINFO_EXTENSION))) . 'css';
     // Try compiling
     try {
         // \MUtil_Echo::track($inFile, $outFile);
         $lessc = new lessc();
         $lessc->registerFunction('base64encode', array($this, 'base64encode'));
         if ($always || array_key_exists('compilecss', \Zend_Controller_Front::getInstance()->getRequest()->getParams())) {
             $result = (bool) $lessc->compileFile($inFile, $outFile);
         } else {
             $result = $lessc->checkedCompile($inFile, $outFile);
         }
     } catch (\Exception $exc) {
         // If we have an error, present it if not in production
         if (APPLICATION_ENV !== 'production' || APPLICATION_ENV !== 'acceptance') {
             \MUtil_Echo::pre($exc->getMessage());
         }
         $result = null;
     }
     return $result;
 }
Пример #10
0
 /**
  * Searches for a matching image location and returns that location when found.
  *
  * $filenames starting with a '/' or with http or https are skipped.
  *
  * @param type $filename The src attribute as filename
  * @return string When a directory matches
  */
 public static function getImageDir($filename)
 {
     if ($filename && '/' != $filename[0] && 'http://' != substr($filename, 0, 7) && 'https://' != substr($filename, 0, 8)) {
         $webRoot = self::getWebRoot();
         foreach (self::$_imageDirs as $dir) {
             if (file_exists($webRoot . $dir . $filename)) {
                 return $dir;
             }
         }
         if (\MUtil_Html::$verbose) {
             \MUtil_Echo::r("File not found: {$filename}. \n\nLooked in: \n" . implode(", \n", self::$_imageDirs));
         }
     }
 }
Пример #11
0
 /**
  * Returns the options from the allowedoptions array, using the supplied options first and trying
  * to find the missing ones in the model.
  *
  * @param string $name
  * @param array $options
  * @param array $allowedOptionKeys_array
  * @return array
  */
 private function _mergeOptions($name, array $options, $allowedOptionKeys_array)
 {
     $args = func_get_args();
     $allowedOptionsKeys = \MUtil_Ra::args($args, 2);
     $allowedOptions = array();
     foreach ($allowedOptionsKeys as $allowedOptionsKey) {
         if (is_array($allowedOptionsKey)) {
             $allowedOptions = array_merge($allowedOptions, $allowedOptionsKey);
         } else {
             if (array_key_exists($allowedOptionsKey, $this->_allowedOptions)) {
                 $allowedOptions = array_merge($allowedOptions, $this->_allowedOptions[$allowedOptionsKey]);
             } else {
                 $allowedOptions[] = $allowedOptionsKey;
             }
         }
     }
     //If not explicitly set, use the form value for translatorDisabled, since we
     //create the element outside the form scope and later add it
     if (!isset($options['disableTranslator']) && array_search('disableTranslator', $allowedOptions) !== false) {
         $options['disableTranslator'] = $this->form->translatorIsDisabled();
     }
     // Move options to model.
     if (isset($options['validator'])) {
         $this->model->set($name, 'validators[]', $options['validator']);
         unset($options['validator']);
     }
     if ($allowedOptions) {
         // Remove options already filled. Using simple array addition
         // might trigger a lot of lazy calculations that are not needed.
         $allowedOptionsFlipped = array_flip($allowedOptions);
         // First strip the options that are not allowed
         if (\MUtil_Model::$verbose) {
             $strippedKeys = array_keys(array_diff_key($options, $allowedOptionsFlipped));
             if (!empty($strippedKeys)) {
                 \MUtil_Echo::r($strippedKeys, 'stripped from options for ' . $name);
             }
         }
         $options = array_intersect_key($options, $allowedOptionsFlipped);
         // Now get allowed options from the model
         $modelOptions = $this->model->get($name, $allowedOptions);
         // Merge them: first use supplied $options, and add missing values from model
         return (array) $options + (array) $modelOptions;
     }
     return $options;
 }
 public function autofilterAction()
 {
     // Make sure all links are generated as if the current request was index.
     $this->aliasAction('index');
     // \MUtil_Model::$verbose = true;
     // We do not need to return the layout, just the above table
     $this->disableLayout();
     $this->html[] = $this->_createTable();
     $this->html->raw(\MUtil_Echo::out());
 }
Пример #13
0
 /**
  * The functions that fixes and returns a value.
  *
  * Be warned: this function may return a lazy value.
  *
  * @param \MUtil_Lazy_StackInterface $stack A \MUtil_Lazy_StackInterface object providing variable data
  * @return mixed
  */
 public function __toValue(\MUtil_Lazy_StackInterface $stack)
 {
     $array = $this->_array;
     $offset = $this->_offset;
     while ($offset instanceof \MUtil_Lazy_LazyInterface) {
         $offset = $offset->__toValue($stack);
     }
     while ($array instanceof \MUtil_Lazy_LazyInterface) {
         $array = $array->__toValue($stack);
     }
     if (\MUtil_Lazy::$verbose) {
         \MUtil_Echo::header('Lazy offset get for offset: <em>' . $offset . '</em>');
         \MUtil_Echo::classToName($array);
     }
     if (null === $offset) {
         if (isset($array[''])) {
             $value = $array[''];
         } else {
             $value = null;
         }
     } elseif (is_array($offset)) {
         // When the offset is itself an array, return an
         // array of values applied to this offset.
         $value = array();
         foreach (\MUtil_Lazy::riseRa($offset, $stack) as $key => $val) {
             if (isset($array[$val])) {
                 $value[$key] = $val;
             }
         }
     } elseif (isset($array[$offset])) {
         $value = $array[$offset];
     } else {
         $value = null;
     }
     while ($value instanceof \MUtil_Lazy_LazyInterface) {
         $value = $value->__toValue($stack);
     }
     if (is_array($value)) {
         $value = \MUtil_Lazy::riseRa($value, $stack);
     }
     return $value;
 }
Пример #14
0
 public function echoRules()
 {
     \MUtil_Echo::r($this->_rules);
 }
 /**
  * Update the track, both in the database and in memory.
  *
  * @param array $values The values that this token should be set to
  * @param int $userId The current user
  * @return int 1 if data changed, 0 otherwise
  */
 private function _update(array $values, $userId)
 {
     if ($this->tracker->filterChangesOnly($this->_trackData, $values)) {
         if (\Gems_Tracker::$verbose) {
             $echo = '';
             foreach ($values as $key => $val) {
                 $echo .= $key . ': ' . $this->_trackData[$key] . ' => ' . $val . "\n";
             }
             \MUtil_Echo::r($echo, 'Updated values for ' . $this->_trackId);
         }
         if (!isset($values['gto_changed'])) {
             $values['gtr_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
         }
         if (!isset($values['gtr_changed_by'])) {
             $values['gtr_changed_by'] = $userId;
         }
         // Update values in this object
         $this->_trackData = $values + $this->_trackData;
         // return 1;
         return $this->db->update('gems__tracks', $values, array('gtr_id_track = ?' => $this->_trackId));
     } else {
         return 0;
     }
 }
Пример #16
0
 /**
  * Returns a nested array containing the items requested.
  *
  * @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 array Nested array or false
  */
 protected function _load(array $filter, array $sort)
 {
     $setcount = 0;
     $results = array();
     if (isset($filter[$this->textFilterField])) {
         $textFilter = $filter[$this->textFilterField];
         unset($filter[$this->textFilterField]);
     } else {
         $textFilter = false;
     }
     foreach ($this->_getFilterModels($filter) as $name => $model) {
         if ($model instanceof \MUtil_Model_ModelAbstract) {
             $modelFilter = $this->_map($filter, $name, false, true);
             if (isset($this->_unionMapsTo[$name]) && $this->_unionMapsTo[$name]) {
                 // Translate the texts filters
                 foreach ($modelFilter as $key => $value) {
                     if (is_numeric($key) && is_string($value)) {
                         $modelFilter[$key] = strtr($value, $this->_unionMapsTo[$name]);
                     }
                 }
             }
             if (\MUtil_Model::$verbose) {
                 \MUtil_Echo::r($modelFilter, "Filter for model {$name}.");
             }
             if ($textFilter) {
                 // Text filter is always on visible fields and uses multiOptions
                 if (isset($this->_unionMapsTo[$name]) && $this->_unionMapsTo[$name]) {
                     foreach ($this->getCol('label') as $fname => $label) {
                         if (isset($this->_unionMapsTo[$name][$fname])) {
                             $mname = $this->_unionMapsTo[$name][$fname];
                         } else {
                             $mname = $fname;
                         }
                         $model->set($mname, 'label', $label, 'multiOptions', $this->get($fname, 'multiOptions'));
                     }
                 } else {
                     foreach ($this->getCol('label') as $fname => $label) {
                         $model->set($fname, 'label', $label, 'multiOptions', $this->get($fname, 'multiOptions'));
                     }
                 }
                 $modelFilter = array_merge($modelFilter, $model->getTextSearchFilter($textFilter));
             }
             $resultset = $model->load($modelFilter, $this->_map($sort, $name, false, false));
             if ($resultset) {
                 $sub = array($this->_modelField => $name);
                 foreach ($resultset as $row) {
                     $results[] = $sub + $this->_map($row, $name, true, false);
                 }
                 $setcount = $setcount + 1;
             }
         }
     }
     if ($setcount && $sort) {
         $results = $this->_sortData($results, $sort);
     }
     return $results;
 }
Пример #17
0
 /**
  * Process the changes in the model caused by dependencies, using this data.
  *
  * @param array $data The input data
  * @param boolean $new True when it is a new item not saved in the model
  * @return array The possibly change input data
  */
 public function processDependencies(array $data, $new)
 {
     foreach ($this->_model_dependencies as $dependency) {
         if ($dependency instanceof DependencyInterface) {
             $dependsOn = $dependency->getDependsOn();
             $context = array_intersect_key($data, $dependsOn);
             // \MUtil_Echo::track($context, $dependsOn, get_class($dependency));
             // If there are required fields and all required fields are there
             if ($dependsOn && count($context) === count($dependsOn)) {
                 $changes = $dependency->getChanges($context, $new);
                 if ($changes) {
                     if (\MUtil_Model::$verbose) {
                         \MUtil_Echo::r($changes, 'Changes by ' . get_class($dependency));
                     }
                     // Here we could allow only those changes this dependency claims to change
                     // but as not specifying this correctly may lead to errors elsewhere
                     // I think there is enough reason for discipline in this not to perform
                     // this extra check. (Though I may change my mind in the future
                     $this->_applyDependencyChanges($this, $changes, $data);
                 }
             } elseif (\MUtil_Model::$verbose) {
                 if ($dependsOn) {
                     $missing = array_diff_key($dependsOn, $data);
                     if (1 === count($missing)) {
                         $msg = "Missing field %s for dependency class %s";
                         $fld = reset($missing);
                     } else {
                         $msg = "Missing fields %s for dependency class %s";
                         $fld = implode(', ', array_keys($missing));
                     }
                 } else {
                     $msg = "%s%s dependency is not dependent on any fields.";
                     $fld = '';
                 }
                 \MUtil_Echo::r(sprintf($msg, $fld, get_class($dependency)), 'Dependency skipped');
             }
         }
     }
     // \MUtil_Echo::track($data);
     return $data;
 }
 /**
  * Action that switches the maintenance lock on or off.
  */
 public function maintenanceAction()
 {
     // Switch lock
     if ($this->util->getMonitor()->reverseMaintenanceMonitor()) {
         $this->accesslog->logChange($this->getRequest(), $this->_('Maintenance mode set ON'));
     } else {
         $this->accesslog->logChange($this->getRequest(), $this->_('Maintenance mode set OFF'));
         // Dump the existing maintenance mode messages.
         $this->escort->getMessenger()->clearCurrentMessages();
         $this->escort->getMessenger()->clearMessages();
         \MUtil_Echo::out();
     }
     // Redirect
     $request = $this->getRequest();
     $this->_reroute(array($request->getActionKey() => 'index'));
 }
 /**
  * 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)
  */
 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;
 }
Пример #20
0
 /**
  * Save a single model item.
  *
  * @param array $newValues The values to store for a single model item.
  * @param array $filter If the filter contains old key values these are used
  * to decide on update versus insert.
  * @param array $saveTables Optional array containing the table names to save,
  * otherwise the tables set to save at model level will be saved.
  * @return array The values as they are after saving (they may change).
  */
 protected function _save(array $newValues, array $filter = null, array $saveTables = null)
 {
     $saveTables = $this->_checkSaveTables($saveTables);
     $oldChanged = $this->getChanged();
     // \MUtil_Echo::track($newValues, $filter, $saveTables, $this->_joinFields);
     $oldValues = $newValues;
     foreach ($saveTables as $tableName => $saveMode) {
         // Gotta repeat this every time, as keys may be set later
         foreach ($this->_joinFields as $source => $target) {
             // Use is_string as $target and $target can be e.g. a \Zend_Db_Expr() object
             // as $source is an index keys it must be a string
             if (is_string($target)) {
                 if (!(isset($newValues[$target]) && $newValues[$target])) {
                     if (!(isset($newValues[$source]) && $newValues[$source])) {
                         if (\MUtil_Model::$verbose) {
                             \MUtil_Echo::r('Missing: ' . $source . ' -> ' . $target, 'ERROR!');
                         }
                         continue;
                     }
                     $newValues[$target] = $newValues[$source];
                 } elseif (!(isset($newValues[$source]) && $newValues[$source])) {
                     $newValues[$source] = $newValues[$target];
                 } elseif (strlen($newValues[$target]) > 0 && strlen($newValues[$source]) > 0 && $newValues[$target] != $newValues[$source]) {
                     // Join key values changed.
                     //
                     // Set the old values as the filter
                     $filter[$target] = $newValues[$target];
                     $filter[$source] = $newValues[$source];
                     // Switch the target value to the value in the source field.
                     //
                     // JOIN FIELD ORDER IS IMPORTANT!!!
                     // The changing field must be stated first in the join statement.
                     $newValues[$target] = $newValues[$source];
                 }
             } elseif ($target instanceof \Zend_Db_Expr && !(isset($newValues[$source]) && $newValues[$source])) {
                 $newValues[$source] = $target;
             }
         }
         //$this->_saveTableData returns the new row values, including any automatic changes.
         $newValues = $this->_saveTableData($this->_tables[$tableName], $newValues, $filter, $saveMode) + $oldValues;
         // \MUtil_Echo::track($oldValues, $newValues, $filter);
         $oldValues = $newValues;
     }
     // If anything has changed, it counts as only one item for the user.
     if ($this->getChanged() > $oldChanged) {
         $this->setChanged(++$oldChanged);
     }
     return $newValues;
 }
Пример #21
0
 /**
  * Send a warning, if not already done
  *
  * @staticvar boolean $warn
  */
 private function _warn()
 {
     static $warn = true;
     if ($warn) {
         \MUtil_Echo::r('Database needs to be updated, tables missing!');
         $warn = false;
     }
 }
 /**
  * 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
  */
 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
     if ($this->_requiredParameters) {
         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;
 }
 /**
  * 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
  */
 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'];
 }
Пример #24
0
 /**
  * Returns a field from the raw answers as a date object.
  *
  * A seperate function as only the source knows what format the date/time value has.
  *
  * @param string $fieldName Name of answer field
  * @param \Gems_Tracker_Token $token Gems token object
  * @param int $surveyId Gems Survey Id
  * @param string $sourceSurveyId Optional Survey Id used by source
  * @return \MUtil_Date date time or null
  */
 public function getAnswerDateTime($fieldName, \Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null)
 {
     $answers = $token->getRawAnswers();
     if (isset($answers[$fieldName]) && $answers[$fieldName]) {
         if (\Zend_Date::isDate($answers[$fieldName], \Zend_Date::ISO_8601)) {
             return new \MUtil_Date($answers[$fieldName], \Zend_Date::ISO_8601);
         }
         if (\Gems_Tracker::$verbose) {
             \MUtil_Echo::r($answers[$fieldName], 'Missed answer date value:');
         }
     }
 }
Пример #25
0
 /**
  * Do a recursive find of the changes
  *
  * @param array $switches Current level of switches array
  * @param array $dependsOn Current level of $dependsOn array
  * @param array $context Context
  * @return array name => array(setting => value)
  */
 protected function _findChanges(array $switches, array $dependsOn, array $context)
 {
     // Found it when depends on is empty
     if (!$dependsOn) {
         return $switches;
     }
     $name = array_shift($dependsOn);
     // When there is no data, return no changes
     if (!array_key_exists($name, $context)) {
         if (\MUtil_Model::$verbose) {
             $names = array_diff_key($this->_dependentOn, $context);
             \MUtil_Echo::r(implode(', ', $names), 'Name(s) not found in ' . get_class($this));
         }
         return array();
     }
     $value = $context[$name];
     if ($value) {
         // All true cases
         foreach ($switches as $key => $rest) {
             if ($value == $key) {
                 return $this->_findChanges($rest, $dependsOn, $context);
             }
         }
     } else {
         // For non-true value we use exact type comparison, except when both are zero's
         if (null === $value) {
             foreach ($switches as $key => $rest) {
                 if (null === $key) {
                     return $this->_findChanges($rest, $dependsOn, $context);
                 }
             }
         } elseif (0 === $value || "0" === $value) {
             foreach ($switches as $key => $rest) {
                 if (0 === $key || "0" === $key) {
                     return $this->_findChanges($rest, $dependsOn, $context);
                 }
             }
         } elseif ("" === $value) {
             foreach ($switches as $key => $rest) {
                 if ("" === $key) {
                     return $this->_findChanges($rest, $dependsOn, $context);
                 }
             }
         }
     }
     if (\MUtil_Model::$verbose) {
         \MUtil_Echo::track($this->_switches, $this->_dependentOn, $this->_effecteds);
         \MUtil_Echo::r("Value '{$value}' not found for field {$name} among the values: " . implode(', ', array_keys($switches)), 'Value not found in ' . get_class($this));
     }
     return array();
 }
Пример #26
0
 /**
  * Survey dependent calculations / answer changes that must occur after a survey is completed
  *
  * @param type $tokenId The tokend the answers are for
  * @param array $tokenAnswers Array with answers. May be changed in process
  * @return array The changed values
  */
 public function handleBeforeAnswering()
 {
     $survey = $this->getSurvey();
     $event = $survey->getSurveyBeforeAnsweringEvent();
     if ($event) {
         try {
             $changed = $event->processTokenInsertion($this);
             if ($changed && is_array($changed)) {
                 $this->setRawAnswers($changed);
                 if (\Gems_Tracker::$verbose) {
                     \MUtil_Echo::r($changed, 'Source values for ' . $this->_tokenId . ' changed by event.');
                 }
                 return $changed;
             }
         } catch (\Exception $e) {
             $this->logger->log(sprintf("Before answering event error for token %s on survey '%s' using event '%s': %s", $this->_tokenId, $this->getSurveyName(), $event->getEventName(), $e->getMessage()), \Zend_Log::ERR);
         }
     }
 }
Пример #27
0
 /**
  * Update the survey, both in the database and in memory.
  *
  * @param array $values The values that this token should be set to
  * @param int $userId The current user
  * @return int 1 if data changed, 0 otherwise
  */
 private function _updateSurvey(array $values, $userId)
 {
     if ($this->tracker->filterChangesOnly($this->_gemsSurvey, $values)) {
         if (\Gems_Tracker::$verbose) {
             $echo = '';
             foreach ($values as $key => $val) {
                 $old = isset($this->_gemsSurvey[$key]) ? $this->_gemsSurvey[$key] : null;
                 $echo .= $key . ': ' . $old . ' => ' . $val . "\n";
             }
             \MUtil_Echo::r($echo, 'Updated values for ' . $this->_surveyId);
         }
         if (!isset($values['gsu_changed'])) {
             $values['gsu_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
         }
         if (!isset($values['gsu_changed_by'])) {
             $values['gsu_changed_by'] = $userId;
         }
         if ($this->exists) {
             // Update values in this object
             $this->_gemsSurvey = $values + $this->_gemsSurvey;
             // return 1;
             return $this->db->update('gems__surveys', $values, array('gsu_id_survey = ?' => $this->_surveyId));
         } else {
             if (!isset($values['gsu_created'])) {
                 $values['gsu_created'] = new \MUtil_Db_Expr_CurrentTimestamp();
             }
             if (!isset($values['gsu_created_by'])) {
                 $values['gsu_created_by'] = $userId;
             }
             // Update values in this object
             $this->_gemsSurvey = $values + $this->_gemsSurvey;
             // Remove the Gems survey id
             unset($this->_gemsSurvey['gsu_id_survey']);
             $this->_surveyId = $this->db->insert('gems__surveys', $this->_gemsSurvey);
             $this->_gemsSurvey['gsu_id_survey'] = $this->_surveyId;
             $this->exists = true;
             return 1;
         }
     } else {
         return 0;
     }
 }
 /**
  * Assign the tokens to the correct relation
  * 
  * Only surveys that have not yet been answered will be assigned to the correct relation.
  * 
  * @return int Number of changes tokens
  */
 public function assignTokensToRelations()
 {
     // Find out if we have relation fields and return when none exists in this track
     $relationFields = $this->getTrackEngine()->getFieldsOfType('relation');
     if (empty($relationFields)) {
         return 0;
     }
     // Check if we have a respondent relation id (grr_id) in the track fields
     // and assign the token to the correct relation or leave open when no
     // relation is defined.
     $this->_ensureRounds();
     $relationFields = $this->getFieldData();
     $fieldPrefix = \Gems\Tracker\Model\FieldMaintenanceModel::FIELDS_NAME . \Gems\Tracker\Engine\FieldsDefinition::FIELD_KEY_SEPARATOR;
     $changes = 0;
     foreach ($this->getTokens() as $token) {
         /* @var $token Gems_Tracker_Token */
         if (!$token->isCompleted() && $token->getReceptionCode()->isSuccess()) {
             $roundId = $token->getRoundId();
             if (!array_key_exists($roundId, $this->_rounds)) {
                 // If not a current round for this track, do check the round when it still exists
                 $round = $this->getTrackEngine()->getRoundModel(true, 'index')->loadFirst(array('gro_id_round' => $roundId));
             } else {
                 $round = $this->_rounds[$roundId];
             }
             $relationFieldId = null;
             $relationId = null;
             // Read from the round
             if (!empty($round) && $round['gro_id_track'] == $this->getTrackId() && $round['gro_active'] == 1) {
                 if ($round['gro_id_relationfield'] > 0) {
                     $relationFieldId = $round['gro_id_relationfield'];
                 }
             } else {
                 // Try to read from token, as this is a token without a round
                 $relationFieldId = $token->getRelationFieldId();
             }
             if ($relationFieldId > 0) {
                 $fieldKey = $fieldPrefix . $relationFieldId;
                 if (isset($relationFields[$fieldKey])) {
                     $relationId = (int) $relationFields[$fieldKey];
                 } else {
                     $relationId = -1 * $relationFieldId;
                 }
             }
             $changes = $changes + $token->assignTo($relationId, $relationFieldId);
         }
     }
     if (MUtil_Model::$verbose && $changes > 0) {
         MUtil_Echo::r(sprintf('%s tokens changed due to changes in respondent relation assignments.', $changes));
     }
     return $changes;
 }
 /**
  * Process the data and return the answers that should be changed.
  *
  * Storing the changed values is handled by the calling function.
  *
  * @param \Gems_Tracker_Token $token Gems token object
  * @return array Containing the changed values
  */
 public function processTokenData(\Gems_Tracker_Token $token)
 {
     $result = var_export($token->getRawAnswers(), true);
     \MUtil_Echo::r($result, $token->getTokenId());
     return false;
 }
Пример #30
0
 /**
  * Hook 6: Called after \Zend_Controller_Router has determined the route set by the request.
  *
  * This events enables you to adjust the route after the routing has run it's course.
  *
  * Not initialized is the $controller object.
  *
  * Previous hook: routeStartup()
  * Actions since: $router->route()
  * Actions after: nothing, but the route consisting of controller, action and module should now be fixed
  * Next hook: dispatchLoopStartup()
  *
  * Also sets $this->currentOrganization and $this->menu to access afterwards
  *
  * @param  \Zend_Controller_Request_Abstract $request
  * @return void
  */
 public function routeShutdown(\Zend_Controller_Request_Abstract $request)
 {
     $loader = $this->getLoader();
     // Load the menu. As building the menu can depend on all resources and the request, we do it here.
     //
     // PS: The REQUEST is needed because otherwise the locale for translate is not certain.
     $menu = $loader->createMenu($this);
     $source = $menu->getParameterSource();
     $user = $this->_container->currentUser;
     $user->setRequest($request);
     $organization = $user->getCurrentOrganization();
     $organization->applyToMenuSource($source);
     $this->_container->currentOrganization = $organization;
     $this->_container->menu = $menu;
     $this->_updateVariable(array('currentOrganization', 'menu'));
     // Now is a good time to check for required values
     // Moved down here to prevent unit test from failing on missing salt
     $this->project->checkRequiredValues();
     /**
      * Check if we are in maintenance mode or not. This is triggeren by a file in the var/settings
      * directory with the name lock.txt
      */
     if ($this->getUtil()->getMaintenanceLock()->isLocked()) {
         if ($user->isActive() && !$user->hasPrivilege('pr.maintenance.maintenance-mode')) {
             //Still allow logoff so we can relogin as master
             if (!('index' == $request->getControllerName() && 'logoff' == $request->getActionName())) {
                 $this->setError($this->_('Please check back later.'), 401, $this->_('System is in maintenance mode'));
             }
             $user->unsetAsCurrentUser();
         } else {
             $this->addMessage($this->_('System is in maintenance mode'));
             \MUtil_Echo::r($this->_('System is in maintenance mode'));
         }
     }
     // Gems does not use index/index
     $action = $request->getActionName();
     if ('index' == $request->getControllerName() && ('index' == $action || $user->isActive() && 'login' == $action)) {
         // Instead Gems routes to the first available menu item when this is the request target
         if (!$user->gotoStartPage($menu, $request)) {
             $this->setError($this->_('No access to site.'), 401, $this->_('You have no access to this site.'), true);
             return;
         }
     } else {
         //find first allowed item in the menu
         $menuItem = $menu->find(array('action' => $request->getActionName(), 'controller' => $request->getControllerName()));
         // Display error when not having the right priviliges
         if (!($menuItem && $menuItem->get('allowed'))) {
             // When logged in
             if ($user->getUserId()) {
                 $this->setError($this->_('No access to page'), 403, sprintf($this->_('Access to the %s/%s page is not allowed for current role: %s.'), $request->getControllerName(), $request->getActionName(), $user->getRole()), true);
             } else {
                 // No longer logged in
                 if (\MUtil_Console::isConsole()) {
                     $this->setError('No access to page.', 401, sprintf('Controller "%s" action "%s" is not accessible.', $request->getControllerName(), $request->getActionName()), true);
                     return;
                 }
                 if ($request->getActionName() == 'autofilter') {
                     // Throw an exception + HTTP 401 when an autofilter is called
                     throw new \Gems_Exception("Session expired", 401);
                 }
                 $menuItem = $menu->findFirst(array('allowed' => true, 'visible' => true));
                 if ($menuItem) {
                     // Do not store previous request & show message when the intended action is logoff
                     if (!($request->getControllerName() == 'index' && $request->getActionName() == 'logoff')) {
                         $this->addMessage($this->_('You are no longer logged in.'));
                         $this->addMessage($this->_('You must login to access this page.'));
                         if (!\MUtil_String::contains($request->getControllerName() . $request->getActionName(), '.')) {
                             // save original request, we will redirect back once the user succesfully logs in
                             $staticSession = $this->getStaticSession();
                             $staticSession->previousRequestParameters = $request->getParams();
                             $staticSession->previousRequestMode = $request->isPost() ? "POST" : "GET";
                         }
                     }
                     $redirector = \Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
                     $redirector->gotoRoute($menuItem->toRouteUrl($request));
                 } else {
                     $this->setError($this->_('You are no longer logged in.'), 401, $this->_('You have no access to this site.'), true);
                     return;
                 }
             }
         }
     }
     if (isset($menuItem)) {
         $menuItem->applyHiddenParameters($request, $source);
         $menu->setCurrent($menuItem);
     }
 }