/**
  * Setup function
  *   - Allow changes to CFG->debug for testing purposes.
  */
 protected function setUp()
 {
     global $CFG, $DB;
     parent::setUp();
     // Settings to force statistic to run during testing.
     $this->setTimezone(self::TIMEZONE);
     core_date::set_default_server_timezone();
     $CFG->statsfirstrun = 'all';
     $CFG->statslastdaily = 0;
     $CFG->statslastexecution = 0;
     // Figure out the broken day start so I can figure out when to the start time should be.
     $time = time();
     // This nonsense needs to be rewritten.
     $date = new DateTime('now', core_date::get_server_timezone_object());
     $offset = $date->getOffset();
     $stime = $time + $offset;
     $stime = intval($stime / (60 * 60 * 24)) * 60 * 60 * 24;
     $stime -= $offset;
     $shour = intval(($time - $stime) / (60 * 60));
     $CFG->statsruntimestarthour = $shour;
     $CFG->statsruntimestartminute = 0;
     if ($DB->record_exists('user', array('username' => 'user1'))) {
         return;
     }
     // Set up the database.
     $datagen = self::getDataGenerator();
     $user1 = $datagen->create_user(array('username' => 'user1'));
     $user2 = $datagen->create_user(array('username' => 'user2'));
     $course1 = $datagen->create_course(array('shortname' => 'course1'));
     $datagen->enrol_user($user1->id, $course1->id);
     $this->generate_replacement_list();
     // Reset between tests.
     $this->resetAfterTest();
 }
Exemple #2
0
/**
 * Given a $time timestamp in GMT (seconds since epoch),
 * returns an array that represents the Gregorian date in user time
 *
 * @package core
 * @category time
 * @param int $time Timestamp in GMT
 * @param float|int|string $timezone user timezone
 * @return array An array that represents the date in user time
 */
function usergetdate($time, $timezone = 99)
{
    date_default_timezone_set(core_date::get_user_timezone($timezone));
    $result = getdate($time);
    core_date::set_default_server_timezone();
    return $result;
}
Exemple #3
0
/**
 * Add an iCalendar event to the Moodle calendar.
 *
 * @param stdClass $event The RFC-2445 iCalendar event
 * @param int $courseid The course ID
 * @param int $subscriptionid The iCalendar subscription ID
 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated,  CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
 */
function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone = 'UTC')
{
    global $DB;
    // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
    if (empty($event->properties['SUMMARY'])) {
        return 0;
    }
    $name = $event->properties['SUMMARY'][0]->value;
    $name = str_replace('\\n', '<br />', $name);
    $name = str_replace('\\', '', $name);
    $name = preg_replace('/\\s+/u', ' ', $name);
    $eventrecord = new stdClass();
    $eventrecord->name = clean_param($name, PARAM_NOTAGS);
    if (empty($event->properties['DESCRIPTION'][0]->value)) {
        $description = '';
    } else {
        $description = $event->properties['DESCRIPTION'][0]->value;
        $description = clean_param($description, PARAM_NOTAGS);
        $description = str_replace('\\n', '<br />', $description);
        $description = str_replace('\\', '', $description);
        $description = preg_replace('/\\s+/u', ' ', $description);
    }
    $eventrecord->description = $description;
    // Probably a repeating event with RRULE etc. TODO: skip for now.
    if (empty($event->properties['DTSTART'][0]->value)) {
        return 0;
    }
    $tz = isset($event->properties['DTSTART'][0]->parameters['TZID']) ? $event->properties['DTSTART'][0]->parameters['TZID'] : $timezone;
    $tz = core_date::normalise_timezone($tz);
    $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
    if (empty($event->properties['DTEND'])) {
        $eventrecord->timeduration = 0;
        // no duration if no end time specified
    } else {
        $endtz = isset($event->properties['DTEND'][0]->parameters['TZID']) ? $event->properties['DTEND'][0]->parameters['TZID'] : $timezone;
        $endtz = core_date::normalise_timezone($endtz);
        $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
    }
    // Check to see if it should be treated as an all day event.
    if ($eventrecord->timeduration == DAYSECS) {
        // Check to see if the event started at Midnight on the imported calendar.
        date_default_timezone_set($timezone);
        if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
            // This event should be an all day event.
            $eventrecord->timeduration = 0;
        }
        core_date::set_default_server_timezone();
    }
    $eventrecord->uuid = $event->properties['UID'][0]->value;
    $eventrecord->timemodified = time();
    // Add the iCal subscription details if required.
    // We should never do anything with an event without a subscription reference.
    $sub = calendar_get_subscription($subscriptionid);
    $eventrecord->subscriptionid = $subscriptionid;
    $eventrecord->userid = $sub->userid;
    $eventrecord->groupid = $sub->groupid;
    $eventrecord->courseid = $sub->courseid;
    $eventrecord->eventtype = $sub->eventtype;
    if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid))) {
        $eventrecord->id = $updaterecord->id;
        $return = CALENDAR_IMPORT_EVENT_UPDATED;
        // Update.
    } else {
        $return = CALENDAR_IMPORT_EVENT_INSERTED;
        // Insert.
    }
    if ($createdevent = calendar_event::create($eventrecord, false)) {
        if (!empty($event->properties['RRULE'])) {
            // Repeating events.
            date_default_timezone_set($tz);
            // Change time zone to parse all events.
            $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
            $rrule->parse_rrule();
            $rrule->create_events($createdevent);
            core_date::set_default_server_timezone();
            // Change time zone back to what it was.
        }
        return $return;
    } else {
        return 0;
    }
}
Exemple #4
0
    $CFG->ostype = 'WINDOWS';
} else {
    $CFG->ostype = 'UNIX';
}
$CFG->os = PHP_OS;
// Configure ampersands in URLs
ini_set('arg_separator.output', '&amp;');
// Work around for a PHP bug   see MDL-11237
ini_set('pcre.backtrack_limit', 20971520);
// 20 MB
// Work around for PHP7 bug #70110. See MDL-52475 .
if (ini_get('pcre.jit')) {
    ini_set('pcre.jit', 0);
}
// Set PHP default timezone to server timezone.
core_date::set_default_server_timezone();
// Location of standard files
$CFG->wordlist = $CFG->libdir . '/wordlist.txt';
$CFG->moddata = 'moddata';
// neutralise nasty chars in PHP_SELF
if (isset($_SERVER['PHP_SELF'])) {
    $phppos = strpos($_SERVER['PHP_SELF'], '.php');
    if ($phppos !== false) {
        $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos + 4);
    }
    unset($phppos);
}
// initialise ME's - this must be done BEFORE starting of session!
initialise_fullme();
// define SYSCONTEXTID in config.php if you want to save some queries,
// after install it must match the system context record id.
Exemple #5
0
 /**
  * Returns a list of files the user has formated for files api
  *
  * @param string $search A search string to do full text search on the documents
  * @return mixed Array of files formated for fileapoi
  */
 public function get_file_list($search = '')
 {
     global $CFG, $OUTPUT;
     $url = self::DOCUMENTFEED_URL;
     if ($search) {
         $url .= '?q=' . urlencode($search);
     }
     $files = array();
     $content = $this->googleoauth->get($url);
     try {
         if (strpos($content, '<?xml') !== 0) {
             throw new moodle_exception('invalidxmlresponse');
         }
         $xml = new SimpleXMLElement($content);
     } catch (Exception $e) {
         // An error occured while trying to parse the XML, let's just return nothing. SimpleXML does not
         // return a more specific Exception, that's why the global Exception class is caught here.
         return $files;
     }
     date_default_timezone_set(core_date::get_user_timezone());
     foreach ($xml->entry as $gdoc) {
         $docid = (string) $gdoc->children('http://schemas.google.com/g/2005')->resourceId;
         list($type, $docid) = explode(':', $docid);
         $title = '';
         $source = '';
         // FIXME: We're making hard-coded choices about format here.
         // If the repo api can support it, we could let the user
         // chose.
         switch ($type) {
             case 'document':
                 $title = $gdoc->title . '.rtf';
                 $source = 'https://docs.google.com/feeds/download/documents/Export?id=' . $docid . '&exportFormat=rtf';
                 break;
             case 'presentation':
                 $title = $gdoc->title . '.ppt';
                 $source = 'https://docs.google.com/feeds/download/presentations/Export?id=' . $docid . '&exportFormat=ppt';
                 break;
             case 'spreadsheet':
                 $title = $gdoc->title . '.xls';
                 $source = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=' . $docid . '&exportFormat=xls';
                 break;
             case 'pdf':
             case 'file':
                 $title = (string) $gdoc->title;
                 // Some files don't have a content probably because the download has been restricted.
                 if (isset($gdoc->content)) {
                     $source = (string) $gdoc->content[0]->attributes()->src;
                 }
                 break;
         }
         $files[] = array('title' => $title, 'url' => "{$gdoc->link[0]->attributes()->href}", 'source' => $source, 'date' => strtotime($gdoc->updated), 'thumbnail' => (string) $OUTPUT->pix_url(file_extension_icon($title, 32)));
     }
     core_date::set_default_server_timezone();
     return $files;
 }
Exemple #6
0
 public function test_set_default_server_timezone()
 {
     global $CFG;
     $this->resetAfterTest();
     $this->setTimezone('Europe/Prague', 'Pacific/Auckland');
     unset($CFG->timezone);
     date_default_timezone_set('UTC');
     core_date::set_default_server_timezone();
     $this->assertSame('Pacific/Auckland', date_default_timezone_get());
     $this->setTimezone('', 'Pacific/Auckland');
     date_default_timezone_set('UTC');
     core_date::set_default_server_timezone();
     $this->assertSame('Pacific/Auckland', date_default_timezone_get());
     $this->setTimezone('99', 'Pacific/Auckland');
     date_default_timezone_set('UTC');
     core_date::set_default_server_timezone();
     $this->assertSame('Pacific/Auckland', date_default_timezone_get());
     $this->setTimezone(99, 'Pacific/Auckland');
     date_default_timezone_set('UTC');
     core_date::set_default_server_timezone();
     $this->assertSame('Pacific/Auckland', date_default_timezone_get());
     $this->setTimezone('Europe/Prague', 'Pacific/Auckland');
     $CFG->timezone = 'UTC';
     core_date::set_default_server_timezone();
     $this->assertSame('UTC', date_default_timezone_get());
     $this->setTimezone('Europe/Prague', 'Pacific/Auckland');
     $CFG->timezone = 'Australia/Perth';
     core_date::set_default_server_timezone();
     $this->assertSame('Australia/Perth', date_default_timezone_get());
     $this->setTimezone('0', 'Pacific/Auckland');
     date_default_timezone_set('UTC');
     core_date::set_default_server_timezone();
     $this->assertSame('Etc/GMT', date_default_timezone_get());
     $this->setTimezone('1', 'Pacific/Auckland');
     date_default_timezone_set('UTC');
     core_date::set_default_server_timezone();
     $this->assertSame('Etc/GMT-1', date_default_timezone_get());
     $this->setTimezone(1, 'Pacific/Auckland');
     date_default_timezone_set('UTC');
     core_date::set_default_server_timezone();
     $this->assertSame('Etc/GMT-1', date_default_timezone_get());
     $this->setTimezone('1.0', 'Pacific/Auckland');
     date_default_timezone_set('UTC');
     core_date::set_default_server_timezone();
     $this->assertSame('Etc/GMT-1', date_default_timezone_get());
 }
 /**
  * Change server and default php timezones.
  *
  * @param string $servertimezone timezone to set in $CFG->timezone (not validated)
  * @param string $defaultphptimezone timezone to fake default php timezone (must be valid)
  */
 public static function setTimezone($servertimezone = 'Australia/Perth', $defaultphptimezone = 'Australia/Perth')
 {
     global $CFG;
     $CFG->timezone = $servertimezone;
     core_date::phpunit_override_default_php_timezone($defaultphptimezone);
     core_date::set_default_server_timezone();
 }
Exemple #8
0
/**
 * Start of month
 * @param int $time timestamp
 * @return int start of month
 */
function stats_get_base_monthly($time = 0)
{
    if (empty($time)) {
        $time = time();
    }
    core_date::set_default_server_timezone();
    $return = strtotime(date('1-M-Y', $time));
    return $return;
}
Exemple #9
0
 /**
  * Returns a formatted string that represents a date in user time.
  *
  * Returns a formatted string that represents a date in user time
  * <b>WARNING: note that the format is for strftime(), not date().</b>
  * Because of a bug in most Windows time libraries, we can't use
  * the nicer %e, so we have to use %d which has leading zeroes.
  * A lot of the fuss in the function is just getting rid of these leading
  * zeroes as efficiently as possible.
  *
  * If parameter fixday = true (default), then take off leading
  * zero from %d, else maintain it.
  *
  * @param int $time the timestamp in UTC, as obtained from the database
  * @param string $format strftime format
  * @param int|float|string $timezone the timezone to use
  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
  * @param bool $fixday if true then the leading zero from %d is removed,
  *        if false then the leading zero is maintained
  * @param bool $fixhour if true then the leading zero from %I is removed,
  *        if false then the leading zero is maintained
  * @return string the formatted date/time
  */
 public function timestamp_to_date_string($time, $format, $timezone, $fixday, $fixhour)
 {
     global $CFG;
     if (empty($format)) {
         $format = get_string('strftimedaydatetime', 'langconfig');
     }
     if (!empty($CFG->nofixday)) {
         // Config.php can force %d not to be fixed.
         $fixday = false;
     } else {
         if ($fixday) {
             $formatnoday = str_replace('%d', 'DD', $format);
             $fixday = $formatnoday != $format;
             $format = $formatnoday;
         }
     }
     // Note: This logic about fixing 12-hour time to remove unnecessary leading
     // zero is required because on Windows, PHP strftime function does not
     // support the correct 'hour without leading zero' parameter (%l).
     if (!empty($CFG->nofixhour)) {
         // Config.php can force %I not to be fixed.
         $fixhour = false;
     } else {
         if ($fixhour) {
             $formatnohour = str_replace('%I', 'HH', $format);
             $fixhour = $formatnohour != $format;
             $format = $formatnohour;
         }
     }
     $time = (int) $time;
     // Moodle allows rubbish in input...
     $datestring = date_format_string($time, $format, $timezone);
     date_default_timezone_set(\core_date::get_user_timezone($timezone));
     if ($fixday) {
         $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $time)));
         $datestring = str_replace('DD', $daystring, $datestring);
     }
     if ($fixhour) {
         $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $time)));
         $datestring = str_replace('HH', $hourstring, $datestring);
     }
     \core_date::set_default_server_timezone();
     return $datestring;
 }
Exemple #10
0
 /**
  * Calculate when this task should next be run based on the schedule.
  * @return int $nextruntime.
  */
 public function get_next_scheduled_time()
 {
     global $CFG;
     $validminutes = $this->eval_cron_field($this->minute, self::MINUTEMIN, self::MINUTEMAX);
     $validhours = $this->eval_cron_field($this->hour, self::HOURMIN, self::HOURMAX);
     // We need to change to the server timezone before using php date() functions.
     \core_date::set_default_server_timezone();
     $daysinmonth = date("t");
     $validdays = $this->eval_cron_field($this->day, 1, $daysinmonth);
     $validdaysofweek = $this->eval_cron_field($this->dayofweek, 0, 7);
     $validmonths = $this->eval_cron_field($this->month, 1, 12);
     $nextvalidyear = date('Y');
     $currentminute = date("i") + 1;
     $currenthour = date("H");
     $currentday = date("j");
     $currentmonth = date("n");
     $currentdayofweek = date("w");
     $nextvalidminute = $this->next_in_list($currentminute, $validminutes);
     if ($nextvalidminute < $currentminute) {
         $currenthour += 1;
     }
     $nextvalidhour = $this->next_in_list($currenthour, $validhours);
     if ($nextvalidhour < $currenthour) {
         $currentdayofweek += 1;
         $currentday += 1;
     }
     $nextvaliddayofmonth = $this->next_in_list($currentday, $validdays);
     $nextvaliddayofweek = $this->next_in_list($currentdayofweek, $validdaysofweek);
     $daysincrementbymonth = $nextvaliddayofmonth - $currentday;
     if ($nextvaliddayofmonth < $currentday) {
         $daysincrementbymonth += $daysinmonth;
     }
     $daysincrementbyweek = $nextvaliddayofweek - $currentdayofweek;
     if ($nextvaliddayofweek < $currentdayofweek) {
         $daysincrementbyweek += 7;
     }
     // Special handling for dayofmonth vs dayofweek:
     // if either field is * - use the other field
     // otherwise - choose the soonest (see man 5 cron).
     if ($this->dayofweek == '*') {
         $daysincrement = $daysincrementbymonth;
     } else {
         if ($this->day == '*') {
             $daysincrement = $daysincrementbyweek;
         } else {
             // Take the smaller increment of days by month or week.
             $daysincrement = $daysincrementbymonth;
             if ($daysincrementbyweek < $daysincrementbymonth) {
                 $daysincrement = $daysincrementbyweek;
             }
         }
     }
     $nextvaliddayofmonth = $currentday + $daysincrement;
     if ($nextvaliddayofmonth > $daysinmonth) {
         $currentmonth += 1;
         $nextvaliddayofmonth -= $daysinmonth;
     }
     $nextvalidmonth = $this->next_in_list($currentmonth, $validmonths);
     if ($nextvalidmonth < $currentmonth) {
         $nextvalidyear += 1;
     }
     // Work out the next valid time.
     $nexttime = mktime($nextvalidhour, $nextvalidminute, 0, $nextvalidmonth, $nextvaliddayofmonth, $nextvalidyear);
     return $nexttime;
 }