/**
  * Hook containing the actual save code.
  *
  * Call's afterSave() for user interaction.
  *
  * @see afterSave()
  */
 public function saveData()
 {
     $model = $this->getModel();
     if ($this->formData['gto_valid_until']) {
         // Make sure date based units are valid until the end of the day.
         $date = new \MUtil_Date($this->formData['gto_valid_until'], $model->get('gto_valid_until', 'dateFormat'));
         $date->setTimeToDayEnd();
         $this->formData['gto_valid_until'] = $date;
     }
     // Save the token using the model
     parent::saveData();
     // $this->token->setValidFrom($this->formData['gto_valid_from'], $this->formData['gto_valid_until'], $this->loader->getCurrentUser()->getUserId());
     // \MUtil_Echo::track($this->formData);
     // Refresh (NOT UPDATE!) token with current form data
     $updateData['gto_valid_from'] = $this->formData['gto_valid_from'];
     $updateData['gto_valid_from_manual'] = $this->formData['gto_valid_from_manual'];
     $updateData['gto_valid_until'] = $this->formData['gto_valid_until'];
     $updateData['gto_valid_until_manual'] = $this->formData['gto_valid_until_manual'];
     $updateData['gto_comment'] = $this->formData['gto_comment'];
     $this->token->refresh($updateData);
     $respTrack = $this->token->getRespondentTrack();
     $userId = $this->loader->getCurrentUser()->getUserId();
     $changed = $respTrack->checkTrackTokens($userId, $this->token);
     if ($changed) {
         $this->addMessage(sprintf($this->plural('%d token changed by recalculation.', '%d tokens changed by recalculation.', $changed), $changed));
     }
 }
 /**
  * Prcesses the filter for the date selector and return the filter to use instead
  * 
  * @param \Zend_Controller_Request_Abstract $request
  * @param array $filter
  * @param string $dateField
  * @return array The new complete filter to use
  */
 public function getFilter(\Zend_Controller_Request_Abstract $request, array $filter = array(), $dateField = null)
 {
     $this->_actionKey = $request->getActionKey();
     // \MUtil_Echo::r($filter, __CLASS__ . '->' . __FUNCTION__ .' 1');
     $filter = $this->processFilter($request, $filter);
     if ($filter) {
         $model = $this->getModel();
         $model->addFilter($filter);
     }
     // \MUtil_Echo::r($filter, __CLASS__ . '->' . __FUNCTION__ . ' 2');
     $newfilter = $filter;
     if ($this->dateCurrentStart && $this->dateCurrentEnd) {
         if (null === $dateField) {
             $dateField = $this->dateFrom;
         }
         $start = $this->dateCurrentStart->getIso();
         $end = $this->dateCurrentEnd->getIso();
         $newfilter[] = "{$dateField} BETWEEN '{$start}' AND '{$end}'";
     }
     if ($this->dateGroup) {
         $fields = $this->getFields();
         if (isset($fields[$this->dateGroup])) {
             if ($groupfilter = $fields[$this->dateGroup]->getFilter()) {
                 $newfilter[] = $groupfilter;
             }
         }
     }
     return $newfilter;
 }
 /**
  * Creates the model
  *
  * @return \MUtil_Model_ModelAbstract
  */
 protected function createModel()
 {
     $model = $this->loader->getTracker()->getRespondentTrackModel();
     $model->addColumn('CONCAT(gr2t_completed, \'' . $this->_(' of ') . '\', gr2t_count)', 'progress');
     $model->resetOrder();
     $model->set('gtr_track_name', 'label', $this->_('Track'));
     $model->set('gr2t_track_info', 'label', $this->_('Description'));
     $model->set('gr2t_start_date', 'label', $this->_('Start'), 'formatFunction', $this->util->getTranslated()->formatDate, 'default', \MUtil_Date::format(new \Zend_Date(), 'dd-MM-yyyy'));
     $model->set('gr2t_reception_code');
     $model->set('progress', 'label', $this->_('Progress'));
     // , 'tdClass', 'rightAlign', 'thClass', 'rightAlign');
     $model->set('assigned_by', 'label', $this->_('Assigned by'));
     return $model;
 }
 /**
  * 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
  */
 public function getHtmlOutput(\Zend_View_Abstract $view)
 {
     $html = $this->getHtmlSequence();
     if (!$this->trackData) {
         $html->h2($this->_('Unknown track'));
         $this->addMessage(sprintf($this->_('Unknown track id %s'), $this->trackId));
         return $html;
     }
     if ($this->showHeader) {
         $html->h2(sprintf($this->_('%s track'), $this->trackData['gtr_track_name']));
     }
     if (isset($this->trackData['gtr_date_until']) && $this->trackData['gtr_date_until']) {
         $html->pInfo(sprintf($this->_('This track can be assigned from %s until %s.'), \MUtil_Date::format($this->trackData['gtr_date_start'], \Zend_Date::DATE_LONG), \MUtil_Date::format($this->trackData['gtr_date_until'], \Zend_Date::DATE_LONG)));
     } else {
         $html->pInfo(sprintf($this->_('This track can be assigned since %s.'), \MUtil_Date::format($this->trackData['gtr_date_start'], \Zend_Date::DATE_LONG)));
     }
     return $html;
 }
 /**
  * Returns current age or at a given date when supplied
  *
  * @param \MUtil_Date|null $date
  * @return int
  */
 public function getAge($date = NULL)
 {
     if (is_null($date)) {
         $date = new \MUtil_Date();
     }
     if ($date instanceof \MUtil_Date) {
         // Now calculate age
         $birthDate = $this->getBirthDate();
         if ($birthDate instanceof \Zend_Date) {
             $age = $date->get('Y') - $birthDate->get('Y');
             if ($date->get('MMdd') < $birthDate->get('MMdd')) {
                 $age--;
             }
         } else {
             return;
         }
     }
     return $age;
 }
示例#6
0
 /**
  * Return an array of functions used to process the value
  *
  * @param string $name The real name and not e.g. the key id
  * @return array
  */
 protected function _compile($name)
 {
     $output = array();
     if ($this->model->has($name, 'multiOptions')) {
         $options = $this->model->get($name, 'multiOptions');
         $output['multiOptions'] = function ($value) use($options) {
             return is_scalar($value) && array_key_exists($value, $options) ? $options[$value] : $value;
         };
     }
     if ($this->model->has($name, 'formatFunction')) {
         $output['formatFunction'] = $this->model->get($name, 'formatFunction');
     } elseif ($this->model->has($name, 'dateFormat')) {
         $format = $this->model->get($name, 'dateFormat');
         if (is_callable($format)) {
             $output['dateFormat'] = $format;
         } else {
             $storageFormat = $this->model->get($name, 'storageFormat');
             $output['dateFormat'] = function ($value) use($format, $storageFormat) {
                 return \MUtil_Date::format($value, $format, $storageFormat);
             };
         }
     } elseif ($this->model->has($name, 'numberFormat')) {
         $format = $this->model->get($name, 'numberFormat');
         if (is_callable($format)) {
             $output['numberFormat'] = $format;
         } else {
             $output['numberFormat'] = function ($value) use($format) {
                 return \Zend_Locale_Format::toNumber($value, array('number_format' => $format));
             };
         }
     }
     if ($this->model->has($name, 'markCallback')) {
         $output['markCallback'] = $this->model->get($name, 'markCallback');
     }
     return $output;
 }
 /**
  * When saving a date by using a string, it should work too
  */
 public function testSetDateFields()
 {
     $respondentTrack = $this->loader->getTracker()->getRespondentTrack(1);
     // $expected = $respondentTrack->getFieldData();
     $date = new \MUtil_Date('2010-11-09', 'yyyy-MM-dd');
     $expected = array('f__1' => 'newvalue', 'code' => 'newvalue', 'f__2' => $date, 'datecode' => $date);
     $actual = $respondentTrack->setFieldData(array('code' => 'newvalue', 'datecode' => $date->toString('yyyy-MM-dd')));
     $this->assertArrayWithDateMatch($expected, $actual, '', 1, 0);
 }
示例#8
0
文件: Log.php 项目: GemsTracker/MUtil
 /**
  * Get the filename to use
  *
  * @param int $index
  * @return string
  */
 protected function _getLogFileName($index = null)
 {
     switch ($this->_logRotate) {
         case self::ROTATE_PER_MONTH:
             if (null === $index) {
                 $now = new \MUtil_Date();
                 $index = $now->toString(\Zend_Date::MONTH);
             } elseif ($index < 10) {
                 $index = "0" . $index;
             }
             $filename = $this->_logFileRoot . '-mon-' . $index . '.log';
             break;
         case self::ROTATE_PER_MONTH:
             if (null === $index) {
                 $now = new \MUtil_Date();
                 $index = $now->toString(\Zend_Date::WEEK);
             } elseif ($index < 10) {
                 $index = "0" . $index;
             }
             $filename = $this->_logFileRoot . '-wk-' . $index . '.log';
             break;
         default:
             $filename = $this->_logFileRoot;
             if (!\MUtil_String::endsWith($filename, '.log')) {
                 $filename .= '.log';
             }
             break;
     }
     return $filename;
 }
示例#9
0
 /**
  * Returns an array of elements for check fields during password reset and/or
  * 'label name' => 'required value' pairs. vor asking extra questions before allowing
  * a password change.
  *
  * Default is asking for the username but you can e.g. ask for someones birthday.
  *
  * @return array Of 'label name' => 'required values' or \Zend_Form_Element elements
  */
 protected function loadResetPasswordCheckFields()
 {
     // CHECK ON SOMEONES BIRTHDAY
     // Birthdays are usually not defined for staff but the do exist for respondents
     if ($value = $this->_getVar('user_birthday')) {
         $label = $this->_('Your birthday');
         $birthdayElem = new \Gems_JQuery_Form_Element_DatePicker('birthday');
         $birthdayElem->setLabel($label)->setOptions(\MUtil_Model_Bridge_FormBridge::getFixedOptions('date'))->setStorageFormat(\Zend_Date::ISO_8601);
         if ($format = $birthdayElem->getDateFormat()) {
             $valueFormatted = \MUtil_Date::format($value, $format, $birthdayElem->getStorageFormat());
         } else {
             $valueFormatted = $value;
         }
         $validator = new \Zend_Validate_Identical($valueFormatted);
         $validator->setMessage(sprintf($this->_('%s is not correct.'), $label), \Zend_Validate_Identical::NOT_SAME);
         $birthdayElem->addValidator($validator);
         return array($birthdayElem);
     }
     // */
     return array($this->_('Username') => $this->getLoginName());
 }
 /**
  * Function to allow the creation of search defaults in code
  *
  * @see getSearchFilter()
  *
  * @return array
  */
 public function getSearchDefaults()
 {
     if (!$this->defaultSearchData) {
         $from = new \MUtil_Date();
         $from->subWeek(2);
         $until = new \MUtil_Date();
         $until->addDay(1);
         $this->defaultSearchData = array('datefrom' => $from, 'dateuntil' => $until);
     }
     return parent::getSearchDefaults();
 }
 /**
  * Function to allow the creation of search defaults in code
  *
  * @see getSearchFilter()
  *
  * @return array
  */
 public function getSearchDefaults()
 {
     if (!$this->defaultSearchData) {
         $from = new \MUtil_Date();
         $from->subWeek(2);
         $until = new \MUtil_Date();
         $until->addDay(1);
         $this->defaultSearchData = array(\Gems_Snippets_AutosearchFormSnippet::PERIOD_DATE_USED => 'grco_created', 'grco_organization' => $this->loader->getOrganization()->getId(), 'datefrom' => $from, 'dateuntil' => $until);
     }
     return parent::getSearchDefaults();
 }
 protected function filterDateFormat($value, $dateFormat, $columnName)
 {
     $storageFormat = $this->model->get($columnName, 'storageFormat');
     return \MUtil_Date::format($value, $dateFormat, $storageFormat);
 }
示例#13
0
 /**
  * Handle sending responses to the response database (if used)
  *
  * Triggered by checkTokenCompletion
  *
  * @param int $userId The id of the gems user
  */
 protected function toResponseDatabase($userId)
 {
     $db = $this->project->getResponseDatabase();
     // WHY EXPLANATION!!
     //
     // For some reason mysql prepared parameters do nothing with a \Zend_Db_Expr
     // object and that causes an error when using CURRENT_TIMESTAMP
     $current = \MUtil_Date::now()->toString(\Gems_Tracker::DB_DATETIME_FORMAT);
     $rValues = array('gdr_id_token' => $this->_tokenId, 'gdr_changed' => $current, 'gdr_changed_by' => $userId, 'gdr_created' => $current, 'gdr_created_by' => $userId);
     $responses = $this->getRawAnswers();
     unset($responses['token'], $responses['id'], $responses['lastpage'], $responses['startlanguage'], $responses['submitdate'], $responses['startdate'], $responses['datestamp']);
     // first read current responses to differentiate between insert and update
     $responseSelect = $db->select()->from('gemsdata__responses', array('gdr_answer_id', 'gdr_response'))->where('gdr_id_token = ?', $this->_tokenId);
     $currentResponses = $db->fetchPairs($responseSelect);
     if (!$currentResponses) {
         $currentResponses = array();
     }
     // \MUtil_Echo::track($currentResponses, $responses);
     // Prepare sql
     $sql = "UPDATE gemsdata__responses\n            SET `gdr_response` = ?, `gdr_changed` = ?, `gdr_changed_by` = ?\n            WHERE gdr_id_token = ? AND gdr_answer_id = ? AND gdr_answer_row = 1";
     $stmt = $db->prepare($sql);
     $inserts = array();
     foreach ($responses as $fieldName => $response) {
         $rValues['gdr_answer_id'] = $fieldName;
         if (is_array($response)) {
             $response = join('|', $response);
         }
         $rValues['gdr_response'] = $response;
         if (array_key_exists($fieldName, $currentResponses)) {
             // Already exists, do update
             // But only if value changed
             if ($currentResponses[$fieldName] != $response) {
                 try {
                     // \MUtil_Echo::track($sql, $rValues['gdr_id_token'], $fieldName, $response);
                     $stmt->execute(array($response, $rValues['gdr_changed'], $rValues['gdr_changed_by'], $rValues['gdr_id_token'], $fieldName));
                 } catch (\Zend_Db_Statement_Exception $e) {
                     error_log($e->getMessage());
                     \Gems_Log::getLogger()->logError($e);
                 }
             }
         } else {
             // We add the inserts together in the next prepared statement to improve speed
             $inserts[$fieldName] = $rValues;
         }
     }
     if (count($inserts) > 0) {
         // \MUtil_Echo::track($inserts);
         try {
             $fields = array_keys(reset($inserts));
             $fields = array_map(array($db, 'quoteIdentifier'), $fields);
             $sql = 'INSERT INTO gemsdata__responses (' . implode(', ', $fields) . ') VALUES (' . implode(', ', array_fill(1, count($fields), '?')) . ')';
             // \MUtil_Echo::track($sql);
             $stmt = $db->prepare($sql);
             foreach ($inserts as $insert) {
                 // \MUtil_Echo::track($insert);
                 $stmt->execute($insert);
             }
         } catch (\Zend_Db_Statement_Exception $e) {
             error_log($e->getMessage());
             \Gems_Log::getLogger()->logError($e);
         }
     }
 }
 /**
  * Translate the set form options to a valid filter for the model
  * @param  array data existing options set in the form
  * @return array Filter for the model
  */
 public function getFilters($data)
 {
     $filters = array();
     $dateOutFormat = 'yyyy-MM-dd';
     $dateInFormat = \MUtil_Model_Bridge_FormBridge::getFixedOption('date', 'dateFormat');
     if (isset($data['sid']) && is_array($data['sid'])) {
         foreach ($data['sid'] as $surveyId) {
             if ($surveyId) {
                 $filter = array();
                 if (isset($data['ids'])) {
                     $idStrings = $data['ids'];
                     $idArray = preg_split('/[\\s,;]+/', $idStrings, -1, PREG_SPLIT_NO_EMPTY);
                     if ($idArray) {
                         // Make sure output is OK
                         // $idArray = array_map(array($this->db, 'quote'), $idArray);
                         $filter['gto_id_respondent'] = $idArray;
                     }
                 }
                 if ($this->project->hasResponseDatabase()) {
                     $this->getResponseDatabaseFilter($data, $filter);
                 }
                 /*if ($this->project->hasResponseDatabase()) {
                       $this->_getResponseDatabaseFilter($data, $filter);
                   }*/
                 if (isset($data['tid']) && !empty($data['tid'])) {
                     $filter['gto_id_track'] = $data['tid'];
                 }
                 if (isset($data['sid'])) {
                     $filter['gto_id_survey'] = $surveyId;
                 }
                 if (isset($data['rounds']) && !empty($data['rounds'])) {
                     $filter['gto_round_description'] = $data['rounds'];
                 }
                 if (isset($data['oid'])) {
                     $filter['gto_id_organization'] = $data['oid'];
                 } else {
                     //Invalid id so when nothing selected... we get nothing
                     // $filter['organizationid'] = '-1';
                 }
                 if (isset($data['valid_from']) && !empty($data['valid_from'])) {
                     $filter[] = "gto_valid_from >= " . $this->db->quote(\MUtil_Date::format($data['valid_from'], $dateOutFormat, $dateInFormat)) . "";
                 }
                 if (isset($data['valid_until']) && !empty($data['valid_until'])) {
                     $filter[] = "gto_valid_until >= " . $this->db->quote(\MUtil_Date::format($data['valid_until'], $dateOutFormat, $dateInFormat)) . "";
                 }
                 /*if (isset($data['valid_until'])) {
                       $filter[] = 'gto_valid_until >= ' . $data['valid_until'];
                   }*/
                 $filter['grc_success'] = 1;
                 $filter[] = "gto_completion_time IS NOT NULL";
                 // Consent codes
                 /*$filter['consentcode'] = array_diff(
                                 (array) $this->util->getConsentTypes(),
                                 (array) $this->util->getConsentRejected()
                                 );
                 		*/
                 $filters[] = $filter;
             }
         }
     }
     // \Gems_Tracker::$verbose = true;
     return $filters;
 }
 /**
  * Update the token data when a Mail has been sent.
  * @param  integer $tokenId TokenId to update. If none is supplied, use the current token
  */
 public function updateToken($tokenId = false)
 {
     if (!$tokenId) {
         $tokenId = $this->token->getTokenId();
     }
     $tokenData['gto_mail_sent_num'] = new \Zend_Db_Expr('gto_mail_sent_num + 1');
     $tokenData['gto_mail_sent_date'] = \MUtil_Date::format(new \Zend_Date(), 'yyyy-MM-dd');
     $this->db->update('gems__tokens', $tokenData, $this->db->quoteInto('gto_id_token = ?', $tokenId));
 }
 protected function processValue($name, $value, $model = false)
 {
     if (!$model) {
         $model = $this->model;
     }
     $result = $value;
     if ($default = $model->get($name, 'default')) {
         if (null === $result) {
             $result = $default;
         }
     }
     if ($formatFunction = $model->get($name, 'formatFunction')) {
         $result = call_user_func($formatFunction, $result);
     } elseif ($dateFormat = $model->get($name, 'dateFormat')) {
         $storageFormat = $model->get($name, 'storageFormat');
         $result = \MUtil_Date::format($result, $dateFormat, $storageFormat);
     }
     if ($itemDisplay = $model->get($name, 'itemDisplay')) {
         if (is_callable($itemDisplay)) {
             $result = call_user_func($itemDisplay, $result);
         } elseif (is_object($itemDisplay)) {
             if ($itemDisplay instanceof \MUtil_Html_ElementInterface || method_exists($itemDisplay, 'append')) {
                 $object = clone $itemDisplay;
                 $result = $object->append($result);
             }
         } elseif (is_string($itemDisplay)) {
             // Assume it is a html tag when a string
             $result = \MUtil_Html::create($itemDisplay, $result);
         }
     }
     return $result;
 }
 /**
  * Helper function to generate a period query string
  *
  * @param array $filter A filter array or $request->getParams()
  * @param \Zend_Db_Adapter_Abstract $db
  * @param $inFormat Optional format to use for date when reading
  * @param $outFormat Optional format to use for date in query
  * @return string
  */
 public static function getPeriodFilter(array &$filter, \Zend_Db_Adapter_Abstract $db, $inFormat = null, $outFormat = null)
 {
     $from = array_key_exists('datefrom', $filter) ? $filter['datefrom'] : null;
     $until = array_key_exists('dateuntil', $filter) ? $filter['dateuntil'] : null;
     $period = array_key_exists(self::PERIOD_DATE_USED, $filter) ? $filter[self::PERIOD_DATE_USED] : null;
     unset($filter[self::PERIOD_DATE_USED], $filter['datefrom'], $filter['dateuntil']);
     if (!$period) {
         return;
     }
     if (null === $outFormat) {
         $outFormat = 'yyyy-MM-dd';
     }
     if (null === $inFormat) {
         $inFormat = \MUtil_Model_Bridge_FormBridge::getFixedOption('date', 'dateFormat');
     }
     if ($from && \Zend_Date::isDate($from, $inFormat)) {
         $datefrom = $db->quote(\MUtil_Date::format($from, $outFormat, $inFormat));
     } else {
         $datefrom = null;
     }
     if ($until && \Zend_Date::isDate($until, $inFormat)) {
         $dateuntil = $db->quote(\MUtil_Date::format($until, $outFormat, $inFormat));
     } else {
         $dateuntil = null;
     }
     if (!($datefrom || $dateuntil)) {
         return;
     }
     switch ($period[0]) {
         case '_':
             // overlaps
             $periods = explode(' ', substr($period, 1));
             if ($datefrom && $dateuntil) {
                 return sprintf('(%1$s <= %4$s OR (%1$s IS NULL AND %2$s IS NOT NULL)) AND
                             (%2$s >= %3$s OR %2$s IS NULL)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $datefrom, $dateuntil);
             }
             if ($datefrom) {
                 return sprintf('%2$s >= %3$s OR (%2$s IS NULL AND %1$s IS NOT NULL)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $datefrom);
             }
             if ($dateuntil) {
                 return sprintf('%1$s <= %3$s OR (%1$s IS NULL AND %2$s IS NOT NULL)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $dateuntil);
             }
             return;
         case '-':
             // within
             $periods = explode(' ', substr($period, 1));
             if ($datefrom && $dateuntil) {
                 return sprintf('%1$s >= %3$s AND %2$s <= %4$s', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $datefrom, $dateuntil);
             }
             if ($datefrom) {
                 return sprintf('%1$s >= %3$s AND (%2$s IS NULL OR %2$s >= %3$s)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $datefrom);
             }
             if ($dateuntil) {
                 return sprintf('%2$s <= %3$s AND (%1$s IS NULL OR %1$s <= %3$s)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $dateuntil);
             }
             return;
         default:
             if ($datefrom && $dateuntil) {
                 return sprintf('%s BETWEEN %s AND %s', $db->quoteIdentifier($period), $datefrom, $dateuntil);
             }
             if ($datefrom) {
                 return sprintf('%s >= %s', $db->quoteIdentifier($period), $datefrom);
             }
             if ($dateuntil) {
                 return sprintf('%s <= %s', $db->quoteIdentifier($period), $dateuntil);
             }
             return;
     }
 }
示例#18
0
 /**
  * Generates a fake element that just displays the item with a hidden extra value field.
  *
  * @access public
  *
  * @param string|array $name If a string, the element name.  If an
  * array, all other parameters are ignored, and the array elements
  * are extracted in place of added parameters.
  *
  * @param mixed $value The element value.
  *
  * @param array $attribs Attributes for the element tag.
  *
  * @return string The element XHTML.
  */
 public function exhibitor($name, $value = null, $attribs = null)
 {
     $result = $value;
     if (isset($attribs['default'])) {
         if (null === $result) {
             $result = $attribs['default'];
         }
     }
     if (isset($attribs['multiOptions'])) {
         $multiOptions = $attribs['multiOptions'];
         if (is_array($multiOptions)) {
             /*
              *  Sometimes a field is an array and will be formatted later on using the
              *  formatFunction -> handle each element in the array.
              */
             if (is_array($result)) {
                 foreach ($result as $key => $arrayValue) {
                     if (array_key_exists($arrayValue, $multiOptions)) {
                         $result[$key] = $multiOptions[$arrayValue];
                     }
                 }
             } else {
                 if (array_key_exists($result, $multiOptions)) {
                     $result = $multiOptions[$result];
                 }
             }
         }
     }
     if (isset($attribs['formatFunction'])) {
         $callback = $attribs['formatFunction'];
         $result = call_user_func($callback, $result);
     } elseif (isset($attribs['dateFormat'])) {
         $dateFormat = $attribs['dateFormat'];
         $storageFormat = isset($attribs['storageFormat']) ? $attribs['storageFormat'] : null;
         $result = \MUtil_Date::format($result, $dateFormat, $storageFormat);
         if ($storageFormat && $value instanceof \Zend_Date) {
             $value = $value->toString($storageFormat);
         }
     }
     if (isset($attribs['itemDisplay'])) {
         $function = $attribs['itemDisplay'];
         if (is_callable($function)) {
             $result = call_user_func($function, $result);
         } elseif (is_object($function)) {
             if ($function instanceof \MUtil_Html_ElementInterface || method_exists($function, 'append')) {
                 $object = clone $function;
                 $result = $object->append($result);
             }
         } elseif (is_string($function)) {
             // Assume it is a html tag when a string
             $result = \MUtil_Html::create($function, $result);
         }
     }
     if ($result instanceof \MUtil_Html_HtmlInterface) {
         $result = $result->render($this->view);
     }
     // By all appearance not in use.
     /* if (isset($attribs['callback'])) {
            $callback = $attribs['callback'];
            $result = $callback($result);
        } */
     if (isset($attribs['nohidden']) && $attribs['nohidden'] || is_array($value)) {
         return $result;
     } else {
         if ($value instanceof \Zend_Date) {
             $value = $value->toString('yyyy-MM-dd HH:mm:ss');
         }
         return $this->_hidden($name, $value) . $result;
     }
 }
 /**
  * Display the time field
  *
  * @param \MUtil_Date $value
  */
 public function formatTime($value)
 {
     return \MUtil_Html::create('span', ' ', \MUtil_Date::format($value, 'HH:mm ' . \Zend_Date::WEEKDAY_SHORT, $this->_dateStorageFormat));
 }
 /**
  * Function to allow the creation of search defaults in code
  *
  * @see getSearchFilter()
  *
  * @return array
  */
 public function getSearchDefaults()
 {
     if (!$this->defaultSearchData) {
         $inFormat = \MUtil_Model_Bridge_FormBridge::getFixedOption('date', 'dateFormat');
         $now = new \MUtil_Date();
         $today = $now->toString($inFormat);
         $this->defaultSearchData = array('datefrom' => $today, 'dateused' => '_gto_valid_from gto_valid_until', 'dateuntil' => $today, 'main_filter' => 'all');
     }
     return parent::getSearchDefaults();
 }
 /**
  * Formats an until date for this display
  *
  * @param \MUtil_Date $dateTime
  * @return string
  */
 public function formatUntil(\MUtil_Date $dateTime = null)
 {
     if (null === $dateTime) {
         return $this->_('Survey has no time limit.');
     }
     $days = $dateTime->diffDays();
     switch ($days) {
         case 0:
             return array(\MUtil_Html::create('strong', $this->_('Warning!!!')), ' ', $this->_('This survey must be answered today!'));
         case 1:
             return array(\MUtil_Html::create('strong', $this->_('Warning!!')), ' ', $this->_('This survey can only be answered until tomorrow!'));
         case 2:
             return $this->_('Warning! This survey can only be answered for another 2 days!');
         default:
             if ($days <= 14) {
                 return sprintf($this->_('Please answer this survey within %d days.'), $days);
             }
             if ($days <= 0) {
                 return $this->_('This survey can no longer be answered.');
             }
             return sprintf($this->_('Please answer this survey before %s.'), $dateTime->toString($this->dateFormat));
     }
 }
 /**
  *
  * @param string $fieldName
  * @return \MUtil_Date
  */
 public function getDate($fieldName)
 {
     if (isset($this->_respTrackData[$fieldName])) {
         $date = $this->_respTrackData[$fieldName];
     } else {
         $this->_ensureFieldData();
         if (isset($this->_fieldData[$fieldName])) {
             $date = $this->_fieldData[$fieldName];
             if ($this->getTrackEngine()->isAppointmentField($fieldName)) {
                 $appointment = $this->tracker->getAppointment($date);
                 if ($appointment->isActive()) {
                     $date = $appointment->getAdmissionTime();
                 } else {
                     $date = false;
                 }
             }
         } else {
             $date = false;
         }
     }
     if ($date) {
         return \MUtil_Date::ifDate($date, array(\Gems_Tracker::DB_DATETIME_FORMAT, \Gems_Tracker::DB_DATE_FORMAT));
     }
 }
 protected function filterDateFormat($value, $dateFormat, $columnName)
 {
     if ($value instanceof \Zend_Date) {
         $year = \MUtil_Date::format($value, 'yyyy');
         $month = \MUtil_Date::format($value, 'MM');
         $day = \MUtil_Date::format($value, 'dd');
         $hours = \MUtil_Date::format($value, 'HH');
         $minutes = \MUtil_Date::format($value, 'mm');
         $seconds = \MUtil_Date::format($value, 'ss');
     } else {
         $time = strtotime($value);
         $year = Date('Y', $time);
         $month = Date('m', $time);
         $day = Date('d', $time);
         $hours = Date('H', $time);
         $minutes = Date('i', $time);
         $seconds = Date('s', $time);
     }
     return PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day, $hours, $minutes, $seconds);
 }
示例#24
0
 /**
  * A ModelAbstract->setOnSave() function that tracks the change
  *
  * @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 Of the values concatenated
  */
 public function saveValue($value, $isNew = false, $name = null, array $context = array())
 {
     // \MUtil_Echo::track($value, $this->_changedValue);
     // Once the value is set (and e.g. stored in the database) do not overwrite it
     if ($this->_changedValue == $value) {
         return $value;
     }
     $compare = $this->_model->get($name, __CLASS__);
     if (!(is_array($compare) && 2 === count($compare))) {
         // Actually a valid setting, do nothring
         return $value;
     }
     list($trackedField, $oldValueField) = $compare;
     if (!isset($context[$trackedField], $context[$oldValueField])) {
         return $value;
     }
     if (!($context[$trackedField] && $context[$oldValueField])) {
         return $context[$trackedField] || $context[$oldValueField] ? $this->_changedValue : $this->_unchangedValue;
     }
     $storageFormat = $this->_model->get($trackedField, 'storageFormat');
     if (!$storageFormat) {
         return $context[$trackedField] == $context[$oldValueField] ? $this->_unchangedValue : $this->_changedValue;
     }
     if ($context[$oldValueField] instanceof \Zend_Date) {
         $oldValue = $context[$oldValueField];
     } else {
         $oldValue = new \MUtil_Date($context[$oldValueField], $storageFormat);
     }
     if ($context[$trackedField] instanceof \Zend_Date) {
         $currentValue = $context[$trackedField];
     } elseif (\Zend_Date::isDate($context[$trackedField], $storageFormat)) {
         $currentValue = new \MUtil_Date($context[$trackedField], $storageFormat);
     } else {
         if ($this->_model->has($trackedField, 'dateFormat')) {
             $secondFormat = $this->_model->get($trackedField, 'dateFormat');
         } else {
             $secondFormat = \MUtil_Model_Bridge_FormBridge::getFixedOption('date', 'dateFormat');
         }
         if (!\Zend_Date::isDate($context[$trackedField], $secondFormat)) {
             // Cannot compare, do nothing
             return $value;
         }
         $currentValue = new \MUtil_Date($context[$trackedField], $secondFormat);
     }
     // \MUtil_Echo::track($trackedField, $oldValueField, $oldValue->toString(), $currentValue->toString(), $oldValue->getTimestamp() === $currentValue->getTimestamp());
     return $oldValue->getTimestamp() === $currentValue->getTimestamp() ? $this->_unchangedValue : $this->_changedValue;
 }
 /**
  * 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
  */
 public function calculateFieldValue($currentValue, array $fieldData, array $trackData)
 {
     if ($currentValue || isset($this->_fieldDefinition['gtf_filter_id'])) {
         $agenda = $this->loader->getAgenda();
         if ($this->_lastActiveKey && isset($this->_fieldDefinition['gtf_filter_id'])) {
             $fromDate = false;
             $lastActive = self::$_lastActiveAppointment[$this->_lastActiveKey];
             if ($lastActive instanceof \Gems_Agenda_Appointment && $lastActive->isActive()) {
                 $fromDate = $lastActive->getAdmissionTime();
             }
             if (!$fromDate && isset($trackData['gr2t_start_date']) && $trackData['gr2t_start_date']) {
                 if ($trackData['gr2t_start_date'] instanceof \Zend_Date) {
                     $fromDate = $trackData['gr2t_start_date'];
                 } else {
                     $fromDate = new \MUtil_Date($trackData['gr2t_start_date'], \Gems_Tracker::DB_DATETIME_FORMAT);
                 }
                 // Always use start of the day for start date comparisons
                 $fromDate->setTime('00:00:00');
             }
             if ($fromDate instanceof \MUtil_Date) {
                 $select = $agenda->createAppointmentSelect(array('gap_id_appointment'));
                 $select->onlyActive()->forFilterId($this->_fieldDefinition['gtf_filter_id'])->forRespondent($trackData['gr2t_id_user'], $trackData['gr2t_id_organization']);
                 $minDate = Period::applyPeriod($fromDate, $this->_fieldDefinition['gtf_min_diff_unit'], $this->_fieldDefinition['gtf_min_diff_length']);
                 if ($this->_fieldDefinition['gtf_max_diff_exists']) {
                     $maxDate = Period::applyPeriod($fromDate, $this->_fieldDefinition['gtf_max_diff_unit'], $this->_fieldDefinition['gtf_max_diff_length']);
                 } else {
                     $maxDate = null;
                 }
                 if ($this->_fieldDefinition['gtf_min_diff_length'] > 0) {
                     $select->forPeriod($minDate, $maxDate, true);
                 } else {
                     $select->forPeriod($maxDate, $minDate, false);
                 }
                 if ($this->_fieldDefinition['gtf_uniqueness']) {
                     switch ($this->_fieldDefinition['gtf_uniqueness']) {
                         case 1:
                             // Track instances may link only once to an appointment
                             $select->uniqueInTrackInstance(self::$_lastActiveAppointmentIds[$this->_lastActiveKey]);
                             break;
                         case 2:
                             // Tracks of this type may link only once to an appointment
                             if (isset($trackData['gr2t_id_respondent_track'])) {
                                 $respTrackId = $trackData['gr2t_id_respondent_track'];
                             } else {
                                 $respTrackId = null;
                             }
                             $select->uniqueForTrackId($this->_trackId, $respTrackId, self::$_lastActiveAppointmentIds[$this->_lastActiveKey]);
                             break;
                             // default:
                     }
                 }
                 // Query ready
                 $newValue = $select->fetchOne();
                 if ($newValue) {
                     $currentValue = $newValue;
                 }
             }
         }
         if ($this->_lastActiveKey && $currentValue) {
             $appointment = $agenda->getAppointment($currentValue);
             if ($appointment->isActive()) {
                 self::$_lastActiveAppointment[$this->_lastActiveKey] = $appointment;
                 self::$_lastActiveAppointmentIds[$this->_lastActiveKey][$currentValue] = $currentValue;
             }
         }
     }
     return $currentValue;
 }
 /**
  * The file name to use for final storage, minus the extension
  *
  * @param string $controller Name of controller (or other id)
  * @return string
  */
 public function getLongtermFileName($controller)
 {
     $date = new \MUtil_Date();
     $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));
 }
示例#27
0
 /**
  * Overrule this function to adapt the display of the agenda items for each project
  *
  * @see \Gems_Agenda_Appointment->getDisplayString()
  *
  * @param array $row Row containing result select
  * @return string
  */
 public function getAppointmentDisplay(array $row)
 {
     $date = new \MUtil_Date($row['gap_admission_time'], 'yyyy-MM-dd HH:mm:ss');
     $results[] = $date->toString($this->appointmentDisplayFormat);
     if ($row['gaa_name']) {
         $results[] = $row['gaa_name'];
     }
     if ($row['gapr_name']) {
         $results[] = $row['gapr_name'];
     }
     if ($row['glo_name']) {
         $results[] = $row['glo_name'];
     }
     return implode($this->_('; '), $results);
 }
示例#28
0
 /**
  * @param string $firstDate
  * @param string $firstFormat
  * @param string $secondDate
  * @param string $secondFormat
  * @param int $expectedDiffDays
  * @param int $expectedDiffSeconds
  *
  * @dataProvider providerTestTimeZones
  */
 public function testDiffTimeZones($firstDate, $firstFormat, $secondDate, $secondFormat, $expectedDiffDays, $expectedDiffSeconds)
 {
     $date = new \MUtil_Date($firstDate, $firstFormat);
     $otherDate = new \MUtil_Date($secondDate, $secondFormat);
     $diff = $date->diffDays($otherDate);
     // echo $secondFormat . ' ' . $date->getTimestamp() . ' - ' . $date->getGmtOffset() . ' vs  ' . $otherDate->getTimestamp() . ' - ' . $otherDate->getGmtOffset() . "\n";
     $this->assertEquals($expectedDiffDays, $diff);
     $this->assertEquals($expectedDiffSeconds, $date->diffSeconds($otherDate));
 }
 /**
  * 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
  */
 protected function createModel($detailed, $action)
 {
     // Load organizationId and respondentId
     $this->loadParams();
     $model = $this->loader->getModels()->createAppointmentModel();
     if ($detailed) {
         if ('edit' === $action || 'create' === $action) {
             $model->applyEditSettings($this->organizationId);
             if ($action == 'create') {
                 // Set default date to tomoorow.
                 $now = new \MUtil_Date();
                 $now->addDay(1);
                 $loid = $this->db->fetchOne("SELECT gap_id_location\n                                FROM gems__appointments\n                                WHERE gap_id_user = ? AND gap_id_organization = ?\n                                ORDER BY gap_admission_time DESC", array($this->respondentId, $this->organizationId));
                 if ($loid !== false) {
                     $model->set('gap_id_location', 'default', $loid);
                 }
                 $model->set('gap_id_user', 'default', $this->respondentId);
                 $model->set('gap_manual_edit', 'default', 1);
                 $model->set('gap_admission_time', 'default', $now);
             } else {
                 // When there is something saved, then set manual edit to 1
                 $model->setSaveOnChange('gap_manual_edit');
                 $model->setOnSave('gap_manual_edit', 1);
             }
         } else {
             $model->applyDetailSettings();
         }
     } else {
         $model->applyBrowseSettings();
         $model->addFilter(array('gap_id_user' => $this->respondentId, 'gap_id_organization' => $this->organizationId));
     }
     return $model;
 }
 /**
  * This is the actual format function, copied from the Exhibitor for field
  *
  * @param type $name
  * @param type $result
  *@param \MUtil_Model_ModelAbstract $model
  * @return type
  */
 private function _format($name, $result, $model)
 {
     static $view = null;
     if (!isset($this->_options[$name])) {
         $this->_options[$name] = $model->get($name, array('default', 'multiOptions', 'formatFunction', 'dateFormat', 'storageFormat', 'itemDisplay'));
     }
     $options = $this->_options[$name];
     foreach ($options as $key => $value) {
         switch ($key) {
             case 'default':
                 if (is_null($result)) {
                     $result = $value;
                 }
                 break;
             case 'multiOptions':
                 $multiOptions = $value;
                 if (is_array($multiOptions)) {
                     /*
                      *  Sometimes a field is an array and will be formatted later on using the
                      *  formatFunction -> handle each element in the array.
                      */
                     if (is_array($result)) {
                         foreach ($result as $key => $value) {
                             if (array_key_exists($value, $multiOptions)) {
                                 $result[$key] = $multiOptions[$value];
                             }
                         }
                     } else {
                         if (array_key_exists($result, $multiOptions)) {
                             $result = $multiOptions[$result];
                         }
                     }
                 }
                 break;
             case 'formatFunction':
                 $callback = $value;
                 $result = call_user_func($callback, $result);
                 break;
             case 'dateFormat':
                 if (array_key_exists('formatFunction', $options)) {
                     // if there is a formatFunction skip the date formatting
                     continue;
                 }
                 $dateFormat = $value;
                 $storageFormat = $model->get($name, 'storageFormat');
                 $result = \MUtil_Date::format($result, $dateFormat, $storageFormat);
                 break;
             case 'itemDisplay':
                 $function = $value;
                 if (is_callable($function)) {
                     $result = call_user_func($function, $result);
                 } elseif (is_object($function)) {
                     if ($function instanceof \MUtil_Html_ElementInterface || method_exists($function, 'append')) {
                         $object = clone $function;
                         $result = $object->append($result);
                     }
                 } elseif (is_string($function)) {
                     // Assume it is a html tag when a string
                     $result = \MUtil_Html::create($function, $result);
                 }
             default:
                 break;
         }
     }
     if (is_object($result)) {
         // If it is Lazy, execute it
         if ($result instanceof \MUtil_Lazy_LazyInterface) {
             $result = \MUtil_Lazy::rise($result);
         }
         // If it is Html, render it
         if ($result instanceof \MUtil_Html_HtmlInterface) {
             if (is_null($view)) {
                 $viewRenderer = \Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
                 if (null === $viewRenderer->view) {
                     $viewRenderer->initView();
                 }
                 $view = $viewRenderer->view;
             }
             $result = $result->render($view);
         }
     }
     return $result;
 }