本文整理汇总了PHP中DateTime::create方法的典型用法代码示例。如果您正苦于以下问题:PHP DateTime::create方法的具体用法?PHP DateTime::create怎么用?PHP DateTime::create使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DateTime
的用法示例。
在下文中一共展示了DateTime::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: filter
/**
*
*
* @param Event $event An Event instance
*/
public function filter(Event $event, Response $response)
{
if (!$configuration = $event->get('request')->attributes->get('_cache')) {
return $response;
}
if (!$response->isSuccessful()) {
return $response;
}
if (null !== $configuration->getSMaxAge()) {
$response->setSharedMaxAge($configuration->getSMaxAge());
}
if (null !== $configuration->getMaxAge()) {
$response->setMaxAge($configuration->getMaxAge());
}
if (null !== $configuration->getExpires()) {
$date = \DateTime::create(\DateTime::createFromFormat('U', $configuration->getExpires(), new \DateTimeZone('UTC')));
$response->setLastModified($date);
}
return $response;
}
示例2: get_dashboard
/**
* Handles get requests for the dashboard
* @todo update check should probably be cron'd and cached, not re-checked every load
*/
public function get_dashboard()
{
// Not sure how best to determine this yet, maybe set an option on install, maybe do this:
$firstpostdate = DB::get_value('SELECT min(pubdate) FROM {posts} WHERE status = ?', array(Post::status('published')));
if ($firstpostdate) {
$this->theme->active_time = DateTime::create($firstpostdate);
}
// check to see if we have updates to display
$this->theme->updates = Options::get('updates_available', array());
// collect all the stats we display on the dashboard
$user = User::identify();
$this->theme->stats = array('author_count' => Users::get(array('count' => 1)), 'post_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('any'), 'status' => Post::status('published'))), 'comment_count' => Comments::count_total('approved', false), 'tag_count' => Tags::vocabulary()->count_total(), 'user_draft_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('any'), 'status' => Post::status('draft'), 'user_id' => $user->id)), 'unapproved_comment_count' => User::identify()->can('manage_all_comments') ? Comments::count_total('unapproved', false) : Comments::count_by_author(User::identify()->id, Comment::status('unapproved')), 'spam_comment_count' => $user->can('manage_all_comments') ? Comments::count_total('spam', false) : Comments::count_by_author($user->id, Comment::status('spam')), 'user_scheduled_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('any'), 'status' => Post::status('scheduled'), 'user_id' => $user->id)));
// check for first run
$u = User::identify();
$uinfo = $u->info;
if (!isset($uinfo->experience_level)) {
$this->theme->first_run = true;
$u->info->experience_level = 'user';
$u->info->commit();
} else {
$this->theme->first_run = false;
}
$this->get_additem_form();
Stack::add('admin_header_javascript', 'dashboard-js');
$this->display('dashboard');
}
示例3: test_delete_on_fail
public function test_delete_on_fail()
{
$job = CronTab::add_single_cron('test_delete_fail', 'this_cron_hook_doesnt_exist', DateTime::create(), 'Test Cron');
for ($z = 0; $z < 10; $z++) {
$job = CronTab::get_cronjob('test_delete_fail');
Options::set('next_cron', 0);
Options::delete('cron_running');
$job->execute();
}
$this->assert_false($job->active, 'The cron is still active after failing more than the allowed number of times.');
CronTab::delete_cronjob('test_delete_fail');
}
示例4: __construct
public function __construct()
{
parent::__construct();
// Let's register the options page form so we can use it with ajax
$self = $this;
FormUI::register('admin_options', function ($form, $name, $extra_data) use($self) {
$option_items = array();
$timezones = \DateTimeZone::listIdentifiers();
$timezones = array_merge(array('' => ''), array_combine(array_values($timezones), array_values($timezones)));
$option_items[_t('Name & Tagline')] = array('title' => array('label' => _t('Site Name'), 'type' => 'text', 'helptext' => ''), 'tagline' => array('label' => _t('Site Tagline'), 'type' => 'text', 'helptext' => ''), 'about' => array('label' => _t('About'), 'type' => 'textarea', 'helptext' => ''));
$option_items[_t('Publishing')] = array('pagination' => array('label' => _t('Items per Page'), 'type' => 'text', 'helptext' => ''), 'atom_entries' => array('label' => _t('Entries to show in Atom feed'), 'type' => 'text', 'helptext' => ''), 'comments_require_id' => array('label' => _t('Require Comment Author Email'), 'type' => 'checkbox', 'helptext' => ''), 'spam_percentage' => array('label' => _t('Comment SPAM Threshold'), 'type' => 'text', 'helptext' => _t('The likelihood a comment is considered SPAM, in percent.')));
$option_items[_t('Time & Date')] = array('timezone' => array('label' => _t('Time Zone'), 'type' => 'select', 'selectarray' => $timezones, 'helptext' => _t('Current Date Time: %s', array(DateTime::create()->format()))), 'dateformat' => array('label' => _t('Date Format'), 'type' => 'text', 'helptext' => _t('Current Date: %s', array(DateTime::create()->date))), 'timeformat' => array('label' => _t('Time Format'), 'type' => 'text', 'helptext' => _t('Current Time: %s', array(DateTime::create()->time))));
$option_items[_t('Language')] = array('locale' => array('label' => _t('Locale'), 'type' => 'select', 'selectarray' => array_merge(array('' => 'default'), array_combine(Locale::list_all(), Locale::list_all())), 'helptext' => Config::exists('locale') ? _t('International language code : This value is set in your config.php file, and cannot be changed here.') : _t('International language code'), 'disabled' => Config::exists('locale'), 'value' => Config::get('locale', Options::get('locale', 'en-us'))), 'system_locale' => array('label' => _t('System Locale'), 'type' => 'text', 'helptext' => _t('The appropriate locale code for your server')));
$option_items[_t('Troubleshooting')] = array('log_min_severity' => array('label' => _t('Minimum Severity'), 'type' => 'select', 'selectarray' => LogEntry::list_severities(), 'helptext' => _t('Only log entries with a this or higher severity.')), 'log_backtraces' => array('label' => _t('Log Backtraces'), 'type' => 'checkbox', 'helptext' => _t('Logs error backtraces to the log table\'s data column. Can drastically increase log size!')));
$option_items = Plugins::filter('admin_option_items', $option_items);
$tab_index = 3;
foreach ($option_items as $name => $option_fields) {
/** @var FormControlFieldset $fieldset */
$fieldset = $form->append(FormControlWrapper::create(Utils::slugify(_u($name)))->set_properties(array('class' => 'container main settings')));
$fieldset->append(FormControlStatic::create($name)->set_static('<h2 class="lead">' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '</h2>'));
$fieldset->set_wrap_each('<div>%s</div>');
foreach ($option_fields as $option_name => $option) {
/** @var FormControlLabel $label */
$label = $fieldset->append(FormControlLabel::create('label_for_' . $option_name, null)->set_label($option['label']));
/** @var FormControl $field */
$field = $label->append($option['type'], $option_name, $option_name);
$label->set_for($field);
if (isset($option['value'])) {
$field->set_value($option['value']);
}
if (isset($option['disabled']) && $option['disabled'] == true) {
$field->set_properties(array('disabled' => 'disabled'));
}
if ($option['type'] == 'select' && isset($option['selectarray'])) {
$field->set_options($option['selectarray']);
}
$field->tabindex = $tab_index;
$tab_index++;
if (isset($option['helptext'])) {
$field->set_helptext($option['helptext']);
}
}
}
$buttons = $form->append(new FormControlWrapper('buttons', null, array('class' => 'container')));
$buttons->append(FormControlSubmit::create('apply', null, array('tabindex' => $tab_index))->set_caption(_t('Apply')));
$form->on_success(array($self, 'form_options_success'));
$form = Plugins::filter('admin_options_form', $form);
});
}
示例5: loginform_do_login
public function loginform_do_login($form)
{
$name = $form->habari_username->value;
$pass = $form->habari_password->value;
if (null != $name || null != $pass) {
$user = User::authenticate($name, $pass);
if ($user instanceof User && $user != false) {
$userinfo = $user->info;
// if there's an unused password reset token, unset it to make sure there's no possibility of a compromise that way
if (isset($userinfo->password_reset)) {
unset($userinfo->password_reset);
}
/* Successfully authenticated. */
// Timestamp last login date and time.
$user->info->authenticate_time = DateTime::create()->format('Y-m-d H:i:s');
$user->update();
// Remove left over expired session error message.
if (Session::has_errors('expired_session')) {
Session::remove_error('expired_session');
}
$login_session = Session::get_set('login');
if (!empty($login_session)) {
/* Now that we know we're dealing with the same user, transfer the form data so he does not lose his request */
if (!empty($login_session['post_data'])) {
Session::add_to_set('last_form_data', $last_form_data['post'], 'post');
}
if (!empty($login_session['get_data'])) {
Session::add_to_set('last_form_data', $last_form_data['get'], 'get');
}
// don't bother parsing out the URL, we store the URI that was requested, so just append that to the hostname and we're done
$login_dest = Site::get_url('host') . $login_session['original'];
} else {
$login_session = null;
$login_dest = Site::get_url('admin');
}
// filter the destination
$login_dest = Plugins::filter('login_redirect_dest', $login_dest, $user, $login_session);
// finally, redirect to the destination
Utils::redirect($login_dest);
return true;
}
/* Authentication failed. */
// Remove submitted password, see, we're secure!
$form->habari_password->value = '';
$this->handler_vars['error'] = _t('Bad credentials');
}
}
示例6: act_poll_cron
/**
* Handles asyncronous cron calls.
*
* @todo next_cron should be the actual next run time and update it when new
* crons are added instead of just maxing out at one day..
*/
function act_poll_cron()
{
Utils::check_request_method(array('GET', 'HEAD', 'POST'));
$time = doubleval($this->handler_vars['time']);
if ($time != Options::get('cron_running')) {
return;
}
// allow script to run for 10 minutes. This only works on host with safe mode DISABLED
if (!ini_get('safe_mode')) {
set_time_limit(600);
}
$time = DateTime::create();
$crons = DB::get_results('SELECT * FROM {crontab} WHERE start_time <= ? AND next_run <= ? AND active != ?', array($time->sql, $time->sql, 0), 'CronJob');
if ($crons) {
foreach ($crons as $cron) {
$cron->execute();
}
}
// set the next run time to the lowest next_run OR a max of one day.
$next_cron = DB::get_value('SELECT next_run FROM {crontab} WHERE active != ? ORDER BY next_run ASC LIMIT 1', array(0));
Options::set('next_cron', min(intval($next_cron), $time->modify('+1 day')->int));
Options::set('cron_running', false);
}
示例7: get_revision_data
/**
* Get the fields of the post that differ from what is stored by date
* @param DateTime|string|int $date The date to fetch the revision of
* @return array An array of field data for the post with the values of those fields at the specified date
*/
public function get_revision_data($date)
{
$sql = <<<GET_REVISION_DATA
SELECT
id, post_id, change_field, old_value, user_id, min(change_date) as change_date
FROM {revisions}
WHERE
post_id = :post_id
AND change_date > :rev_date
GROUP BY change_field
ORDER BY change_date;
GET_REVISION_DATA;
return DB::get_results($sql, array('post_id' => $this->id, 'rev_date' => DateTime::create($date)->sql));
}
示例8: fetch_logs
private function fetch_logs()
{
// load all the values for our filter drop-downs
$dates = $this->fetch_log_dates();
$users = $this->fetch_log_users();
$ips = $this->fetch_log_ips();
extract($this->fetch_log_modules_types());
// $modules and $types
$severities = LogEntry::list_severities();
// parse out the arguments we'll fetch logs for
// the initial arguments
$arguments = array('limit' => Controller::get_var('limit', 20), 'offset' => Controller::get_var('offset', 0));
// filter for the search field
$search = Controller::get_var('search', '');
if ($search != '') {
$arguments['criteria'] = $search;
}
// filter by date
$date = Controller::get_var('date', 'any');
if ($date != 'any') {
$d = DateTime::create($date);
// ! means fill any non-specified pieces with default Unix Epoch ones
$arguments['year'] = $d->format('Y');
$arguments['month'] = $d->format('m');
}
// filter by user
$user = Controller::get_var('user', 'any');
if ($user != 'any') {
$arguments['user_id'] = $user;
}
// filter by ip
$ip = Controller::get_var('address', 'any');
if ($ip != 'any') {
$arguments['ip'] = $ip;
}
// filter modules and types
// @todo get events of a specific type in a specific module, instead of either of the two
// the interface doesn't currently make any link between module and type, so we won't worry about it for now
$module = Controller::get_var('module', 'any');
$type = Controller::get_var('type', 'any');
if ($module != 'any') {
// we get a slugified key back, get the actual module name
$arguments['module'] = $modules[$module];
}
if ($type != 'any') {
// we get a slugified key back, get the actual type name
$arguments['type'] = $types[$type];
}
// filter by severity
$severity = Controller::get_var('severity', 0);
if ($severity != 0) {
$arguments['severity'] = $severity;
}
// get the logs!
$logs = EventLog::get($arguments);
// last, but not least, generate the list of years used for the timeline
$months = EventLog::get(array_merge($arguments, array('month_cts' => true)));
$years = array();
foreach ($months as $m) {
$years[$m->year][] = $m;
}
// assign all our theme values in one spot
// first the filter options
$this->theme->dates = $dates;
$this->theme->users = $users;
$this->theme->addresses = $ips;
$this->theme->modules = $modules;
$this->theme->types = $types;
$this->theme->severities = $severities;
// next the filter criteria we used
$this->theme->search_args = $search;
$this->theme->date = $date;
$this->theme->user = $user;
$this->theme->address = $ip;
$this->theme->module = $module;
$this->theme->type = $type;
$this->theme->severity = $severity;
$this->theme->logs = $logs;
$this->theme->years = $years;
$form = new FormUI('logs_batch', 'logs_batch');
$form->append(FormControlAggregate::create('entries')->set_selector('.log_entry')->set_value(array())->label('None Selected'));
$form->append($actions = FormControlDropbutton::create('actions'));
$actions->append(FormControlSubmit::create('delete_selected')->on_success(function (FormUI $form) {
$ids = $form->entries->value;
$count = 0;
/** @var LogEntry $log */
foreach ($ids as $id) {
$logs = EventLog::get(array('id' => $id));
foreach ($logs as $log) {
$log->delete();
$count++;
}
}
Session::notice(_t('Deleted %d logs.', array($count)));
$form->bounce(false);
})->set_caption(_t('Delete Selected')));
$actions->append(FormControlSubmit::create('purge_logs')->on_success(function (FormUI $form) {
if (EventLog::purge()) {
Session::notice(_t('Logs purged.'));
} else {
//.........这里部分代码省略.........
示例9: get
//.........这里部分代码省略.........
if (isset($paramset['criteria_fields'])) {
// Support 'criteria_fields' => 'author,ip' rather than 'criteria_fields' => array( 'author', 'ip' )
if (!is_array($paramset['criteria_fields']) && is_string($paramset['criteria_fields'])) {
$paramset['criteria_fields'] = explode(',', $paramset['criteria_fields']);
}
} else {
$paramset['criteria_fields'] = array('content');
}
$paramset['criteria_fields'] = array_unique($paramset['criteria_fields']);
preg_match_all('/(?<=")([\\p{L}\\p{N}]+[^"]*)(?=")|([\\p{L}\\p{N}]+)/u', $paramset['criteria'], $matches);
$where_search = array();
foreach ($matches[0] as $word) {
foreach ($paramset['criteria_fields'] as $criteria_field) {
$where_search[] .= "( LOWER( {comments}.{$criteria_field} ) LIKE ? )";
$params[] = '%' . MultiByte::strtolower($word) . '%';
}
}
if (count($where_search) > 0) {
$where[] = '(' . implode(" \nOR\n ", $where_search) . ')';
}
}
/*
* Build the pubdate
* If we've got the day, then get the date.
* If we've got the month, but no date, get the month.
* If we've only got the year, get the whole year.
* @todo Ensure that we've actually got all the needed parts when we query on them
* @todo Ensure that the value passed in is valid to insert into a SQL date (ie '04' and not '4')
*/
if (isset($paramset['day'])) {
/* Got the full date */
$where[] = 'date BETWEEN ? AND ?';
$start_date = sprintf('%d-%02d-%02d', $paramset['year'], $paramset['month'], $paramset['day']);
$start_date = DateTime::create($start_date);
$params[] = $start_date->sql;
$params[] = $start_date->modify('+1 day')->sql;
} elseif (isset($paramset['month'])) {
$where[] = 'date BETWEEN ? AND ?';
$start_date = sprintf('%d-%02d-%02d', $paramset['year'], $paramset['month'], 1);
$start_date = DateTime::create($start_date);
$params[] = $start_date->sql;
$params[] = $start_date->modify('+1 month')->sql;
} elseif (isset($paramset['year'])) {
$where[] = 'date BETWEEN ? AND ?';
$start_date = sprintf('%d-%02d-%02d', $paramset['year'], 1, 1);
$start_date = DateTime::create($start_date);
$params[] = $start_date->sql;
$params[] = $start_date->modify('+1 year')->sql;
}
// Concatenate the WHERE clauses
if (count($where) > 0) {
$wheres[] = ' (' . implode(' AND ', $where) . ') ';
}
}
}
// Only show comments to which the current user has permission to read the associated post
if (isset($paramset['ignore_permissions'])) {
$master_perm_where = '';
// Set up the merge params
$merge_params = array($join_params, $params);
$params = call_user_func_array('array_merge', $merge_params);
} else {
// This set of wheres will be used to generate a list of comment_ids that this user can read
$perm_where = array();
$perm_where_denied = array();
$params_where = array();
示例10: check_plugins
/**
* Compare the current set of plugins with those we last checked for updates.
* This is run by AdminHandler on every page load to make sure we always have fresh data on the dashboard.
*/
public static function check_plugins()
{
// register the beacons
self::register_beacons();
// get the list we checked last time
$checked_list = Options::get('updates_beacons');
// if the lists are different
if ($checked_list != self::instance()->beacons) {
// remove any stored updates, just to avoid showing stale data
Options::delete('updates_available');
// schedule an update check the next time cron runs
CronTab::add_single_cron('update_check_single', Method::create('\\Habari\\Update', 'cron'), DateTime::create()->int, _t('Perform a single check for plugin updates, the plugin set has changed.'));
}
}
示例11: __set
/**
* Magic property setter to set the cronjob properties.
* Serializes the callback if needed.
*
* @see QueryRecord::__set()
* @param string $name The name of the property to set.
* @param mixed $value The value of the property to set.
* @return mixed The new value of the property.
*/
public function __set($name, $value)
{
switch ($name) {
case 'callback':
if (is_array($value) || is_object($value)) {
$value = serialize($value);
}
break;
case 'next_run':
case 'last_run':
case 'start_time':
case 'end_time':
if (!$value instanceof DateTime && !is_null($value)) {
$value = DateTime::create($value);
}
break;
}
return parent::__set($name, $value);
}
示例12: difference
/**
* Returns an array representing the difference between two times by interval.
*
* <code>
* print_r( DateTime::difference( 'now', 'January 1, 2010' ) );
* // output (past): Array ( [invert] => [y] => 0 [m] => 9 [w] => 3 [d] => 5 [h] => 22 [i] => 33 [s] => 5 )
* print_r( DateTime::difference( 'now', 'January 1, 2011' ) );
* // output (future): Array ( [invert] => 1 [y] => 0 [m] => 2 [w] => 0 [d] => 3 [h] => 5 [i] => 33 [s] => 11 )
* </code>
*
* If 'invert' is true, the time is in the future (ie: x from now). If it is false, the time is in the past (ie: x ago).
*
* For more information, see PHP's DateInterval class, which this and friendly() attempt to emulate for < PHP 5.3
*
* @todo Add total_days, total_years, etc. values?
*
* @param mixed $start_date The start date, as a HDT object or any format accepted by DateTime::create().
* @param mixed $end_date The end date, as a HDT object or any format accepted by DateTime::create().
* @return array Array of each interval and whether the interval is inverted or not.
*/
public static function difference($start_date, $end_date)
{
// if the dates aren't HDT objects, try to convert them to one. this lets you pass in just about any format
if (!$start_date instanceof DateTime) {
$start_date = DateTime::create($start_date);
}
if (!$end_date instanceof DateTime) {
$end_date = DateTime::create($end_date);
}
$result = array();
// calculate the difference, in seconds
$difference = $end_date->int - $start_date->int;
if ($difference < 0) {
// if it's negative, time AGO
$result['invert'] = false;
} else {
// if it's positive, time UNTIL
$result['invert'] = true;
}
$difference = abs($difference);
// we'll progressively subtract from the seconds left, so initialize it
$seconds_left = $difference;
$result['y'] = floor($seconds_left / self::YEAR);
$seconds_left = $seconds_left - $result['y'] * self::YEAR;
$result['m'] = floor($seconds_left / self::MONTH);
$seconds_left = $seconds_left - $result['m'] * self::MONTH;
$result['w'] = floor($seconds_left / self::WEEK);
$seconds_left = $seconds_left - $result['w'] * self::WEEK;
$result['d'] = floor($seconds_left / self::DAY);
$seconds_left = $seconds_left - $result['d'] * self::DAY;
$result['h'] = floor($seconds_left / self::HOUR);
$seconds_left = $seconds_left - $result['h'] * self::HOUR;
$result['i'] = floor($seconds_left / self::MINUTE);
$seconds_left = $seconds_left - $result['i'] * self::MINUTE;
$result['s'] = $seconds_left;
return $result;
}
示例13: max
/**
* Return max validator
*
* @return DateTime
*/
public function max()
{
return DateTime::create();
}
示例14: update_scheduled_posts_cronjob
/**
* function update_scheduled_posts_cronjob
*
* Creates or recreates the cronjob to publish
* scheduled posts. It is called whenever a post
* is updated or created
*
*/
public static function update_scheduled_posts_cronjob()
{
$min_time = DB::get_value('SELECT MIN(pubdate) FROM {posts} WHERE status = ?', array(Post::status('scheduled')));
CronTab::delete_cronjob('publish_scheduled_posts');
if ($min_time) {
CronTab::add_single_cron('publish_scheduled_posts', Method::create('\\Habari\\Posts', 'publish_scheduled_posts'), $min_time, 'Next run: ' . DateTime::create($min_time)->get('c'));
}
}
示例15: trim
public static function trim()
{
// allow an option to be set to override the log retention - in days
$retention_days = Options::get('log_retention', 14);
// default to 14 days
// make it into the string we'll use
$retention = '-' . intval($retention_days) . ' days';
// Trim the log table down
$date = DateTime::create()->modify($retention);
$result = DB::query('DELETE FROM {log} WHERE timestamp < ?', array($date->sql));
if ($result) {
EventLog::log(_t('Entries over %d days old were trimmed from the EventLog', array($retention_days)), 'info');
} else {
EventLog::log(_t('There was an error trimming old entries from the EventLog!'), 'err');
}
return $result;
}