Steps to reproduce

Note that @mparker17 tried these steps in comment #23 and could not reproduce the problem.

  1. Set up a fresh Drupal installation
  2. Install the Date module
  3. Create new content type with a date field
  4. Add content of that type.

Observed behavior:

  1. The following errors are displayed:
    Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 384 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 384 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 384 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 384 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 384 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 384 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 384 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::setTimezone(): The DateTime object has not been correctly initialized by its constructor in DateObject->setTimezone() (line 358 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::setDate(): The DateTime object has not been correctly initialized by its constructor in DateObject->setTimezone() (line 359 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::setTime(): The DateTime object has not been correctly initialized by its constructor in DateObject->setTimezone() (line 360 of [...]\sites\all\modules\date\date_api\date_api.module).
    Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 384 of [...]\sites\all\modules\date\date_api\date_api.module).
        

Desired behaviour:

  1. No warnings.

Problem/Motivation

In some circumstances, interacting with the Date API submodule's DateObject class can result in errors like: The DateTime object has not been correctly initialized by its constructor.

This has been observed to happen when error_reporting is set to 32767 (E_ALL) on the following PHP versions:

  • PHP 5.4.38
  • PHP 5.5.24

This is probably because the parent constructor (DateTime::__construct()) is not being called, because, apparently, "parent constructors are not called implicitly if the child class defines a constructor" ( http://php.net/manual/en/language.oop5.decon.php ).

Proposed resolution

Explicitly call parent::__construct() from DateObject::__construct().

Remaining tasks

  1. Write a patch
  2. Review and RTBC
  3. Commit

User interface changes

None.

API changes

None.

Comments

Max1’s picture

Max1’s picture

Max1’s picture

Max1’s picture

date-7.x-2.x-dev is throwing the same error, but with other numbers - 392, 366, 367, 368.

Max1’s picture

Max1’s picture

Hmm... It does not reproduce on simplytest.me

derekw’s picture

I get the same error. On my site it occurs when a http:// page request gets redirected to a https:// page request by the securepages module. (It shows the request to https:// as the location for the error, and the http:// version as the referral source.)

If I visit the https:// page directly, no error.

My totally unsubstantiated guess is that the error is caused by a spider visiting those pages and not having some date-related headers set correctly.

Max1’s picture

I was trying to on/off/change different date-related options and in the some moment errors disappeared. Sorry but for now I cannot localize that was the cause of the errors in my case. Maybe it was some poisoned cache... I did not reset it when changed options. I will reinstall and re-check it in some days.

katannshaw’s picture

I'm receiving these same warnings as well when users visit a specific view for news items on our site. It's a simple view, so I'm not sure why there's suddenly an issue. I first noticed the issue after applying patch #70 from issue report 2294973 (see comment #93) but I'm not sure if it's related.

I see these warnings from anonymous users and authenticated users alike, so it's not related to the Secure Pages module in my instance.

And a Google search pulls up several other sites with the same error: http://goo.gl/4yfRdS

mparker17’s picture

Version: 7.x-2.8 » 7.x-2.x-dev
Component: Code » Date API
Priority: Normal » Major

I can confirm this happens on the 7.x-2.x version of the module.

I think this meets the criteria for a Major bug, as it is a PHP error which is only triggered under rare circumstances or which affects only a small percentage of all users.

The errors happen in date_api.module, so changing the component.

Seems like this is a duplicate of #2280211: Fatal error: Call to a member function format() on a non-object in date_api.module on line 1797 and is probably related to #1923630: Warning: DateTime::getTimezone(): The DateTime object has not been correctly initialized by its constructor.


In addition to all of the above errors, I also get a similar error on line 283:

Warning: DateTime::getTimezone(): The DateTime object has not been correctly initialized by its constructor in DateObject->__construct() (line 283 of sites/all/modules/date/date_api/date_api.module).
mparker17’s picture

Upon inspection, calling parent::__construct() in the first line of \DateObject::__construct() stops all the warnings I was seeing.

katannshaw’s picture

@mparker17: Glad to know that I'm now alone. Forgive my newbie question: is your suggestion to put this on line 284 of date.module.api?

parent::__construct();

mparker17’s picture

Status: Active » Needs review
StatusFileSize
new708 bytes

I'm guessing these errors are happening because the parent constructor is not being called — from the PHP.net documentation page on constructors and deconstructors:

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Here's a patch that adds the parent::__construct() call. Feedback is very much welcome!

mparker17’s picture

Issue summary: View changes

Updating the issue summary.

katannshaw’s picture

Thanks for the patch mparker17. I tried to run the patch and it failed. I then manually applied the patch by entering parent::__construct(); onto the first line of the __contstruct() function (Line 198) and cleared the cache, but I'm still seeing the errors. I noticed that you marked the PHP version you've observed this on as 5.4.38 and I'm running 5.5.24.

mparker17’s picture

@jayhawkfan75, I've tested the patch and it applies cleanly to 7.x-2.7, 7.x-2.8, 7.x-2.9-rc1, and the latest commit to 7.x-2.x-dev, and seems to fix the errors for me. If it applies properly and fixes the errors for you, please post that here and mark the issue as "Reviewed & tested by the community".

See the handbook page on applying patches if you need help applying the patch.

mparker17’s picture

Title: Error with DateTime::format() » Incorrectly-initialized DateTime object(s) cause PHP warnings in DateTime::format(), other DateObject functions

More-meaningful title.

mparker17’s picture

Issue summary: View changes

Adding PHP 5.5.24 to the issue summary as per #17.

mparker17’s picture

@jayhawkfan75, I should have mentioned earlier that, if the patch doesn't work for you, please provide more information about which version of Drupal 7 and the Date module you are using, and mark the issue as "Needs work".

katannshaw’s picture

Status: Needs review » Needs work

@mparker17: Thanks. I'm running Drupal 7.37 and Date 7.x-2.8.

I tried applying the patch using NetBeans via Tools/Apply Diff Patch... as usual and that's when it failed for me. I also tried it on an install that uses Drupal 7.38 and Date 7.x-2.8.

mparker17’s picture

Issue summary: View changes
Issue tags: +Needs manual testing

@jayhawkfan75, I switched my environment to use PHP 5.5.22, Drupal 7.37, Date 7.x-2.8, and I cannot reproduce the errors using the Steps to Reproduce in the issue description neither before nor after applying the patch in #15.

Can you please post (in a comment) some Steps to Reproduce the errors you're seeing? Ideally start from a fresh installation of Drupal.

This will help me to figure out what's wrong and correct the patch.

Thanks!

katannshaw’s picture

Will do. I'll post the results soon.

mparker17’s picture

@jayhawkfan75, have you had any luck reproducing the problem? Is there anything I can help with?

katannshaw’s picture

@mparker17: Sorry, been busy in my one-person shop over here.

Concerning the error, after further troubleshooting I now believe that it's an issue with a specific view on my site. It's only one specific view block that's having the issue. So I won't worry about steps to reproduce, as that's why you weren't able to reproduce the error.

Concerning the patch, I ran the patch again to view the more detailed patch output report. Here it is:
May 13, 2015 2:22:02 PM ===================
applying patch: error_with-2457423-14.patch
--- Successfully Patched ---

--- Failed ---
sites\all\modules\date\date_api\date_api.module (Cannot apply hunk @@ 6 )

katannshaw’s picture

@mparker17: Any luck on the patch? I'm ready to try it again whenever you're ready. Thanks for your help with that.

dsdeiz’s picture

The patch here applies cleanly on date 7.x-2.9-rc1 on my end. It also solves the error I have.

sagannotcarl’s picture

Status: Needs work » Needs review
StatusFileSize
new436 bytes

The patch above seems to be copied out of an email.

Here is a reformatted version that should apply more easily.

mparker17’s picture

@sagannotcarl, I include a bit of extra metadata in my patches so that the patch doesn't need to be re-rolled as often. patch(1) will still work with this format because it ignores any lines at the beginning of the patchfile up to the first valid header line.

It works because, in Git 1.7.12, git-apply was changed so that when a patch does not apply cleanly, it falls back on a 3-way merge if the patch records the identity of the commit it is supposed to apply to (which my patchfile does, on the very first line), and Git has that commit available locally (which any clone of the module will).

If you're interested in how to generate this type of patch yourself, I've written a blog post to explain how.

bmateus’s picture

I was seeing the error at line 392. Applied the patch and it still remained.

Added the parent::__construct(); to the beginning of the offending function (in my case, function format($format, $force = FALSE) on line 391), and it fixed it.

katannshaw’s picture

@bmateus: I just tried your fix on #31 and it worked for me as well. The php warnings are now gone from my logs. This is what that function looks like for me now (on Line 384 in my case?!):

  public function format($format, $force = FALSE) {
    parent::__construct();
    return parent::format($force ? $format : date_limit_format($format, $this->granularity));
  }

Thank you for your help!

UPDATE: Unfortunately I spoke too soon. After this change I started receiving these errors in my PHP logs which kept crashing the site:

[05-Aug-2015 15:01:52 America/Chicago] PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 24 bytes) in sites\all\modules\date\date_api\date_api.module on line 1351
[05-Aug-2015 16:29:28 America/Chicago] PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 79 bytes) in sites\all\modules\date\date_api\date_api.module on line 1377
[05-Aug-2015 16:31:39 America/Chicago] PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 36 bytes) in sites\all\modules\date\date_api\date_api.module on line 1352
[05-Aug-2015 17:16:34 America/Chicago] PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 36 bytes) in sites\all\modules\date\date_api\date_api.module on line 1354

So I had to remove parent::__construct(); from that function.

istryker’s picture

Status: Needs review » Needs work

Error on line 392 confirm. PHP 5.6 Apache 2.4. I think this problem comes from 5.4.x

ashzade’s picture

Patch #24 worked for me. No more wall of errors!

katannshaw’s picture

Still receiving errors on Line 392 with Date 7.x-2.9, PHP 5.5.29 and Patch #15. @iStryker has a good question about whether the errors on Line 384 could be specific to PHP 5.4 users. Would PHP versions matter? @ashgotti: are you using 5.3, 5.4 or 5.5?

bmateus’s picture

@jayhawkfan75 It definitely has something to do with PHP versions. I was on 5.3, and updated to 5.5 resulted in "winning" this error...

In any case, I had to revert what I done in #31. The errors were gone, but every date field became 'now'! So back to the drawing board.

bmateus’s picture

StatusFileSize
new472 bytes

Ok, not sure if it solves everyone, but for me (on PHP 5.5.2), the only solution was to change line 392 on version 7.x-2.9+1-dev, from
return parent::format($force ? $format : date_limit_format($format, $this->granularity));
to
return @parent::format($force ? $format : date_limit_format($format, $this->granularity));

Everything else either crashed the site, or made funny bugs like turning all fields to 'now' value.

I've uploaded a patch, but I'm a newbie at patching - dunno how to test - so please someone a kind soul could test it for me? :)

katannshaw’s picture

Status: Needs work » Needs review

@bmateus: I just applied your #37 patch at it's working swimmingly! No errors in the logs when visiting that view. I'll keep an eye on the logs for errors and post back tomorrow but it's looking good. Thanks!

If others running PHP 5.5+ could please test that would be great.

Status: Needs review » Needs work

The last submitted patch, 37: error_with-2457423-36.patch, failed testing.

nicrodgers’s picture

Adding the @ to ignore the error isn't really fixing the underlying cause of the problem.

Michele Wickham’s picture

Not seeing the error with PHP 5.5.9-1, but I am seeing it on Pantheon with PHP version 5.5.24. Patch #37 did not work for me.

derekw’s picture

Could the cause of this be misconfigured browsers/spiders/bots with bad time zone configurations? I have only one page that generates this error according to the logs. The page is a registration form with one date field in it (both start and end dates).

I suspect a spider browser is the cause because I cannot cause the error by visiting that page with any of my browsers. Also our site is set to run all https:// but the Incorrectly-initialized DateTime object(s) error always shows the referrer as the http:// version which is not coming from browsing our site (the client is redirected from the http:// version to https://version on all pages).

derekw’s picture

For what it's worth, I suspect this theme function of mine may be what's triggering the errors, just because I'll get so many errors from one page view/visitor.

When from and to dates are within the same month, this is supposed to eliminate the second month in the display.
i.e. Instead of October 30 - October 31, it would display as October 30-31

function mytheme_date_display_range($variables) {
  $date1 = $variables['date1'];  
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  if ($variables['dates']['value'] && $variables['dates']['value2'] && $variables['dates']['format'] == 'F j') { // Have a range
    $date1month = date_format_date($variables['dates']['value']['local']['object'],'custom','F');
    $date2month = date_format_date($variables['dates']['value2']['local']['object'],'custom','F');
    $date2day = date_format_date($variables['dates']['value2']['local']['object'],'custom','j');
    //if months of the range are the same, omit the second month
    if ($date1month === $date2month){
        $date2 = $date2day;
    }
  } 
  // Wrap the result with the attributes.
  return t('!start-date-!end-date', array(
    '!start-date' => '<span class="date-display-start"' . drupal_attributes($attributes_start) . '>' . $date1 . '</span>',
    '!end-date' => '<span class="date-display-end"' . drupal_attributes($attributes_end) . '>' . $date2 . $timezone . '</span>',
  ));
}
ninabyte’s picture

I also get this error on my Drupal 7.41 site. It's happened with both Date 7.x-2.x-dev and 7.x-2.9. Server is running PHP 5.4.45. The patch in #29 fixes the error but sets all of my events to 'now', so I undid that.

I noticed that this only happens on one page, which consists of a handful of views. To troubleshoot, I built one of these views again from scratch with auto-preview turned on. Everything was going swimmingly until I added a date filter to display Event nodes that only take place on X date, at which point auto-preview stopped working. When I was first troubleshooting this, I thought that the error seemed erratic, as most of my views use reference date fields but this was only happening on one page. The page that was originally showing this error consists of views that are filtered by date, and this is the only page on this site that references Date as a filter parameter in any way. I've tried to create other views to test this out and the error shows up consistently in views that filter by date.

ckellyirish’s picture

Ok, I think I know what's going on here. If a user provides a value of '+1' for the time parameter when constructing a DateObject, the constructor will mistakenly assume that the user has entered a Unix timestamp, and prepends it with a '@'. Of Course, '@+1' is not a valid timestamp, so the constructor fails to initialize the object properly, and so warnings start appearing all over whenever the object's methods are called.

If you want to see this happen yourself, here's the steps to reproduce:

1: Install the Date Module.
2. Enable Date and Date API.
2. Create new content type with a Date Field.
3. In the 'Default Values' section, select 'Relative' for Default date and enter '+1' for 'Relative default value'.
4. Save the new content type.
5. Create a new node of that content type.

And php warnings everywhere!

I've attached a patch that solves this issue. ninabyte & jayhawkfan75, can you let me know if this patch solves your issues?

Additionally, I'm wondering if the validation on 'Relative default value' should be improved to let the user know that they might be making a mistake. On the one hand, '+1' is a valid datetime string, but on the other, it's far more likely that somebody's going to accidentally enter it when they meant to enter something like '+1 week'.

ckellyirish’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 46: incorrectly-initialized-datetime-object-2457423-46.patch, failed testing.

ckellyirish’s picture

Status: Needs work » Needs review
StatusFileSize
new715 bytes

Oops! Sorry about that last patch causing failing tests, this one should be good.

captainack’s picture

FYI #15 worked like a charm for me. Thanks!

In my case, the error would only appear when there was a failed form validation (e.g. end date before start date).

jenlampton’s picture

I was also able to generate this error by deleting YEAR from my short date format, and then adjusting exposed date filters on a view from January to Decembner and back again. See https://www.drupal.org/node/2630762

anpolimus’s picture

@ckellyirish, your patch is fixing existed problem but fails other time-zone test cases.
Patch # 15 is fixing this problem too, but fails Timezone test cases.

alansaunders92’s picture

I was getting the same error, when default values had been set for the start and end dates which appeared after updating to the latest stable version 7.x-2.9. Removing the default values removed the errors.

So I added in parent::__construct(); to the function as suggested in #15 and #31 and this has fixed the errors that I was having.

alansaunders92’s picture

However, after testing.
Every node with the event content type now defaults to the current date and time when you go to the edit screen, even when the date and time that was set were not the current date, removing the line of code I added in parent::__construct(); made it work again but brought the errors back.

Even replacing the function using the code #32

 public function format($format, $force = FALSE) {
    parent::__construct();
    return parent::format($force ? $format : date_limit_format($format, $this->granularity));
  }

Fixed the issue in terms of removing the errors, but does give the same issue of the date and time is defaulting the current date and time even when the date and time is in the future, but if a end date is set, it is not being shown. Reverting the change back fixes the issue.

alansaunders92’s picture

I have worked out that the errors seem to be displaying when a default value has been set for the end date.
In my case, the relative date was set to relative with +1.
Changing the end date from relative to now.
Appears to have removed the errors and fixed all the issues that I was having.

vishal.sheladiya’s picture

I have 2 field collection form and added date field in both form.
1st form contain start date and end date. while 2nd form contain only start date and browse field,
now when i select start date grater that end date from 1st form, and in 2nd form i only upload image at that time i am getting
Notice: Undefined index: timezone in date_field_validate() (line 364 of \sites\all\modules\date\date.field.inc).
Notice: Undefined index: timezone in date_field_validate() (line 369 of \sites\all\modules\date\date.field.inc)
error.
i already applied patch-15 but it removes most of all error except these two.
also from admin config, i've not selected hours, min, sec., i only need month year and day.

alex awg 2015’s picture

Assigned: Unassigned » alex awg 2015
alex awg 2015’s picture

Status: Needs review » Reviewed & tested by the community

It's good.

jshosseini’s picture

hi, patch in #15 solved my problem. thanks

akolahi’s picture

Status: Reviewed & tested by the community » Needs work

Applied the patches. Appears to have reduced the number of 'DateTime object has not been correctly initialized' errors, but still getting the error at this location as well:

public function format($format, $force = FALSE) {
return parent::format($force ? $format : date_limit_format($format, $this->granularity));

error: Warning: DateTime::format(): The DateTime object has not been correctly initialized by its constructor in DateObject->format() (line 393

brad.bulger’s picture

fwiw, I was getting this error as a result of the initial $time parameter being NULL. I changed it to handle NULL the same way it would handle a string and that seems to have fixed it.

cameron prince’s picture

#15 worked for me as well, using PHP v5.6.

vali hutchison’s picture

Same as #55 for me - when using a relative end date I got these errors. When switching to no default value the errors stopped.

trumanru’s picture

I'd had the situation described in #46 (relative +1 default date value).

Patch #49 solved my problem.
I've applied both patches - #15 and #49.

trumanru’s picture

Status: Needs work » Needs review
liam morland’s picture

Reroll of #49.

damienmckenna’s picture

Assigned: alex awg 2015 » Unassigned
chris matthews’s picture

The rerolled patch in #66 applied cleanly to the latest 7.x-2.x-dev and fixes this issue for me.

liam morland’s picture

Reroll of #66.

damienmckenna’s picture

Status: Needs review » Needs work
Issue tags: -Needs manual testing +Needs tests

Lets add some tests for this, and thankfully ckellyirish provided some steps for reproducing the error so this should be

1: Install the Date Module.
2. Enable Date and Date API.
2. Create new content type with a Date Field.
3. In the 'Default Values' section, select 'Relative' for Default date and enter '+1' for 'Relative default value'.
4. Save the new content type.
5. Create a new node of that content type.

And php warnings everywhere!

wylbur’s picture

This patch resolved errors using date 7.x-2.11-beta2 with php 7.1

Not sure if that helps anything, but it works!

liam morland’s picture

Status: Needs work » Needs review
StatusFileSize
new2.58 KB

Patch #69 with test as described in #70. This test fails without the fix.

wylbur’s picture

Status: Needs review » Reviewed & tested by the community

We reapplied this patch to the latest release 7.x-2.11-beta3 and it is working as expected.

Drupal 7.69
Date 7.x-2.11-beta3
PHP 7.3

Marking this as RTBC

damienmckenna’s picture

Excellent work, everyone. Let's add this to the next release.

damienmckenna’s picture

StatusFileSize
new2.73 KB

Reroll after #3111299 was committed.

damienmckenna’s picture

  • DamienMcKenna committed 9539b0a on 7.x-2.x
    Issue #2457423 by Liam Morland, ckellyirish, mparker17, DamienMcKenna,...
damienmckenna’s picture

Status: Reviewed & tested by the community » Fixed
Issue tags: -Needs tests

Committed. Thank you all.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.