/** * Prepara os dados para processar o arquivo do webservice * * @param string $sArquivo * @return bool * @throws Exception */ public function preparaDados($sArquivo) { try { // Foi comentado o if de verificação pois estava ocorrendo um problema na emissão e retornava um arquivo em branco. // Somente em ambiente de desenvolvimento //if (APPLICATION_ENV == 'development') { $oDomDocument = new DOMDocument(); $oDomDocument->loadXml($sArquivo); $oData = new Zend_Date(); $this->sNomeArquivo = "/RecepcionarLote-{$oData->getTimestamp()}.xml"; $this->sCaminhoArquivo = TEMP_PATH; /** * Verifica se o caminho do arquivo não existe recria a pasta */ if (!file_exists($this->sCaminhoArquivo)) { mkdir($this->sCaminhoArquivo, 0777); } /** * Escreve os dados no arquivo */ $this->sCaminhoNomeArquivo = $this->sCaminhoArquivo . $this->sNomeArquivo; $aArquivo = fopen($this->sCaminhoNomeArquivo, 'w'); fputs($aArquivo, print_r($sArquivo, TRUE)); fclose($aArquivo); //} $oValidacao = new DBSeller_Helper_Xml_AssinaturaDigital($sArquivo); /** * Validação digital do arquivo */ if (!$oValidacao->validar()) { throw new Exception($oValidacao->getLastError()); } $oUsuario = Administrativo_Model_Usuario::getByAttribute('cnpj', $oValidacao->getCnpj()); if (!is_object($oUsuario)) { throw new Exception('Usuário contribuinte não existe!', 157); } /** * Busca usuário contribuinte através do usuário cadastrado */ $aUsuarioContribuinte = Administrativo_Model_UsuarioContribuinte::getByAttributes(array('usuario' => $oUsuario->getId(), 'cnpj_cpf' => $oUsuario->getCnpj())); if (!is_object($aUsuarioContribuinte[0])) { throw new Exception('Usuário contribuinte não encontrado!', 160); } /** * Seta os dados do contribuinte */ $this->oDadosUsuario = $oUsuario; $this->oContribuinte->sCpfCnpj = $aUsuarioContribuinte[0]->getCnpjCpf(); $this->oContribuinte->iCodigoUsuario = $oUsuario->getId(); $this->oContribuinte->iIdUsuarioContribuinte = $aUsuarioContribuinte[0]->getId(); /** * Atualiza os dados do contribuinte na sessão */ $oSessao = new Zend_Session_Namespace('nfse'); $oSessao->contribuinte = Contribuinte_Model_Contribuinte::getById($this->oContribuinte->iIdUsuarioContribuinte); return TRUE; } catch (Exception $oErro) { throw new Exception($oErro->getMessage(), $oErro->getCode()); } }
/** * @param date $d data a ser comparada */ public function getDays($d) { $now = time(); $date = new Zend_Date($d, Zend_Date::ISO_8601); $time = $now - $date->getTimestamp(); if ($time < 86400) { //60*60*24 $time = 'hoje'; } elseif ($time < 172800) { //60*60*24*2 $time = 'ontem'; //mostrar quantidade de dias até 14 dias } elseif ($time < 604800) { //60*60*24*30 $time = 'há ' . round(floatval($time) / 86400) . ' dias'; //mostrar quantidades de semanas apartir da 2 semana até 1 mes } elseif ($time > 1209600 && $time <= 2592000) { //60*60*24*(7*4) $time = 'há ' . round(floatval($time) / 604800) . ' semanas'; } elseif ($time > 2592000 && $time <= 5184000) { //60*60*24*30 && 60*60*24*30*2 $time = 'há ' . round(floatval($time) / 2592000) . ' mês'; } elseif ($time > 5184000 && $time < 31104000) { //60*60*24*30*2 && 60*60*24*30*12 $time = 'há ' . round(floatval($time) / 2592000) . ' meses'; } else { //if ($time < 31104000) { //60*60*24*30*12 $time = 'há mais de um ano (' . $date->toString() . ')'; } return $time; }
public function timing($time) { $date = new Zend_Date(); $diffTime = $date->getTimestamp() - $time; $date = null; if ($diffTime < 60) { return ($diffTime <= 0 ? 1 : $diffTime) . '秒前'; } $minute = ceil($diffTime / 60); if ($minute < 60) { return $minute . '分钟前'; } $minute = ceil($diffTime / 3600); if ($minute < 24) { return $minute . '小时前'; } $day = ceil($diffTime / 3600 / 24); if ($day < 30) { return $day . '天前'; } $month = ceil($diffTime / 3600 / 24 / 30); if ($month < 12) { return $month . '月前'; } $year = floor($diffTime / 3600 / 24 / 30 / 12); return $year . '年前'; }
public function execute($lastRunDt = null) { $config = Zend_Registry::get('config'); $checkDtStart = new Zend_Date($this->_lastRunDt); $checkDtEnd = new Zend_Date(); $event = new Event(); $events = $event->getEvents(null, null, null, $checkDtStart->getTimestamp(), $checkDtEnd->getTimestamp(), 'open'); $location = new Location(); $workshop = new Workshop(); $instructor = new Event_Instructor(); $attendee = new Event_Attendee(); $eu = new Evaluation_User(); foreach ($events as $e) { $startDt = strtotime($e->date . ' ' . $e->startTime); $endDt = strtotime($e->date . ' ' . $e->endTime); if ($checkDtStart->getTimestamp() < $endDt && $checkDtEnd->getTimestamp() >= $endDt) { echo 'Event to Send:'; var_dump($e->toArray(), '<br /><br />'); $thisLocation = $location->find($e->locationId); if (is_null($thisLocation)) { throw new Ot_Exception_Data('msg-error-noLocation'); } $thisWorkshop = $workshop->find($e->workshopId); if (is_null($thisWorkshop)) { throw new Ot_Exception_Data('msg-error-noWorkshop'); } $instructors = $instructor->getInstructorsForEvent($e->eventId); $instructorNames = array(); $instructorEmails = array(); foreach ($instructors as $i) { $instructorNames[] = $i['firstName'] . ' ' . $i['lastName']; $instructorEmails[] = $i['emailAddress']; } $data = array('workshopName' => $thisWorkshop->title, 'workshopDate' => date('m/d/Y', $startDt), 'workshopStartTime' => date('g:i a', $startDt), 'workshopEndTime' => date('g:i a', $endDt), 'workshopMinimumEnrollment' => $e->minSize, 'workshopCurrentEnrollment' => $e->roleSize, 'locationName' => $thisLocation->name, 'locationAddress' => $thisLocation->address, 'instructorNames' => implode(', ', $instructorNames), 'instructorEmails' => implode(', ', $instructorEmails)); $attenders = $attendee->getAttendeesForEvent($e->eventId, 'attending', true); foreach ($attenders as $a) { $trigger = new Ot_Trigger(); $trigger->setVariables($data); $trigger->accountId = $a['accountId']; $trigger->studentEmail = $a['emailAddress']; $trigger->studentName = $a['firstName'] . ' ' . $a['lastName']; $trigger->studentUsername = $a['username']; $trigger->dispatch('Event_Evaluation_Notification'); } } } }
public function testToTimestamp() { $date = new Zend_Date(); $this->assertEquals($date->getTimestamp(), Varien_Date::toTimestamp($date)); $this->assertEquals(time(), Varien_Date::toTimestamp(true)); $date = '2012-07-19 16:52'; $this->assertEquals(strtotime($date), Varien_Date::toTimestamp($date)); }
/** * Returns the current tag's data for web service export * @param mixed $params * @abstract * @return array */ public function getForWebserviceExport($document = null, $params = []) { if ($this->date) { return $this->date->getTimestamp(); } else { return null; } }
/** * Returns the current tag's data for web service export * * @abstract * @return array */ public function getForWebserviceExport() { if ($this->date) { return $this->date->getTimestamp(); } else { return null; } }
public function isStillValid() { $validTo = time() - (int) $this->getConfig()->get('re-request/log_vadility_lifetime'); $createdAt = new Zend_Date($this->getCreatedAt()); $previousCheckouts = (int) $this->getCheckoutsAfterThisRequest(); $maxCheckouts = (int) $this->getConfig()->get('re-request/max_number_of_checkouts'); return $previousCheckouts < $maxCheckouts && $validTo <= $createdAt->getTimestamp(); }
/** * Convert date to UNIX timestamp * Returns current UNIX timestamp if date is true * * @param Zend_Date|string|bool $date * @return int */ public static function toTimestamp($date) { if ($date instanceof Zend_Date) { return $date->getTimestamp(); } if ($date === true) { return time(); } return strtotime($date); }
/** * File type is based on db values table: filetypes * */ public function render($content) { $element = $this->getElement(); if (!$element instanceof TA_Form_Element_MagicFile) { return $content; } $view = $element->getView(); if (!$view instanceof Zend_View_Interface) { // using view helpers, so do nothing if no view present return $content; } $output = null; if ($file = $element->getTaFile()) { switch ($type = $file->core_filetype) { case 'userimage': $output = '<li><img src="/core/file/' . $file->file_id . '" alt="userimage_' . $file->file_id . '" /></li>'; break; case 'submission': $date = new Zend_Date($file->modified, Zend_Date::ISO_8601); $output = '<li><a title="download paper" href="/core/file/getfile/id/' . $file->file_id . '">' . htmlspecialchars($file->filename_orig) . '</a> (' . $view->timeSince($date->getTimestamp()) . ' ago' . ')</li>'; break; case 'paper': $date = new Zend_Date($file->modified, Zend_Date::ISO_8601); $output = '<li><a title="download paper" href="/core/file/getfile/id/' . $file->file_id . '">' . htmlspecialchars($file->filename_orig) . '</a> (' . $view->timeSince($date->getTimestamp()) . ' ago' . ')</li>'; break; case 'slides': $date = new Zend_Date($file->modified, Zend_Date::ISO_8601); $output = '<li><a title="download slides" href="/core/file/getfile/id/' . $file->file_id . '">' . htmlspecialchars($file->filename_orig) . '</a> (' . $view->timeSince($date->getTimestamp()) . ' ago' . ')</li>'; break; case 'location': $date = new Zend_Date($file->modified, Zend_Date::ISO_8601); $output = '<li><img src="/core/file/' . $file->file_id . '" alt="location_' . $file->file_id . '" />' . '</a> (' . $view->timeSince($date->getTimestamp()) . ' ago' . ')</li>'; break; case 'misc': $date = new Zend_Date($file->modified, Zend_Date::ISO_8601); $output = '<li><a title="download slides" href="/core/file/getfile/id/' . $file->file_id . '">' . htmlspecialchars($file->filename_orig) . '</a> (' . $view->timeSince($date->getTimestamp()) . ' ago' . ')</li>'; break; default: $date = new Zend_Date($file->modified, Zend_Date::ISO_8601); $output = '<li><a title="download file" href="/core/file/getfile/id/' . $file->file_id . '">' . htmlspecialchars($file->filename_orig) . '</a> (' . $view->timeSince($date->getTimestamp()) . ' ago' . ')</li>'; break; } } $placement = $this->getPlacement(); $separator = $this->getSeparator(); switch ($placement) { case 'PREPEND': return $output . $separator . $content; case 'APPEND': default: return $content . $separator . $output; } }
public function getIntervals() { if (!$this->_intervals) { $this->_intervals = array(); if (!$this->_from && !$this->_to) { return $this->_intervals; } $dateStart = new Zend_Date($this->_from); $dateEnd = new Zend_Date($this->_to); $t = array(); $firstInterval = true; /** START AITOC FIX **/ if (in_array((string) $this->_period, array('day', 'month', 'year'))) { /** END AITOC FIX **/ while ($dateStart->compare($dateEnd) <= 0) { switch ($this->_period) { case 'day': $t['title'] = $dateStart->toString(Mage::app()->getLocale()->getDateFormat()); $t['start'] = $dateStart->toString('yyyy-MM-dd HH:mm:ss'); $t['end'] = $dateStart->toString('yyyy-MM-dd 23:59:59'); $dateStart->addDay(1); break; case 'month': $t['title'] = $dateStart->toString('MM/yyyy'); $t['start'] = $firstInterval ? $dateStart->toString('yyyy-MM-dd 00:00:00') : $dateStart->toString('yyyy-MM-01 00:00:00'); $lastInterval = $dateStart->compareMonth($dateEnd->getMonth()) == 0; $t['end'] = $lastInterval ? $dateStart->setDay($dateEnd->getDay())->toString('yyyy-MM-dd 23:59:59') : $dateStart->toString('yyyy-MM-' . date('t', $dateStart->getTimestamp()) . ' 23:59:59'); $dateStart->addMonth(1); if ($dateStart->compareMonth($dateEnd->getMonth()) == 0) { $dateStart->setDay(1); } $firstInterval = false; break; case 'year': $t['title'] = $dateStart->toString('yyyy'); $t['start'] = $firstInterval ? $dateStart->toString('yyyy-MM-dd 00:00:00') : $dateStart->toString('yyyy-01-01 00:00:00'); $lastInterval = $dateStart->compareYear($dateEnd->getYear()) == 0; $t['end'] = $lastInterval ? $dateStart->setMonth($dateEnd->getMonth())->setDay($dateEnd->getDay())->toString('yyyy-MM-dd 23:59:59') : $dateStart->toString('yyyy-12-31 23:59:59'); $dateStart->addYear(1); if ($dateStart->compareYear($dateEnd->getYear()) == 0) { $dateStart->setMonth(1)->setDay(1); } $firstInterval = false; break; } $this->_intervals[$t['title']] = $t; } /** START AITOC FIX **/ } /** END AITOC FIX **/ } return $this->_intervals; }
/** * Imprime a data no formato correto * * @param date $d Data a ser impressa * @param string $format Formato da data * @param string $locale Localização da data * */ public function getTime($d, $format = null, $locale = null) { // Define o formato if (!isset($format)) { $format = Zend_Date::ISO_8601; } elseif ($format == 'twitter') { $format = 'EEE MMM dd HH:mm:ss ZZZ yyyy'; $locale = 'en_US'; } elseif ($format == 'fb') { $format = 'EEE, MMM dd yyyy HH:mm:ss ZZZ'; $locale = 'en_US'; } // Cria a data $date = new Zend_Date($d, $format, $locale); $date->setLocale('pt_BR')->setTimezone('America/Sao_Paulo'); if ($date->get('Y') == 0) { $date->set(date('Y'), 'Y'); } //echo "<br/><b>$d => " . $date->get('Y') .'</b>'; // Calcula a diferença $now = time(); $time = $now - $date->getTimestamp(); // Formata a hora if ($time < 60) { $time .= ' segundos'; } elseif ($time < 3600) { //60*60 $time = round(floatval($time) / 60) . ' minutos'; } elseif ($time < 7200) { //60*60*2 $time = round(floatval($time) / 3660) . ' hora'; } elseif ($time < 86400) { //60*60*24 $time = round(floatval($time) / 3660) . ' horas'; } elseif ($time < 604800) { //60*60*24*30 $time = round(floatval($time) / 86400) . ' dias'; } elseif ($time > 1209600 && $time <= 2592000) { //60*60*24*(7*4) $time = round(floatval($time) / 604800) . ' semanas'; } elseif ($time > 2592000 && $time <= 5184000) { //60*60*24*30 && 60*60*24*30*2 $time = round(floatval($time) / 2592000) . ' mês'; } elseif ($time > 5184000 && $time < 31104000) { //60*60*24*30*2 && 60*60*24*30*12 $time = round(floatval($time) / 2592000) . ' meses'; } else { //if ($time < 31104000) { //60*60*24*30*12 $time = ' mais de um ano (' . $date->toString() . ')'; } return $time; }
/** * Retrieve array of intervals * * @param string $from * @param string $to * @param string $period * @return array */ public function getIntervals($from, $to, $period = self::REPORT_PERIOD_TYPE_DAY) { $intervals = array(); if (!$from && !$to) { return $intervals; } $start = new Zend_Date($from, Varien_Date::DATE_INTERNAL_FORMAT); if ($period == self::REPORT_PERIOD_TYPE_DAY) { $dateStart = $start; } if ($period == self::REPORT_PERIOD_TYPE_MONTH) { $dateStart = new Zend_Date(date("Y-m", $start->getTimestamp()), Varien_Date::DATE_INTERNAL_FORMAT); } if ($period == self::REPORT_PERIOD_TYPE_YEAR) { $dateStart = new Zend_Date(date("Y", $start->getTimestamp()), Varien_Date::DATE_INTERNAL_FORMAT); } $dateEnd = new Zend_Date($to, Varien_Date::DATE_INTERNAL_FORMAT); while ($dateStart->compare($dateEnd) <= 0) { switch ($period) { case self::REPORT_PERIOD_TYPE_DAY: $t = $dateStart->toString('yyyy-MM-dd'); $dateStart->addDay(1); break; case self::REPORT_PERIOD_TYPE_MONTH: $t = $dateStart->toString('yyyy-MM'); $dateStart->addMonth(1); break; case self::REPORT_PERIOD_TYPE_YEAR: $t = $dateStart->toString('yyyy'); $dateStart->addYear(1); break; } $intervals[] = $t; } return $intervals; }
protected function _afterSave(Mage_Core_Model_Abstract $object) { //insert field values if (count($object->getData('field')) > 0) { foreach ($object->getData('field') as $field_id => $value) { if (is_array($value)) { $value = implode("\n", $value); } $field = Mage::getModel('webforms/fields')->load($field_id); if (strstr($field->getType(), 'date') && strlen($value) > 0) { $date = new Zend_Date(); $date->setDate($value, $field->getDateFormat(), Mage::app()->getLocale()->getLocaleCode()); if ($field->getType() == 'datetime') { $date->setTime($value, $field->getDateFormat(), Mage::app()->getLocale()->getLocaleCode()); } $value = date($field->getDbDateFormat(), $date->getTimestamp()); } if ($field->getType() == 'select/contact' && is_numeric($value)) { $value = $field->getContactValueById($value); } if ($value == $field->getHint()) { $value = ''; } // create key $key = ""; if ($field->getType() == 'file' || $field->getType() == 'image') { $key = Mage::helper('webforms')->randomAlphaNum(6); if ($object->getData('key_' . $field_id)) { $key = $object->getData('key_' . $field_id); } } $object->setData('key_' . $field_id, $key); $select = $this->_getReadAdapter()->select()->from($this->getTable('webforms/results_values'))->where('result_id = ?', $object->getId())->where('field_id = ?', $field_id); $result_value = $this->_getReadAdapter()->fetchAll($select); if (!empty($result_value[0])) { $this->_getWriteAdapter()->update($this->getTable('webforms/results_values'), array("value" => $value, "key" => $key), "id = " . $result_value[0]['id']); } else { $this->_getWriteAdapter()->insert($this->getTable('webforms/results_values'), array("result_id" => $object->getId(), "field_id" => $field_id, "value" => $value, "key" => $key)); } } } Mage::dispatchEvent('webforms_result_save', array('result' => $object)); return parent::_afterSave($object); }
public function getIntervals() { if (!$this->_intervals) { $this->_intervals = array(); if (!$this->_from && !$this->_to) { return $this->_intervals; } $dateStart = new Zend_Date($this->_from); $dateStart2 = new Zend_Date($this->_from); $dateEnd = new Zend_Date($this->_to); $t = array(); while ($dateStart->compare($dateEnd) <= 0) { switch ($this->_period) { case 'day': $t['title'] = $dateStart->toString(Mage::app()->getLocale()->getDateFormat()); $t['start'] = $dateStart->toString('yyyy-MM-dd HH:mm:ss'); $t['end'] = $dateStart->toString('yyyy-MM-dd 23:59:59'); $dateStart->addDay(1); break; case 'month': $t['title'] = $dateStart->toString('MM/yyyy'); $t['start'] = $dateStart->toString('yyyy-MM-01 00:00:00'); $t['end'] = $dateStart->toString('yyyy-MM-' . date('t', $dateStart->getTimestamp()) . ' 23:59:59'); $dateStart->addMonth(1); break; case 'year': $t['title'] = $dateStart->toString('yyyy'); $t['start'] = $dateStart->toString('yyyy-01-01 00:00:00'); $t['end'] = $dateStart->toString('yyyy-12-31 23:59:59'); $dateStart->addYear(1); break; } $this->_intervals[$t['title']] = $t; } if ($this->_period != 'day') { $titles = array_keys($this->_intervals); if (count($titles) > 0) { $this->_intervals[$titles[0]]['start'] = $dateStart2->toString('yyyy-MM-dd 00:00:00'); $this->_intervals[$titles[count($titles) - 1]]['end'] = $dateEnd->toString('yyyy-MM-dd 23:59:59'); } } } return $this->_intervals; }
function isEditable() { $date = new Zend_Date($this->dt . ' ' . $this->tm); #d($date->getTimestamp()); $seconds = Zx_Db_Table_Comment::EDIT_TIMELIMIT * 60; $diff = time() - $date->getTimestamp(); return $diff <= $seconds; /* $res = $date->compare($seconds, Zend_Date::SECOND); d($res); // 0 = equal, 1 = later, -1 = earlier if ($res > -1) { return true; } else { return false; } */ }
/** * Save report rows collected in settlement model * * @param Mage_Paypal_Model_Report_Settlement $object * @return Mage_Paypal_Model_Resource_Report_Settlement */ protected function _afterSave(Mage_Core_Model_Abstract $object) { $rows = $object->getRows(); if (is_array($rows)) { $adapter = $this->_getWriteAdapter(); $reportId = (int) $object->getId(); try { $adapter->beginTransaction(); if ($reportId) { $adapter->delete($this->_rowsTable, array('report_id = ?' => $reportId)); } /** @var $date Mage_Core_Model_Date */ $date = Mage::getSingleton('core/date'); foreach ($rows as $key => $row) { /* * Converting dates */ $completionDate = new Zend_Date($rows[$key]['transaction_completion_date']); $rows[$key]['transaction_completion_date'] = $date->date(null, $completionDate->getTimestamp()); $initiationDate = new Zend_Date($rows[$key]['transaction_initiation_date']); $rows[$key]['transaction_initiation_date'] = $date->date(null, $initiationDate->getTimestamp()); /* * Converting numeric */ $rows[$key]['fee_amount'] = (double) $rows[$key]['fee_amount']; /* * Setting reportId */ $rows[$key]['report_id'] = $reportId; } if (!empty($rows)) { $adapter->insertMultiple($this->_rowsTable, $rows); } $adapter->commit(); } catch (Exception $e) { $adapter->rollback(); } } return $this; }
public static function ago($date, $format = null) { $zendDate = new Zend_Date(); if (!$format) { $format = Zend_Date::ISO_8601; } $zendDate->set($date, $format); $ago = time() - $zendDate->getTimestamp(); if ($ago < 120) { return "less than {$ago} seconds ago"; } if ($ago < 60 * 120) { return ceil($ago / 60) . " minutes ago"; } if ($ago < 60 * 60 * 48) { return "about " . floor($ago / (60 * 60)) . " hours ago"; } if ($ago < 60 * 60 * 24 * 60) { return floor($ago / (60 * 60 * 24)) . " days ago"; } return floor($ago / (60 * 60 * 24 * 7)) . " weeks ago"; }
public function execute($lastRunDt = null) { $config = Zend_Registry::get('config'); $event = new Event(); $events = $event->getEvents(null, null, null, time(), null, 'open'); $location = new Location(); $workshop = new Workshop(); $instructor = new Event_Instructor(); $checkDt = new Zend_Date($this->_lastRunDt); $checkDt->addHour($config->user->numHoursLowAttendanceNotification->val); foreach ($events as $e) { if ($e->roleSize < $e->minSize) { $startDt = strtotime($e->date . ' ' . $e->startTime); $endDt = strtotime($e->date . ' ' . $e->endTime); if ($checkDt->getTimestamp() > $startDt && $this->_lastRunDt < $startDt) { $thisLocation = $location->find($e->locationId); if (is_null($thisLocation)) { throw new Ot_Exception_Data('msg-error-noLocation'); } $thisWorkshop = $workshop->find($e->workshopId); if (is_null($thisWorkshop)) { throw new Ot_Exception_Data('msg-error-noWorkshop'); } $instructors = $instructor->getInstructorsForEvent($e->eventId); $instructorNames = array(); $instructorEmails = array(); foreach ($instructors as $i) { $instructorNames[] = $i['firstName'] . ' ' . $i['lastName']; $instructorEmails[] = $i['emailAddress']; } $data = array('workshopName' => $thisWorkshop->title, 'workshopDate' => date('m/d/Y', $startDt), 'workshopStartTime' => date('g:i a', $startDt), 'workshopEndTime' => date('g:i a', $endDt), 'workshopMinimumEnrollment' => $e->minSize, 'workshopCurrentEnrollment' => $e->roleSize, 'locationName' => $thisLocation->name, 'locationAddress' => $thisLocation->address, 'instructorNames' => implode(', ', $instructorNames), 'instructorEmails' => implode(', ', $instructorEmails)); $trigger = new Ot_Trigger(); $trigger->setVariables($data); $trigger->dispatch('Event_LowAttendance'); } } } }
function feedAction() { $test = $this->_request->getParam('test'); if (empty($test)) { $this->_helper->layout->setLayout('printable'); } // not test // create array for feed $afeed = array('title' => $this->view->config->feed->feed_title, 'link' => $this->view->baseUrl . '/feed/feed', 'description' => $this->view->config->feed->feed_desc, 'charset' => "UTF-8", 'entries' => array()); // terminated Jobs $jobs = new Job(); $result = $jobs->getTerminatedJobs(1); foreach ($result as $item) { // convert date to timestamp format $date = new Zend_Date($item['starttime'], 'YYYY-MM-dd HH:mm:ss'); $itemTimestamp = $date->getTimestamp(); $content = '<pre><b>' . $this->view->translate->_("Job Id") . ' : </b>' . $item['jobid'] . '<br>' . '<b>' . $this->view->translate->_("Job Name") . ' : </b>' . $item['jobname'] . '<br>' . '<b>' . $this->view->translate->_("Status") . ' : </b>' . $item['jobstatuslong'] . '<br>' . '<b>' . $this->view->translate->_("Level") . ' : </b>' . $item['level'] . '<br>' . '<b>' . $this->view->translate->_("Client") . ' : </b>' . $item['clientname'] . '<br>' . '<b>' . $this->view->translate->_("Pool") . ' : </b>' . $item['poolname'] . '<br>' . '<b>' . $this->view->translate->_("Start Time") . ' : </b>' . $item['starttime'] . '<br>' . '<b>' . $this->view->translate->_("End Time") . ' : </b>' . $item['endtime'] . '<br>' . '<b>' . $this->view->translate->_("Duration") . ' : </b>' . $item['durationtime'] . '<br>' . '<b>' . $this->view->translate->_("Files") . ' : </b>' . number_format($item['jobfiles']) . '<br>' . '<b>' . $this->view->translate->_("Bytes") . ' : </b>' . $this->view->convBytes($item['jobbytes']) . '<br>' . '<b>' . $this->view->translate->_("Errors") . ' : </b>' . number_format($item['joberrors']) . '<br>' . '</pre>'; $afeed['entries'][] = array('title' => $item['jobname'] . ' ' . $item['jobstatuslong'], 'link' => $this->view->baseUrl . '/job/detail/jobid/' . $item['jobid'], 'description' => $content, 'lastUpdate' => $itemTimestamp); } // Get info Volumes with Status of media: Disabled, Error $media = new Media(); $result = $media->getProblemVolumes(); if ($result) { foreach ($result as $item) { $content = '<pre><b>' . $this->view->translate->_("Volume Name") . ' : </b>' . $item['volumename'] . '<br>' . '<b>' . $this->view->translate->_("Volume Status") . ' : </b>' . $item['volstatus'] . '<br>' . '</pre>'; $afeed['entries'][] = array('title' => $this->view->translate->_("Volumes with errors"), 'link' => $this->view->baseUrl . '/volume/problem/', 'description' => $content, 'lastUpdate' => time()); } } // import array to feed $feed = Zend_Feed::importArray($afeed, 'rss'); // dump feed // print "<pre>".$feed->saveXML();exit; if (empty($test)) { $feed->send(); } else { print $feed->saveXML(); // for unit tests } }
public function formatData($data) { $date = \Zend_Date::now(); $timestart = new \Zend_Date($data['calendar'] . ' ' . $data['slotinput'] . ':00', 'dd-MM-YYYY HH:mm:ss'); //$timestart = \Zend_Date::now(); $location = \Object\Location::getById($data['locationid'], 1); if ($location instanceof \Object\Location) { $societe = $location->getSociete(); $serving = \Object\Serving::getById($data['servinginput'], 1); if ($serving instanceof \Object\Serving) { $mealduration = $serving->getMealduration(); } $end = $timestart->getTimestamp() + $mealduration * 60; $timeend = new \Zend_Date($end); $guest = \Object\Guest::getByEmail($data['email'], 1); if (!$guest instanceof \Object\Guest) { $guest = new \Object\Guest(); $guest->updateData(array('tel' => $data['tel'], 'email' => $data['email'], 'lastname' => $data['lastname'], 'societe' => $societe, 'dateregister' => $date, 'location' => $location)); } } $result = array(); $result['id'] = $data['id']; $result['method'] = $data['method']; $result['tel'] = $data['tel']; $result['email'] = $data['email']; $result['lastname'] = $data['lastname']; $result['partysize'] = $data['partysize']; $result['person'] = $data['person']; $result['societe'] = $societe; $result['location'] = $location; $result['guest'] = $guest; $result['serving'] = $serving; $result['start'] = $timestart; $result['datereservation'] = $timestart; $result['end'] = $timeend; return $result; }
public function indexAction() { $request = $this->getRequest(); $form = new Logic_Raports_Form_Search(); $search = new Logic_Raports_Search($this->_model); if ($request->isPost()) { $values = $request->getPost(); if ($form->isValid($values)) { if (isset($values['create_raport'])) { if ($this->_model->getRaportByDate($values['date_for'], $values['date_to']) === null) { $config = Zend_Registry::get('config'); $base = $config['general']['default']['base_path']; $date = new Zend_Date(); $values['hash'] = SHA1($date->getTimestamp()); $this->_model->addRaport($values); $form->date_for->setValue(''); $form->date_to->setValue(''); $view = new Zend_View(); $date = new Zend_Date(); throw new Exception("Do zmiany."); $packageModel = new WsPackageMail(); $packageQueue = new WsPackageQueue(); $packageData = new WsPackageDataMail(); $package = $packageModel->addPackage(array('name' => 'wysyka raportu', 'time_send_start' => '08:00', 'time_send_end' => "20:00", 'send_start' => $date->getDate()->toString('YYYY-MM-dd'), 'file_type' => Logic_Ws_ServiceSet_ServiceSet::TYPE_ANY)); /* TODO zmiana adresu email doręczena raportów */ $view->setScriptPath(APPLICATION_PATH . '/views/scripts/_mail/'); $view->output = array('baseurl' => $base, 'hash' => $values['hash']); $packageData->addPackageData(array('message' => $view->render('sendreport.phtml'), 'ws_package_id' => $package, 'email_address' => '*****@*****.**')); $packageQueue->addQueue(array('ws_package_id' => $package)); } } } } $this->view->form = $form; $this->view->headers = $search->getHeaders(); $this->view->paginator = $search->paginator(); }
/** * Generate a new Cookie object from a cookie string * (for example the value of the Set-Cookie HTTP header) * * @param string $cookieStr * @param Zend_Uri_Http|string $refUri Reference URI for default values (domain, path) * @param boolean $encodeValue Whether or not the cookie's value should be * passed through urlencode/urldecode * @return Zend_Http_Cookie A new Zend_Http_Cookie object or false on failure. */ public static function fromString($cookieStr, $refUri = null, $encodeValue = true) { // Set default values if (is_string($refUri)) { $refUri = Zend_Uri_Http::factory($refUri); } $name = ''; $value = ''; $domain = ''; $path = ''; $expires = null; $secure = false; $parts = explode(';', $cookieStr); // If first part does not include '=', fail if (strpos($parts[0], '=') === false) { return false; } // Get the name and value of the cookie list($name, $value) = explode('=', trim(array_shift($parts)), 2); $name = trim($name); if ($encodeValue) { $value = urldecode(trim($value)); } // Set default domain and path if ($refUri instanceof Zend_Uri_Http) { $domain = $refUri->getHost(); $path = $refUri->getPath(); $path = substr($path, 0, strrpos($path, '/')); } // Set other cookie parameters foreach ($parts as $part) { $part = trim($part); if (strtolower($part) == 'secure') { $secure = true; continue; } $keyValue = explode('=', $part, 2); if (count($keyValue) == 2) { list($k, $v) = $keyValue; switch (strtolower($k)) { case 'expires': if (($expires = strtotime($v)) === false) { /** * The expiration is past Tue, 19 Jan 2038 03:14:07 UTC * the maximum for 32-bit signed integer. Zend_Date * can get around that limit. * * @see Zend_Date */ require_once 'Zend/Date.php'; $expireDate = new Zend_Date($v); $expires = $expireDate->getTimestamp(); } break; case 'path': $path = $v; break; case 'domain': $domain = $v; break; default: break; } } } if ($name !== '') { $ret = new self($name, $value, $domain, $expires, $path, $secure); $ret->encodeValue = $encodeValue ? true : false; return $ret; } else { return false; } }
public function chartAction() { // Disable layout and viewrenderer $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $viewer = Engine_Api::_()->user()->getViewer(); // Get params $start = $this->_getParam('start'); $offset = $this->_getParam('offset', 0); $type = $this->_getParam('type', 'all'); $mode = $this->_getParam('mode'); $chunk = $this->_getParam('chunk'); $period = $this->_getParam('period'); $periodCount = $this->_getParam('periodCount', 1); $campaign_ids = $this->_getParam('campaign_ids'); // Validate chunk/period if (!$chunk || !in_array($chunk, $this->_periods)) { $chunk = Zend_Date::DAY; } if (!$period || !in_array($period, $this->_periods)) { $period = Zend_Date::MONTH; } if (array_search($chunk, $this->_periods) >= array_search($period, $this->_periods)) { die('whoops'); return; } // Validate start if ($start && !is_numeric($start)) { $start = strtotime($start); } if (!$start) { $start = time(); } // Fixes issues with month view Zend_Date::setOptions(array('extend_month' => true)); // Get timezone $timezone = Engine_Api::_()->getApi('settings', 'core')->getSetting('core_locale_timezone', 'GMT'); if ($viewer && $viewer->getIdentity() && !empty($viewer->timezone)) { $timezone = $viewer->timezone; } // Make start fit to period? $startObject = new Zend_Date($start); $startObject->setTimezone($timezone); $partMaps = $this->_periodMap[$period]; foreach ($partMaps as $partType => $partValue) { $startObject->set($partValue, $partType); } // Do offset if ($offset != 0) { $startObject->add($offset, $period); } $arr_campaigns = array(); if ($campaign_ids) { $arr_campaigns = explode(',', $campaign_ids); } // Get end time $endObject = new Zend_Date($startObject->getTimestamp()); $endObject->setTimezone($timezone); $endObject->add($periodCount, $period); $endObject->sub(1, Zend_Date::SECOND); // Subtract one second $adTbl = Engine_Api::_()->getDbtable('ads', 'ynsocialads'); if (count($arr_campaigns)) { $adList = $adTbl->fetchAll($adTbl->select()->from($adTbl->info("name"), 'ad_id')->where('campaign_id IN (?)', $arr_campaigns)); $adList = $adList->toArray(); } else { $adList = array(); } // Get data $staTable = Engine_Api::_()->getDbtable('statistics', 'ynsocialads'); $staName = $staTable->info('name'); if ($type != "all") { $select = $staTable->select(); // Get data if (count($adList)) { $select->where('ad_id IN (?)', $adList)->where('timestamp >= ?', gmdate('Y-m-d H:i:s', $startObject->getTimestamp()))->where('timestamp < ?', gmdate('Y-m-d H:i:s', $endObject->getTimestamp()))->order('timestamp ASC'); if ($type != "all") { $select->where('type = ?', $type); } $rawData = $staTable->fetchAll($select); } else { $rawData = array(); } // Now create data structure $currentObject = clone $startObject; $nextObject = clone $startObject; $data = array(); $dataLabels = array(); $cumulative = 0; $previous = 0; do { $nextObject->add(1, $chunk); $currentObjectTimestamp = $currentObject->getTimestamp(); $nextObjectTimestamp = $nextObject->getTimestamp(); $data[$this->view->locale()->toDate($currentObjectTimestamp)] = $cumulative; // Get everything that matches $currentPeriodCount = 0; foreach ($rawData as $rawDatum) { $rawDatumDate = strtotime($rawDatum->timestamp); if ($rawDatumDate >= $currentObjectTimestamp && $rawDatumDate < $nextObjectTimestamp) { $currentPeriodCount += 1; } } // Now do stuff with it switch ($mode) { default: case 'normal': $data[$this->view->locale()->toDate($currentObjectTimestamp)] = $currentPeriodCount; break; case 'cumulative': $cumulative += $currentPeriodCount; $data[$this->view->locale()->toDate($currentObjectTimestamp)] = $cumulative; break; case 'delta': $data[$this->view->locale()->toDate($currentObjectTimestamp)] = $currentPeriodCount - $previous; $previous = $currentPeriodCount; break; } $currentObject->add(1, $chunk); } while ($currentObject->getTimestamp() < $endObject->getTimestamp()); // Remove some grid lines if there are too many $xsteps = 1; if (count($data) > 100) { $xsteps = ceil(count($data) / 100); } $title = $this->view->locale()->toDate($startObject) . ' to ' . $this->view->locale()->toDate($endObject); echo Zend_Json::encode(array('json' => $data, 'title' => $title)); } else { $selectClick = $staTable->select(); // Get data if (count($adList)) { $selectClick->where('ad_id IN (?)', $adList)->where('timestamp >= ?', gmdate('Y-m-d H:i:s', $startObject->getTimestamp()))->where('timestamp < ?', gmdate('Y-m-d H:i:s', $endObject->getTimestamp()))->order('timestamp ASC'); $selectClick->where("type = 'click'"); $clickData = $staTable->fetchAll($selectClick); } else { $clickData = array(); } $selectImpression = $staTable->select(); // Get data if (count($adList)) { $selectImpression->where('ad_id IN (?)', $adList)->where('timestamp >= ?', gmdate('Y-m-d H:i:s', $startObject->getTimestamp()))->where('timestamp < ?', gmdate('Y-m-d H:i:s', $endObject->getTimestamp()))->order('timestamp ASC'); $selectImpression->where("type = 'impression'"); $impressionData = $staTable->fetchAll($selectImpression); } else { $impressionData = array(); } // Now create data structure $currentObject = clone $startObject; $nextObject = clone $startObject; $dataClick = array(); $dataImpression = array(); $dataLabels = array(); $cumulativeClick = 0; $cumulativeIm = 0; $previousClick = 0; $previousIm = 0; do { $nextObject->add(1, $chunk); $currentObjectTimestamp = $currentObject->getTimestamp(); $nextObjectTimestamp = $nextObject->getTimestamp(); $dataClick[$this->view->locale()->toDate($currentObjectTimestamp)] = $cumulativeClick; $dataImpression[$this->view->locale()->toDate($currentObjectTimestamp)] = $cumulativeIm; // Get everything that matches $currentPeriodCountClick = 0; foreach ($clickData as $rawDatum) { $rawDatumDate = strtotime($rawDatum->timestamp); if ($rawDatumDate >= $currentObjectTimestamp && $rawDatumDate < $nextObjectTimestamp) { $currentPeriodCountClick += 1; } } $currentPeriodCountIm = 0; foreach ($impressionData as $rawDatum) { $rawDatumDate = strtotime($rawDatum->timestamp); if ($rawDatumDate >= $currentObjectTimestamp && $rawDatumDate < $nextObjectTimestamp) { $currentPeriodCountIm += 1; } } // Now do stuff with it switch ($mode) { default: case 'normal': $dataClick[$this->view->locale()->toDate($currentObjectTimestamp)] = $currentPeriodCountClick; $dataImpression[$this->view->locale()->toDate($currentObjectTimestamp)] = $currentPeriodCountIm; break; case 'cumulative': $cumulativeClick += $currentPeriodCountClick; $cumulativeIm += $currentPeriodCountIm; $dataClick[$this->view->locale()->toDate($currentObjectTimestamp)] = $cumulativeClick; $dataImpression[$this->view->locale()->toDate($currentObjectTimestamp)] = $cumulativeIm; break; case 'delta': $dataClick[$this->view->locale()->toDate($currentObjectTimestamp)] = $currentPeriodCountClick - $previousClick; $dataImpression[$this->view->locale()->toDate($currentObjectTimestamp)] = $currentPeriodCountIm - $previousIm; $previousClick = $currentPeriodCountClick; $previousIm = $currentPeriodCountIm; break; } $currentObject->add(1, $chunk); } while ($currentObject->getTimestamp() < $endObject->getTimestamp()); // Remove some grid lines if there are too many $xsteps = 1; if (count($dataClick) > 100) { $xsteps = ceil(count($dataClick) / 100); } $title = $this->view->locale()->toDate($startObject) . ' to ' . $this->view->locale()->toDate($endObject); echo Zend_Json::encode(array('json' => $dataClick, 'title' => $title, 'json2' => $dataImpression)); } return true; }
/** * @see Object\ClassDefinition\Data::getDataForEditmode * @param \Zend_Date $data * @param null|Object\AbstractObject $object * @return string */ public function getDataForEditmode($data, $object = null) { if ($data instanceof \Zend_Date) { return $data->getTimestamp(); } }
public function getAttributeValidateRules($inputType, array $data) { $inputTypes = $this->getAttributeInputTypes(); $rules = array(); if (isset($inputTypes[$inputType])) { foreach ($inputTypes[$inputType]['validate_types'] as $validateType) { if (!empty($data[$validateType])) { $rules[$validateType] = $data[$validateType]; } } //transform date validate rules to timestamp if ($inputType === 'date') { foreach (array('date_range_min', 'date_range_max') as $dateRangeBorder) { if (isset($rules[$dateRangeBorder])) { $date = new Zend_Date($rules[$dateRangeBorder], $this->getDateFormat()); //zend_debug::dump($date); $rules[$dateRangeBorder] = $date->getTimestamp(); } } } if (!empty($inputTypes[$inputType]['validate_filters']) && !empty($data['input_validation'])) { if (in_array($data['input_validation'], $inputTypes[$inputType]['validate_filters'])) { $rules['input_validation'] = $data['input_validation']; } } } return $rules; }
/** * @ZF-7913 */ public function testUsePhpNFormat() { Zend_Date::setOptions(array('format_type' => 'php')); date_default_timezone_set('GMT'); $date = new Zend_Date(mktime(20, 10, 0, 00, 20, 2009)); $this->assertSame(gmdate('w', $date->getTimestamp()), $date->toString('w')); $this->assertSame(gmdate('d', $date->getTimestamp()), $date->toString('d')); $this->assertSame(gmdate('D', $date->getTimestamp()), $date->toString('D', 'en')); $this->assertSame(gmdate('j', $date->getTimestamp()), $date->toString('j')); $this->assertSame(gmdate('l', $date->getTimestamp()), $date->toString('l', 'en')); $this->assertSame(gmdate('N', $date->getTimestamp()), $date->toString('N')); $this->assertSame(gmdate('S', $date->getTimestamp()), $date->toString('S')); $this->assertSame(gmdate('z', $date->getTimestamp()), $date->toString('z')); $this->assertSame(gmdate('W', $date->getTimestamp()), $date->toString('W')); $this->assertSame(gmdate('F', $date->getTimestamp()), $date->toString('F', 'en')); $this->assertSame(gmdate('m', $date->getTimestamp()), $date->toString('m')); $this->assertSame(gmdate('M', $date->getTimestamp()), $date->toString('M', 'en')); $this->assertSame(gmdate('n', $date->getTimestamp()), $date->toString('n')); $this->assertSame(gmdate('t', $date->getTimestamp()), $date->toString('t')); $this->assertSame(gmdate('L', $date->getTimestamp()), $date->toString('L')); $this->assertSame(gmdate('o', $date->getTimestamp()), $date->toString('o')); $this->assertSame(gmdate('Y', $date->getTimestamp()), $date->toString('Y')); $this->assertSame(gmdate('y', $date->getTimestamp()), $date->toString('y')); $this->assertSame(gmdate('a', $date->getTimestamp()), strtolower($date->toString('a', 'en'))); $this->assertSame(gmdate('A', $date->getTimestamp()), strtoupper($date->toString('A', 'en'))); $this->assertSame(gmdate('B', $date->getTimestamp()), $date->toString('B')); $this->assertSame(gmdate('g', $date->getTimestamp()), $date->toString('g')); $this->assertSame(gmdate('G', $date->getTimestamp()), $date->toString('G')); $this->assertSame(gmdate('h', $date->getTimestamp()), $date->toString('h')); $this->assertSame(gmdate('H', $date->getTimestamp()), $date->toString('H')); $this->assertSame(gmdate('i', $date->getTimestamp()), $date->toString('i')); $this->assertSame(gmdate('s', $date->getTimestamp()), $date->toString('s')); $this->assertSame(date('e', $date->getTimestamp()), $date->toString('e')); $this->assertSame(gmdate('I', $date->getTimestamp()), $date->toString('I')); $this->assertSame(gmdate('O', $date->getTimestamp()), $date->toString('O')); $this->assertSame(gmdate('P', $date->getTimestamp()), $date->toString('P')); $this->assertSame(gmdate('T', $date->getTimestamp()), $date->toString('T')); $this->assertSame(gmdate('Z', $date->getTimestamp()), $date->toString('Z')); $this->assertSame(gmdate('c', $date->getTimestamp()), $date->toString('c')); $this->assertSame(gmdate('r', $date->getTimestamp()), $date->toString('r')); $this->assertSame(gmdate('U', $date->getTimestamp()), $date->toString('U')); date_default_timezone_set('Indian/Maldives'); $date = new Zend_Date(mktime(20, 10, 0, 00, 20, 2009)); $this->assertSame(date('w', $date->getTimestamp()), $date->toString('w')); $this->assertSame(date('d', $date->getTimestamp()), $date->toString('d')); $this->assertSame(date('D', $date->getTimestamp()), $date->toString('D', 'en')); $this->assertSame(date('j', $date->getTimestamp()), $date->toString('j')); $this->assertSame(date('l', $date->getTimestamp()), $date->toString('l', 'en')); $this->assertSame(date('N', $date->getTimestamp()), $date->toString('N')); $this->assertSame(date('S', $date->getTimestamp()), $date->toString('S')); $this->assertSame(date('z', $date->getTimestamp()), $date->toString('z')); $this->assertSame(date('W', $date->getTimestamp()), $date->toString('W')); $this->assertSame(date('F', $date->getTimestamp()), $date->toString('F', 'en')); $this->assertSame(date('m', $date->getTimestamp()), $date->toString('m')); $this->assertSame(date('M', $date->getTimestamp()), $date->toString('M', 'en')); $this->assertSame(date('n', $date->getTimestamp()), $date->toString('n')); $this->assertSame(date('t', $date->getTimestamp()), $date->toString('t')); $this->assertSame(date('L', $date->getTimestamp()), $date->toString('L')); $this->assertSame(date('o', $date->getTimestamp()), $date->toString('o')); $this->assertSame(date('Y', $date->getTimestamp()), $date->toString('Y')); $this->assertSame(date('y', $date->getTimestamp()), $date->toString('y')); $this->assertSame(date('a', $date->getTimestamp()), strtolower($date->toString('a', 'en'))); $this->assertSame(date('A', $date->getTimestamp()), strtoupper($date->toString('A', 'en'))); $this->assertSame(date('B', $date->getTimestamp()), $date->toString('B')); $this->assertSame(date('g', $date->getTimestamp()), $date->toString('g')); $this->assertSame(date('G', $date->getTimestamp()), $date->toString('G')); $this->assertSame(date('h', $date->getTimestamp()), $date->toString('h')); $this->assertSame(date('H', $date->getTimestamp()), $date->toString('H')); $this->assertSame(date('i', $date->getTimestamp()), $date->toString('i')); $this->assertSame(date('s', $date->getTimestamp()), $date->toString('s')); $this->assertSame(date('e', $date->getTimestamp()), $date->toString('e')); $this->assertSame(date('I', $date->getTimestamp()), $date->toString('I')); $this->assertSame(date('O', $date->getTimestamp()), $date->toString('O')); $this->assertSame(date('P', $date->getTimestamp()), $date->toString('P')); $this->assertSame(date('T', $date->getTimestamp()), $date->toString('T')); $this->assertSame(date('Z', $date->getTimestamp()), $date->toString('Z')); $this->assertSame(date('c', $date->getTimestamp()), $date->toString('c')); $this->assertSame(date('r', $date->getTimestamp()), $date->toString('r')); $this->assertSame(date('U', $date->getTimestamp()), $date->toString('U')); Zend_Date::setOptions(array('format_type' => 'iso')); }
public static function format_dateToTimeStamp($strDate) { $date = new Zend_Date($strDate, 'yyyy-MM-dd'); return $date->getTimestamp(); }
public function chartDataAction() { // Disable layout and viewrenderer $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); // Get params $type = $this->_getParam('type'); $start = $this->_getParam('start'); $offset = $this->_getParam('offset', 0); $mode = $this->_getParam('mode'); $chunk = $this->_getParam('chunk'); $period = $this->_getParam('period'); $periodCount = $this->_getParam('periodCount', 1); //$end = $this->_getParam('end'); // Validate chunk/period if (!$chunk || !in_array($chunk, $this->_periods)) { $chunk = Zend_Date::DAY; } if (!$period || !in_array($period, $this->_periods)) { $period = Zend_Date::MONTH; } if (array_search($chunk, $this->_periods) >= array_search($period, $this->_periods)) { die('whoops'); return; } // Validate start if ($start && !is_numeric($start)) { $start = strtotime($start); } if (!$start) { $start = time(); } // Fixes issues with month view Zend_Date::setOptions(array('extend_month' => true)); // Get timezone $timezone = Engine_Api::_()->getApi('settings', 'core')->getSetting('core_locale_timezone', 'GMT'); $viewer = Engine_Api::_()->user()->getViewer(); if ($viewer && $viewer->getIdentity() && !empty($viewer->timezone)) { $timezone = $viewer->timezone; } // Make start fit to period? $startObject = new Zend_Date($start); $startObject->setTimezone($timezone); $partMaps = $this->_periodMap[$period]; foreach ($partMaps as $partType => $partValue) { $startObject->set($partValue, $partType); } // Do offset if ($offset != 0) { $startObject->add($offset, $period); } // Get end time $endObject = new Zend_Date($startObject->getTimestamp()); $endObject->setTimezone($timezone); $endObject->add($periodCount, $period); $endObject->sub(1, Zend_Date::SECOND); // Subtract one second // Get data $statsTable = Engine_Api::_()->getDbtable('statistics', 'core'); $statsSelect = $statsTable->select()->where('type = ?', $type)->where('date >= ?', gmdate('Y-m-d H:i:s', $startObject->getTimestamp()))->where('date < ?', gmdate('Y-m-d H:i:s', $endObject->getTimestamp()))->order('date ASC'); $rawData = $statsTable->fetchAll($statsSelect); // Now create data structure $currentObject = clone $startObject; $nextObject = clone $startObject; $data = array(); $dataLabels = array(); $cumulative = 0; $previous = 0; do { $nextObject->add(1, $chunk); $currentObjectTimestamp = $currentObject->getTimestamp(); $nextObjectTimestamp = $nextObject->getTimestamp(); $data[$currentObjectTimestamp] = $cumulative; // Get everything that matches $currentPeriodCount = 0; foreach ($rawData as $rawDatum) { $rawDatumDate = strtotime($rawDatum->date); if ($rawDatumDate >= $currentObjectTimestamp && $rawDatumDate < $nextObjectTimestamp) { $currentPeriodCount += $rawDatum->value; } } // Now do stuff with it switch ($mode) { default: case 'normal': $data[$currentObjectTimestamp] = $currentPeriodCount; break; case 'cumulative': $cumulative += $currentPeriodCount; $data[$currentObjectTimestamp] = $cumulative; break; case 'delta': $data[$currentObjectTimestamp] = $currentPeriodCount - $previous; $previous = $currentPeriodCount; break; } $currentObject->add(1, $chunk); } while ($currentObject->getTimestamp() < $endObject->getTimestamp()); // Reprocess label $labelStrings = array(); $labelDate = new Zend_Date(); foreach ($data as $key => $value) { $labelDate->set($key); $labelStrings[] = $this->view->locale()->toDate($labelDate, array('size' => 'short')); //date('D M d Y', $key); } // Let's expand them by 1.1 just for some nice spacing $minVal = min($data); $maxVal = max($data); $minVal = floor($minVal * ($minVal < 0 ? 1.1 : 1 / 1.1) / 10) * 10; $maxVal = ceil($maxVal * ($maxVal > 0 ? 1.1 : 1 / 1.1) / 10) * 10; // Remove some labels if there are too many $xlabelsteps = 1; if (count($data) > 10) { $xlabelsteps = ceil(count($data) / 10); } // Remove some grid lines if there are too many $xsteps = 1; if (count($data) > 100) { $xsteps = ceil(count($data) / 100); } // Create base chart require_once 'OFC/OFC_Chart.php'; // Make x axis labels $x_axis_labels = new OFC_Elements_Axis_X_Label_Set(); $x_axis_labels->set_steps($xlabelsteps); $x_axis_labels->set_labels($labelStrings); // Make x axis $labels = new OFC_Elements_Axis_X(); $labels->set_labels($x_axis_labels); $labels->set_colour("#416b86"); $labels->set_grid_colour("#dddddd"); $labels->set_steps($xsteps); // Make y axis $yaxis = new OFC_Elements_Axis_Y(); $yaxis->set_range($minVal, $maxVal); $yaxis->set_colour("#416b86"); $yaxis->set_grid_colour("#dddddd"); // Make data $graph = new OFC_Charts_Line(); $graph->set_values(array_values($data)); $graph->set_colour("#5ba1cd"); // Make title $locale = Zend_Registry::get('Locale'); $translate = Zend_Registry::get('Zend_Translate'); $titleStr = $translate->_('_CORE_ADMIN_STATS_' . strtoupper(trim(preg_replace('/[^a-zA-Z0-9]+/', '_', $type), '_'))); $title = new OFC_Elements_Title($titleStr . ': ' . $this->view->locale()->toDateTime($startObject) . ' to ' . $this->view->locale()->toDateTime($endObject)); $title->set_style("{font-size: 14px;font-weight: bold;margin-bottom: 10px; color: #777777;}"); // Make full chart $chart = new OFC_Chart(); $chart->set_bg_colour('#ffffff'); $chart->set_x_axis($labels); $chart->add_y_axis($yaxis); $chart->add_element($graph); $chart->set_title($title); // Send $this->getResponse()->setBody($chart->toPrettyString()); }
/** * @param $date * @param $relativeDate * @return float|int|string */ protected function calcDate($date, $relativeDate) { if (strpos($relativeDate, '-') !== false || strpos($relativeDate, '+') !== false) { $modifiers = explode(' ', str_replace(' ', ' ', $relativeDate)); $applyModifiers = array(); foreach ($modifiers as $modifier) { $modifier = trim($modifier); if (preg_match('/^([+-])(\\d+)([dmy])$/', $modifier, $matches)) { if (in_array($matches[1], array('+', '-')) && is_numeric($matches[2]) && in_array($matches[3], array('d', 'm', 'y'))) { $applyModifiers[] = array('sign' => $matches[1], 'number' => $matches[2], 'type' => $matches[3]); } } } if (sizeof($applyModifiers)) { $date = new \Zend_Date(); foreach ($applyModifiers as $modifier) { if ($modifier['sign'] == '-') { $modifier['number'] *= -1; } $typeMap = array('d' => \Zend_Date::DAY, 'm' => \Zend_Date::MONTH, 'y' => \Zend_Date::YEAR); $date->add($modifier['number'], $typeMap[$modifier['type']]); } return $date->getTimestamp(); } } return $date / 1000; }