Exemple #1
0
/**
 * Returns a float which represents the user's timezone difference from GMT in hours
 * Checks various settings and picks the most dominant of those which have a value
 * @deprecated since Moodle 2.9
 * @param float|int|string $tz timezone user timezone
 * @return float
 */
function get_user_timezone_offset($tz = 99)
{
    debugging('get_user_timezone_offset() is deprecated, use PHP DateTimeZone instead', DEBUG_DEVELOPER);
    $tz = core_date::get_user_timezone($tz);
    $date = new DateTime('now', new DateTimeZone($tz));
    return ($date->getOffset() - dst_offset_on(time(), $tz)) / 3600.0;
}
Exemple #2
0
 /**
  * Test for the forum email renderable postdate.
  *
  * @dataProvider postdate_provider
  *
  * @param array  $globalconfig      The configuration to set on $CFG
  * @param array  $forumconfig       The configuration for this forum
  * @param array  $postconfig        The configuration for this post
  * @param array  $discussionconfig  The configuration for this discussion
  * @param string $expectation       The expected date
  */
 public function test_postdate($globalconfig, $forumconfig, $postconfig, $discussionconfig, $expectation)
 {
     global $CFG, $DB;
     $this->resetAfterTest(true);
     // Apply the global configuration.
     foreach ($globalconfig as $key => $value) {
         $CFG->{$key} = $value;
     }
     // Create the fixture.
     $user = $this->getDataGenerator()->create_user();
     $course = $this->getDataGenerator()->create_course();
     $forum = $this->getDataGenerator()->create_module('forum', (object) array('course' => $course->id));
     $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
     $this->getDataGenerator()->enrol_user($user->id, $course->id);
     // Create a new discussion.
     $discussion = $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion((object) array_merge($discussionconfig, array('course' => $course->id, 'forum' => $forum->id, 'userid' => $user->id)));
     // Apply the discussion configuration.
     // Some settings are ignored by the generator and must be set manually.
     $discussion = $DB->get_record('forum_discussions', array('id' => $discussion->id));
     foreach ($discussionconfig as $key => $value) {
         $discussion->{$key} = $value;
     }
     $DB->update_record('forum_discussions', $discussion);
     // Apply the post configuration.
     // Some settings are ignored by the generator and must be set manually.
     $post = $DB->get_record('forum_posts', array('discussion' => $discussion->id));
     foreach ($postconfig as $key => $value) {
         $post->{$key} = $value;
     }
     $DB->update_record('forum_posts', $post);
     // Create the renderable.
     $renderable = new mod_forum\output\forum_post_email($course, $cm, $forum, $discussion, $post, $user, $user, true);
     // Check the postdate matches our expectations.
     $this->assertEquals(userdate($expectation, "", \core_date::get_user_timezone($user)), $renderable->get_postdate());
 }
    public function date($message, $viewmail = false) {
        $tz = core_date::get_user_timezone();
        $date = new DateTime('now', new DateTimeZone($tz));
        $offset = ($date->getOffset() - dst_offset_on(time(), $tz)) / (3600.0);
        $time = ($offset < 13) ? $message->time() + $offset : $message->time();
        $now = ($offset < 13) ? time() + $offset : time();
        $daysago = floor($now / 86400) - floor($time / 86400);
        $yearsago = (int) date('Y', $now) - (int) date('Y', $time);
        $tooltip = userdate($time, get_string('strftimedatetime'));

        if ($viewmail) {
            $content = userdate($time, get_string('strftimedatetime'));
            $tooltip = '';
        } else if ($daysago == 0) {
            $content = userdate($time, get_string('strftimetime'));
        } else if ($yearsago == 0) {
            $content = userdate($time, get_string('strftimedateshort'));
        } else {
            $content = userdate($time, get_string('strftimedate'));
        }

        return html_writer::tag('span', s($content), array('class' => 'mail_date', 'title' => $tooltip));
    }
Exemple #4
0
/**
 * @global object
 * @param object $message message to be displayed.
 * @param mixed $chatuser user chat data
 * @param object $currentuser current user for whom the message should be displayed.
 * @param int $groupingid course module grouping id
 * @param string $theme name of the chat theme.
 * @return bool|string Returns HTML or false
 */
function chat_format_message_theme($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble')
{
    global $CFG, $USER, $OUTPUT, $COURSE, $DB, $PAGE;
    require_once $CFG->dirroot . '/mod/chat/locallib.php';
    static $users;
    // Cache user lookups.
    $result = new stdClass();
    if (file_exists($CFG->dirroot . '/mod/chat/gui_ajax/theme/' . $theme . '/config.php')) {
        include $CFG->dirroot . '/mod/chat/gui_ajax/theme/' . $theme . '/config.php';
    }
    if (isset($users[$message->userid])) {
        $sender = $users[$message->userid];
    } else {
        if ($sender = $DB->get_record('user', array('id' => $message->userid), user_picture::fields())) {
            $users[$message->userid] = $sender;
        } else {
            return null;
        }
    }
    // Find the correct timezone for displaying this message.
    $tz = core_date::get_user_timezone($currentuser);
    if (empty($chatuser->course)) {
        $courseid = $COURSE->id;
    } else {
        $courseid = $chatuser->course;
    }
    $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
    $message->picture = $OUTPUT->user_picture($sender, array('courseid' => $courseid));
    $message->picture = "<a target='_blank'" . " href=\"{$CFG->wwwroot}/user/view.php?id={$sender->id}&amp;course={$courseid}\">{$message->picture}</a>";
    // Start processing the message.
    if (!empty($message->system)) {
        $result->type = 'system';
        $senderprofile = $CFG->wwwroot . '/user/view.php?id=' . $sender->id . '&amp;course=' . $courseid;
        $event = get_string('message' . $message->message, 'chat', fullname($sender));
        $eventmessage = new event_message($senderprofile, fullname($sender), $message->strtime, $event, $theme);
        $output = $PAGE->get_renderer('mod_chat');
        $result->html = $output->render($eventmessage);
        return $result;
    }
    // It's not a system event.
    $text = trim($message->message);
    // Parse the text to clean and filter it.
    $options = new stdClass();
    $options->para = false;
    $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
    // And now check for special cases.
    $special = false;
    $outtime = $message->strtime;
    // Initialise variables.
    $outmain = '';
    $patternto = '#^\\s*To\\s([^:]+):(.*)#';
    if (substr($text, 0, 5) == 'beep ') {
        $special = true;
        // It's a beep!
        $result->type = 'beep';
        $beepwho = trim(substr($text, 5));
        if ($beepwho == 'all') {
            // Everyone.
            $outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
        } else {
            if ($beepwho == $currentuser->id) {
                // Current user.
                $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
            } else {
                if ($sender->id == $currentuser->id) {
                    // Something is not caught?
                    // Allow beep for a active chat user only, else user can beep anyone and get fullname.
                    if (!empty($chatuser) && is_numeric($beepwho)) {
                        $chatusers = chat_get_users($chatuser->chatid, $chatuser->groupid, $groupingid);
                        if (array_key_exists($beepwho, $chatusers)) {
                            $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
                        } else {
                            $outmain = get_string('messageyoubeep', 'chat', $beepwho);
                        }
                    } else {
                        $outmain = get_string('messageyoubeep', 'chat', $beepwho);
                    }
                }
            }
        }
    } else {
        if (substr($text, 0, 1) == '/') {
            // It's a user command.
            $special = true;
            $result->type = 'command';
            $pattern = '#(^\\/)(\\w+).*#';
            preg_match($pattern, $text, $matches);
            $command = isset($matches[2]) ? $matches[2] : false;
            // Support some IRC commands.
            switch ($command) {
                case 'me':
                    $outmain = '*** <b>' . $sender->firstname . ' ' . substr($text, 4) . '</b>';
                    break;
                default:
                    // Error, we set special back to false to use the classic message output.
                    $special = false;
                    break;
            }
        } else {
            if (preg_match($patternto, $text)) {
                $special = true;
                $result->type = 'dialogue';
                $matches = array();
                preg_match($patternto, $text, $matches);
                if (isset($matches[1]) && isset($matches[2])) {
                    $outmain = $sender->firstname . ' <b>' . get_string('saidto', 'chat') . '</b> <i>' . $matches[1] . '</i>: ' . $matches[2];
                } else {
                    // Error, we set special back to false to use the classic message output.
                    $special = false;
                }
            }
        }
    }
    if (!$special) {
        $outmain = $text;
    }
    $result->text = strip_tags($outtime . ': ' . $outmain);
    $mymessageclass = '';
    if ($sender->id == $USER->id) {
        $mymessageclass = 'chat-message-mymessage';
    }
    $senderprofile = $CFG->wwwroot . '/user/view.php?id=' . $sender->id . '&amp;course=' . $courseid;
    $usermessage = new user_message($senderprofile, fullname($sender), $message->picture, $mymessageclass, $outtime, $outmain, $theme);
    $output = $PAGE->get_renderer('mod_chat');
    $result->html = $output->render($usermessage);
    // When user beeps other user, then don't show any timestamp to other users in chat.
    if ('' === $outmain && $special) {
        return false;
    } else {
        return $result;
    }
}
Exemple #5
0
/**
 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
 * - Note: Daylight saving only works for string timezones and not for float.
 *
 * @package core
 * @category time
 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
 * @param int|float|string $strtimezone user timezone
 * @return int
 */
function dst_offset_on($time, $strtimezone = null)
{
    $tz = core_date::get_user_timezone($strtimezone);
    $date = new DateTime('@' . $time);
    $date->setTimezone(new DateTimeZone($tz));
    if ($date->format('I') == '1') {
        if ($tz === 'Australia/Lord_Howe') {
            return 1800;
        }
        return 3600;
    }
    return 0;
}
Exemple #6
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 #7
0
/**
 * Given the data about a posting, builds up the HTML to display it and
 * returns the HTML in a string.  This is designed for sending via HTML email.
 *
 * @global object
 * @param object $course
 * @param object $cm
 * @param object $forum
 * @param object $discussion
 * @param object $post
 * @param object $userform
 * @param object $userto
 * @param bool $ownpost
 * @param bool $reply
 * @param bool $link
 * @param bool $rate
 * @param string $footer
 * @return string
 */
function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $ownpost = false, $reply = false, $link = false, $rate = false, $footer = "")
{
    global $CFG, $OUTPUT;
    $modcontext = context_module::instance($cm->id);
    if (!isset($userto->viewfullnames[$forum->id])) {
        $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
    } else {
        $viewfullnames = $userto->viewfullnames[$forum->id];
    }
    // add absolute file links
    $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
    // format the post body
    $options = new stdClass();
    $options->para = true;
    $formattedtext = format_text($post->message, $post->messageformat, $options, $course->id);
    $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
    $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
    $output .= $OUTPUT->user_picture($userfrom, array('courseid' => $course->id));
    $output .= '</td>';
    if ($post->parent) {
        $output .= '<td class="topic">';
    } else {
        $output .= '<td class="topic starter">';
    }
    $output .= '<div class="subject">' . format_string($post->subject) . '</div>';
    $fullname = fullname($userfrom, $viewfullnames);
    $by = new stdClass();
    $by->name = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $userfrom->id . '&amp;course=' . $course->id . '">' . $fullname . '</a>';
    $by->date = userdate($post->modified, '', core_date::get_user_timezone($userto));
    $output .= '<div class="author">' . get_string('bynameondate', 'forum', $by) . '</div>';
    $output .= '</td></tr>';
    $output .= '<tr><td class="left side" valign="top">';
    if (isset($userfrom->groups)) {
        $groups = $userfrom->groups[$forum->id];
    } else {
        $groups = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
    }
    if ($groups) {
        $output .= print_group_picture($groups, $course->id, false, true, true);
    } else {
        $output .= '&nbsp;';
    }
    $output .= '</td><td class="content">';
    $attachments = forum_print_attachments($post, $cm, 'html');
    if ($attachments !== '') {
        $output .= '<div class="attachments">';
        $output .= $attachments;
        $output .= '</div>';
    }
    $output .= $formattedtext;
    // Commands
    $commands = array();
    if ($post->parent) {
        $commands[] = '<a target="_blank" href="' . $CFG->wwwroot . '/mod/forum/discuss.php?d=' . $post->discussion . '&amp;parent=' . $post->parent . '">' . get_string('parent', 'forum') . '</a>';
    }
    if ($reply) {
        $commands[] = '<a target="_blank" href="' . $CFG->wwwroot . '/mod/forum/post.php?reply=' . $post->id . '">' . get_string('reply', 'forum') . '</a>';
    }
    $output .= '<div class="commands">';
    $output .= implode(' | ', $commands);
    $output .= '</div>';
    // Context link to post if required
    if ($link) {
        $output .= '<div class="link">';
        $output .= '<a target="_blank" href="' . $CFG->wwwroot . '/mod/forum/discuss.php?d=' . $post->discussion . '#p' . $post->id . '">' . get_string('postincontext', 'forum') . '</a>';
        $output .= '</div>';
    }
    if ($footer) {
        $output .= '<div class="footer">' . $footer . '</div>';
    }
    $output .= '</td></tr></table>' . "\n\n";
    return $output;
}
Exemple #8
0
 public function test_get_user_timezone()
 {
     global $CFG, $USER;
     $this->resetAfterTest();
     // Null parameter.
     $this->setTimezone('Europe/Prague', 'Pacific/Auckland');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = '99';
     $this->assertSame('Pacific/Auckland', core_date::get_user_timezone(null));
     $this->assertSame('Pacific/Auckland', core_date::get_user_timezone());
     $this->setTimezone('Europe/Prague', 'Pacific/Auckland');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = 'Europe/Berlin';
     $this->assertSame('Europe/Berlin', core_date::get_user_timezone(null));
     $this->assertSame('Europe/Berlin', core_date::get_user_timezone());
     $this->setTimezone('Europe/Prague', 'Pacific/Auckland');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = 'xxx/yyy';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone(null));
     $this->assertSame('Europe/Prague', core_date::get_user_timezone());
     $this->setTimezone('Europe/Prague', 'Pacific/Auckland');
     $USER->timezone = 'abc/def';
     $CFG->forcetimezone = '99';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone(null));
     $this->assertSame('Europe/Prague', core_date::get_user_timezone());
     $this->setTimezone('xxx/yyy', 'Europe/London');
     $USER->timezone = 'abc/def';
     $CFG->forcetimezone = 'Europe/Berlin';
     $this->assertSame('Europe/Berlin', core_date::get_user_timezone(null));
     $this->assertSame('Europe/Berlin', core_date::get_user_timezone());
     $this->setTimezone('xxx/yyy', 'Europe/London');
     $USER->timezone = 'abc/def';
     $CFG->forcetimezone = 99;
     $this->assertSame('Europe/London', core_date::get_user_timezone(null));
     $this->assertSame('Europe/London', core_date::get_user_timezone());
     // User object parameter.
     $admin = get_admin();
     $this->setTimezone('Europe/London');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = '99';
     $admin->timezone = 'Australia/Perth';
     $this->assertSame('Australia/Perth', core_date::get_user_timezone($admin));
     $this->setTimezone('Europe/Prague');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = '99';
     $admin->timezone = '99';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone($admin));
     $this->setTimezone('99', 'Europe/London');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = '99';
     $admin->timezone = '99';
     $this->assertSame('Europe/London', core_date::get_user_timezone($admin));
     $this->setTimezone('Europe/Prague');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = '99';
     $admin->timezone = 'xx/zz';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone($admin));
     $this->setTimezone('Europe/Prague');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = '99';
     unset($admin->timezone);
     $this->assertSame('Europe/Prague', core_date::get_user_timezone($admin));
     $this->setTimezone('Europe/Prague');
     $USER->timezone = 'Pacific/Auckland';
     $CFG->forcetimezone = 'Europe/Berlin';
     $admin->timezone = 'Australia/Perth';
     $this->assertSame('Europe/Berlin', core_date::get_user_timezone($admin));
     // Other scalar parameter.
     $this->setTimezone('Europe/Prague');
     $CFG->forcetimezone = '99';
     $USER->timezone = 'Pacific/Auckland';
     $this->assertSame('Pacific/Auckland', core_date::get_user_timezone('99'));
     $this->assertSame('Etc/GMT-1', core_date::get_user_timezone('1'));
     $this->assertSame('Etc/GMT+1', core_date::get_user_timezone(-1));
     $this->assertSame('Europe/London', core_date::get_user_timezone('Europe/London'));
     $USER->timezone = '99';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone('99'));
     $this->assertSame('Europe/London', core_date::get_user_timezone('Europe/London'));
     $this->assertSame('Europe/Prague', core_date::get_user_timezone('xxx/zzz'));
     $USER->timezone = 'xxz/zzz';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone('99'));
     $this->setTimezone('99', 'Europe/Prague');
     $CFG->forcetimezone = '99';
     $USER->timezone = 'Pacific/Auckland';
     $this->assertSame('Pacific/Auckland', core_date::get_user_timezone('99'));
     $this->assertSame('Europe/London', core_date::get_user_timezone('Europe/London'));
     $USER->timezone = '99';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone('99'));
     $this->assertSame('Europe/London', core_date::get_user_timezone('Europe/London'));
     $this->assertSame('Europe/Prague', core_date::get_user_timezone('xxx/zzz'));
     $USER->timezone = 99;
     $this->assertSame('Europe/London', core_date::get_user_timezone('Europe/London'));
     $this->assertSame('Europe/Prague', core_date::get_user_timezone('xxx/zzz'));
     $USER->timezone = 'xxz/zzz';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone('99'));
     $this->setTimezone('xxx', 'Europe/Prague');
     $CFG->forcetimezone = '99';
     $USER->timezone = 'xxx';
     $this->assertSame('Europe/Prague', core_date::get_user_timezone('99'));
     $this->assertSame('Europe/Prague', core_date::get_user_timezone(99));
     $this->assertSame('Etc/GMT-1', core_date::get_user_timezone(1));
     $this->setTimezone('Europe/Prague');
     $CFG->forcetimezone = 'Pacific/Auckland';
     $USER->timezone = 'Europe/London';
     $this->assertSame('Pacific/Auckland', core_date::get_user_timezone(99));
     $this->assertSame('Europe/Berlin', core_date::get_user_timezone('Europe/Berlin'));
     // TZ object param.
     $this->setTimezone('UTC');
     $USER->timezone = 'Europe/London';
     $CFG->forcetimezone = 99;
     $tz = new DateTimeZone('Pacific/Auckland');
     $this->assertSame('Pacific/Auckland', core_date::get_user_timezone($tz));
 }
Exemple #9
0
// we need hotpot/lib.php for the callback validation functions
require_once $CFG->dirroot . '/mod/hotpot/lib.php';
require_once $CFG->dirroot . '/mod/hotpot/locallib.php';
// admin_setting_xxx classes are defined in "lib/adminlib.php"
// new admin_setting_configcheckbox($name, $visiblename, $description, $defaultsetting);
// show Quizports on MyMoodle page (default=1)
$settings->add(new admin_setting_configcheckbox('hotpot_enablemymoodle', get_string('enablemymoodle', 'mod_hotpot'), get_string('configenablemymoodle', 'mod_hotpot'), 1));
// enable caching of browser content for each quiz (default=1)
$str = get_string('clearcache', 'mod_hotpot');
$url = new moodle_url('/mod/hotpot/tools/clear_cache.php', array('sesskey' => sesskey()));
$link = html_writer::link($url, $str, array('class' => 'small', 'style' => 'white-space: nowrap', 'onclick' => "this.target='_blank'")) . "\n";
$settings->add(new admin_setting_configcheckbox('hotpot_enablecache', get_string('enablecache', 'mod_hotpot'), get_string('configenablecache', 'mod_hotpot') . ' ' . $link, 1));
// restrict cron job to certain hours of the day (default=never)
if (class_exists('core_date') && method_exists('core_date', 'get_user_timezone')) {
    // Moodle >= 2.9
    $timezone = core_date::get_user_timezone(99);
    $datetime = new DateTime('now', new DateTimeZone($timezone));
    $timezone = ($datetime->getOffset() - dst_offset_on(time(), $timezone)) / 3600.0;
} else {
    // Moodle <= 2.8
    $timezone = get_user_timezone_offset();
}
if (abs($timezone) > 13) {
    $timezone = 0;
} else {
    if ($timezone > 0) {
        $timezone = $timezone - 24;
    }
}
$options = array();
for ($i = 0; $i <= 23; $i++) {
Exemple #10
0
 /**
  * this is a very cut down version of what is in forum_make_mail_post
  *
  * @global object
  * @param int $post
  * @return string
  */
 private function prepare_post($post, $fileoutputextras = null)
 {
     global $DB;
     static $users;
     if (empty($users)) {
         $users = array($this->user->id => $this->user);
     }
     if (!array_key_exists($post->userid, $users)) {
         $users[$post->userid] = $DB->get_record('user', array('id' => $post->userid));
     }
     // add the user object on to the post so we can pass it to the leap writer if necessary
     $post->author = $users[$post->userid];
     $viewfullnames = true;
     // format the post body
     $options = portfolio_format_text_options();
     $format = $this->get('exporter')->get('format');
     $formattedtext = format_text($post->message, $post->messageformat, $options, $this->get('course')->id);
     $formattedtext = portfolio_rewrite_pluginfile_urls($formattedtext, $this->modcontext->id, 'mod_forum', 'post', $post->id, $format);
     $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
     $output .= '<tr class="header"><td>';
     // can't print picture.
     $output .= '</td>';
     if ($post->parent) {
         $output .= '<td class="topic">';
     } else {
         $output .= '<td class="topic starter">';
     }
     $output .= '<div class="subject">' . format_string($post->subject) . '</div>';
     $fullname = fullname($users[$post->userid], $viewfullnames);
     $by = new stdClass();
     $by->name = $fullname;
     $by->date = userdate($post->modified, '', core_date::get_user_timezone($this->user));
     $output .= '<div class="author">' . get_string('bynameondate', 'forum', $by) . '</div>';
     $output .= '</td></tr>';
     $output .= '<tr><td class="left side" valign="top">';
     $output .= '</td><td class="content">';
     $output .= $formattedtext;
     if (is_array($this->keyedfiles) && array_key_exists($post->id, $this->keyedfiles) && is_array($this->keyedfiles[$post->id]) && count($this->keyedfiles[$post->id]) > 0) {
         $output .= '<div class="attachments">';
         $output .= '<br /><b>' . get_string('attachments', 'forum') . '</b>:<br /><br />';
         foreach ($this->keyedfiles[$post->id] as $file) {
             $output .= $format->file_output($file) . '<br/ >';
         }
         $output .= "</div>";
     }
     $output .= '</td></tr></table>' . "\n\n";
     return $output;
 }
/**
 * Construct an array with subtitution rules for mail templates, relating to
 * a single appointment. Any of the parameters can be null.
 * @param scheduler_instance $scheduler The scheduler instance
 * @param scheduler_slot $slot The slot data as an MVC object
 * @param user $attendant A {@link $USER} object describing the attendant (teacher)
 * @param user $attendee A {@link $USER} object describing the attendee (student)
 * @param object $course A course object relating to the ontext of the message
 * @param object $recipient A {@link $USER} object describing the recipient of the message (used for determining the message language)
 * @return array A hash with mail template substitutions
 */
function scheduler_get_mail_variables(scheduler_instance $scheduler, scheduler_slot $slot, $attendant, $attendee, $course, $recipient)
{
    global $CFG;
    $lang = scheduler_get_message_language($recipient, $course);
    // Force any string formatting to happen in the target language.
    $oldlang = force_current_language($lang);
    $tz = core_date::get_user_timezone($recipient);
    $vars = array();
    if ($scheduler) {
        $vars['MODULE'] = $scheduler->name;
        $vars['STAFFROLE'] = $scheduler->get_teacher_name();
        $vars['SCHEDULER_URL'] = $CFG->wwwroot . '/mod/scheduler/view.php?id=' . $scheduler->cmid;
    }
    if ($slot) {
        $vars['DATE'] = userdate($slot->starttime, get_string('strftimedate'), $tz);
        $vars['TIME'] = userdate($slot->starttime, get_string('strftimetime'), $tz);
        $vars['ENDTIME'] = userdate($slot->endtime, get_string('strftimetime'), $tz);
        $vars['LOCATION'] = format_string($slot->appointmentlocation);
    }
    if ($attendant) {
        $vars['ATTENDANT'] = fullname($attendant);
        $vars['ATTENDANT_URL'] = $CFG->wwwroot . '/user/view.php?id=' . $attendant->id . '&course=' . $scheduler->course;
    }
    if ($attendee) {
        $vars['ATTENDEE'] = fullname($attendee);
        $vars['ATTENDEE_URL'] = $CFG->wwwroot . '/user/view.php?id=' . $attendee->id . '&course=' . $scheduler->course;
    }
    // Reset language settings.
    force_current_language($oldlang);
    return $vars;
}
Exemple #12
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 #13
0
 /**
  * The date of the post, formatted according to the postto user's
  * preferences.
  *
  * @return string.
  */
 public function get_postdate()
 {
     return userdate($this->post->modified, "", \core_date::get_user_timezone($this->get_postto()));
 }
Exemple #14
0
 /**
  * Return user's deadlines from the calendar.
  *
  * Usually called twice, once for all deadlines from today, then any from the next 12 months up to the
  * max requested.
  *
  * Based on the calender function calendar_get_upcoming.
  *
  * @param \stdClass|int $userorid
  * @param array $courses ids of all user's courses.
  * @param int $maxevents to return
  * @param bool $todayonly true if only the next 24 hours to be returned
  * @return array
  */
 private static function get_upcoming_deadlines($userorid, $courses, $maxevents, $todayonly = false)
 {
     $user = self::get_user($userorid);
     if (!$user) {
         return [];
     }
     // We need to do this so that we can calendar events and mod visibility for a specific user.
     self::swap_global_user($user);
     $tz = new \DateTimeZone(\core_date::get_user_timezone($user));
     $today = new \DateTime('today', $tz);
     $tomorrow = new \DateTime('tomorrow', $tz);
     if ($todayonly === true) {
         $starttime = $today->getTimestamp();
         $endtime = $tomorrow->getTimestamp() - 1;
     } else {
         $starttime = $tomorrow->getTimestamp();
         $endtime = $starttime + 365 * DAYSECS - 1;
     }
     $userevents = false;
     $groupevents = false;
     $events = calendar_get_events($starttime, $endtime, $userevents, $groupevents, $courses);
     $processed = 0;
     $output = array();
     foreach ($events as $event) {
         if ($event->eventtype === 'course') {
             // Not an activity deadline.
             continue;
         }
         if ($event->eventtype === 'open' && $event->timeduration == 0) {
             // Only the opening of multi-day event, not a deadline.
             continue;
         }
         if (!empty($event->modulename)) {
             $modinfo = get_fast_modinfo($event->courseid);
             $mods = $modinfo->get_instances_of($event->modulename);
             if (isset($mods[$event->instance])) {
                 $cminfo = $mods[$event->instance];
                 if (!$cminfo->uservisible) {
                     continue;
                 }
                 if ($event->eventtype === 'close') {
                     // Revert the addition of e.g. "(Quiz closes)" to the event name.
                     $event->name = $cminfo->name;
                 }
             }
         }
         $output[$event->id] = $event;
         ++$processed;
         if ($processed >= $maxevents) {
             break;
         }
     }
     self::swap_global_user(false);
     return $output;
 }
Exemple #15
0
 /**
  * The date of the post, formatted according to the postto user's
  * preferences.
  *
  * @return string.
  */
 public function get_postdate()
 {
     global $CFG;
     $postmodified = $this->post->modified;
     if (!empty($CFG->forum_enabletimedposts) && $this->discussion->timestart > $postmodified) {
         $postmodified = $this->discussion->timestart;
     }
     return userdate($postmodified, "", \core_date::get_user_timezone($this->get_postto()));
 }