use Friendica\App;
use Friendica\Core\Addon;
-use Friendica\Core\System;
-use Friendica\Core\Cache;
use Friendica\Core\Config;
-use Friendida\Core\L10n;
+use Friendica\Core\L10n;
use Friendica\Core\PConfig;
+use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
-use Friendica\Model\Contact;
use Friendica\Database\DBStructure;
-use Friendica\Module\Login;
+use Friendica\Model\Contact;
+use Friendica\Util\DateTimeFormat;
require_once 'include/text.php';
require_once 'include/datetime.php';
* This can be used in HTML and JavaScript where needed a line break.
*/
define('EOL', "<br />\r\n");
-define('ATOM_TIME', 'Y-m-d\TH:i:s\Z');
/**
* @brief Image storage quality.
if (DBM::is_result($p)) {
$tmp_dob = substr($p[0]['dob'], 5);
if (intval($tmp_dob)) {
- $y = datetime_convert($tz, $tz, 'now', 'Y');
+ $y = DateTimeFormat::timezoneNow($tz, 'Y');
$bd = $y . '-' . $tmp_dob . ' 00:00';
$t_dob = strtotime($bd);
- $now = strtotime(datetime_convert($tz, $tz, 'now'));
+ $now = strtotime(DateTimeFormat::timezoneNow($tz));
if ($t_dob < $now) {
$bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
}
- $birthday = datetime_convert($tz, 'UTC', $bd, ATOM_TIME);
+ $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
}
}
* @file include/api.php
* @todo Automatically detect if incoming data is HTML or BBCode
*/
+
use Friendica\App;
use Friendica\Content\ContactSelector;
use Friendica\Content\Feature;
use Friendica\Content\Text\BBCode;
use Friendica\Core\Addon;
-use Friendica\Core\System;
use Friendica\Core\Config;
-use Friendica\Core\NotificationsManager;
use Friendica\Core\L10n;
+use Friendica\Core\NotificationsManager;
use Friendica\Core\PConfig;
+use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Group;
+use Friendica\Model\Item;
use Friendica\Model\Mail;
use Friendica\Model\Photo;
use Friendica\Model\User;
-use Friendica\Model\Item;
use Friendica\Network\FKOAuth1;
use Friendica\Network\HTTPException;
use Friendica\Network\HTTPException\BadRequestException;
use Friendica\Network\HTTPException\MethodNotAllowedException;
use Friendica\Network\HTTPException\NotFoundException;
use Friendica\Network\HTTPException\NotImplementedException;
-use Friendica\Network\HTTPException\UnauthorizedException;
use Friendica\Network\HTTPException\TooManyRequestsException;
+use Friendica\Network\HTTPException\UnauthorizedException;
use Friendica\Object\Image;
use Friendica\Protocol\Diaspora;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\XML;
function api_date($str)
{
// Wed May 23 06:01:13 +0000 2007
- return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
+ return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
}
/**
'self' => System::baseUrl() . "/" . $a->query_string,
'base' => System::baseUrl(),
'updated' => api_date(null),
- 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
+ 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'language' => $user_info['language'],
'logo' => System::baseUrl() . "/images/friendica-32.png",
];
// Check for throttling (maximum posts per day, week and month)
$throttle_day = Config::get('system', 'throttle_limit_day');
if ($throttle_day > 0) {
- $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
+ $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
$r = q(
"SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
$throttle_week = Config::get('system', 'throttle_limit_week');
if ($throttle_week > 0) {
- $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
+ $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
$r = q(
"SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
$throttle_month = Config::get('system', 'throttle_limit_month');
if ($throttle_month > 0) {
- $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
+ $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
$r = q(
"SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
'@attributes' => ["type" => "integer"],
'hourly-limit' => '150',
'@attributes2' => ["type" => "integer"],
- 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
+ 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
'@attributes3' => ["type" => "datetime"],
'reset_time_in_seconds' => strtotime('now + 1 hour'),
'@attributes4' => ["type" => "integer"],
'reset_time_in_seconds' => strtotime('now + 1 hour'),
'remaining_hits' => '150',
'hourly_limit' => '150',
- 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
+ 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
];
}
$result = q(
"UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
$sql_extra,
- datetime_convert(), // update edited timestamp
+ DateTimeFormat::utcNow(), // update edited timestamp
intval(api_user()),
dbesc($photo_id),
dbesc($album)
q(
"UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
intval(local_user())
);
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\Markdown;
use Friendica\Core\Addon;
+use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Model\Contact;
use Friendica\Network\Probe;
+use Friendica\Util\DateTimeFormat;
use League\HTMLToMarkdown\HtmlConverter;
require_once 'include/event.php';
$o .= '**' . (($ev['summary']) ? bb2diaspora($ev['summary']) : bb2diaspora($ev['desc'])) . '**' . "\n";
- $o .= L10n::t('Starts:') . ' ' . '['
- . (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC',
- $ev['start'] , $bd_format ))
- : day_translate(datetime_convert('UTC', 'UTC',
- $ev['start'] , $bd_format)))
- . '](' . System::baseUrl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['start'])) . ")\n";
+ // @todo What. Is. Going. On. With. This. Useless. Ternary. Operator? - mrpetovan
+ $o .= L10n::t('Starts:') . ' ' . '[' . day_translate(
+ $ev['adjust'] ? DateTimeFormat::utc($ev['start'], $bd_format) : DateTimeFormat::utc($ev['start'], $bd_format)
+ )
+ . '](' . System::baseUrl() . '/localtime/?f=&time=' . urlencode(DateTimeFormat::utc($ev['start'])) . ")\n";
if (! $ev['nofinish']) {
- $o .= L10n::t('Finishes:') . ' ' . '['
- . (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC',
- $ev['finish'] , $bd_format ))
- : day_translate(datetime_convert('UTC', 'UTC',
- $ev['finish'] , $bd_format )))
- . '](' . System::baseUrl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['finish'])) . ")\n";
+ $o .= L10n::t('Finishes:') . ' ' . '[' . day_translate(
+ $ev['adjust'] ? DateTimeFormat::utc($ev['finish'], $bd_format) : DateTimeFormat::utc($ev['finish'], $bd_format)
+ )
+ . '](' . System::baseUrl() . '/localtime/?f=&time=' . urlencode(DateTimeFormat::utc($ev['finish'])) . ")\n";
}
if (strlen($ev['location'])) {
/**
* @file include/conversation.php
*/
+
use Friendica\App;
use Friendica\Content\ContactSelector;
use Friendica\Content\Feature;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Profile;
-use Friendica\Object\Thread;
use Friendica\Object\Post;
use Friendica\Util\XML;
+use Friendica\Object\Thread;
+use Friendica\Util\DateTimeFormat;
require_once "include/bbcode.php";
require_once "include/acl_selectors.php";
'categories' => $categories,
'folders' => $folders,
'text' => strip_tags($body_e),
- 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
+ 'localtime' => DateTimeFormat::local($item['created'], 'r'),
'ago' => (($item['app']) ? L10n::t('%s from %s', relative_date($item['created']),$item['app']) : relative_date($item['created'])),
'location' => $location_e,
'indent' => '',
* @brief Some functions for date and time related tasks.
*/
-use Friendica\Core\Config;
-use Friendica\Core\L10n;
-use Friendica\Core\PConfig;
-use Friendica\Database\DBM;
+use Friendica\Model\Contact;
+use Friendica\Util\Temporal;
-/**
- * @brief Two-level sort for timezones.
- *
- * @param string $a
- * @param string $b
- * @return int
- */
-function timezone_cmp($a, $b) {
- if (strstr($a, '/') && strstr($b, '/')) {
- if (L10n::t($a) == L10n::t($b)) {
- return 0;
- }
- return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
- }
-
- if (strstr($a, '/')) {
- return -1;
- } elseif (strstr($b, '/')) {
- return 1;
- } elseif (L10n::t($a) == L10n::t($b)) {
- return 0;
- }
-
- return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
+function dob($dob) {
+ return Temporal::getDateofBirthField($dob);
}
-/**
- * @brief Emit a timezone selector grouped (primarily) by continent
- *
- * @param string $current Timezone
- * @return string Parsed HTML output
- */
-function select_timezone($current = 'America/Los_Angeles') {
-
- $timezone_identifiers = DateTimeZone::listIdentifiers();
-
- $o ='<select id="timezone_select" name="timezone">';
-
- usort($timezone_identifiers, 'timezone_cmp');
- $continent = '';
- foreach ($timezone_identifiers as $value) {
- $ex = explode("/", $value);
- if (count($ex) > 1) {
- if ($ex[0] != $continent) {
- if ($continent != '') {
- $o .= '</optgroup>';
- }
- $continent = $ex[0];
- $o .= '<optgroup label="' . L10n::t($continent) . '">';
- }
- if (count($ex) > 2) {
- $city = substr($value,strpos($value,'/')+1);
- } else {
- $city = $ex[1];
- }
- } else {
- $city = $ex[0];
- if ($continent != L10n::t('Miscellaneous')) {
- $o .= '</optgroup>';
- $continent = L10n::t('Miscellaneous');
- $o .= '<optgroup label="' . L10n::t($continent) . '">';
- }
- }
- $city = str_replace('_', ' ', L10n::t($city));
- $selected = (($value == $current) ? " selected=\"selected\" " : "");
- $o .= "<option value=\"$value\" $selected >$city</option>";
- }
- $o .= '</optgroup></select>';
- return $o;
+function datesel($min, $max, $default, $id = 'datepicker') {
+ return Temporal::getDateField($min, $max, $default, $id);
}
-
-
-/**
- * @brief Generating a Timezone selector
- *
- * Return a select using 'field_select_raw' template, with timezones
- * groupped (primarily) by continent
- * arguments follow convetion as other field_* template array:
- * 'name', 'label', $value, 'help'
- *
- * @param string $name Name of the selector
- * @param string $label Label for the selector
- * @param string $current Timezone
- * @param string $help Help text
- *
- * @return string Parsed HTML
- */
-function field_timezone($name='timezone', $label='', $current = 'America/Los_Angeles', $help){
- $options = select_timezone($current);
- $options = str_replace('<select id="timezone_select" name="timezone">','', $options);
- $options = str_replace('</select>','', $options);
-
- $tpl = get_markup_template('field_select_raw.tpl');
- return replace_macros($tpl, [
- '$field' => [$name, $label, $current, $help, $options],
- ]);
-
+function timesel($h, $m, $id = 'timepicker') {
+ return Temporal::getTimeField($h, $m, $id);
}
-/**
- * @brief General purpose date parse/convert function.
- *
- * @param string $from Source timezone
- * @param string $to Dest timezone
- * @param string $s Some parseable date/time string
- * @param string $fmt Output format recognised from php's DateTime class
- * http://www.php.net/manual/en/datetime.format.php
- *
- * @return string Formatted date according to given format
- */
-function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") {
-
- // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
- // Provide some sane defaults regardless.
-
- if ($from === '') {
- $from = 'UTC';
- }
- if ($to === '') {
- $to = 'UTC';
- }
- if ( ($s === '') || (! is_string($s)) ) {
- $s = 'now';
- }
-
- /*
- * Slight hackish adjustment so that 'zero' datetime actually returns what is intended
- * otherwise we end up with -0001-11-30 ...
- * add 32 days so that we at least get year 00, and then hack around the fact that
- * months and days always start with 1.
- */
-
- if (substr($s,0,10) <= '0001-01-01') {
- $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
- return str_replace('1','0',$d->format($fmt));
- }
-
- try {
- $from_obj = new DateTimeZone($from);
- } catch (Exception $e) {
- $from_obj = new DateTimeZone('UTC');
- }
-
- try {
- $d = new DateTime($s, $from_obj);
- } catch (Exception $e) {
- logger('datetime_convert: exception: ' . $e->getMessage());
- $d = new DateTime('now', $from_obj);
- }
-
- try {
- $to_obj = new DateTimeZone($to);
- } catch (Exception $e) {
- $to_obj = new DateTimeZone('UTC');
- }
-
- $d->setTimeZone($to_obj);
-
- return $d->format($fmt);
-}
-
-
-/**
- * @brief Wrapper for date selector, tailored for use in birthday fields.
- *
- * @param string $dob Date of Birth
- * @return string Formatted html
- */
-function dob($dob)
-{
- list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
-
- if ($dob < '0000-01-01') {
- $value = '';
- } else {
- $value = (($year > 1000) ? datetime_convert('UTC', 'UTC', $dob, 'Y-m-d') : datetime_convert('UTC', 'UTC', '1000-' . $month . '-'. $day, 'm-d'));
- }
-
- $age = (intval($value) ? age($value, $a->user["timezone"], $a->user["timezone"]) : "");
-
- $o = replace_macros(get_markup_template("field_input.tpl"), [
- '$field' => [
- 'dob',
- L10n::t('Birthday:'),
- $value,
- (((intval($age)) > 0 ) ? L10n::t('Age: ') . $age : ""),
- '',
- 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
- ]
- ]);
-
- return $o;
-}
-
-/**
- * @brief Returns a date selector
- *
- * @param string $min
- * Unix timestamp of minimum date
- * @param string $max
- * Unix timestap of maximum date
- * @param string $default
- * Unix timestamp of default date
- * @param string $id
- * ID and name of datetimepicker (defaults to "datetimepicker")
- *
- * @return string Parsed HTML output.
- */
-function datesel($min, $max, $default, $id = 'datepicker')
-{
- return datetimesel($min, $max, $default, '', $id, true, false, '', '');
-}
-
-/**
- * @brief Returns a time selector
- *
- * @param $h
- * Already selected hour
- * @param $m
- * Already selected minute
- * @param string $id
- * ID and name of datetimepicker (defaults to "timepicker")
- *
- * @return string Parsed HTML output.
- */
-function timesel($h, $m, $id = 'timepicker')
-{
- return datetimesel(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
-}
-
-/**
- * @brief Returns a datetime selector.
- *
- * @param string $min
- * unix timestamp of minimum date
- * @param string $max
- * unix timestap of maximum date
- * @param string $default
- * unix timestamp of default date
- * @param string $id
- * id and name of datetimepicker (defaults to "datetimepicker")
- * @param bool $pickdate
- * true to show date picker (default)
- * @param boolean $picktime
- * true to show time picker (default)
- * @param $minfrom
- * set minimum date from picker with id $minfrom (none by default)
- * @param $maxfrom
- * set maximum date from picker with id $maxfrom (none by default)
- * @param bool $required default false
- *
- * @return string Parsed HTML output.
- *
- * @todo Once browser support is better this could probably be replaced with
- * native HTML5 date picker.
- */
-function datetimesel($min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false)
-{
- // First day of the week (0 = Sunday)
- $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
-
- $lang = substr(L10n::getBrowserLanguage(), 0, 2);
-
- // Check if the detected language is supported by the picker
- if (!in_array($lang, ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr", "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
- $lang = Config::get('system', 'language', 'en');
- }
-
- $o = '';
- $dateformat = '';
-
- if ($pickdate) {
- $dateformat .= 'Y-m-d';
- }
- if ($pickdate && $picktime) {
- $dateformat .= ' ';
- }
- if ($picktime) {
- $dateformat .= 'H:i';
- }
-
- $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
- $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
-
- $input_text = $default ? date($dateformat, $default->getTimestamp()) : '';
- $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
-
- $pickers = '';
- if (!$pickdate) {
- $pickers .= ', datepicker: false';
- }
- if (!$picktime) {
- $pickers .= ',timepicker: false';
- }
-
- $extra_js = '';
- $pickers .= ",dayOfWeekStart: " . $firstDay . ",lang:'" . $lang . "'";
- if ($minfrom != '') {
- $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
- }
- if ($maxfrom != '') {
- $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
- }
-
- $readable_format = $dateformat;
- $readable_format = str_replace('Y','yyyy',$readable_format);
- $readable_format = str_replace('m','mm',$readable_format);
- $readable_format = str_replace('d','dd',$readable_format);
- $readable_format = str_replace('H','HH',$readable_format);
- $readable_format = str_replace('i','MM',$readable_format);
-
- $tpl = get_markup_template('field_input.tpl');
- $o .= replace_macros($tpl, [
- '$field' => [$id, $label, $input_text, '', (($required) ? '*' : ''), 'placeholder="' . $readable_format . '"'],
- ]);
-
- $o .= "<script type='text/javascript'>";
- $o .= "\$(function () {var picker = \$('#id_$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
- $o .= "</script>";
-
- return $o;
+function datetimesel($min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
+ return Temporal::getDateTimeField($min, $max, $default, $label, $id, $pickdate, $picktime, $minfrom, $maxfrom, $required);
}
-/**
- * @brief Returns a relative date string.
- *
- * Implements "3 seconds ago" etc.
- * Based on $posted_date, (UTC).
- * Results relative to current timezone.
- * Limited to range of timestamps.
- *
- * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
- * @param string $format (optional) Parsed with sprintf()
- * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
- *
- * @return string with relative date
- */
function relative_date($posted_date, $format = null) {
-
- $localtime = $posted_date . ' UTC';
-
- $abs = strtotime($localtime);
-
- if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === false) {
- return L10n::t('never');
- }
-
- $etime = time() - $abs;
-
- if ($etime < 1) {
- return L10n::t('less than a second ago');
- }
-
- $a = [ 12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
- 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
- 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
- 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
- 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
- 60 => [L10n::t('minute'), L10n::t('minutes')],
- 1 => [L10n::t('second'), L10n::t('seconds')]
- ];
-
- foreach ($a as $secs => $str) {
- $d = $etime / $secs;
- if ($d >= 1) {
- $r = round($d);
- // translators - e.g. 22 hours ago, 1 minute ago
- if (!$format) {
- $format = L10n::t('%1$d %2$s ago');
- }
-
- return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
- }
- }
+ return Temporal::getRelativeDate($posted_date, $format);
}
-/**
- * @brief Returns timezone correct age in years.
- *
- * Returns the age in years, given a date of birth, the timezone of the person
- * whose date of birth is provided, and the timezone of the person viewing the
- * result.
- *
- * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
- * is on New Year's. You live in San Bruno, California.
- * When exactly are you going to see my age increase?
- *
- * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
- * and become a year older. If you wish me happy birthday on January 1
- * (San Bruno time), you'll be a day late.
- *
- * @param string $dob Date of Birth
- * @param string $owner_tz (optional) Timezone of the person of interest
- * @param string $viewer_tz (optional) Timezone of the person viewing
- *
- * @return int Age in years
- */
function age($dob, $owner_tz = '', $viewer_tz = '') {
- if (! intval($dob)) {
- return 0;
- }
- if (! $owner_tz) {
- $owner_tz = date_default_timezone_get();
- }
- if (! $viewer_tz) {
- $viewer_tz = date_default_timezone_get();
- }
-
- $birthdate = datetime_convert('UTC', $owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
- list($year, $month, $day) = explode("-", $birthdate);
- $year_diff = datetime_convert('UTC',$viewer_tz, 'now', 'Y') - $year;
- $curr_month = datetime_convert('UTC',$viewer_tz, 'now', 'm');
- $curr_day = datetime_convert('UTC',$viewer_tz, 'now', 'd');
-
- if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
- $year_diff--;
- }
-
- return $year_diff;
+ return Temporal::getAgeByTimezone($dob, $owner_tz, $viewer_tz);
}
-/**
- * @brief Get days of a month in a given year.
- *
- * Returns number of days in the month of the given year.
- * $m = 1 is 'January' to match human usage.
- *
- * @param int $y Year
- * @param int $m Month (1=January, 12=December)
- *
- * @return int Number of days in the given month
- */
function get_dim($y, $m) {
-
- $dim = [ 0,
- 31, 28, 31, 30, 31, 30,
- 31, 31, 30, 31, 30, 31];
-
- if ($m != 2) {
- return $dim[$m];
- } elseif (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) {
- return 29;
- }
-
- return $dim[2];
+ return Temporal::getDaysInMonth($y, $m);
}
-/**
- * @brief Returns the first day in month for a given month, year.
- *
- * Months start at 1.
- *
- * @param int $y Year
- * @param int $m Month (1=January, 12=December)
- *
- * @return string day 0 = Sunday through 6 = Saturday
- */
function get_first_dim($y,$m) {
- $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
-
- return datetime_convert('UTC','UTC',$d,'w');
+ return Temporal::getFirstDayInMonth($y, $m);
}
-/**
- * @brief Output a calendar for the given month, year.
- *
- * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
- * date 12 will be linked appropriately. Today's date is also noted by
- * altering td class.
- * Months count from 1.
- *
- * @param int $y Year
- * @param int $m Month
- * @param array $links (default null)
- * @param string $class
- *
- * @return string
- *
- * @todo Provide (prev,next) links, define class variations for different size calendars
- */
function cal($y = 0, $m = 0, $links = null, $class = '')
{
- // month table - start at 1 to match human usage.
- $mtab = [' ',
- 'January', 'February', 'March',
- 'April' , 'May' , 'June',
- 'July' , 'August' , 'September',
- 'October', 'November', 'December'
- ];
-
- $thisyear = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
- $thismonth = datetime_convert('UTC', date_default_timezone_get(), 'now', 'm');
- if (!$y) {
- $y = $thisyear;
- }
-
- if (!$m) {
- $m = intval($thismonth);
- }
-
- $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
- $f = get_first_dim($y, $m);
- $l = get_dim($y, $m);
- $d = 1;
- $dow = 0;
- $started = false;
-
- if (($y == $thisyear) && ($m == $thismonth)) {
- $tddate = intval(datetime_convert('UTC', date_default_timezone_get(), 'now', 'j'));
- }
-
- $str_month = day_translate($mtab[$m]);
- $o = '<table class="calendar' . $class . '">';
- $o .= "<caption>$str_month $y</caption><tr>";
- for ($a = 0; $a < 7; $a ++) {
- $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
- }
-
- $o .= '</tr><tr>';
-
- while ($d <= $l) {
- if (($dow == $f) && (! $started)) {
- $started = true;
- }
-
- $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
- $o .= "<td $today>";
- $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
- if ($started) {
- if (x($links, $d) !== false) {
- $o .= "<a href=\"{$links[$d]}\">$day</a>";
- } else {
- $o .= $day;
- }
-
- $d ++;
- } else {
- $o .= ' ';
- }
-
- $o .= '</td>';
- $dow ++;
- if (($dow == 7) && ($d <= $l)) {
- $dow = 0;
- $o .= '</tr><tr>';
- }
- }
- if ($dow) {
- for ($a = $dow; $a < 7; $a ++) {
- $o .= '<td> </td>';
- }
- }
-
- $o .= '</tr></table>' . "\r\n";
-
- return $o;
+ return Temporal::getCalendarTable($y, $m, $links, $class);
}
-/**
- * @brief Create a birthday event.
- *
- * Update the year and the birthday.
- */
function update_contact_birthdays() {
-
- // This only handles foreign or alien networks where a birthday has been provided.
- // In-network birthdays are handled within local_delivery
-
- $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
- if (DBM::is_result($r)) {
- foreach ($r as $rr) {
-
- logger('update_contact_birthday: ' . $rr['bd']);
-
- $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'], 4);
-
- /*
- * Add new birthday event for this person
- *
- * $bdtext is just a readable placeholder in case the event is shared
- * with others. We will replace it during presentation to our $importer
- * to contain a sparkle link and perhaps a photo.
- */
-
- // Check for duplicates
- $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
- intval($rr['uid']),
- intval($rr['id']),
- dbesc(datetime_convert('UTC','UTC', $nextbd)),
- dbesc('birthday'));
-
- if (DBM::is_result($s)) {
- continue;
- }
-
- $bdtext = L10n::t('%s\'s birthday', $rr['name']);
- $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
-
- q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
- VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
- intval($rr['uid']),
- intval($rr['id']),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
- dbesc(datetime_convert('UTC','UTC', $nextbd)),
- dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
- dbesc($bdtext),
- dbesc($bdtext2),
- dbesc('birthday'),
- intval(0)
- );
-
-
- // update bdyear
- q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d",
- dbesc(substr($nextbd,0,4)),
- dbesc($nextbd),
- intval($rr['uid']),
- intval($rr['id'])
- );
-
- }
- }
+ return Contact::updateBirthdays();
}
<?php
+
+use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Database\DBStructure;
+use Friendica\Util\DateTimeFormat;
require_once('include/datetime.php');
if ($log) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
- @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
+ @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
$row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
basename($backtrace[1]["file"])."\t".
$backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
$duration = round($duration, 3);
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
- @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
+ @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
basename($backtrace[1]["file"])."\t".
$backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
/**
* @file include/enotify.php
*/
-use Friendica\App;
+
use Friendica\Core\Addon;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\DBM;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Emailer;
require_once 'include/bbcode.php';
$datarray['name_cache'] = strip_tags(bbcode($params['source_name']));
$datarray['url'] = $params['source_link'];
$datarray['photo'] = $params['source_photo'];
- $datarray['date'] = datetime_convert();
+ $datarray['date'] = DateTimeFormat::utcNow();
$datarray['uid'] = $params['uid'];
$datarray['link'] = $itemlink;
$datarray['iid'] = $item_id;
* @brief functions specific to event handling
*/
-use Friendica\App;
use Friendica\Content\Feature;
use Friendica\Core\Addon;
use Friendica\Core\L10n;
use Friendica\Database\DBM;
use Friendica\Model\Item;
use Friendica\Model\Profile;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Map;
require_once 'include/bbcode.php';
$bd_format = L10n::t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM.
- $event_start = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
- $ev['start'] , $bd_format ))
- : day_translate(datetime_convert('UTC', 'UTC',
- $ev['start'] , $bd_format)));
+ $event_start = day_translate(
+ $ev['adjust'] ?
+ DateTimeFormat::local($ev['start'], $bd_format)
+ : DateTimeFormat::utc($ev['start'], $bd_format)
+ );
- $event_end = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
- $ev['finish'] , $bd_format ))
- : day_translate(datetime_convert('UTC', 'UTC',
- $ev['finish'] , $bd_format )));
+ $event_end = day_translate(
+ $ev['adjust'] ?
+ DateTimeFormat::local($ev['finish'], $bd_format)
+ : DateTimeFormat::utc($ev['finish'], $bd_format)
+ );
if ($simple) {
$o = "<h3>" . bbcode($ev['summary']) . "</h3>";
$o .= '<div class="summary event-summary">' . bbcode($ev['summary']) . '</div>' . "\r\n";
$o .= '<div class="event-start"><span class="event-label">' . L10n::t('Starts:') . '</span> <span class="dtstart" title="'
- . datetime_convert('UTC', 'UTC', $ev['start'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
+ . DateTimeFormat::utc($ev['start'], (($ev['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s' ))
. '" >'.$event_start
. '</span></div>' . "\r\n";
if (! $ev['nofinish']) {
$o .= '<div class="event-end" ><span class="event-label">' . L10n::t('Finishes:') . '</span> <span class="dtend" title="'
- . datetime_convert('UTC', 'UTC', $ev['finish'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
+ . DateTimeFormat::utc($ev['finish'], (($ev['adjust']) ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s' ))
. '" >'.$event_end
. '</span></div>' . "\r\n";
}
function ev_compare($a,$b) {
- $date_a = (($a['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $a['start']) : $a['start']);
- $date_b = (($b['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $b['start']) : $b['start']);
+ $date_a = (($a['adjust']) ? DateTimeFormat::local($a['start']) : $a['start']);
+ $date_b = (($b['adjust']) ? DateTimeFormat::local($b['start']) : $b['start']);
if ($date_a === $date_b) {
return strcasecmp($a['desc'], $b['desc']);
$a = get_app();
- $arr['created'] = (($arr['created']) ? $arr['created'] : datetime_convert());
- $arr['edited'] = (($arr['edited']) ? $arr['edited'] : datetime_convert());
+ $arr['created'] = (($arr['created']) ? $arr['created'] : DateTimeFormat::utcNow());
+ $arr['edited'] = (($arr['edited']) ? $arr['edited'] : DateTimeFormat::utcNow());
$arr['type'] = (($arr['type']) ? $arr['type'] : 'event' );
$arr['cid'] = ((intval($arr['cid'])) ? intval($arr['cid']) : 0);
$arr['uri'] = (x($arr, 'uri') ? $arr['uri'] : item_new_uri($a->get_hostname(), $arr['uid']));
$fmt = L10n::t('l, F j');
if (count($arr)) {
foreach ($arr as $rr) {
- $j = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'j') : datetime_convert('UTC', 'UTC', $rr['start'], 'j'));
- $d = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], $fmt) : datetime_convert('UTC', 'UTC', $rr['start'], $fmt));
+ $j = (($rr['adjust']) ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j'));
+ $d = (($rr['adjust']) ? DateTimeFormat::local($rr['start'], $fmt) : DateTimeFormat::utc($rr['start'], $fmt));
$d = day_translate($d);
- $start = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'c') : datetime_convert('UTC', 'UTC', $rr['start'], 'c'));
+ $start = (($rr['adjust']) ? DateTimeFormat::local($rr['start'], 'c') : DateTimeFormat::utc($rr['start'], 'c'));
if ($rr['nofinish']) {
$end = null;
} else {
- $end = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['finish'], 'c') : datetime_convert('UTC', 'UTC', $rr['finish'], 'c'));
+ $end = (($rr['adjust']) ? DateTimeFormat::local($rr['finish'], 'c') : DateTimeFormat::utc($rr['finish'], 'c'));
}
$is_first = ($d !== $last_date);
$tformat = L10n::t('g:i A'); // 8:01 AM.
// Convert the time to different formats.
- $dtstart_dt = (($item['event-adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], $dformat)) : day_translate(datetime_convert('UTC', 'UTC', $item['event-start'], $dformat)));
- $dtstart_title = datetime_convert('UTC', 'UTC', $item['event-start'], (($item['event-adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s'));
+ $dtstart_dt = day_translate(
+ $item['event-adjust'] ?
+ DateTimeFormat::local($item['event-start'], $dformat)
+ : DateTimeFormat::utc($item['event-start'], $dformat)
+ );
+ $dtstart_title = DateTimeFormat::utc($item['event-start'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
// Format: Jan till Dec.
- $month_short = (($item['event-adjust']) ? day_short_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], 'M')) : day_short_translate(datetime_convert('UTC', 'UTC', $item['event-start'], 'M')));
+ $month_short = day_short_translate(
+ $item['event-adjust'] ?
+ DateTimeFormat::local($item['event-start'], 'M')
+ : DateTimeFormat::utc($item['event-start'], 'M')
+ );
// Format: 1 till 31.
- $date_short = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], 'j') : datetime_convert('UTC', 'UTC', $item['event-start'], 'j'));
- $start_time = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], $tformat) : datetime_convert('UTC', 'UTC', $item['event-start'], $tformat));
- $start_short = (($item['event-adjust']) ? day_short_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-start'], $dformat_short)) : day_short_translate(datetime_convert('UTC', 'UTC', $item['event-start'], $dformat_short)));
+ $date_short = $item['event-adjust'] ?
+ DateTimeFormat::local($item['event-start'], 'j')
+ : DateTimeFormat::utc($item['event-start'], 'j');
+ $start_time = $item['event-adjust'] ?
+ DateTimeFormat::local($item['event-start'], $tformat)
+ : DateTimeFormat::utc($item['event-start'], $tformat);
+ $start_short = day_short_translate(
+ $item['event-adjust'] ?
+ DateTimeFormat::local($item['event-start'], $dformat_short)
+ : DateTimeFormat::utc($item['event-start'], $dformat_short)
+ );
// If the option 'nofinisch' isn't set, we need to format the finish date/time.
if (!$item['event-nofinish']) {
$finish = true;
- $dtend_dt = (($item['event-adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-finish'], $dformat)) : day_translate(datetime_convert('UTC', 'UTC', $item['event-finish'], $dformat)));
- $dtend_title = datetime_convert('UTC', 'UTC', $item['event-finish'], (($item['event-adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s'));
- $end_short = (($item['event-adjust']) ? day_short_translate(datetime_convert('UTC', date_default_timezone_get(), $item['event-finish'], $dformat_short)) : day_short_translate(datetime_convert('UTC', 'UTC', $item['event-finish'], $dformat_short)));
- $end_time = (($item['event-adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $item['event-finish'], $tformat) : datetime_convert('UTC', 'UTC', $item['event-finish'], $tformat));
+ $dtend_dt = day_translate(
+ $item['event-adjust'] ?
+ DateTimeFormat::local($item['event-finish'], $dformat)
+ : DateTimeFormat::utc($item['event-finish'], $dformat)
+ );
+ $dtend_title = DateTimeFormat::utc($item['event-finish'], $item['event-adjust'] ? DateTimeFormat::ATOM : 'Y-m-d\TH:i:s');
+ $end_short = day_short_translate(
+ $item['event-adjust'] ?
+ DateTimeFormat::local($item['event-finish'], $dformat_short)
+ : DateTimeFormat::utc($item['event-finish'], $dformat_short)
+ );
+ $end_time = $item['event-adjust'] ?
+ DateTimeFormat::local($item['event-finish'], $tformat)
+ : DateTimeFormat::utc($item['event-finish'], $tformat);
// Check if start and finish time is at the same day.
if (substr($dtstart_title, 0, 10) === substr($dtend_title, 0, 10)) {
$same_date = true;
/**
* @file include/items.php
*/
-use Friendica\App;
+
use Friendica\Content\Feature;
use Friendica\Core\Addon;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\PConfig;
-use Friendica\Core\Worker;
use Friendica\Core\System;
use Friendica\Database\DBM;
-use Friendica\Model\Contact;
-use Friendica\Model\GContact;
-use Friendica\Model\Group;
-use Friendica\Model\Term;
-use Friendica\Model\User;
use Friendica\Model\Item;
-use Friendica\Model\Conversation;
-use Friendica\Object\Image;
use Friendica\Protocol\DFRN;
-use Friendica\Protocol\OStatus;
use Friendica\Protocol\Feed;
+use Friendica\Protocol\OStatus;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\ParseUrl;
/* arrange the list in years */
function list_post_dates($uid, $wall) {
- $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
+ $dnow = DateTimeFormat::localNow('Y-m-d');
$dthen = Item::firstPostDate($uid, $wall);
if (!$dthen) {
$dyear = intval(substr($dnow, 0, 4));
$dstart = substr($dnow, 0, 8) . '01';
$dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
- $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
- $end_month = datetime_convert('', '', $dend, 'Y-m-d');
- $str = day_translate(datetime_convert('', '', $dnow, 'F'));
+ $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
+ $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
+ $str = day_translate(DateTimeFormat::utc($dnow, 'F'));
if (!$ret[$dyear]) {
$ret[$dyear] = [];
}
$ret[$dyear][] = [$str, $end_month, $start_month];
- $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
+ $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
}
return $ret;
}
return $o;
}
- $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
+ $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
$cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
$o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
/**
* @file include/security.php
*/
-use Friendica\App;
+
use Friendica\Core\Addon;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Model\Group;
+use Friendica\Util\DateTimeFormat;
/**
* @brief Calculate the hash that is needed for the "Friendica" cookie
header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
if ($login_initial || $login_refresh) {
- dba::update('user', ['login_date' => datetime_convert()], ['uid' => $_SESSION['uid']]);
+ dba::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
// Set the login date for all identities of the user
- dba::update('user', ['login_date' => datetime_convert()],
+ dba::update('user', ['login_date' => DateTimeFormat::utcNow()],
['password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false]);
}
/**
* @file include/text.php
*/
+
use Friendica\App;
use Friendica\Content\ContactSelector;
use Friendica\Content\Feature;
use Friendica\Database\DBM;
use Friendica\Model\Profile;
use Friendica\Model\Term;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Map;
require_once "mod/proxy.php";
return $template;
}
-
-/**
- *
- * @param App $a
- * @param string $filename
- * @param string $root
- * @return string
- */
-function get_template_file($a, $filename, $root = '') {
- $theme = current_theme();
-
- // Make sure $root ends with a slash /
- if ($root !== '' && substr($root, -1, 1) !== '/') {
- $root = $root . '/';
- }
-
- if (file_exists("{$root}view/theme/$theme/$filename")) {
- $template_file = "{$root}view/theme/$theme/$filename";
- } elseif (x($a->theme_info, "extends") && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename))) {
- $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename);
- } elseif (file_exists("{$root}/$filename")) {
- $template_file = "{$root}/$filename";
- } else {
- $template_file = "{$root}view/$filename";
- }
-
- return $template_file;
-}
-
-
/**
* for html,xml parsing - let's say you've got
* an attribute foobar="class1 class2 class3"
$callers = debug_backtrace();
$logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
- datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z'),
+ DateTimeFormat::utcNow(DateTimeFormat::ATOM),
$process_id,
$LOGGER_LEVELS[$level],
basename($callers[0]['file']),
$callers = debug_backtrace();
$logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
- datetime_convert(),
+ DateTimeFormat::utcNow(),
$process_id,
basename($callers[0]['file']),
$callers[0]['line'],
use Friendica\Database\DBM;
use Friendica\Database\DBStructure;
use Friendica\Model\Contact;
-use Friendica\Model\User;
use Friendica\Model\Item;
+use Friendica\Model\User;
use Friendica\Module\Login;
+use Friendica\Util\DateTimeFormat;
require_once 'include/enotify.php';
require_once 'include/text.php';
if (!$last_worker_call) {
$showwarning = true;
$warningtext[] = L10n::t('The worker was never executed. Please check your database structure!');
- } elseif ((strtotime(datetime_convert()) - strtotime($last_worker_call)) > 60 * 60) {
+ } elseif ((strtotime(DateTimeFormat::utcNow()) - strtotime($last_worker_call)) > 60 * 60) {
$showwarning = true;
$warningtext[] = L10n::t('The last worker execution was on %s UTC. This is older than one hour. Please check your crontab settings.', $last_worker_call);
}
* This calendar is for profile visitors and contains only the events
* of the profile owner
*/
+
use Friendica\App;
use Friendica\Content\Feature;
use Friendica\Content\Nav;
use Friendica\Model\Group;
use Friendica\Model\Profile;
use Friendica\Protocol\DFRN;
+use Friendica\Util\DateTimeFormat;
require_once 'include/event.php';
// The view mode part is similiar to /mod/events.php
if ($mode == 'view') {
- $thisyear = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
- $thismonth = datetime_convert('UTC', date_default_timezone_get(), 'now', 'm');
+ $thisyear = DateTimeFormat::localNow('Y');
+ $thismonth = DateTimeFormat::localNow('m');
if (!$y) {
$y = intval($thisyear);
}
}
}
- $start = datetime_convert('UTC', 'UTC', $start);
- $finish = datetime_convert('UTC', 'UTC', $finish);
+ $start = DateTimeFormat::utc($start);
+ $finish = DateTimeFormat::utc($finish);
- $adjust_start = datetime_convert('UTC', date_default_timezone_get(), $start);
- $adjust_finish = datetime_convert('UTC', date_default_timezone_get(), $finish);
+ $adjust_start = DateTimeFormat::local($start);
+ $adjust_finish = DateTimeFormat::local($finish);
// put the event parametes in an array so we can better transmit them
$event_params = [
if (DBM::is_result($r)) {
$r = sort_by_date($r);
foreach ($r as $rr) {
- $j = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'j') : datetime_convert('UTC', 'UTC', $rr['start'], 'j'));
+ $j = $rr['adjust'] ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j');
if (!x($links, $j)) {
$links[$j] = System::baseUrl() . '/' . $a->cmd . '#link-' . $j;
}
/**
* @file mod/contacts.php
*/
+
use Friendica\App;
use Friendica\Content\ContactSelector;
use Friendica\Content\Nav;
use Friendica\Model\Group;
use Friendica\Model\Profile;
use Friendica\Network\Probe;
+use Friendica\Util\DateTimeFormat;
require_once 'mod/proxy.php';
$insecure = L10n::t('Private communications are not available for this contact.');
- $last_update = (($contact['last-update'] <= NULL_DATE) ? L10n::t('Never') : datetime_convert('UTC', date_default_timezone_get(), $contact['last-update'], 'D, j M Y, g:i A'));
+ $last_update = (($contact['last-update'] <= NULL_DATE) ? L10n::t('Never') : DateTimeFormat::local($contact['last-update'], 'D, j M Y, g:i A'));
if ($contact['last-update'] > NULL_DATE) {
$last_update .= ' ' . (($contact['last-update'] <= $contact['success_update']) ? L10n::t("\x28Update was successful\x29") : L10n::t("\x28Update was not successful\x29"));
// tabs
$tab_str = contacts_tab($a, $contact_id, 2);
- $lost_contact = (($contact['archive'] && $contact['term-date'] > NULL_DATE && $contact['term-date'] < datetime_convert('', '', 'now')) ? L10n::t('Communications lost with this contact!') : '');
+ $lost_contact = (($contact['archive'] && $contact['term-date'] > NULL_DATE && $contact['term-date'] < DateTimeFormat::utcNow()) ? L10n::t('Communications lost with this contact!') : '');
$fetch_further_information = null;
if ($contact['network'] == NETWORK_FEED) {
use Friendica\Network\Probe;
use Friendica\Protocol\Diaspora;
use Friendica\Util\Crypto;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\XML;
`network` = '%s' WHERE `id` = %d
",
intval($new_relation),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
intval($duplex),
intval($hidden),
dbesc(NETWORK_DFRN),
`rel` = %d
WHERE `id` = %d
",
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($addr),
dbesc($notify),
dbesc($poll),
`network` = '%s' WHERE `id` = %d
",
intval($new_relation),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
intval($duplex),
intval($forum),
intval($prv),
* You also find a graphic which describes the confirmation process at
* https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_request.png
*/
+
use Friendica\App;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Group;
-use Friendica\Model\User;
use Friendica\Model\Profile;
+use Friendica\Model\User;
use Friendica\Module\Login;
use Friendica\Network\Probe;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
require_once 'include/enotify.php';
`request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
intval(local_user()),
- datetime_convert(),
+ DateTimeFormat::utcNow(),
dbesc($dfrn_url),
dbesc(normalise_link($dfrn_url)),
$parms['addr'],
// Block friend request spam
if ($maxreq) {
$r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
- dbesc(datetime_convert('UTC', 'UTC', 'now - 24 hours')),
+ dbesc(DateTimeFormat::utc('now - 24 hours')),
intval($uid)
);
if (DBM::is_result($r) && count($r) > $maxreq) {
`request`, `confirm`, `notify`, `poll`, `poco`, `network`, `blocked`, `pending` )
VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
intval($uid),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
$parms['url'],
dbesc(normalise_link($url)),
$parms['addr'],
((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
dbesc(notags(trim($_POST['dfrn-request-message']))),
dbesc($hash),
- dbesc(datetime_convert())
+ dbesc(DateTimeFormat::utcNow())
);
}
* @file mod/events.php
* @brief The events module
*/
+
use Friendica\App;
use Friendica\Content\Nav;
-use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
-use Friendica\Model\Profile;
use Friendica\Model\Item;
+use Friendica\Model\Profile;
+use Friendica\Util\DateTimeFormat;
require_once 'include/bbcode.php';
require_once 'include/datetime.php';
}
if ($adjust) {
- $start = datetime_convert(date_default_timezone_get(), 'UTC', $start);
+ $start = DateTimeFormat::convert($start, 'UTC', date_default_timezone_get());
if (! $nofinish) {
- $finish = datetime_convert(date_default_timezone_get(), 'UTC', $finish);
+ $finish = DateTimeFormat::convert($finish, 'UTC', date_default_timezone_get());
}
} else {
- $start = datetime_convert('UTC', 'UTC', $start);
+ $start = DateTimeFormat::utc($start);
if (! $nofinish) {
- $finish = datetime_convert('UTC', 'UTC', $finish);
+ $finish = DateTimeFormat::utc($finish);
}
}
// The view mode part is similiar to /mod/cal.php
if ($mode == 'view') {
- $thisyear = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
- $thismonth = datetime_convert('UTC', date_default_timezone_get(), 'now', 'm');
+ $thisyear = DateTimeFormat::localNow('Y');
+ $thismonth = DateTimeFormat::localNow('m');
if (! $y) {
$y = intval($thisyear);
}
}
}
- $start = datetime_convert('UTC', 'UTC', $start);
- $finish = datetime_convert('UTC', 'UTC', $finish);
+ $start = DateTimeFormat::utc($start);
+ $finish = DateTimeFormat::utc($finish);
- $adjust_start = datetime_convert('UTC', date_default_timezone_get(), $start);
- $adjust_finish = datetime_convert('UTC', date_default_timezone_get(), $finish);
+ $adjust_start = DateTimeFormat::local($start);
+ $adjust_finish = DateTimeFormat::local($finish);
// put the event parametes in an array so we can better transmit them
$event_params = [
if (DBM::is_result($r)) {
$r = sort_by_date($r);
foreach ($r as $rr) {
- $j = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'j') : datetime_convert('UTC', 'UTC', $rr['start'], 'j'));
+ $j = $rr['adjust'] ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j');
if (! x($links,$j)) {
$links[$j] = System::baseUrl() . '/' . $a->cmd . '#link-' . $j;
}
$tz = (($orig_event['adjust']) ? date_default_timezone_get() : 'UTC');
}
- $syear = datetime_convert('UTC', $tz, $sdt, 'Y');
- $smonth = datetime_convert('UTC', $tz, $sdt, 'm');
- $sday = datetime_convert('UTC', $tz, $sdt, 'd');
+ $syear = DateTimeFormat::convert($sdt, $tz, 'UTC', 'Y');
+ $smonth = DateTimeFormat::convert($sdt, $tz, 'UTC', 'm');
+ $sday = DateTimeFormat::convert($sdt, $tz, 'UTC', 'd');
- $shour = ((x($orig_event)) ? datetime_convert('UTC', $tz, $sdt, 'H') : 0);
- $sminute = ((x($orig_event)) ? datetime_convert('UTC', $tz, $sdt, 'i') : 0);
+ $shour = ((x($orig_event)) ? DateTimeFormat::convert($sdt, $tz, 'UTC', 'H') : '00');
+ $sminute = ((x($orig_event)) ? DateTimeFormat::convert($sdt, $tz, 'UTC', 'i') : '00');
- $fyear = datetime_convert('UTC', $tz, $fdt, 'Y');
- $fmonth = datetime_convert('UTC', $tz, $fdt, 'm');
- $fday = datetime_convert('UTC', $tz, $fdt, 'd');
+ $fyear = DateTimeFormat::convert($fdt, $tz, 'UTC', 'Y');
+ $fmonth = DateTimeFormat::convert($fdt, $tz, 'UTC', 'm');
+ $fday = DateTimeFormat::convert($fdt, $tz, 'UTC', 'd');
- $fhour = ((x($orig_event)) ? datetime_convert('UTC', $tz, $fdt, 'H') : 0);
- $fminute = ((x($orig_event)) ? datetime_convert('UTC', $tz, $fdt, 'i') : 0);
+ $fhour = ((x($orig_event)) ? DateTimeFormat::convert($fdt, $tz, 'UTC', 'H') : '00');
+ $fminute = ((x($orig_event)) ? DateTimeFormat::convert($fdt, $tz, 'UTC', 'i') : '00');
require_once 'include/acl_selectors.php' ;
/**
* @file mod/fsuggest.php
*/
+
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
+use Friendica\Util\DateTimeFormat;
function fsuggest_post(App $a)
{
dbesc($r[0]['request']),
dbesc($r[0]['photo']),
dbesc($hash),
- dbesc(datetime_convert())
+ dbesc(DateTimeFormat::utcNow())
);
$r = q("SELECT `id` FROM `fsuggest` WHERE `note` = '%s' AND `uid` = %d LIMIT 1",
dbesc($hash),
/**
* @file mod/install.php
*/
+
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\DBStructure;
use Friendica\Object\Image;
use Friendica\Util\Network;
+use Friendica\Util\Temporal;
$install_wizard_pass = 1;
'$adminmail' => ['adminmail', L10n::t('Site administrator email address'), $adminmail, L10n::t('Your account email address must match this in order to use the web admin panel.'), 'required', 'autofocus', 'email'],
- '$timezone' => field_timezone('timezone', L10n::t('Please select a default timezone for your website'), $timezone, ''),
+ '$timezone' => Temporal::getTimezoneField('timezone', L10n::t('Please select a default timezone for your website'), $timezone, ''),
'$language' => ['language', L10n::t('System Language:'), 'en', L10n::t('Set the default language for your Friendica installation interface and to send emails.'), $lang_choices],
'$baseurl' => System::baseUrl(),
* Send email invitations to join social network
*
*/
+
use Friendica\App;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\PConfig;
use Friendica\Core\System;
use Friendica\Protocol\Email;
+use Friendica\Util\DateTimeFormat;
function invite_post(App $a)
{
$r = q("INSERT INTO `register` (`hash`,`created`) VALUES ('%s', '%s') ",
dbesc($code),
- dbesc(datetime_convert())
+ dbesc(DateTimeFormat::utcNow())
);
if (! is_site_admin()) {
* All of these become an "item" which is our basic unit of
* information.
*/
+
use Friendica\App;
use Friendica\Content\Text\BBCode;
use Friendica\Core\Addon;
use Friendica\Model\Contact;
use Friendica\Model\GContact;
use Friendica\Model\Item;
-use Friendica\Network\Probe;
use Friendica\Protocol\Diaspora;
use Friendica\Protocol\Email;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Emailer;
require_once 'include/enotify.php';
$datarray['author-link'] = $author['url'];
$datarray['author-avatar'] = $author['thumb'];
$datarray['author-id'] = Contact::getIdForURL($datarray['author-link'], 0);
- $datarray['created'] = datetime_convert();
- $datarray['edited'] = datetime_convert();
- $datarray['commented'] = datetime_convert();
- $datarray['received'] = datetime_convert();
- $datarray['changed'] = datetime_convert();
+ $datarray['created'] = DateTimeFormat::utcNow();
+ $datarray['edited'] = DateTimeFormat::utcNow();
+ $datarray['commented'] = DateTimeFormat::utcNow();
+ $datarray['received'] = DateTimeFormat::utcNow();
+ $datarray['changed'] = DateTimeFormat::utcNow();
$datarray['extid'] = $extid;
$datarray['guid'] = $guid;
$datarray['uri'] = $uri;
'file' => $datarray['file'],
'rendered-html' => $datarray['rendered-html'],
'rendered-hash' => $datarray['rendered-hash'],
- 'edited' => datetime_convert(),
- 'changed' => datetime_convert()];
+ 'edited' => DateTimeFormat::utcNow(),
+ 'changed' => DateTimeFormat::utcNow()];
Item::update($fields, ['id' => $post_id]);
/**
* @file mod/localtime.php
*/
+
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Core\System;
+use Friendica\Util\Temporal;
require_once 'include/datetime.php';
$bd_format = L10n::t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
if ($_POST['timezone']) {
- $a->data['mod-localtime'] = datetime_convert('UTC', $_POST['timezone'], $t, $bd_format);
+ $a->data['mod-localtime'] = DateTimeFormat::convert($t, $_POST['timezone'], 'UTC', $bd_format);
}
}
$o .= '<p>' . L10n::t('Please select your timezone:') . '</p>';
- $o .= select_timezone(($_REQUEST['timezone']) ? $_REQUEST['timezone'] : 'America/Los_Angeles');
+ $o .= Temporal::getTimezoneSelect(($_REQUEST['timezone']) ? $_REQUEST['timezone'] : 'America/Los_Angeles');
$o .= '<input type="submit" name="submit" value="' . L10n::t('Submit') . '" /></form>';
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Model\User;
+use Friendica\Util\DateTimeFormat;
require_once 'boot.php';
require_once 'include/datetime.php';
$fields = [
'pwdreset' => $pwdreset_token,
- 'pwdreset_time' => datetime_convert()
+ 'pwdreset_time' => DateTimeFormat::utcNow()
];
$result = dba::update('user', $fields, ['uid' => $user['uid']]);
if ($result) {
}
// Password reset requests expire in 60 minutes
- if ($user['pwdreset_time'] < datetime_convert('UTC', 'UTC', 'now - 1 hour')) {
+ if ($user['pwdreset_time'] < DateTimeFormat::utc('now - 1 hour')) {
$fields = [
'pwdreset' => null,
'pwdreset_time' => null
/**
* @file mod/message.php
*/
+
use Friendica\App;
use Friendica\Content\Nav;
use Friendica\Content\Smilies;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Mail;
+use Friendica\Util\DateTimeFormat;
require_once 'include/acl_selectors.php';
require_once 'include/conversation.php';
'body' => $body_e,
'delete' => L10n::t('Delete message'),
'to_name' => $to_name_e,
- 'date' => datetime_convert('UTC', date_default_timezone_get(), $message['created'], 'D, d M Y - g:i A'),
+ 'date' => DateTimeFormat::local($message['created'], 'D, d M Y - g:i A'),
'ago' => relative_date($message['created']),
];
'$delete' => L10n::t('Delete conversation'),
'$body' => $body_e,
'$to_name' => $to_name_e,
- '$date' => datetime_convert('UTC', date_default_timezone_get(), $rr['mailcreated'], L10n::t('D, d M Y - g:i A')),
+ '$date' => DateTimeFormat::local($rr['mailcreated'], L10n::t('D, d M Y - g:i A')),
'$ago' => relative_date($rr['mailcreated']),
'$seen' => $rr['mailseen'],
'$count' => L10n::tt('%d message', '%d messages', $rr['count']),
/**
* @file mod/network.php
*/
+
use Friendica\App;
use Friendica\Content\Feature;
use Friendica\Content\ForumManager;
use Friendica\Content\Nav;
use Friendica\Content\Widget;
use Friendica\Core\Addon;
-use Friendica\Core\L10n;
use Friendica\Core\Config;
+use Friendica\Core\L10n;
use Friendica\Core\PConfig;
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Model\Group;
use Friendica\Model\Profile;
use Friendica\Module\Login;
+use Friendica\Util\DateTimeFormat;
require_once 'include/conversation.php';
require_once 'include/items.php';
if ($datequery) {
$sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created <= '%s' ",
- dbesc(datetime_convert(date_default_timezone_get(), '', $datequery))));
+ dbesc(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
}
if ($datequery2) {
$sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created >= '%s' ",
- dbesc(datetime_convert(date_default_timezone_get(), '', $datequery2))));
+ dbesc(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));
}
$sql_order = '';
$top_limit = current($r)['order_date'];
$bottom_limit = end($r)['order_date'];
} else {
- $top_limit = datetime_convert();
- $bottom_limit = datetime_convert();
+ $top_limit = DateTimeFormat::utcNow();
+ $bottom_limit = DateTimeFormat::utcNow();
}
// When checking for updates we need to fetch from the newest date to the newest date before
$top_limit = $last_date;
} elseif ($a->pager['page'] == 1) {
// Highest possible top limit when we are on the first page
- $top_limit = datetime_convert();
+ $top_limit = DateTimeFormat::utcNow();
}
$items = dba::p("SELECT `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`uid` AS `contact_uid` FROM `item`
/**
* @file mod/photos.php
*/
+
use Friendica\App;
use Friendica\Content\Feature;
use Friendica\Content\Nav;
use Friendica\Core\Addon;
+use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\System;
-use Friendica\Core\Config;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Network\Probe;
use Friendica\Object\Image;
use Friendica\Protocol\DFRN;
+use Friendica\Util\DateTimeFormat;
+use Friendica\Util\Map;
require_once 'include/items.php';
require_once 'include/acl_selectors.php';
if (DBM::is_result($r)) {
foreach ($r as $rr) {
q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($rr['parent-uri']),
intval($page_owner_uid)
);
);
if (DBM::is_result($i)) {
q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($i[0]['uri']),
intval($page_owner_uid)
);
$resource_id = $a->argv[2];
if (!strlen($albname)) {
- $albname = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
+ $albname = DateTimeFormat::localNow('Y');
}
if (x($_POST,'rotate') !== false &&
$r = q("UPDATE `item` SET `tag` = '%s', `inform` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d",
dbesc($newtag),
dbesc($newinform),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
intval($item_id),
intval($page_owner_uid)
);
if (strlen($newalbum)) {
$album = $newalbum;
} else {
- $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
+ $album = DateTimeFormat::localNow('Y');
}
}
$photo = [
'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
'title'=> L10n::t('View Full Size'),
- 'src' => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('','','','ymdhis'),
+ 'src' => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . DateTimeFormat::utcNow('ymdhis'),
'height' => $hires['height'],
'width' => $hires['width'],
'album' => $hires['album'],
/**
* @file include/ping.php
*/
+
use Friendica\App;
use Friendica\Content\Feature;
use Friendica\Content\ForumManager;
use Friendica\Core\Addon;
use Friendica\Core\Cache;
use Friendica\Core\L10n;
-use Friendica\Core\System;
use Friendica\Core\PConfig;
+use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Group;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\XML;
require_once 'include/datetime.php';
WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
ORDER BY `start` ASC ",
intval(local_user()),
- dbesc(datetime_convert('UTC', 'UTC', 'now + 7 days')),
- dbesc(datetime_convert('UTC', 'UTC', 'now'))
+ dbesc(DateTimeFormat::utc('now + 7 days')),
+ dbesc(DateTimeFormat::utcNow())
);
if (DBM::is_result($ev)) {
Cache::set($cachekey, $ev, CACHE_HOUR);
$all_events = count($ev);
if ($all_events) {
- $str_now = datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d');
+ $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
foreach ($ev as $x) {
$bd = false;
if ($x['type'] === 'birthday') {
} else {
$events ++;
}
- if (datetime_convert('UTC', ((intval($x['adjust'])) ? $a->timezone : 'UTC'), $x['start'], 'Y-m-d') === $str_now) {
+ if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
$all_events_today ++;
if ($bd) {
$birthdays_today ++;
$notif['photo'] = proxy_url($notif['photo'], false, PROXY_SIZE_MICRO);
}
- $local_time = datetime_convert('UTC', date_default_timezone_get(), $notif['date']);
+ $local_time = DateTimeFormat::local($notif['date']);
$notifications[] = [
'id' => $notif['id'],
// See here for a documentation for portable contacts:
// https://web.archive.org/web/20160405005550/http://portablecontacts.net/draft-spec.html
+
use Friendica\App;
use Friendica\Core\Cache;
use Friendica\Core\Config;
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Protocol\PortableContact;
+use Friendica\Util\DateTimeFormat;
function poco_init(App $a) {
$system_mode = false;
if ($a->argc > 1 && $a->argv[1] === '@global') {
// List of all profiles that this server recently had data from
$global = true;
- $update_limit = date("Y-m-d H:i:s", time() - 30 * 86400);
+ $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
}
if ($a->argc > 2 && $a->argv[2] === '@me') {
$justme = true;
$sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
}
if (x($_GET, 'updatedSince')) {
- $update_limit = date("Y-m-d H:i:s", strtotime($_GET['updatedSince']));
+ $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
}
if ($global) {
$contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
/**
* @file mod/profile.php
*/
+
use Friendica\App;
-use Friendica\Content\Widget;
use Friendica\Content\Nav;
+use Friendica\Content\Widget;
use Friendica\Core\Addon;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Model\Profile;
use Friendica\Module\Login;
use Friendica\Protocol\DFRN;
+use Friendica\Util\DateTimeFormat;
function profile_init(App $a)
{
if ($is_owner || !$last_updated) {
$sql_extra4 = " AND `item`.`unseen`";
} else {
- $gmupdate = gmdate("Y-m-d H:i:s", $last_updated);
+ $gmupdate = gmdate(DateTimeFormat::MYSQL, $last_updated);
$sql_extra4 = " AND `item`.`received` > '" . $gmupdate . "'";
}
}
if ($datequery) {
- $sql_extra2 .= protect_sprintf(sprintf(" AND `thread`.`created` <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(), '', $datequery))));
+ $sql_extra2 .= protect_sprintf(sprintf(" AND `thread`.`created` <= '%s' ", dbesc(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
}
if ($datequery2) {
- $sql_extra2 .= protect_sprintf(sprintf(" AND `thread`.`created` >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(), '', $datequery2))));
+ $sql_extra2 .= protect_sprintf(sprintf(" AND `thread`.`created` >= '%s' ", dbesc(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));
}
// Belongs the profile page to a forum?
/**
* @file mod/profile_photo.php
*/
+
use Friendica\App;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Model\Photo;
use Friendica\Model\Profile;
use Friendica\Object\Image;
+use Friendica\Util\DateTimeFormat;
function profile_photo_init(App $a)
{
// so that browsers will do a cache update unconditionally
$r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
intval(local_user())
);
);
$r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
intval(local_user())
);
/**
* @file mod/profiles.php
*/
+
use Friendica\App;
use Friendica\Content\ContactSelector;
use Friendica\Content\Feature;
use Friendica\Model\Profile;
use Friendica\Model\Item;
use Friendica\Network\Probe;
+use Friendica\Util\DateTimeFormat;
function profiles_init(App $a) {
$ignore_year = true;
$dob = substr($dob, 5);
}
- $dob = datetime_convert('UTC', 'UTC', (($ignore_year) ? '1900-' . $dob : $dob), (($ignore_year) ? 'm-d' : 'Y-m-d'));
if ($ignore_year) {
- $dob = '0000-' . $dob;
+ $dob = '0000-' . DateTimeFormat::utc('1900-' . $dob, 'm-d');
+ } else {
+ $dob = DateTimeFormat::utc($dob, 'Y-m-d');
}
}
if (! strlen($howlong)) {
$howlong = NULL_DATE;
} else {
- $howlong = datetime_convert(date_default_timezone_get(), 'UTC', $howlong);
+ $howlong = DateTimeFormat::convert($howlong, 'UTC', date_default_timezone_get());
}
// linkify the relationship target if applicable
if ($namechanged && $is_default) {
$r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
dbesc($name),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
intval(local_user())
);
$r = q("UPDATE `user` set `username` = '%s' where `uid` = %d",
'$gender' => ContactSelector::gender($r[0]['gender']),
'$marital' => ContactSelector::maritalStatus($r[0]['marital']),
'$with' => ['with', L10n::t("Who: \x28if applicable\x29"), strip_tags($r[0]['with']), L10n::t('Examples: cathy123, Cathy Williams, cathy@example.com')],
- '$howlong' => ['howlong', L10n::t('Since [date]:'), ($r[0]['howlong'] <= NULL_DATE ? '' : datetime_convert('UTC',date_default_timezone_get(),$r[0]['howlong']))],
+ '$howlong' => ['howlong', L10n::t('Since [date]:'), ($r[0]['howlong'] <= NULL_DATE ? '' : DateTimeFormat::local($r[0]['howlong']))],
'$sexual' => ContactSelector::sexualPreference($r[0]['sexual']),
'$about' => ['about', L10n::t('Tell us about yourself...'), $r[0]['about']],
'$xmpp' => ['xmpp', L10n::t("XMPP \x28Jabber\x29 address:"), $r[0]['xmpp'], L10n::t("The XMPP address will be propagated to your contacts so that they can follow you.")],
use Friendica\Database\DBM;
use Friendica\Model\Photo;
use Friendica\Object\Image;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
define('PROXY_DEFAULT_TIME', 86400); // 1 Day
die();
}
- $fields = ['uid' => 0, 'contact-id' => 0, 'guid' => get_guid(), 'resource-id' => $urlhash, 'created' => datetime_convert(), 'edited' => datetime_convert(),
+ $fields = ['uid' => 0, 'contact-id' => 0, 'guid' => get_guid(), 'resource-id' => $urlhash, 'created' => DateTimeFormat::utcNow(), 'edited' => DateTimeFormat::utcNow(),
'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime];
use Friendica\Core\Config;
use Friendica\Core\System;
use Friendica\Database\DBM;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
function post_var($name) {
dbesc($hub_callback));
if ($subscribe) {
- $last_update = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
+ $last_update = DateTimeFormat::utcNow();
$push_flag = 0;
// if we are just updating an old subscription, keep the
/**
* @file mod/register.php
*/
+
use Friendica\App;
use Friendica\Core\Addon;
use Friendica\Core\Config;
use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Model\User;
+use Friendica\Util\DateTimeFormat;
require_once 'include/enotify.php';
require_once 'include/bbcode.php';
$hash = random_string();
$r = q("INSERT INTO `register` ( `hash`, `created`, `uid`, `password`, `language`, `note` ) VALUES ( '%s', '%s', %d, '%s', '%s', '%s' ) ",
dbesc($hash),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
intval($user['uid']),
dbesc($result['password']),
dbesc($lang),
use Friendica\Model\Group;
use Friendica\Model\User;
use Friendica\Protocol\Email;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
+use Friendica\Util\Temporal;
function get_theme_config_file($theme)
{
if ($name_change) {
q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `self`",
dbesc($username),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
intval(local_user())
);
}
'$h_basic' => L10n::t('Basic Settings'),
'$username' => ['username', L10n::t('Full Name:'), $username, ''],
'$email' => ['email', L10n::t('Email Address:'), $email, '', '', '', 'email'],
- '$timezone' => ['timezone_select' , L10n::t('Your Timezone:'), select_timezone($timezone), ''],
+ '$timezone' => ['timezone_select' , L10n::t('Your Timezone:'), Temporal::getTimezoneSelect($timezone), ''],
'$language' => ['language', L10n::t('Your Language:'), $language, L10n::t('Set the language we use to show you friendica interface and to send you emails'), $lang_choices],
'$defloc' => ['defloc', L10n::t('Default Post Location:'), $defloc, ''],
'$allowloc' => ['allow_location', L10n::t('Use Browser Location:'), ($a->user['allow_location'] == 1), ''],
/**
* @file mod/videos.php
*/
+
use Friendica\App;
use Friendica\Content\Nav;
use Friendica\Core\Config;
use Friendica\Model\Group;
use Friendica\Model\Profile;
use Friendica\Protocol\DFRN;
+use Friendica\Util\DateTimeFormat;
require_once 'include/items.php';
require_once 'include/acl_selectors.php';
//echo "<pre>"; var_dump($i); killme();
if (DBM::is_result($i)) {
q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($i[0]['uri']),
intval(local_user())
);
/**
* @file mod/wall_attach.php
*/
+
use Friendica\App;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Database\DBM;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Mimetype;
require_once 'include/datetime.php';
$filedata = @file_get_contents($src);
$mimetype = Mimetype::getContentType($filename);
$hash = get_guid(64);
- $created = datetime_convert();
+ $created = DateTimeFormat::utcNow();
$fields = ['uid' => $page_owner_uid, 'hash' => $hash, 'filename' => $filename, 'filetype' => $mimetype,
'filesize' => $filesize, 'data' => $filedata, 'created' => $created, 'edited' => $created,
<?php
+
/**
* @file src/Content/OEmbed.php
*/
use Friendica\Core\Addon;
use Friendica\Core\Cache;
+use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\System;
-use Friendica\Core\Config;
use Friendica\Database\DBM;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\ParseUrl;
use dba;
use DOMDocument;
-use DOMXPath;
use DOMNode;
+use DOMText;
+use DOMXPath;
use Exception;
require_once 'include/dba.php';
'url' => normalise_link($embedurl),
'maxwidth' => $a->videowidth,
'content' => $txt,
- 'created' => datetime_convert()
+ 'created' => DateTimeFormat::utcNow()
], true);
}
use Friendica\Core\Config;
use Friendica\Database\DBM;
+use Friendica\Util\DateTimeFormat;
use dba;
+use Memcache;
require_once 'include/dba.php';
*/
public static function memcache()
{
- if (!class_exists('\Memcache', false)) {
+ if (!class_exists('Memcache', false)) {
return false;
}
$memcache_host = Config::get('system', 'memcache_host', '127.0.0.1');
$memcache_port = Config::get('system', 'memcache_port', 11211);
- $memcache = new \Memcache();
+ $memcache = new Memcache();
if (!$memcache->connect($memcache_host, $memcache_port)) {
return false;
$memcache->set(get_app()->get_hostname().":".$key, serialize($value), MEMCACHE_COMPRESSED, self::duration($duration));
return;
}
- $fields = ['v' => serialize($value), 'expire_mode' => $duration, 'updated' => datetime_convert()];
+ $fields = ['v' => serialize($value), 'expire_mode' => $duration, 'updated' => DateTimeFormat::utcNow()];
$condition = ['k' => $key];
dba::update('cache', $fields, $condition, true);
}
if (Config::get("system", "cache_cleared_day") < time() - self::duration(CACHE_DAY)) {
if ($max_level == CACHE_MONTH) {
$condition = ["`updated` < ? AND `expire_mode` = ?",
- datetime_convert('UTC', 'UTC', "now - 30 days"),
+ DateTimeFormat::utc("now - 30 days"),
CACHE_MONTH];
dba::delete('cache', $condition);
}
if ($max_level <= CACHE_WEEK) {
$condition = ["`updated` < ? AND `expire_mode` = ?",
- datetime_convert('UTC', 'UTC', "now - 7 days"),
+ DateTimeFormat::utc("now - 7 days"),
CACHE_WEEK];
dba::delete('cache', $condition);
}
if ($max_level <= CACHE_DAY) {
$condition = ["`updated` < ? AND `expire_mode` = ?",
- datetime_convert('UTC', 'UTC', "now - 1 days"),
+ DateTimeFormat::utc("now - 1 days"),
CACHE_DAY];
dba::delete('cache', $condition);
}
if (($max_level <= CACHE_HOUR) && (Config::get("system", "cache_cleared_hour")) < time() - self::duration(CACHE_HOUR)) {
$condition = ["`updated` < ? AND `expire_mode` = ?",
- datetime_convert('UTC', 'UTC', "now - 1 hours"),
+ DateTimeFormat::utc("now - 1 hours"),
CACHE_HOUR];
dba::delete('cache', $condition);
if (($max_level <= CACHE_HALF_HOUR) && (Config::get("system", "cache_cleared_half_hour")) < time() - self::duration(CACHE_HALF_HOUR)) {
$condition = ["`updated` < ? AND `expire_mode` = ?",
- datetime_convert('UTC', 'UTC', "now - 30 minutes"),
+ DateTimeFormat::utc("now - 30 minutes"),
CACHE_HALF_HOUR];
dba::delete('cache', $condition);
if (($max_level <= CACHE_QUARTER_HOUR) && (Config::get("system", "cache_cleared_quarter_hour")) < time() - self::duration(CACHE_QUARTER_HOUR)) {
$condition = ["`updated` < ? AND `expire_mode` = ?",
- datetime_convert('UTC', 'UTC', "now - 15 minutes"),
+ DateTimeFormat::utc("now - 15 minutes"),
CACHE_QUARTER_HOUR];
dba::delete('cache', $condition);
if (($max_level <= CACHE_FIVE_MINUTES) && (Config::get("system", "cache_cleared_five_minute")) < time() - self::duration(CACHE_FIVE_MINUTES)) {
$condition = ["`updated` < ? AND `expire_mode` = ?",
- datetime_convert('UTC', 'UTC', "now - 5 minutes"),
+ DateTimeFormat::utc("now - 5 minutes"),
CACHE_FIVE_MINUTES];
dba::delete('cache', $condition);
if (($max_level <= CACHE_MINUTE) && (Config::get("system", "cache_cleared_minute")) < time() - self::duration(CACHE_MINUTE)) {
$condition = ["`updated` < ? AND `expire_mode` = ?",
- datetime_convert('UTC', 'UTC', "now - 1 minutes"),
+ DateTimeFormat::utc("now - 1 minutes"),
CACHE_MINUTE];
dba::delete('cache', $condition);
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Profile;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\XML;
require_once 'include/dba.php';
{
$rets = [];
foreach ($notes as $n) {
- $local_time = datetime_convert('UTC', date_default_timezone_get(), $n['date']);
+ $local_time = DateTimeFormat::local($n['date']);
$n['timestamp'] = strtotime($local_time);
$n['date_rel'] = relative_date($n['date']);
$n['msg_html'] = bbcode($n['msg'], false, false, false, false);
$default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
$default_item_url = $it['url'];
$default_item_text = strip_tags(bbcode($it['msg']));
- $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
+ $default_item_when = DateTimeFormat::local($it['date'], 'r');
$default_item_ago = relative_date($it['date']);
break;
$default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
$default_item_url = $it['author-link'];
$default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['pname']);
- $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
+ $default_item_when = DateTimeFormat::local($it['created'], 'r');
$default_item_ago = relative_date($it['created']);
break;
$default_item_text = (($it['id'] == $it['parent'])
? L10n::t("%s created a new post", $it['author-name'])
: L10n::t("%s commented on %s's post", $it['author-name'], $it['pname']));
- $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
+ $default_item_when = DateTimeFormat::local($it['created'], 'r');
$default_item_ago = relative_date($it['created']);
}
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Model\Process;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Lock;
use Friendica\Util\Network;
use dba;
if ($age > 1) {
$stamp = (float)microtime(true);
- dba::update('workerqueue', ['executed' => datetime_convert()], ['pid' => $mypid, 'done' => false]);
+ dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
self::$db_duration += (microtime(true) - $stamp);
}
$stamp = (float)microtime(true);
if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
- Config::set('system', 'last_poller_execution', datetime_convert());
+ Config::set('system', 'last_poller_execution', DateTimeFormat::utcNow());
}
self::$db_duration = (microtime(true) - $stamp);
if ($age > 1) {
$stamp = (float)microtime(true);
- dba::update('workerqueue', ['executed' => datetime_convert()], ['pid' => $mypid, 'done' => false]);
+ dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
self::$db_duration += (microtime(true) - $stamp);
}
$stamp = (float)microtime(true);
if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
- Config::set('system', 'last_poller_execution', datetime_convert());
+ Config::set('system', 'last_poller_execution', DateTimeFormat::utcNow());
}
self::$db_duration = (microtime(true) - $stamp);
} else {
}
dba::update(
'workerqueue',
- ['executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0],
+ ['executed' => NULL_DATE, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
['id' => $entry["id"]]
);
} else {
if ($found) {
$condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
array_unshift($ids, $condition);
- dba::update('workerqueue', ['executed' => datetime_convert(), 'pid' => $mypid], $ids);
+ dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
}
return $found;
/// @todo We should clean up the corresponding workerqueue entries as well
$condition = ["`created` < ? AND `command` = 'worker.php'",
- datetime_convert('UTC', 'UTC', "now - ".$timeout." minutes")];
+ DateTimeFormat::utc("now - ".$timeout." minutes")];
dba::delete('process', $condition);
}
$priority = PRIORITY_MEDIUM;
$dont_fork = Config::get("system", "worker_dont_fork");
- $created = datetime_convert();
+ $created = DateTimeFormat::utcNow();
if (is_int($run_parameter)) {
$priority = $run_parameter;
namespace Friendica\Database;
use dba;
+use Friendica\Util\DateTimeFormat;
require_once 'include/dba.php';
$timestamp = -62135596800;
}
- return date('Y-m-d H:i:s', (int)$timestamp);
+ return date(DateTimeFormat::MYSQL, (int)$timestamp);
}
}
use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
-use Friendica\Network\Probe;
use Friendica\Model\Photo;
use Friendica\Model\Profile;
-use Friendica\Protocol\Diaspora;
+use Friendica\Network\Probe;
use Friendica\Protocol\DFRN;
+use Friendica\Protocol\Diaspora;
use Friendica\Protocol\OStatus;
use Friendica\Protocol\PortableContact;
use Friendica\Protocol\Salmon;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use dba;
$return = dba::insert('contact', [
'uid' => $user['uid'],
- 'created' => datetime_convert(),
+ 'created' => DateTimeFormat::utcNow(),
'self' => 1,
'name' => $user['username'],
'nick' => $user['nickname'],
'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
- 'name-date' => datetime_convert(),
- 'uri-date' => datetime_convert(),
- 'avatar-date' => datetime_convert(),
+ 'name-date' => DateTimeFormat::utcNow(),
+ 'uri-date' => DateTimeFormat::utcNow(),
+ 'avatar-date' => DateTimeFormat::utcNow(),
'closeness' => 0
]);
}
if ($contact['term-date'] <= NULL_DATE) {
- dba::update('contact', ['term-date' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
if ($contact['url'] != '') {
- dba::update('contact', ['term-date' => datetime_convert()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
+ dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
}
} else {
/* @todo
/// @todo Check for contact vitality via probing
$expiry = $contact['term-date'] . ' + 32 days ';
- if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
+ if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
/* Relationship is really truly dead. archive them rather than
* delete, though if the owner tries to unarchive them we'll start
* the whole process over again.
$contact_id = $contact["id"];
// Update the contact every 7 days
- $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
+ $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
// We force the update if the avatar is empty
if (!x($contact, 'avatar')) {
if (!$contact_id) {
dba::insert('contact', [
'uid' => $uid,
- 'created' => datetime_convert(),
+ 'created' => DateTimeFormat::utcNow(),
'url' => $data["url"],
'nurl' => normalise_link($data["url"]),
'addr' => $data["addr"],
'request' => $data["request"],
'confirm' => $data["confirm"],
'poco' => $data["poco"],
- 'name-date' => datetime_convert(),
- 'uri-date' => datetime_convert(),
- 'avatar-date' => datetime_convert(),
+ 'name-date' => DateTimeFormat::utcNow(),
+ 'uri-date' => DateTimeFormat::utcNow(),
+ 'avatar-date' => DateTimeFormat::utcNow(),
'writable' => 1,
'blocked' => 0,
'readonly' => 0,
}
if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
- $updated['uri-date'] = datetime_convert();
+ $updated['uri-date'] = DateTimeFormat::utcNow();
}
if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
- $updated['name-date'] = datetime_convert();
+ $updated['name-date'] = DateTimeFormat::utcNow();
}
- $updated['avatar-date'] = datetime_convert();
+ $updated['avatar-date'] = DateTimeFormat::utcNow();
dba::update('contact', $updated, ['id' => $contact_id], $contact);
if ($photos) {
dba::update(
'contact',
- ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()],
+ ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
['id' => $cid]
);
// create contact record
dba::insert('contact', [
'uid' => $uid,
- 'created' => datetime_convert(),
+ 'created' => DateTimeFormat::utcNow(),
'url' => $ret['url'],
'nurl' => normalise_link($ret['url']),
'addr' => $ret['addr'],
Contact::remove($contact['id']);
}
}
+
+ /**
+ * @brief Create a birthday event.
+ *
+ * Update the year and the birthday.
+ */
+ public static function updateBirthdays()
+ {
+ // This only handles foreign or alien networks where a birthday has been provided.
+ // In-network birthdays are handled within local_delivery
+
+ $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
+ if (DBM::is_result($r)) {
+ foreach ($r as $rr) {
+ logger('update_contact_birthday: ' . $rr['bd']);
+
+ $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
+
+ /*
+ * Add new birthday event for this person
+ *
+ * $bdtext is just a readable placeholder in case the event is shared
+ * with others. We will replace it during presentation to our $importer
+ * to contain a sparkle link and perhaps a photo.
+ */
+
+ // Check for duplicates
+ $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
+ intval($rr['uid']), intval($rr['id']), dbesc(DateTimeFormat::utc($nextbd)), dbesc('birthday'));
+
+ if (DBM::is_result($s)) {
+ continue;
+ }
+
+ $bdtext = L10n::t('%s\'s birthday', $rr['name']);
+ $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
+
+ q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
+ VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
+ dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utc($nextbd)),
+ dbesc(DateTimeFormat::utc($nextbd . ' + 1 day ')), dbesc($bdtext), dbesc($bdtext2), dbesc('birthday'),
+ intval(0)
+ );
+
+
+ // update bdyear
+ q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(substr($nextbd, 0, 4)),
+ dbesc($nextbd), intval($rr['uid']), intval($rr['id'])
+ );
+ }
+ }
+ }
}
<?php
+
/**
* @file src/Model/GlobalContact.php
* @brief This file includes the GlobalContact class with directory related functions
use Friendica\Model\Profile;
use Friendica\Network\Probe;
use Friendica\Protocol\PortableContact;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use dba;
use Exception;
intval($uid),
intval($gcid),
intval($zcid),
- dbesc(datetime_convert())
+ dbesc(DateTimeFormat::utcNow())
);
} else {
q(
"UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
intval($cid),
intval($uid),
intval($gcid),
dbesc($contact["url"]),
dbesc(normalise_link($contact["url"])),
dbesc($contact["photo"]),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($contact["location"]),
dbesc($contact["about"]),
intval($contact["hide"]),
foreach ($r as $server) {
self::fetchGsUsers($server["url"]);
- q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
+ q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(DateTimeFormat::utcNow()), dbesc($server["nurl"]));
}
}
use Friendica\Object\Image;
use Friendica\Protocol\Diaspora;
use Friendica\Protocol\OStatus;
+use Friendica\Util\DateTimeFormat;
use dba;
use Text_LanguageDetect;
// Set the item to "deleted"
dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
- 'edited' => datetime_convert(), 'changed' => datetime_convert()],
+ 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
['id' => $item['id']]);
create_tags_from_item($item['id']);
$arr['owner-name'] = trim(defaults($arr, 'owner-name', ''));
$arr['owner-link'] = trim(defaults($arr, 'owner-link', ''));
$arr['owner-avatar'] = trim(defaults($arr, 'owner-avatar', ''));
- $arr['received'] = ((x($arr, 'received') !== false) ? datetime_convert('UTC','UTC', $arr['received']) : datetime_convert());
- $arr['created'] = ((x($arr, 'created') !== false) ? datetime_convert('UTC','UTC', $arr['created']) : $arr['received']);
- $arr['edited'] = ((x($arr, 'edited') !== false) ? datetime_convert('UTC','UTC', $arr['edited']) : $arr['created']);
- $arr['changed'] = ((x($arr, 'changed') !== false) ? datetime_convert('UTC','UTC', $arr['changed']) : $arr['created']);
- $arr['commented'] = ((x($arr, 'commented') !== false) ? datetime_convert('UTC','UTC', $arr['commented']) : $arr['created']);
+ $arr['received'] = ((x($arr, 'received') !== false) ? DateTimeFormat::utc($arr['received']) : DateTimeFormat::utcNow());
+ $arr['created'] = ((x($arr, 'created') !== false) ? DateTimeFormat::utc($arr['created']) : $arr['received']);
+ $arr['edited'] = ((x($arr, 'edited') !== false) ? DateTimeFormat::utc($arr['edited']) : $arr['created']);
+ $arr['changed'] = ((x($arr, 'changed') !== false) ? DateTimeFormat::utc($arr['changed']) : $arr['created']);
+ $arr['commented'] = ((x($arr, 'commented') !== false) ? DateTimeFormat::utc($arr['commented']) : $arr['created']);
$arr['title'] = trim(defaults($arr, 'title', ''));
$arr['location'] = trim(defaults($arr, 'location', ''));
$arr['coord'] = trim(defaults($arr, 'coord', ''));
}
// Items cannot be stored before they happen ...
- if ($arr['created'] > datetime_convert()) {
- $arr['created'] = datetime_convert();
+ if ($arr['created'] > DateTimeFormat::utcNow()) {
+ $arr['created'] = DateTimeFormat::utcNow();
}
// We haven't invented time travel by now.
- if ($arr['edited'] > datetime_convert()) {
- $arr['edited'] = datetime_convert();
+ if ($arr['edited'] > DateTimeFormat::utcNow()) {
+ $arr['edited'] = DateTimeFormat::utcNow();
}
if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
// update the commented timestamp on the parent
// Only update "commented" if it is really a comment
if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
- dba::update('item', ['commented' => datetime_convert(), 'changed' => datetime_convert()], ['id' => $parent_id]);
+ dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
} else {
- dba::update('item', ['changed' => datetime_convert()], ['id' => $parent_id]);
+ dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
}
if ($dsprsig) {
intval($wall ? 1 : 0)
);
if (DBM::is_result($r)) {
- return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
+ return substr(DateTimeFormat::local($r[0]['created']),0,10);
}
return false;
}
$like_item = $existing_like[0];
// Already voted, undo it
- $fields = ['deleted' => true, 'unseen' => true, 'changed' => datetime_convert()];
+ $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
dba::update('item', $fields, ['id' => $like_item['id']]);
// Clean up the Diaspora signatures for this like
<?php
+
/**
* @file src/Model/Mail.php
*/
namespace Friendica\Model;
-use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
+use Friendica\Network\Probe;
+use Friendica\Util\DateTimeFormat;
use dba;
require_once 'include/dba.php';
$handles = $recip_handle . ';' . $sender_handle;
$fields = ['uid' => local_user(), 'guid' => $conv_guid, 'creator' => $sender_handle,
- 'created' => datetime_convert(), 'updated' => datetime_convert(),
+ 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(),
'subject' => $subject, 'recips' => $handles];
if (dba::insert('conv', $fields)) {
$convid = dba::lastInsertId();
'replied' => 0,
'uri' => $uri,
'parent-uri' => $replyto,
- 'created' => datetime_convert()
+ 'created' => DateTimeFormat::utcNow()
]
);
$convid = null;
$fields = ['uid' => $recipient['uid'], 'guid' => $conv_guid, 'creator' => $sender_handle,
- 'created' => datetime_convert(), 'updated' => datetime_convert(),
+ 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(),
'subject' => $subject, 'recips' => $handles];
if (dba::insert('conv', $fields)) {
$convid = dba::lastInsertId();
}
-
+
if (!$convid) {
logger('send message: conversation not found.');
return -4;
'replied' => 0,
'uri' => $uri,
'parent-uri' => $replyto,
- 'created' => datetime_convert(),
+ 'created' => DateTimeFormat::utcNow(),
'unknown' => 1
]
);
<?php
+
/**
* @file src/Model/Photo.php
* @brief This file contains the Photo class for database interface
use Friendica\Core\Cache;
use Friendica\Core\Config;
use Friendica\Core\L10n;
-use Friendica\Core\PConfig;
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Object\Image;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use dba;
'contact-id' => $cid,
'guid' => $guid,
'resource-id' => $rid,
- 'created' => datetime_convert(),
- 'edited' => datetime_convert(),
+ 'created' => DateTimeFormat::utcNow(),
+ 'edited' => DateTimeFormat::utcNow(),
'filename' => basename($filename),
'type' => $Image->getType(),
'album' => $album,
namespace Friendica\Model;
use Friendica\BaseObject;
+use Friendica\Util\DateTimeFormat;
use dba;
require_once 'include/dba.php';
dba::transaction();
if (!dba::exists('process', ['pid' => $pid])) {
- $return = dba::insert('process', ['pid' => $pid, 'command' => $command, 'created' => datetime_convert()]);
+ $return = dba::insert('process', ['pid' => $pid, 'command' => $command, 'created' => DateTimeFormat::utcNow()]);
}
dba::commit();
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Protocol\Diaspora;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use dba;
WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
ORDER BY `start` ASC ",
local_user(),
- datetime_convert('UTC', 'UTC', 'now + 6 days'),
- datetime_convert('UTC', 'UTC', 'now')
+ DateTimeFormat::utc('now + 6 days'),
+ DateTimeFormat::utcNow()
);
if (DBM::is_result($s)) {
$r = dba::inArray($s);
$rr['link'] = $url;
$rr['title'] = $rr['name'];
- $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
+ $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
$rr['startime'] = null;
$rr['today'] = $today;
}
WHERE `event`.`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?
ORDER BY `start` ASC ",
local_user(),
- datetime_convert('UTC', 'UTC', 'now + 7 days'),
- datetime_convert('UTC', 'UTC', 'now - 1 days')
+ DateTimeFormat::utc('now + 7 days'),
+ DateTimeFormat::utc('now - 1 days')
);
$r = [];
$total ++;
}
- $strt = datetime_convert('UTC', $rr['convert'] ? $a->timezone : 'UTC', $rr['start'], 'Y-m-d');
- if ($strt === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) {
+ $strt = DateTimeFormat::convert($rr['start'], $rr['convert'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
+ if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
$istoday = true;
}
$description = L10n::t('[No description]');
}
- $strt = datetime_convert('UTC', $rr['convert'] ? $a->timezone : 'UTC', $rr['start']);
+ $strt = DateTimeFormat::convert($rr['start'], $rr['convert'] ? $a->timezone : 'UTC');
- if (substr($strt, 0, 10) < datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) {
+ if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
continue;
}
- $today = ((substr($strt, 0, 10) === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) ? true : false);
+ $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
$rr['title'] = $title;
$rr['description'] = $description;
- $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
+ $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
$rr['startime'] = $strt;
$rr['today'] = $today;
$year_bd_format = L10n::t('j F, Y');
$short_bd_format = L10n::t('j F');
- $val = intval($a->profile['dob']) ?
- day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format))
- : day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format));
+ $val = day_translate(
+ intval($a->profile['dob']) ?
+ DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
+ : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
+ );
$profile['birthday'] = [L10n::t('Birthday:'), $val];
}
use Friendica\Core\Config;
use Friendica\Database\DBM;
+use Friendica\Util\DateTimeFormat;
use dba;
require_once 'include/dba.php';
public static function updateTime($id)
{
logger('queue: requeue item ' . $id);
- dba::update('queue', ['last' => datetime_convert()], ['id' => $id]);
+ dba::update('queue', ['last' => DateTimeFormat::utcNow()], ['id' => $id]);
}
-
+
/**
* @param string $id id
*/
logger('queue: remove queue item ' . $id);
dba::delete('queue', ['id' => $id]);
}
-
+
/**
* @brief Checks if the communication with a given contact had problems recently
*
AND `last` > UTC_TIMESTAMP() - INTERVAL 15 MINUTE LIMIT 1",
intval($cid)
);
-
+
$was_delayed = DBM::is_result($r);
-
+
// We set "term-date" to a current date if the communication has problems.
// If the communication works again we reset this value.
if ($was_delayed) {
);
$was_delayed = !DBM::is_result($r);
}
-
+
return $was_delayed;
}
-
+
/**
* @param string $cid cid
* @param string $network network
*/
public static function add($cid, $network, $msg, $batch = false)
{
-
+
$max_queue = Config::get('system', 'max_contact_queue');
if ($max_queue < 1) {
$max_queue = 500;
}
-
+
$batch_queue = Config::get('system', 'max_batch_queue');
if ($batch_queue < 1) {
$batch_queue = 1000;
}
-
+
$r = q("SELECT COUNT(*) AS `total` FROM `queue` INNER JOIN `contact` ON `queue`.`cid` = `contact`.`id`
WHERE `queue`.`cid` = %d AND `contact`.`self` = 0 ",
intval($cid)
return;
}
}
-
- dba::insert('queue', ['cid' => $cid, 'network' => $network, 'created' => datetime_convert(), 'last' => datetime_convert(), 'content' => $msg, 'batch' =>($batch) ? 1 : 0]);
+
+ dba::insert('queue', [
+ 'cid' => $cid,
+ 'network' => $network,
+ 'created' => DateTimeFormat::utcNow(),
+ 'last' => DateTimeFormat::utcNow(),
+ 'content' => $msg,
+ 'batch' =>($batch) ? 1 : 0
+ ]);
}
}
use Friendica\Core\Addon;
use Friendica\Core\Config;
-use Friendica\Core\PConfig;
use Friendica\Core\L10n;
+use Friendica\Core\PConfig;
use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
use Friendica\Model\Photo;
use Friendica\Object\Image;
use Friendica\Util\Crypto;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use dba;
use Exception;
+use LightOpenID;
require_once 'boot.php';
require_once 'include/dba.php';
$_SESSION['register'] = 1;
$_SESSION['openid'] = $openid_url;
- $openid = new \LightOpenID;
+ $openid = new LightOpenID;
$openid->identity = $openid_url;
$openid->returnUrl = System::baseUrl() . '/openid';
$openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
'verified' => $verified,
'blocked' => $blocked,
'timezone' => 'UTC',
- 'register_date' => datetime_convert(),
+ 'register_date' => DateTimeFormat::utcNow(),
'default-location' => ''
]);
dba::insert('userd', ['username' => $user['nickname']]);
// The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
- dba::update('user', ['account_removed' => true, 'account_expires_on' => datetime_convert()], ['uid' => $uid]);
+ dba::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utcNow()], ['uid' => $uid]);
Worker::add(PRIORITY_HIGH, "Notifier", "removeme", $uid);
// Send an update to the directory
use Friendica\Core\L10n;
use Friendica\Database\DBM;
use Friendica\Model\User;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use dba;
+use Exception;
+use LightOpenID;
require_once 'boot.php';
require_once 'include/datetime.php';
// Otherwise it's probably an openid.
try {
- $openid = new \LightOpenID;
+ $openid = new LightOpenID;
$openid->identity = $openid_url;
$_SESSION['openid'] = $openid_url;
$_SESSION['remember'] = $_POST['remember'];
// if we haven't failed up this point, log them in.
$_SESSION['remember'] = $_POST['remember'];
- $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
+ $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
authenticate_success($record, true, true);
if (x($_SESSION, 'return_url')) {
// stays logged in for a long time, e.g. with "Remember Me"
$login_refresh = false;
if (!x($_SESSION['last_login_date'])) {
- $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
+ $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
}
- if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) {
- $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
+ if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
+ $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
$login_refresh = true;
}
authenticate_success($user, false, false, $login_refresh);
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Network\FKOAuthDataStore;
+use Friendica\Util\DateTimeFormat;
use dba;
use OAuthServer;
use OAuthSignatureMethod_HMAC_SHA1;
$_SESSION['cid'] = $a->cid;
}
- dba::update('user', ['login_date' => datetime_convert()], ['uid' => $_SESSION['uid']]);
+ dba::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
Addon::callHooks('logged_in', $a->user);
}
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Profile;
+use Friendica\Util\DateTimeFormat;
use dba;
require_once 'include/dba.php';
if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
$edited = [
'label' => L10n::t('This entry was edited'),
- 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
+ 'date' => DateTimeFormat::local($item['edited'], 'r'),
'relative' => relative_date($item['edited'])
];
}
$comment = $this->getCommentBox($indent);
- if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
+ if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
$shiny = 'shiny';
}
'osparkle' => $osparkle,
'sparkle' => $sparkle,
'title' => $title_e,
- 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
+ 'localtime' => DateTimeFormat::local($item['created'], 'r'),
'ago' => $item['app'] ? L10n::t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
'app' => $item['app'],
'created' => relative_date($item['created']),
use Friendica\Object\Image;
use Friendica\Protocol\OStatus;
use Friendica\Util\Crypto;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\XML;
use Friendica\Content\Text\BBCode;
}
}
- $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
+ $check_date = DateTimeFormat::utc($last_update);
$r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`,
XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
- XML::addElement($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME));
+ XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
XML::addElement($doc, $mail, "dfrn:content", $item['body']);
/// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
- XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
+ XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
$author = self::addAuthor($doc, $owner, $authorelement, $public);
$root->appendChild($author);
$author = $doc->createElement($authorelement);
- $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
- $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
- $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
+ $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
+ $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
+ $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
$attributes = [];
}
if ($item['deleted']) {
- $attributes = ["ref" => $item['uri'], "when" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME)];
+ $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
return XML::createElement($doc, "at:deleted-entry", "", $attributes);
}
XML::addElement($doc, $entry, "id", $item["uri"]);
XML::addElement($doc, $entry, "title", $item["title"]);
- XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
- XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME));
+ XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
+ XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
// "dfrn:env" is used to read the content
XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
"SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
intval($contact["uid"]),
intval($contact["id"]),
- dbesc(datetime_convert("UTC", "UTC", $birthday)),
+ dbesc(DateTimeFormat::utc($birthday)),
dbesc("birthday")
);
VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
intval($contact["uid"]),
intval($contact["id"]),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
- dbesc(datetime_convert("UTC", "UTC", $birthday)),
- dbesc(datetime_convert("UTC", "UTC", $birthday . " + 1 day ")),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utc($birthday)),
+ dbesc(DateTimeFormat::utc($birthday . " + 1 day ")),
dbesc($bdtext),
dbesc($bdtext2),
dbesc("birthday")
intval($suggest["cid"]),
dbesc($suggest["body"]),
dbesc($hash),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
intval(0)
);
if (self::isEditedTimestampNewer($current, $item)) {
// do not accept (ignore) an earlier edit than one we currently have.
- if (datetime_convert("UTC", "UTC", $item["edited"]) < $current["edited"]) {
+ if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
return false;
}
$fields = ['title' => $item["title"], 'body' => $item["body"],
- 'tag' => $item["tag"], 'changed' => datetime_convert(),
- 'edited' => datetime_convert("UTC", "UTC", $item["edited"])];
+ 'tag' => $item["tag"], 'changed' => DateTimeFormat::utcNow(),
+ 'edited' => DateTimeFormat::utc($item["edited"])];
$condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
dba::update('item', $fields, $condition);
// Is there an existing item?
if (DBM::is_result($current) && self::isEditedTimestampNewer($current[0], $item)
- && (datetime_convert("UTC", "UTC", $item["edited"]) < $current[0]["edited"])
+ && (DateTimeFormat::utc($item["edited"]) < $current[0]["edited"])
) {
logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
return;
}
}
if ($when) {
- $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
+ $when = DateTimeFormat::utc($when);
} else {
- $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
+ $when = DateTimeFormat::utcNow();
}
if (!$uri || !$importer["id"]) {
`body` = '', `title` = ''
WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
dbesc($when),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($uri),
intval($importer["uid"])
);
`body` = '', `title` = ''
WHERE `uri` = '%s' AND `uid` IN (0, %d)",
dbesc($when),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($uri),
intval($importer["uid"])
);
return false;
}
- $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
- $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
+ $existing_edited = DateTimeFormat::utc($existing['edited']);
+ $update_edited = DateTimeFormat::utc($update['edited']);
return (strcmp($existing_edited, $update_edited) < 0);
}
*/
namespace Friendica\Protocol;
-use Friendica\App;
-use Friendica\Core\System;
use Friendica\Core\Cache;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\PConfig;
+use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\User;
use Friendica\Network\Probe;
use Friendica\Util\Crypto;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\XML;
use dba;
$r = q(
"INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
- datetime_convert(),
+ DateTimeFormat::utcNow(),
dbesc($addr),
dbesc($addr),
dbesc($server),
dbesc($batch),
dbesc(NETWORK_DIASPORA),
intval(CONTACT_IS_FOLLOWER),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
- dbesc(datetime_convert())
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow())
);
$relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
dbesc($arr["confirm"]),
dbesc($arr["alias"]),
dbesc($arr["pubkey"]),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($arr["url"]),
dbesc($arr["network"])
);
dbesc($arr["network"]),
dbesc($arr["alias"]),
dbesc($arr["pubkey"]),
- dbesc(datetime_convert())
+ dbesc(DateTimeFormat::utcNow())
);
}
$text = unxmlify($data->text);
if (isset($data->created_at)) {
- $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+ $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
} else {
- $created_at = datetime_convert();
+ $created_at = DateTimeFormat::utcNow();
}
if (isset($data->thread_parent_guid)) {
$msg_guid = notags(unxmlify($mesg->guid));
$msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
$msg_text = unxmlify($mesg->text);
- $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
+ $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
if ($msg_conversation_guid != $guid) {
logger("message conversation guid does not belong to the current conversation.");
dba::unlock();
- dba::update('conv', ['updated' => datetime_convert()], ['id' => $conversation["id"]]);
+ dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
notification(
[
$author = notags(unxmlify($data->author));
$guid = notags(unxmlify($data->guid));
$subject = notags(unxmlify($data->subject));
- $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+ $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
$participants = notags(unxmlify($data->participants));
$messages = $data->message;
dbesc($guid),
dbesc($author),
dbesc($created_at),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($subject),
dbesc($participants)
);
$guid = notags(unxmlify($data->guid));
$conversation_guid = notags(unxmlify($data->conversation_guid));
$text = unxmlify($data->text);
- $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+ $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
$contact = self::allowedContactByHandle($importer, $author, true);
if (!$contact) {
dba::unlock();
- dba::update('conv', ['updated' => datetime_convert()], ['id' => $conversation["id"]]);
+ dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
return true;
}
$birthday = str_replace("1000", "1901", $birthday);
if ($birthday != "") {
- $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
+ $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
}
// this is to prevent multiple birthday notifications in a single year
dbesc($name),
dbesc($nick),
dbesc($author),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
dbesc($birthday),
dbesc($location),
dbesc($about),
intval($importer["uid"]),
dbesc($ret["network"]),
dbesc($ret["addr"]),
- datetime_convert(),
+ DateTimeFormat::utcNow(),
dbesc($ret["url"]),
dbesc(normalise_link($ret["url"])),
dbesc($batch),
0,
dbesc(L10n::t("Sharing notification from Diaspora network")),
dbesc($hash),
- dbesc(datetime_convert())
+ dbesc(DateTimeFormat::utcNow())
);
} else {
// automatic friend approval
WHERE `id` = %d
",
intval($new_relation),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
+ dbesc(DateTimeFormat::utcNow()),
+ dbesc(DateTimeFormat::utcNow()),
intval($contact_record["id"])
);
{
$author = notags(unxmlify($data->author));
$guid = notags(unxmlify($data->guid));
- $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+ $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
$root_author = notags(unxmlify($data->root_author));
$root_guid = notags(unxmlify($data->root_guid));
/// @todo handle unprocessed property "provider_display_name"
'deleted' => true,
'title' => '',
'body' => '',
- 'edited' => datetime_convert(),
- 'changed' => datetime_convert()],
+ 'edited' => DateTimeFormat::utcNow(),
+ 'changed' => DateTimeFormat::utcNow()],
['id' => $item["id"]]
);
{
$author = notags(unxmlify($data->author));
$guid = notags(unxmlify($data->guid));
- $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+ $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
$public = notags(unxmlify($data->public));
$text = unxmlify($data->text);
$provider_display_name = notags(unxmlify($data->provider_display_name));
$eventdata['guid'] = $event['guid'];
}
- $mask = 'Y-m-d\TH:i:s\Z';
+ $mask = DateTimeFormat::ATOM;
/// @todo - establish "all day" events in Friendica
$eventdata["all_day"] = "false";
}
if ($event['start']) {
- $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
+ $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
}
if ($event['finish'] && !$event['nofinish']) {
- $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
+ $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
}
if ($event['summary']) {
$eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
$public = (($item["private"]) ? "false" : "true");
- $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
+ $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
// Detect a share element and do a reshare
if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
$parent = $p[0];
$text = html_entity_decode(bb2diaspora($item["body"]));
- $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
+ $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
$comment = ["author" => self::myHandle($owner),
"guid" => $item["guid"],
"author" => $cnv["creator"],
"guid" => $cnv["guid"],
"subject" => $cnv["subject"],
- "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
+ "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
"participants" => $cnv["recips"]
];
$body = bb2diaspora($item["body"]);
- $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
+ $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
$msg = [
"author" => $myaddr,
"author" => $cnv["creator"],
"guid" => $cnv["guid"],
"subject" => $cnv["subject"],
- "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
+ "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
"participants" => $cnv["recips"],
"message" => $msg];
if ($year < 1004) {
$year = 1004;
}
- $dob = datetime_convert('UTC', 'UTC', $year . '-' . $month . '-'. $day, 'Y-m-d');
+ $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
}
$about = $profile['about'];
*/
namespace Friendica\Protocol;
-use Friendica\App;
use Friendica\Content\Text\BBCode;
use Friendica\Core\Cache;
use Friendica\Core\Config;
use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
-use Friendica\Model\GContact;
use Friendica\Model\Conversation;
+use Friendica\Model\GContact;
use Friendica\Model\Item;
use Friendica\Network\Probe;
use Friendica\Object\Image;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Lock;
use Friendica\Util\Network;
use Friendica\Util\XML;
$contact["location"] = $value;
}
- $contact['name-date'] = datetime_convert();
+ $contact['name-date'] = DateTimeFormat::utcNow();
dba::update('contact', $contact, ['id' => $contact["id"]], $current);
'nurl' => normalise_link($author["author-link"]),
'nick' => $contact["nick"], 'alias' => $contact["alias"],
'about' => $contact["about"], 'location' => $contact["location"],
- 'success_update' => datetime_convert(), 'last-update' => datetime_convert()];
+ 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
dba::update('contact', $fields, ['id' => $cid], $old_contact);
dba::update(
'item',
['deleted' => true, 'title' => '', 'body' => '',
- 'edited' => datetime_convert(), 'changed' => datetime_convert()],
+ 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
['id' => $deleted["id"]]
);
XML::addElement($doc, $root, "title", $title);
XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
XML::addElement($doc, $root, "logo", $owner["photo"]);
- XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
+ XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
$author = self::addAuthor($doc, $owner);
$root->appendChild($author);
XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
XML::addElement($doc, $source, "icon", $contact["photo"]);
- XML::addElement($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME));
+ XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
return $source;
}
XML::addElement($doc, $entry, "activity:verb", $verb);
- XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME));
- XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME));
+ XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
+ XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
}
/**
$last_update = 'now -30 days';
}
- $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
+ $check_date = DateTimeFormat::utc($last_update);
$authorid = Contact::getIdForURL($owner["url"], 0);
$sql_extra = '';
use Friendica\Model\GContact;
use Friendica\Model\Profile;
use Friendica\Network\Probe;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use dba;
use DOMDocument;
}
if (isset($entry->updated)) {
- $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
+ $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
}
if (isset($entry->network)) {
$contact = ["url" => $profile];
if ($gcontacts[0]["created"] <= NULL_DATE) {
- $contact['created'] = datetime_convert();
+ $contact['created'] = DateTimeFormat::utcNow();
}
if ($force) {
if ($server_url != "") {
if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
if ($force) {
- $fields = ['last_failure' => datetime_convert()];
+ $fields = ['last_failure' => DateTimeFormat::utcNow()];
dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
}
// Set the date of the last contact
/// @todo By now the function "update_gcontact" doesn't work with this field
- //$contact["last_contact"] = datetime_convert();
+ //$contact["last_contact"] = DateTimeFormat::utcNow();
$contact = array_merge($contact, $noscrape);
GContact::update($contact);
if (trim($noscrape["updated"]) != "") {
- $fields = ['last_contact' => datetime_convert()];
+ $fields = ['last_contact' => DateTimeFormat::utcNow()];
dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
}
if (($data["poll"] == "") || (in_array($data["network"], [NETWORK_FEED, NETWORK_PHANTOM]))) {
- $fields = ['last_failure' => datetime_convert()];
+ $fields = ['last_failure' => DateTimeFormat::utcNow()];
dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
$feedret = Network::curl($data["poll"]);
if (!$feedret["success"]) {
- $fields = ['last_failure' => datetime_convert()];
+ $fields = ['last_failure' => DateTimeFormat::utcNow()];
dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
public static function updateNeeded($created, $updated, $last_failure, $last_contact)
{
- $now = strtotime(datetime_convert());
+ $now = strtotime(DateTimeFormat::utcNow());
if ($updated > $last_contact) {
$contact_time = strtotime($updated);
$gserver = dba::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
if (DBM::is_result($gserver)) {
if ($gserver["created"] <= NULL_DATE) {
- $fields = ['created' => datetime_convert()];
+ $fields = ['created' => DateTimeFormat::utcNow()];
$condition = ['nurl' => normalise_link($server_url)];
dba::update('gserver', $fields, $condition);
}
// Mastodon uses the "@" for user profiles.
// But this can be misunderstood.
if (parse_url($server_url, PHP_URL_USER) != '') {
- dba::update('gserver', ['last_failure' => datetime_convert()], ['nurl' => normalise_link($server_url)]);
+ dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
return false;
}
if (DBM::is_result($gserver) && ($orig_server_url == $server_url) &&
($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
- dba::update('gserver', ['last_failure' => datetime_convert()], ['nurl' => normalise_link($server_url)]);
+ dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
return false;
}
// Quit if there is a timeout
if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
- dba::update('gserver', ['last_failure' => datetime_convert()], ['nurl' => normalise_link($server_url)]);
+ dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
return false;
}
if ($failure) {
$last_contact = $orig_last_contact;
- $last_failure = datetime_convert();
+ $last_failure = DateTimeFormat::utcNow();
} else {
- $last_contact = datetime_convert();
+ $last_contact = DateTimeFormat::utcNow();
$last_failure = $orig_last_failure;
}
dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
} elseif (!$failure) {
$fields['nurl'] = normalise_link($server_url);
- $fields['created'] = datetime_convert();
+ $fields['created'] = DateTimeFormat::utcNow();
dba::insert('gserver', $fields);
}
logger("End discovery for server " . $server_url, LOGGER_DEBUG);
$timeframe = 30;
}
- $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
+ $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
// Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
$url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
}
}
- $fields = ['last_poco_query' => datetime_convert()];
+ $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
return true;
self::checkServer($server["url"], $server["network"], true);
// If we couldn't reach the server, we will try it some time later
- $fields = ['last_poco_query' => datetime_convert()];
+ $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
return false;
foreach ($r as $server) {
if (!self::checkServer($server["url"], $server["network"])) {
// The server is not reachable? Okay, then we will try it later
- $fields = ['last_poco_query' => datetime_convert()];
+ $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
continue;
}
}
if (isset($entry->updated)) {
- $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
+ $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
}
if (isset($entry->network)) {
\r
use Smarty;\r
\r
-define('SMARTY3_TEMPLATE_FOLDER', 'templates');\r
-\r
/**\r
- * Description of FriendicaSmarty\r
+ * Friendica extension of the Smarty3 template engine\r
*\r
- * @author benlo\r
+ * @author Hypolite Petovan <mrpetovan@gmail.com>\r
*/\r
class FriendicaSmarty extends Smarty\r
{\r
+ const SMARTY3_TEMPLATE_FOLDER = 'templates';\r
+\r
public $filename;\r
\r
function __construct()\r
\r
// setTemplateDir can be set to an array, which Smarty will parse in order.\r
// The order is thus very important here\r
- $template_dirs = ['theme' => "view/theme/$theme/" . SMARTY3_TEMPLATE_FOLDER . "/"];\r
+ $template_dirs = ['theme' => "view/theme/$theme/" . self::SMARTY3_TEMPLATE_FOLDER . "/"];\r
if (x($a->theme_info, "extends")) {\r
- $template_dirs = $template_dirs + ['extends' => "view/theme/" . $a->theme_info["extends"] . "/" . SMARTY3_TEMPLATE_FOLDER . "/"];\r
+ $template_dirs = $template_dirs + ['extends' => "view/theme/" . $a->theme_info["extends"] . "/" . self::SMARTY3_TEMPLATE_FOLDER . "/"];\r
}\r
\r
- $template_dirs = $template_dirs + ['base' => "view/" . SMARTY3_TEMPLATE_FOLDER . "/"];\r
+ $template_dirs = $template_dirs + ['base' => "view/" . self::SMARTY3_TEMPLATE_FOLDER . "/"];\r
$this->setTemplateDir($template_dirs);\r
\r
$this->setCompileDir('view/smarty3/compiled/');\r
use Friendica\Core\Addon;
-define('SMARTY3_TEMPLATE_FOLDER', 'templates');
-
+/**
+ * Smarty implementation of the Friendica template engine interface
+ *
+ * @author Hypolite Petovan <mrpetovan@gmail.com>
+ */
class FriendicaSmartyEngine implements ITemplateEngine
{
static $name = "smarty3";
public function getTemplateFile($file, $root = '')
{
$a = get_app();
- $template_file = get_template_file($a, SMARTY3_TEMPLATE_FOLDER . '/' . $file, $root);
$template = new FriendicaSmarty();
+
+ // Make sure $root ends with a slash /
+ if ($root !== '' && substr($root, -1, 1) !== '/') {
+ $root = $root . '/';
+ }
+
+ $theme = current_theme();
+ $filename = $template::SMARTY3_TEMPLATE_FOLDER . '/' . $file;
+
+ if (file_exists("{$root}view/theme/$theme/$filename")) {
+ $template_file = "{$root}view/theme/$theme/$filename";
+ } elseif (x($a->theme_info, 'extends') && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info['extends'], $filename))) {
+ $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info['extends'], $filename);
+ } elseif (file_exists("{$root}/$filename")) {
+ $template_file = "{$root}/$filename";
+ } else {
+ $template_file = "{$root}view/$filename";
+ }
+
$template->filename = $template_file;
return $template;
--- /dev/null
+<?php
+
+/**
+ * @file src/Util/DateTimeFormat.php
+ */
+
+namespace Friendica\Util;
+
+use DateTime;
+use DateTimeZone;
+use Exception;
+
+/**
+ * @brief Temporal class
+ */
+class DateTimeFormat
+{
+ const ATOM = 'Y-m-d\TH:i:s\Z';
+ const MYSQL = 'Y-m-d H:i:s';
+
+ /**
+ * convert() shorthand for UTC.
+ *
+ * @param string $time A date/time string
+ * @param string $format DateTime format string or Temporal constant
+ * @return string
+ */
+ public static function utc($time, $format = self::MYSQL)
+ {
+ return self::convert($time, 'UTC', 'UTC', $format);
+ }
+
+ /**
+ * convert() shorthand for local.
+ *
+ * @param string $time A date/time string
+ * @param string $format DateTime format string or Temporal constant
+ * @return string
+ */
+ public static function local($time, $format = self::MYSQL)
+ {
+ return self::convert($time, date_default_timezone_get(), 'UTC', $format);
+ }
+
+ /**
+ * convert() shorthand for timezoned now.
+ *
+ * @param string $format DateTime format string or Temporal constant
+ * @return string
+ */
+ public static function timezoneNow($timezone, $format = self::MYSQL)
+ {
+ return self::convert('now', $timezone, 'UTC', $format);
+ }
+
+ /**
+ * convert() shorthand for local now.
+ *
+ * @param string $format DateTime format string or Temporal constant
+ * @return string
+ */
+ public static function localNow($format = self::MYSQL)
+ {
+ return self::local('now', $format);
+ }
+
+ /**
+ * convert() shorthand for UTC now.
+ *
+ * @param string $format DateTime format string or Temporal constant
+ * @return string
+ */
+ public static function utcNow($format = self::MYSQL)
+ {
+ return self::utc('now', $format);
+ }
+
+ /**
+ * @brief General purpose date parse/convert/format function.
+ *
+ * @param string $s Some parseable date/time string
+ * @param string $tz_to Destination timezone
+ * @param string $tz_from Source timezone
+ * @param string $format Output format recognised from php's DateTime class
+ * http://www.php.net/manual/en/datetime.format.php
+ *
+ * @return string Formatted date according to given format
+ */
+ public static function convert($s = 'now', $tz_to = 'UTC', $tz_from = 'UTC', $format = self::MYSQL)
+ {
+ // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
+ // Provide some sane defaults regardless.
+ if ($from === '') {
+ $from = 'UTC';
+ }
+
+ if ($to === '') {
+ $to = 'UTC';
+ }
+
+ if (($s === '') || (!is_string($s))) {
+ $s = 'now';
+ }
+
+ /*
+ * Slight hackish adjustment so that 'zero' datetime actually returns what is intended
+ * otherwise we end up with -0001-11-30 ...
+ * add 32 days so that we at least get year 00, and then hack around the fact that
+ * months and days always start with 1.
+ */
+ if (substr($s, 0, 10) <= '0001-01-01') {
+ $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
+ return str_replace('1', '0', $d->format($format));
+ }
+
+ try {
+ $from_obj = new DateTimeZone($tz_from);
+ } catch (Exception $e) {
+ $from_obj = new DateTimeZone('UTC');
+ }
+
+ try {
+ $d = new DateTime($s, $from_obj);
+ } catch (Exception $e) {
+ logger('datetime_convert: exception: ' . $e->getMessage());
+ $d = new DateTime('now', $from_obj);
+ }
+
+ try {
+ $to_obj = new DateTimeZone($tz_to);
+ } catch (Exception $e) {
+ $to_obj = new DateTimeZone('UTC');
+ }
+
+ $d->setTimeZone($to_obj);
+
+ return $d->format($format);
+ }
+}
[
'url' => normalise_link($url), 'guessing' => !$no_guessing,
'oembed' => $do_oembed, 'content' => serialize($data),
- 'created' => datetime_convert()],
+ 'created' => DateTimeFormat::utcNow()
+ ],
true
);
--- /dev/null
+<?php
+
+/**
+ * @file src/Util/Temporal.php
+ */
+
+namespace Friendica\Util;
+
+use DateTime;
+use DateTimeZone;
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\PConfig;
+
+require_once 'boot.php';
+require_once 'include/text.php';
+
+/**
+ * @brief Temporal class
+ */
+class Temporal
+{
+ /**
+ * @brief Two-level sort for timezones.
+ *
+ * @param string $a
+ * @param string $b
+ * @return int
+ */
+ private static function timezoneCompareCallback($a, $b)
+ {
+ if (strstr($a, '/') && strstr($b, '/')) {
+ if (L10n::t($a) == L10n::t($b)) {
+ return 0;
+ }
+ return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
+ }
+
+ if (strstr($a, '/')) {
+ return -1;
+ } elseif (strstr($b, '/')) {
+ return 1;
+ } elseif (L10n::t($a) == L10n::t($b)) {
+ return 0;
+ }
+
+ return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
+ }
+
+ /**
+ * @brief Emit a timezone selector grouped (primarily) by continent
+ *
+ * @param string $current Timezone
+ * @return string Parsed HTML output
+ */
+ public static function getTimezoneSelect($current = 'America/Los_Angeles')
+ {
+ $timezone_identifiers = DateTimeZone::listIdentifiers();
+
+ $o = '<select id="timezone_select" name="timezone">';
+
+ usort($timezone_identifiers, [self, 'timezoneCompareCallback']);
+ $continent = '';
+ foreach ($timezone_identifiers as $value) {
+ $ex = explode("/", $value);
+ if (count($ex) > 1) {
+ if ($ex[0] != $continent) {
+ if ($continent != '') {
+ $o .= '</optgroup>';
+ }
+ $continent = $ex[0];
+ $o .= '<optgroup label="' . L10n::t($continent) . '">';
+ }
+ if (count($ex) > 2) {
+ $city = substr($value, strpos($value, '/') + 1);
+ } else {
+ $city = $ex[1];
+ }
+ } else {
+ $city = $ex[0];
+ if ($continent != L10n::t('Miscellaneous')) {
+ $o .= '</optgroup>';
+ $continent = L10n::t('Miscellaneous');
+ $o .= '<optgroup label="' . L10n::t($continent) . '">';
+ }
+ }
+ $city = str_replace('_', ' ', L10n::t($city));
+ $selected = (($value == $current) ? " selected=\"selected\" " : "");
+ $o .= "<option value=\"$value\" $selected >$city</option>";
+ }
+ $o .= '</optgroup></select>';
+ return $o;
+ }
+
+ /**
+ * @brief Generating a Timezone selector
+ *
+ * Return a select using 'field_select_raw' template, with timezones
+ * grouped (primarily) by continent
+ * arguments follow convention as other field_* template array:
+ * 'name', 'label', $value, 'help'
+ *
+ * @param string $name Name of the selector
+ * @param string $label Label for the selector
+ * @param string $current Timezone
+ * @param string $help Help text
+ *
+ * @return string Parsed HTML
+ */
+ public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
+ {
+ $options = self::getTimezoneSelect($current);
+ $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
+ $options = str_replace('</select>', '', $options);
+
+ $tpl = get_markup_template('field_select_raw.tpl');
+ return replace_macros($tpl, [
+ '$field' => [$name, $label, $current, $help, $options],
+ ]);
+ }
+
+ /**
+ * @brief Wrapper for date selector, tailored for use in birthday fields.
+ *
+ * @param string $dob Date of Birth
+ * @return string Formatted HTML
+ */
+ public static function getDateofBirthField($dob)
+ {
+ list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
+
+ if ($dob < '0000-01-01') {
+ $value = '';
+ } else {
+ $value = DateTimeFormat::utc(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'Y-m-d');
+ }
+
+ $age = (intval($value) ? age($value, $a->user["timezone"], $a->user["timezone"]) : "");
+
+ $tpl = get_markup_template("field_input.tpl");
+ $o = replace_macros($tpl,
+ [
+ '$field' => [
+ 'dob',
+ L10n::t('Birthday:'),
+ $value,
+ intval($age) > 0 ? L10n::t('Age: ') . $age : "",
+ '',
+ 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
+ ]
+ ]);
+
+ return $o;
+ }
+
+ /**
+ * @brief Returns a date selector
+ *
+ * @param string $min Unix timestamp of minimum date
+ * @param string $max Unix timestap of maximum date
+ * @param string $default Unix timestamp of default date
+ * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
+ *
+ * @return string Parsed HTML output.
+ */
+ public static function getDateField($min, $max, $default, $id = 'datepicker')
+ {
+ return datetimesel($min, $max, $default, '', $id, true, false, '', '');
+ }
+
+ /**
+ * @brief Returns a time selector
+ *
+ * @param string $h Already selected hour
+ * @param string $m Already selected minute
+ * @param string $id ID and name of datetimepicker (defaults to "timepicker")
+ *
+ * @return string Parsed HTML output.
+ */
+ public static function getTimeField($h, $m, $id = 'timepicker')
+ {
+ return datetimesel(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
+ }
+
+ /**
+ * @brief Returns a datetime selector.
+ *
+ * @param DateTime $minDate Minimum date
+ * @param DateTime $maxDate Maximum date
+ * @param DateTime $defaultDate Default date
+ * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
+ * @param bool $pickdate true to show date picker (default)
+ * @param bool $picktime true to show time picker (default)
+ * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
+ * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
+ * @param bool $required default false
+ *
+ * @return string Parsed HTML output.
+ *
+ * @todo Once browser support is better this could probably be replaced with
+ * native HTML5 date picker.
+ */
+ public static function getDateTimeField(
+ DateTime $minDate,
+ DateTime $maxDate,
+ DateTime $defaultDate,
+ $label,
+ $id = 'datetimepicker',
+ $pickdate = true,
+ $picktime = true,
+ $minfrom = '',
+ $maxfrom = '',
+ $required = false)
+ {
+ // First day of the week (0 = Sunday)
+ $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
+
+ $lang = substr(L10n::getBrowserLanguage(), 0, 2);
+
+ // Check if the detected language is supported by the picker
+ if (!in_array($lang,
+ ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
+ "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
+ $lang = Config::get('system', 'language', 'en');
+ }
+
+ $o = '';
+ $dateformat = '';
+
+ if ($pickdate) {
+ $dateformat .= 'Y-m-d';
+ }
+
+ if ($pickdate && $picktime) {
+ $dateformat .= ' ';
+ }
+
+ if ($picktime) {
+ $dateformat .= 'H:i';
+ }
+
+ $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
+
+ $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
+
+ $tpl = get_markup_template('field_datetime.tpl');
+ $o .= replace_macros($tpl, [
+ '$field' => [
+ $id,
+ $label,
+ $input_text,
+ '',
+ $required ? '*' : '',
+ 'placeholder="' . $readable_format . '"'
+ ],
+ '$datetimepicker' => [
+ 'minDate' => $minDate,
+ 'maxDate' => $maxDate,
+ 'defaultDate' => $defaultDate,
+ 'dateformat' => $dateformat,
+ 'firstDay' => $firstDay,
+ 'lang' => $lang,
+ 'minfrom' => $minfrom,
+ 'maxfrom' => $maxfrom,
+ ]
+ ]);
+
+ return $o;
+ }
+
+ /**
+ * @brief Returns a relative date string.
+ *
+ * Implements "3 seconds ago" etc.
+ * Based on $posted_date, (UTC).
+ * Results relative to current timezone.
+ * Limited to range of timestamps.
+ *
+ * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
+ * @param string $format (optional) Parsed with sprintf()
+ * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
+ *
+ * @return string with relative date
+ */
+ public static function getRelativeDate($posted_date, $format = null)
+ {
+ $localtime = $posted_date . ' UTC';
+
+ $abs = strtotime($localtime);
+
+ if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === false) {
+ return L10n::t('never');
+ }
+
+ $etime = time() - $abs;
+
+ if ($etime < 1) {
+ return L10n::t('less than a second ago');
+ }
+
+ $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
+ 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
+ 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
+ 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
+ 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
+ 60 => [L10n::t('minute'), L10n::t('minutes')],
+ 1 => [L10n::t('second'), L10n::t('seconds')]
+ ];
+
+ foreach ($a as $secs => $str) {
+ $d = $etime / $secs;
+ if ($d >= 1) {
+ $r = round($d);
+ // translators - e.g. 22 hours ago, 1 minute ago
+ if (!$format) {
+ $format = L10n::t('%1$d %2$s ago');
+ }
+
+ return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
+ }
+ }
+ }
+
+ /**
+ * @brief Returns timezone correct age in years.
+ *
+ * Returns the age in years, given a date of birth, the timezone of the person
+ * whose date of birth is provided, and the timezone of the person viewing the
+ * result.
+ *
+ * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
+ * is on New Year's. You live in San Bruno, California.
+ * When exactly are you going to see my age increase?
+ *
+ * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
+ * and become a year older. If you wish me happy birthday on January 1
+ * (San Bruno time), you'll be a day late.
+ *
+ * @param string $dob Date of Birth
+ * @param string $owner_tz (optional) Timezone of the person of interest
+ * @param string $viewer_tz (optional) Timezone of the person viewing
+ *
+ * @return int Age in years
+ */
+ public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
+ {
+ if (!intval($dob)) {
+ return 0;
+ }
+ if (!$owner_tz) {
+ $owner_tz = date_default_timezone_get();
+ }
+ if (!$viewer_tz) {
+ $viewer_tz = date_default_timezone_get();
+ }
+
+ $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
+ list($year, $month, $day) = explode("-", $birthdate);
+ $year_diff = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
+ $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
+ $curr_day = DateTimeFormat::timezoneNow($viewer_tz, 'd');
+
+ if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
+ $year_diff--;
+ }
+
+ return $year_diff;
+ }
+
+ /**
+ * @brief Get days of a month in a given year.
+ *
+ * Returns number of days in the month of the given year.
+ * $m = 1 is 'January' to match human usage.
+ *
+ * @param int $y Year
+ * @param int $m Month (1=January, 12=December)
+ *
+ * @return int Number of days in the given month
+ */
+ public static function getDaysInMonth($y, $m)
+ {
+ return date('t', mktime(0, 0, 0, $m, 1, $y));
+ }
+
+ /**
+ * @brief Returns the first day in month for a given month, year.
+ *
+ * Months start at 1.
+ *
+ * @param int $y Year
+ * @param int $m Month (1=January, 12=December)
+ *
+ * @return string day 0 = Sunday through 6 = Saturday
+ */
+ public static function getFirstDayInMonth($y, $m)
+ {
+ $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
+
+ return DateTimeFormat::utc($d, 'w');
+ }
+
+ /**
+ * @brief Output a calendar for the given month, year.
+ *
+ * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
+ * date 12 will be linked appropriately. Today's date is also noted by
+ * altering td class.
+ * Months count from 1.
+ *
+ * @param int $y Year
+ * @param int $m Month
+ * @param array $links (default null)
+ * @param string $class
+ *
+ * @return string
+ *
+ * @todo Provide (prev, next) links, define class variations for different size calendars
+ */
+ public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
+ {
+ // month table - start at 1 to match human usage.
+ $mtab = [' ',
+ 'January', 'February', 'March',
+ 'April', 'May', 'June',
+ 'July', 'August', 'September',
+ 'October', 'November', 'December'
+ ];
+
+ $thisyear = DateTimeFormat::localNow('Y');
+ $thismonth = DateTimeFormat::localNow('m');
+ if (!$y) {
+ $y = $thisyear;
+ }
+
+ if (!$m) {
+ $m = intval($thismonth);
+ }
+
+ $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
+ $f = get_first_dim($y, $m);
+ $l = get_dim($y, $m);
+ $d = 1;
+ $dow = 0;
+ $started = false;
+
+ if (($y == $thisyear) && ($m == $thismonth)) {
+ $tddate = intval(DateTimeFormat::localNow('j'));
+ }
+
+ $str_month = day_translate($mtab[$m]);
+ $o = '<table class="calendar' . $class . '">';
+ $o .= "<caption>$str_month $y</caption><tr>";
+ for ($a = 0; $a < 7; $a ++) {
+ $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
+ }
+
+ $o .= '</tr><tr>';
+
+ while ($d <= $l) {
+ if (($dow == $f) && (!$started)) {
+ $started = true;
+ }
+
+ $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
+ $o .= "<td $today>";
+ $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
+ if ($started) {
+ if (x($links, $d) !== false) {
+ $o .= "<a href=\"{$links[$d]}\">$day</a>";
+ } else {
+ $o .= $day;
+ }
+
+ $d ++;
+ } else {
+ $o .= ' ';
+ }
+
+ $o .= '</td>';
+ $dow ++;
+ if (($dow == 7) && ($d <= $l)) {
+ $dow = 0;
+ $o .= '</tr><tr>';
+ }
+ }
+
+ if ($dow) {
+ for ($a = $dow; $a < 7; $a ++) {
+ $o .= '<td> </td>';
+ }
+ }
+
+ $o .= '</tr></table>' . "\r\n";
+
+ return $o;
+ }
+}
use Friendica\Core\Config;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
+use Friendica\Util\DateTimeFormat;
use dba;
require_once 'include/dba.php';
// once daily run birthday_updates and then expire in background
$d1 = Config::get('system', 'last_expire_day');
- $d2 = intval(datetime_convert('UTC', 'UTC', 'now', 'd'));
+ $d2 = intval(DateTimeFormat::utcNow('d'));
if ($d2 != intval($d1)) {
Addon::reload();
- $d = datetime_convert();
+ $d = DateTimeFormat::utcNow();
// Only poll from those with suitable relationships,
// and which have a polling address and ignore Diaspora since
*/
switch ($contact['priority']) {
case 5:
- if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 month")) {
+ if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 month")) {
$update = true;
}
break;
case 4:
- if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 week")) {
+ if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 week")) {
$update = true;
}
break;
case 3:
- if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
+ if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
$update = true;
}
break;
case 2:
- if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 12 hour")) {
+ if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 12 hour")) {
$update = true;
}
break;
case 1:
- if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 hour")) {
+ if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 hour")) {
$update = true;
}
break;
case 0:
default:
- if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + ".$min_poll_interval." minute")) {
+ if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + ".$min_poll_interval." minute")) {
$update = true;
}
break;
use Friendica\Core\Addon;
use Friendica\Core\Config;
use Friendica\Core\Worker;
+use Friendica\Util\DateTimeFormat;
Class CronHooks {
public static function execute($hook = '') {
logger('cronhooks: start');
- $d = datetime_convert();
+ $d = DateTimeFormat::utcNow();
if (is_array($a->hooks) && array_key_exists("cron", $a->hooks)) {
foreach ($a->hooks["cron"] as $hook) {
use Friendica\Model\GContact;
use Friendica\Network\Probe;
use Friendica\Protocol\PortableContact;
+use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
require_once 'include/datetime.php';
}
} else {
q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
- dbesc(datetime_convert()), dbesc(normalise_link($user["url"])));
+ dbesc(DateTimeFormat::utcNow()), dbesc(normalise_link($user["url"])));
}
// Quit the loop after 3 minutes
use Friendica\Protocol\PortableContact;
use Friendica\Util\Network;
use Friendica\Util\XML;
+use Friendica\Util\Temporal;
+use Friendica\Util\DateTimeFormat;
use dba;
require_once 'include/dba.php';
return;
}
- $d = datetime_convert();
+ $d = DateTimeFormat::utcNow();
$contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
if (!DBM::is_result($contact)) {
// Diaspora users, archived users and followers are only checked if they still exist.
if ($contact['archive'] || ($contact["network"] == NETWORK_DIASPORA) || ($contact["rel"] == CONTACT_IS_FOLLOWER)) {
$last_updated = PortableContact::lastUpdated($contact["url"], true);
- $updated = datetime_convert();
+ $updated = DateTimeFormat::utcNow();
if ($last_updated) {
logger('Contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
$contact['priority'] = intval($poll_interval);
$hub_update = false;
- if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', $t . " + 1 day")) {
+ if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
$hub_update = true;
}
} else {
}
$last_update = (($contact['last-update'] <= NULL_DATE)
- ? datetime_convert('UTC', 'UTC', 'now - 7 days', ATOM_TIME)
- : datetime_convert('UTC', 'UTC', $contact['last-update'], ATOM_TIME)
+ ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
+ : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
);
// Update the contact entry
logger("Skipping probably dead contact ".$contact['url']);
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
return;
}
logger('Contact is marked dead');
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
return;
} else {
Contact::unmarkForArchival($contact);
logger('Ignore public contacts');
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
return;
}
logger('No self contact for user '.$importer_uid);
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
return;
}
if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
Contact::markForArchival($contact);
return;
}
Contact::markForArchival($contact);
// set the last-update so we don't keep polling
- $fields = ['last-update' => datetime_convert(), 'failure_update' => datetime_convert()];
+ $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
self::updateContact($contact, $fields);
return;
}
Contact::markForArchival($contact);
- $fields = ['last-update' => datetime_convert(), 'failure_update' => datetime_convert()];
+ $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
self::updateContact($contact, $fields);
return;
}
// we may not be friends anymore. Will keep trying for one month.
// set the last-update so we don't keep polling
- $fields = ['last-update' => datetime_convert(), 'failure_update' => datetime_convert()];
+ $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
self::updateContact($contact, $fields);
Contact::markForArchival($contact);
if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
return;
}
logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
Contact::markForArchival($contact);
return;
}
if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
return;
}
if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
Contact::markForArchival($contact);
return;
}
$mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
if ($mail_disabled) {
// set the last-update so we don't keep polling
- dba::update('contact', ['last-update' => datetime_convert()], ['id' => $contact['id']]);
+ dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
Contact::markForArchival($contact);
return;
}
unset($password);
logger("Mail: Connect to " . $mailconf['user']);
if ($mbox) {
- $fields = ['last_check' => datetime_convert()];
+ $fields = ['last_check' => DateTimeFormat::utcNow()];
dba::update('mailacct', $fields, ['id' => $mailconf['id']]);
logger("Mail: Connected to " . $mailconf['user']);
} else {
// Only delete when mails aren't automatically moved or deleted
if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
if ($meta->deleted && ! $item['deleted']) {
- $fields = ['deleted' => true, 'changed' => datetime_convert()];
+ $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
dba::update('item', $fields, ['id' => $item['id']]);
}
$datarray['title'] = notags(trim($datarray['title']));
//$datarray['title'] = notags(trim($meta->subject));
- $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
+ $datarray['created'] = DateTimeFormat::utc($meta->date);
// Is it a reply?
$reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
if (!strstr($xml, '<')) {
logger('post_handshake: response from ' . $url . ' did not contain XML.');
- $fields = ['last-update' => datetime_convert(), 'failure_update' => datetime_convert()];
+ $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
self::updateContact($contact, $fields);
Contact::markForArchival($contact);
return;
}
}
- $updated = datetime_convert();
+ $updated = DateTimeFormat::utcNow();
self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
dba::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
Contact::unmarkForArchival($contact);
} elseif (in_array($contact["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED])) {
- $updated = datetime_convert();
+ $updated = DateTimeFormat::utcNow();
self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
dba::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
Contact::markForArchival($contact);
} else {
- $updated = datetime_convert();
+ $updated = DateTimeFormat::utcNow();
dba::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
}
<?php
+
/**
* @file src/Worker/UpdateGcontact.php
*/
+
namespace Friendica\Worker;
-use Friendica\Core\Config;
use Friendica\Database\DBM;
use Friendica\Network\Probe;
use Friendica\Protocol\PortableContact;
+use Friendica\Util\DateTimeFormat;
-class UpdateGContact {
- public static function execute($contact_id) {
+class UpdateGContact
+{
+ public static function execute($contact_id)
+ {
global $a;
logger('update_gcontact: start');
$data = Probe::uri($r[0]["url"]);
if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
- if ($r[0]["server_url"] != "")
+ if ($r[0]["server_url"] != "") {
PortableContact::checkServer($r[0]["server_url"], $r[0]["network"]);
+ }
q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `id` = %d",
- dbesc(datetime_convert()), intval($contact_id));
+ dbesc(DateTimeFormat::utcNow()), intval($contact_id));
return;
}
- if (($data["name"] == "") && ($r[0]['name'] != ""))
+ if (($data["name"] == "") && ($r[0]['name'] != "")) {
$data["name"] = $r[0]['name'];
+ }
- if (($data["nick"] == "") && ($r[0]['nick'] != ""))
+ if (($data["nick"] == "") && ($r[0]['nick'] != "")) {
$data["nick"] = $r[0]['nick'];
+ }
- if (($data["addr"] == "") && ($r[0]['addr'] != ""))
+ if (($data["addr"] == "") && ($r[0]['addr'] != "")) {
$data["addr"] = $r[0]['addr'];
+ }
- if (($data["photo"] == "") && ($r[0]['photo'] != ""))
+ if (($data["photo"] == "") && ($r[0]['photo'] != "")) {
$data["photo"] = $r[0]['photo'];
+ }
q("UPDATE `gcontact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `photo` = '%s'
dbesc($data["nick"]),
dbesc($data["addr"]),
dbesc($data["photo"]),
- intval($contact_id)
- );
+ intval($contact_id)
+ );
q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `photo` = '%s'
WHERE `uid` = 0 AND `addr` = '' AND `nurl` = '%s'",
dbesc($data["addr"]),
dbesc($data["photo"]),
dbesc(normalise_link($data["url"]))
- );
+ );
q("UPDATE `contact` SET `addr` = '%s'
WHERE `uid` != 0 AND `addr` = '' AND `nurl` = '%s'",
dbesc($data["addr"]),
dbesc(normalise_link($data["url"]))
- );
+ );
}
}
--- /dev/null
+{{include file='field_input.tpl' field=$field}}<script type="text/javascript">
+ $(function () {
+ $('#id_{{$field.0}}').datetimepicker({
+ step: 5,
+ format: '{{$datetimepicker.dateformat}}',
+{{if $datetimepicker.minDate}}
+ minDate: new Date({{$datetimepicker.minDate->getTimestamp()}} * 1000),
+ yearStart: {{$datetimepicker.minDate->format('Y')}},
+{{/if}}
+{{if $datetimepicker.maxDate}}
+ maxDate: new Date({{$datetimepicker.maxDate->getTimestamp()}} * 1000),
+ yearEnd: {{$datetimepicker.maxDate->format('Y')}},
+{{/if}}
+{{if $datetimepicker.defaultDate}}
+ defaultDate: new Date({{$datetimepicker.defaultDate->getTimestamp()}} * 1000),
+{{/if}}
+ dayOfWeekStart: {{$datetimepicker.firstDay}},
+ lang: '{{$datetimepicker.lang}}'
+ });
+{{if $datetimepicker.minfrom }}
+ $('#id_{{$datetimepicker.minfrom}}').data('xdsoft_datetimepicker').setOptions({
+ onChangeDateTime: function (currentDateTime) {
+ $('#id_{{$field.0}}').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime});
+ }
+ });
+{{/if}}
+{{if $datetimepicker.maxfrom }}
+ $('#id_{{$datetimepicker.maxfrom}}').data('xdsoft_datetimepicker').setOptions({
+ onChangeDateTime: function (currentDateTime) {
+ $('#id_{{$field.0}}').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime});
+ }
+ });
+{{/if}}
+ })
+</script>
<div id="id_{{$field.0}}_wrapper" class="form-group field input">
<label for="id_{{$field.0}}" id="label_{{$field.0}}">{{$field.1}}{{if $field.4}}<span class="required"> {{$field.4}}</span>{{/if}}</label>
- <input class="form-control" name="{{$field.0}}" id="id_{{$field.0}}" {{if $field.6 eq "email"}} type="email"{{elseif $field.6 eq "url"}} type="url"{{else}} type="text"{{/if}} value="{{$field.2|escape:'html'}}" {{if $field.4 eq "required"}} required{{/if}}{{if $field.5 eq "autofocus"}} autofocus{{elseif $field.5}} {{$field.5}}{{/if}} aria-describedby="{{$field.0}}_tip">
+ <input class="form-control" name="{{$field.0}}" id="id_{{$field.0}}"{{if $field.6 eq "email"}} type="email"{{elseif $field.6 eq "url"}} type="url"{{else}} type="text"{{/if}} value="{{$field.2|escape:'html'}}"{{if $field.4 eq "required"}} required{{/if}}{{if $field.5 eq "autofocus"}} autofocus{{elseif $field.5}} {{$field.5}}{{/if}} aria-describedby="{{$field.0}}_tip">
<span id="{{$field.0}}_tip" class="help-block" role="tooltip">{{$field.3}}</span>
<div class="clear"></div>
</div>