/** * This function writes out the message div so the message can be viewed. * * @param object $record This is the DB record for the message to write out * @param string $outputbuffer The output html code will be written here. * */ private function write_message_div($record, &$outputbuffer) { global $DB, $USER; $timesent = $record->timesent; $time = userdate($timesent, '%H:%M'); $dates = usergetdate($timesent); $userfrom = block_course_message_map_ids_to_names($record->useridfrom, 'inbox'); $userto = block_course_message_map_ids_to_names($record->recipients, 'sent'); $outputbuffer .= "<div class='message_div_bar'><div class='message_bar_to'><span class='label'>To:</span>\n <span class='field'> {$userto}</span></div>"; if ($record->carboncopy !== null) { $carboncopy = block_course_message_map_ids_to_names($record->carboncopy, 'sent'); $outputbuffer .= "<div class='message_bar_to'><span class='label'>CC:</span>\n <span class='field'> {$carboncopy}</span></div>"; } $outputbuffer .= "<div class='message_bar_from'><span class='label'>From:</span><span class='field'> {$userfrom}</span>\n </div><div class='message_bar_time'>{$time} {$dates['month']} {$dates['mday']}</div>"; $outputbuffer .= "<div class='clear'></div></div>"; $outputbuffer .= "<div class='message_container"; if ($USER->id == $record->useridfrom) { $outputbuffer .= " usersent'>"; } else { $outputbuffer .= " userrecieved'>"; } // Message has already been cleaned when sent. $outputbuffer .= "<div class='message_div_body'>{$record->message}</div>"; $this->process_attachment($record, $outputbuffer); // Close the message container div. $outputbuffer .= "</div>"; }
function definition() { global $CFG, $USER, $DB, $COURSE; $mform =& $this->_form; // Don't forget the underscore! //check reportend make sure that if $this->userid != $USER->id that they have //the correct capability TODO /* $canmanage = false; if(has_capability('block/timetracker:manageworkers',$this->context)){ $canmanage = true; } */ //$userinfo = $DB->get_record('block_timetracker_workerinfo', // array('id'=>$this->userid)); /* $index = new moodle_url($CFG->wwwroot.'/blocks/timetracker/index.php', array('id'=>$this->courseid,'userid'=>$this->userid)); */ $index = new moodle_url($CFG->wwwroot . 'blocks/timetracker/'); /* if(!$canmanage && $USER->id != $userinfo->mdluserid){ redirect($nextpage,'You do not have permission to generate this report.',1); } */ $categoryinfo = $DB->get_record('course_categories', array('id' => $this->catid)); if (!$categoryinfo) { $mform->addElement('header', 'general', 'Report Generator'); } else { $mform->addElement('header', 'general', 'Report Generator for ' . $categoryinfo->name); } $now = time(); if ($this->reportstart == 0 || $this->reportend == 0) { $starttime = usergetdate($now); $starttime_mid = make_timestamp($starttime['year'], $starttime['mon'] - 1, $starttime['mday']); $this->reportstart = $starttime_mid; $endtime = usergetdate($now); $endtime_mid = make_timestamp($endtime['year'], $endtime['mon'], $endtime['mday']); $this->reportend = $endtime_mid; } $buttonarray = array(); $buttonarray[] =& $mform->createElement('submit', 'conflicts', 'Conflicts'); $buttonarray[] =& $mform->createElement('submit', 'earningsactive', 'Earnings - active workers only'); $buttonarray[] =& $mform->createElement('submit', 'earningsall', 'Earnings - all workers'); $mform->addElement('html', 'Please provide a date and time range for the report(s) you wish to generate.'); $mform->addElement('date_selector', 'reportstart', 'Start Date: ', array('optional' => false, 'step' => 1)); $mform->setDefault('reportstart', $this->reportstart); $mform->addElement('date_selector', 'reportend', 'End Date: ', array('optional' => false, 'step' => 1)); $mform->setDefault('reportend', $this->reportend); $mform->addElement('hidden', 'catid', $this->catid); //$mform->addElement('hidden','userid', $this->userid); $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false); $mform->closeHeaderBefore('buttonar'); }
public function __construct(local_attendance $att) { global $PAGE; $this->pageparams = $att->pageparams; $this->curdate = $att->pageparams->curdate; $date = usergetdate($att->pageparams->curdate); $mday = $date['mday']; $wday = $date['wday']; $mon = $date['mon']; $year = $date['year']; switch ($this->pageparams->view) { case LOCAL_ATT_VIEW_DAYS: $format = get_string('strftimedm', 'local_attendance'); $this->prevcur = make_timestamp($year, $mon, $mday - 1); $this->nextcur = make_timestamp($year, $mon, $mday + 1); $this->curdatetxt = userdate($att->pageparams->startdate, $format); break; case LOCAL_ATT_VIEW_WEEKS: $format = get_string('strftimedm', 'local_attendance'); $this->prevcur = $att->pageparams->startdate - WEEKSECS; $this->nextcur = $att->pageparams->startdate + WEEKSECS; $this->curdatetxt = userdate($att->pageparams->startdate, $format) . " - " . userdate($att->pageparams->enddate, $format); break; case LOCAL_ATT_VIEW_MONTHS: $format = '%B'; $this->prevcur = make_timestamp($year, $mon - 1); $this->nextcur = make_timestamp($year, $mon + 1); $this->curdatetxt = userdate($att->pageparams->startdate, $format); break; } $this->urlpath = $PAGE->url->out_omit_querystring(); $params = $att->pageparams->get_significant_params(); $params['id'] = $att->id; $this->urlparams = $params; $this->att = $att; }
function organizer_add_calendar() { global $PAGE, $DB; $courseid = optional_param('course', SITEID, PARAM_INT); if ($courseid != SITEID && !empty($courseid)) { $course = $DB->get_record('course', array('id' => $courseid)); $courses = array($course->id => $course); $issite = false; } else { $course = get_site(); $courses = calendar_get_default_courses(); $issite = true; } $now = usergetdate(time()); $calendar = new calendar_information($now['mday'], $now['mon'], $now['year']); $calendar->prepare_for_view($course, $courses); $renderer = $PAGE->get_renderer('core_calendar'); $calendar->add_sidecalendar_blocks($renderer, true, 'month'); $PAGE->requires->js_init_call('M.mod_organizer.fix_calendar_styles'); }
public function get_content() { global $COURSE; if ($this->content !== null) { return $this->content; } // Create empty content. $this->content = new stdClass(); $this->content->text = ''; // Use Strict as this block should only ever be in a course context. $context = context_course::instance($this->page->course->id); if (!has_capability('block/eclass_course_management:canseeblock', $context)) { return $this->content->text = ''; } $open = EclassCourseManager::get_course_open($context->instanceid); $close = EclassCourseManager::get_course_close($context->instanceid); if ($open) { $date = usergetdate($open); $this->content->text .= '<br/>' . get_string('open_label', 'block_eclass_course_management') . ' ' . "{$date['month']} {$date['mday']}, {$date['year']}"; } else { $this->content->text .= '<br/>' . get_string('nostartdate', 'block_eclass_course_management'); } if ($close) { $date = usergetdate($close); $this->content->text .= '<br/>' . get_string('close_label', 'block_eclass_course_management') . ' ' . "{$date['month']} {$date['mday']}, {$date['year']}"; } else { $this->content->text .= '<br/>' . get_string('noenddate', 'block_eclass_course_management'); } if ($COURSE->visible) { $this->content->text .= '<br/>' . get_string('status_label', 'block_eclass_course_management') . ' ' . get_string('visible', 'block_eclass_course_management'); } else { $this->content->text .= '<br/>' . get_string('status_label', 'block_eclass_course_management') . ' ' . get_string('notvisible', 'block_eclass_course_management'); } if (!empty($this->content->text)) { $this->content->text = get_string('blockpreamble', 'block_eclass_course_management') . '<br/>' . $this->content->text; } if (has_capability('moodle/course:update', $context)) { $this->content->text .= "<br/><a href='/blocks/eclass_course_management/configure.php?course={$COURSE->id}'>Edit</a>"; } return $this->content; }
/** * Helper function to return an array of messages. * * @param int $userid * @param array $messages * @return array */ public static function create_messages($userid, $messages) { // Store the messages. $arrmessages = array(); // We always view messages from oldest to newest, ensure we have it in that order. $lastmessage = end($messages); $firstmessage = reset($messages); if ($lastmessage->timecreated < $firstmessage->timecreated) { $messages = array_reverse($messages); } // Keeps track of the last day, month and year combo we were viewing. $day = ''; $month = ''; $year = ''; foreach ($messages as $message) { // Check if we are now viewing a different block period. $displayblocktime = false; $date = usergetdate($message->timecreated); if ($day != $date['mday'] || $month != $date['month'] || $year != $date['year']) { $day = $date['mday']; $month = $date['month']; $year = $date['year']; $displayblocktime = true; } // Store the message to pass to the renderable. $msg = new \stdClass(); $msg->id = $message->id; $msg->text = message_format_message_text($message); $msg->currentuserid = $userid; $msg->useridfrom = $message->useridfrom; $msg->useridto = $message->useridto; $msg->displayblocktime = $displayblocktime; $msg->timecreated = $message->timecreated; $msg->timeread = $message->timeread; $arrmessages[] = $msg; } return $arrmessages; }
/** * This is a shortcut for making an hour selector menu. * * @param string $type The type of selector (years, months, days, hours, minutes) * @param string $name fieldname * @param int $currenttime A default timestamp in GMT * @param int $step minute spacing * @param array $attributes - html select element attributes * @return HTML fragment */ public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) { if (!$currenttime) { $currenttime = time(); } $currentdate = usergetdate($currenttime); $userdatetype = $type; $timeunits = array(); switch ($type) { case 'years': for ($i = 1970; $i <= 2020; $i++) { $timeunits[$i] = $i; } $userdatetype = 'year'; break; case 'months': for ($i = 1; $i <= 12; $i++) { $timeunits[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), "%B"); } $userdatetype = 'month'; $currentdate['month'] = (int) $currentdate['mon']; break; case 'days': for ($i = 1; $i <= 31; $i++) { $timeunits[$i] = $i; } $userdatetype = 'mday'; break; case 'hours': for ($i = 0; $i <= 23; $i++) { $timeunits[$i] = sprintf("%02d", $i); } break; case 'minutes': if ($step != 1) { $currentdate['minutes'] = ceil($currentdate['minutes'] / $step) * $step; } for ($i = 0; $i <= 59; $i += $step) { $timeunits[$i] = sprintf("%02d", $i); } break; default: throw new coding_exception("Time type {$type} is not supported by html_writer::select_time()."); } if (empty($attributes['id'])) { $attributes['id'] = self::random_id('ts_'); } $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, $attributes); $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for' => $attributes['id'], 'class' => 'accesshide')); return $label . $timerselector; }
function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true, $showtime = 0) { $startdate = usergetdate($event->timestart); $enddate = usergetdate($event->timestart + $event->timeduration); $usermidnightstart = usergetmidnight($event->timestart); if ($event->timeduration) { // To avoid doing the math if one IF is enough :) $usermidnightend = usergetmidnight($event->timestart + $event->timeduration); } else { $usermidnightend = $usermidnightstart; } // OK, now to get a meaningful display... // First of all we have to construct a human-readable date/time representation if ($event->timeduration) { // It has a duration if ($usermidnightstart == $usermidnightend || $event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399) || $event->timestart + $event->timeduration <= $usermidnightstart + 86400) { // But it's all on the same day $timestart = calendar_time_representation($event->timestart); $timeend = calendar_time_representation($event->timestart + $event->timeduration); $time = $timestart . ' <strong>»</strong> ' . $timeend; if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) { $time = get_string('allday', 'calendar'); } // Set printable representation if (!$showtime) { $day = calendar_day_representation($event->timestart, $now, $usecommonwords); $eventtime = calendar_get_link_tag($day, CALENDAR_URL . 'view.php?view=day' . $morehref . '&', $enddate['mday'], $enddate['mon'], $enddate['year']) . ', ' . $time; } else { $eventtime = $time; } } else { // It spans two or more days $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', '; if ($showtime == $usermidnightstart) { $daystart = ''; } $timestart = calendar_time_representation($event->timestart); $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', '; if ($showtime == $usermidnightend) { $dayend = ''; } $timeend = calendar_time_representation($event->timestart + $event->timeduration); // Set printable representation if ($now >= $usermidnightstart && $now < $usermidnightstart + 86400) { $eventtime = $timestart . ' <strong>»</strong> ' . calendar_get_link_tag($dayend, CALENDAR_URL . 'view.php?view=day' . $morehref . '&', $enddate['mday'], $enddate['mon'], $enddate['year']) . $timeend; } else { $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL . 'view.php?view=day' . $morehref . '&', $startdate['mday'], $startdate['mon'], $startdate['year']) . $timestart . ' <strong>»</strong> ' . calendar_get_link_tag($dayend, CALENDAR_URL . 'view.php?view=day' . $morehref . '&', $enddate['mday'], $enddate['mon'], $enddate['year']) . $timeend; } } } else { $time = ' '; // Set printable representation if (!$showtime) { $day = calendar_day_representation($event->timestart, $now, $usecommonwords); $eventtime = calendar_get_link_tag($day, CALENDAR_URL . 'view.php?view=day' . $morehref . '&', $startdate['mday'], $startdate['mon'], $startdate['year']) . trim($time); } else { $eventtime = $time; } } if ($event->timestart + $event->timeduration < $now) { // It has expired $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>'; } return $eventtime; }
public function init_start_end_date() { global $CFG; // HOURSECS solves issue for weeks view with Daylight saving time and clocks adjusting by one hour backward. $date = usergetdate($this->curdate + HOURSECS); $mday = $date['mday']; $wday = $date['wday'] - $CFG->calendar_startwday; if ($wday < 0) { $wday += 7; } $mon = $date['mon']; $year = $date['year']; switch ($this->view) { case ATT_VIEW_DAYS: $this->startdate = make_timestamp($year, $mon, $mday); $this->enddate = make_timestamp($year, $mon, $mday + 1); break; case ATT_VIEW_WEEKS: $this->startdate = make_timestamp($year, $mon, $mday - $wday); $this->enddate = make_timestamp($year, $mon, $mday + 7 - $wday) - 1; break; case ATT_VIEW_MONTHS: $this->startdate = make_timestamp($year, $mon); $this->enddate = make_timestamp($year, $mon + 1); break; case ATT_VIEW_ALLPAST: $this->startdate = 1; $this->enddate = time(); break; case ATT_VIEW_ALL: $this->startdate = 0; $this->enddate = 0; break; } }
} $PAGE->set_url($url); if ($courseid != SITEID && !empty($courseid)) { $course = $DB->get_record('course', array('id' => $courseid)); $courses = array($course->id => $course); $issite = false; navigation_node::override_active_url(new moodle_url('/course/view.php', array('id' => $course->id))); } else { $course = get_site(); $courses = calendar_get_default_courses(); $issite = true; } require_course_login($course); $calendar = new calendar_information($day, $mon, $yr); $calendar->prepare_for_view($course, $courses); $now = usergetdate(time()); $pagetitle = ''; $strcalendar = get_string('calendar', 'calendar'); if (!checkdate($mon, $day, $yr)) { $day = intval($now['mday']); $mon = intval($now['mon']); $yr = intval($now['year']); } $time = make_timestamp($yr, $mon, $day); switch ($view) { case 'day': $PAGE->navbar->add(userdate($time, get_string('strftimedate'))); $pagetitle = get_string('dayview', 'calendar'); break; case 'month': $PAGE->navbar->add(userdate($time, get_string('strftimemonthyear')));
echo '</td>'; echo '<td align="center">'; echo print_user_picture($user2->id, SITEID, $user2->picture, 100, true, true, 'userwindow') . '<br />'; echo fullname($user2); echo '</td>'; echo '</tr></table>'; print_simple_box_end(); /// Get all the messages and print them if ($messages = message_get_history($user1, $user2)) { $current->mday = ''; $current->month = ''; $current->year = ''; $messagedate = get_string('strftimetime'); $blockdate = get_string('strftimedaydate'); foreach ($messages as $message) { $date = usergetdate($message->timecreated); if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) { $current->mday = $date['mday']; $current->month = $date['month']; $current->year = $date['year']; echo '<a name="' . $date['year'] . $date['mon'] . $date['mday'] . '"></a>'; print_heading(userdate($message->timecreated, $blockdate), 'center', 4); } if ($message->useridfrom == $user1->id) { echo message_format_message($message, $user1, $messagedate, $search, 'other'); } else { echo message_format_message($message, $user2, $messagedate, $search, 'me'); } } } else { print_heading(get_string('nomessagesfound', 'message'));
/** * Print the message history between two users * @param object $user1 the current user * @param object $user2 the other user * @param string $search search terms to highlight * @param int $messagelimit maximum number of messages to return * @param string $messagehistorylink the html for the message history link or false * @param bool $viewingnewmessages are we currently viewing new messages? */ function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) { global $CFG, $OUTPUT; echo $OUTPUT->box_start('center'); echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures')); echo html_writer::start_tag('tr'); echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1')); echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID)); echo html_writer::tag('div', fullname($user1), array('class' => 'heading')); echo html_writer::end_tag('td'); echo html_writer::start_tag('td', array('align' => 'center')); echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from'))); echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to'))); echo html_writer::end_tag('td'); echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2')); echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID)); echo html_writer::tag('div', fullname($user2), array('class' => 'heading')); if (isset($user2->iscontact) && isset($user2->isblocked)) { $incontactlist = $user2->iscontact; $isblocked = $user2->isblocked; $script = null; $text = true; $icon = false; $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon); $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon); $useractionlinks = $strcontact.' |'.$strblock; echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks')); } echo html_writer::end_tag('td'); echo html_writer::end_tag('tr'); echo html_writer::end_tag('table'); echo $OUTPUT->box_end(); if (!empty($messagehistorylink)) { echo $messagehistorylink; } /// Get all the messages and print them if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) { $tablecontents = ''; $current = new stdClass(); $current->mday = ''; $current->month = ''; $current->year = ''; $messagedate = get_string('strftimetime'); $blockdate = get_string('strftimedaydate'); foreach ($messages as $message) { if ($message->notification) { $notificationclass = ' notification'; } else { $notificationclass = null; } $date = usergetdate($message->timecreated); if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) { $current->mday = $date['mday']; $current->month = $date['month']; $current->year = $date['year']; $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday'])); $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading')); $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align'); } $formatted_message = $side = null; if ($message->useridfrom == $user1->id) { $formatted_message = message_format_message($message, $messagedate, $search, 'me'); $side = 'left'; } else { $formatted_message = message_format_message($message, $messagedate, $search, 'other'); $side = 'right'; } $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass")); } echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory')); } else { echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory')); } }
function calendar_show_month_detailed($m, $y, $courses, $groups, $users, $courseid) { global $CFG, $SESSION, $USER, $CALENDARDAYS; global $day, $mon, $yr; $getvars = 'from=month&cal_d=' . $day . '&cal_m=' . $mon . '&cal_y=' . $yr; // For filtering $display =& new stdClass(); $display->minwday = get_user_preferences('calendar_startwday', CALENDAR_STARTING_WEEKDAY); $display->maxwday = $display->minwday + 6; if (!empty($m) && !empty($y)) { $thisdate = usergetdate(time()); // Time and day at the user's location if ($m == $thisdate['mon'] && $y == $thisdate['year']) { // Navigated to this month $date = $thisdate; $display->thismonth = true; } else { // Navigated to other month, let's do a nice trick and save us a lot of work... if (!checkdate($m, 1, $y)) { $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']); $display->thismonth = true; } else { $date = array('mday' => 1, 'mon' => $m, 'year' => $y); $display->thismonth = false; } } } else { $date = usergetdate(time()); $display->thismonth = true; } // Fill in the variables we 're going to use, nice and tidy list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display $display->maxdays = calendar_days_in_month($m, $y); $startwday = 0; if (get_user_timezone_offset() < 99) { // We 'll keep these values as GMT here, and offset them when the time comes to query the db $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT $startwday = gmdate('w', $display->tstart); // $display->tstart is already GMT, so don't use date(): messes with server's TZ } else { // no timezone info specified $display->tstart = mktime(0, 0, 0, $m, 1, $y); $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y); $startwday = date('w', $display->tstart); // $display->tstart not necessarily GMT, so use date() } // Align the starting weekday to fall in our display range if ($startwday < $display->minwday) { $startwday += 7; } // Get events from database $events = calendar_get_events(usertime($display->tstart), usertime($display->tend), $users, $groups, $courses); if (!empty($events)) { foreach ($events as $eventid => $event) { if (!empty($event->modulename)) { $cm = get_coursemodule_from_instance($event->modulename, $event->instance); if (!groups_course_module_visible($cm)) { unset($events[$eventid]); } } } } // Extract information: events vs. time calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses); $text = ''; if (!isguest() && !empty($USER->id) && calendar_user_can_add_event()) { $text .= '<div class="buttons"><form action="' . CALENDAR_URL . 'event.php" method="get">'; $text .= '<div>'; $text .= '<input type="hidden" name="action" value="new" />'; $text .= '<input type="hidden" name="course" value="' . $courseid . '" />'; $text .= '<input type="hidden" name="cal_m" value="' . $m . '" />'; $text .= '<input type="hidden" name="cal_y" value="' . $y . '" />'; $text .= '<input type="submit" value="' . get_string('newevent', 'calendar') . '" />'; $text .= '</div></form></div>'; } $text .= '<label for="cal_course_flt_jump">' . get_string('detailedmonthview', 'calendar') . ':</label>' . calendar_course_filter_selector($getvars); echo '<div class="header">' . $text . '</div>'; echo '<div class="controls">'; echo calendar_top_controls('month', array('id' => $courseid, 'm' => $m, 'y' => $y)); echo '</div>'; // Start calendar display echo '<table class="calendarmonth"><tr class="weekdays">'; // Begin table. First row: day names // Print out the names of the weekdays for ($i = $display->minwday; $i <= $display->maxwday; ++$i) { // This uses the % operator to get the correct weekday no matter what shift we have // applied to the $display->minwday : $display->maxwday range from the default 0 : 6 echo '<th scope="col">' . get_string($CALENDARDAYS[$i % 7], 'calendar') . '</th>'; } echo '</tr><tr>'; // End of day names; prepare for day numbers // For the table display. $week is the row; $dayweek is the column. $week = 1; $dayweek = $startwday; // Paddding (the first week may have blank days in the beginning) for ($i = $display->minwday; $i < $startwday; ++$i) { echo '<td class="nottoday"> </td>' . "\n"; } // Now display all the calendar for ($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) { if ($dayweek > $display->maxwday) { // We need to change week (table row) echo "</tr>\n<tr>"; $dayweek = $display->minwday; ++$week; } // Reset vars $cell = ''; $dayhref = calendar_get_link_href(CALENDAR_URL . 'view.php?view=day&course=' . $courseid . '&', $day, $m, $y); if (CALENDAR_WEEKEND & 1 << $dayweek % 7) { // Weekend. This is true no matter what the exact range is. $class = 'weekend'; } else { // Normal working day. $class = ''; } // Special visual fx if an event is defined if (isset($eventsbyday[$day])) { if (count($eventsbyday[$day]) == 1) { $title = get_string('oneevent', 'calendar'); } else { $title = get_string('manyevents', 'calendar', count($eventsbyday[$day])); } $cell = '<div class="day"><a href="' . $dayhref . '" title="' . $title . '">' . $day . '</a></div>'; } else { $cell = '<div class="day">' . $day . '</div>'; } // Special visual fx if an event spans many days if (isset($typesbyday[$day]['durationglobal'])) { $class .= ' duration_global'; } else { if (isset($typesbyday[$day]['durationcourse'])) { $class .= ' duration_course'; } else { if (isset($typesbyday[$day]['durationgroup'])) { $class .= ' duration_group'; } else { if (isset($typesbyday[$day]['durationuser'])) { $class .= ' duration_user'; } } } } // Special visual fx for today if ($display->thismonth && $day == $d) { $class .= ' today'; } else { $class .= ' nottoday'; } // Just display it if (!empty($class)) { $class = ' class="' . trim($class) . '"'; } echo '<td' . $class . '>' . $cell; if (isset($eventsbyday[$day])) { echo '<ul class="events-new">'; foreach ($eventsbyday[$day] as $eventindex) { // If event has a class set then add it to the event <li> tag $eventclass = ''; if (!empty($events[$eventindex]->class)) { $eventclass = ' class="' . $events[$eventindex]->class . '"'; } echo '<li' . $eventclass . '><a href="' . $dayhref . '#event_' . $events[$eventindex]->id . '">' . format_string($events[$eventindex]->name, true) . '</a></li>'; } echo '</ul>'; } if (isset($durationbyday[$day])) { echo '<ul class="events-underway">'; foreach ($durationbyday[$day] as $eventindex) { echo '<li>[' . format_string($events[$eventindex]->name, true) . ']</li>'; } echo '</ul>'; } echo "</td>\n"; } // Paddding (the last week may have blank days at the end) for ($i = $dayweek; $i <= $display->maxwday; ++$i) { echo '<td class="nottoday"> </td>'; } echo "</tr>\n"; // Last row ends echo "</table>\n"; // Tabular display of days ends // OK, now for the filtering display echo '<div class="filters"><table><tr>'; // Global events if ($SESSION->cal_show_global) { echo '<td class="event_global" style="width: 8px;"></td><td><strong>' . get_string('globalevents', 'calendar') . ':</strong> '; echo get_string('shown', 'calendar') . ' (<a href="' . CALENDAR_URL . 'set.php?var=showglobal&' . $getvars . '">' . get_string('clickhide', 'calendar') . '</a>)</td>' . "\n"; } else { echo '<td style="width: 8px;"></td><td><strong>' . get_string('globalevents', 'calendar') . ':</strong> '; echo get_string('hidden', 'calendar') . ' (<a href="' . CALENDAR_URL . 'set.php?var=showglobal&' . $getvars . '">' . get_string('clickshow', 'calendar') . '</a>)</td>' . "\n"; } // Course events if (!empty($SESSION->cal_show_course)) { echo '<td class="event_course" style="width: 8px;"></td><td><strong>' . get_string('courseevents', 'calendar') . ':</strong> '; echo get_string('shown', 'calendar') . ' (<a href="' . CALENDAR_URL . 'set.php?var=showcourses&' . $getvars . '">' . get_string('clickhide', 'calendar') . '</a>)</td>' . "\n"; } else { echo '<td style="width: 8px;"></td><td><strong>' . get_string('courseevents', 'calendar') . ':</strong> '; echo get_string('hidden', 'calendar') . ' (<a href="' . CALENDAR_URL . 'set.php?var=showcourses&' . $getvars . '">' . get_string('clickshow', 'calendar') . '</a>)</td>' . "\n"; } echo "</tr>\n"; if (!empty($USER->id) && !isguest()) { echo '<tr>'; // Group events if ($SESSION->cal_show_groups) { echo '<td class="event_group" style="width: 8px;"></td><td><strong>' . get_string('groupevents', 'calendar') . ':</strong> '; echo get_string('shown', 'calendar') . ' (<a href="' . CALENDAR_URL . 'set.php?var=showgroups&' . $getvars . '">' . get_string('clickhide', 'calendar') . '</a>)</td>' . "\n"; } else { echo '<td style="width: 8px;"></td><td><strong>' . get_string('groupevents', 'calendar') . ':</strong> '; echo get_string('hidden', 'calendar') . ' (<a href="' . CALENDAR_URL . 'set.php?var=showgroups&' . $getvars . '">' . get_string('clickshow', 'calendar') . '</a>)</td>' . "\n"; } // User events if ($SESSION->cal_show_user) { echo '<td class="event_user" style="width: 8px;"></td><td><strong>' . get_string('userevents', 'calendar') . ':</strong> '; echo get_string('shown', 'calendar') . ' (<a href="' . CALENDAR_URL . 'set.php?var=showuser&' . $getvars . '">' . get_string('clickhide', 'calendar') . '</a>)</td>' . "\n"; } else { echo '<td style="width: 8px;"></td><td><strong>' . get_string('userevents', 'calendar') . ':</strong> '; echo get_string('hidden', 'calendar') . ' (<a href="' . CALENDAR_URL . 'set.php?var=showuser&' . $getvars . '">' . get_string('clickshow', 'calendar') . '</a>)</td>' . "\n"; } echo "</tr>\n"; } echo '</table></div>'; }
function construct_sessions_data_for_add($formdata) { global $CFG; $duration = $formdata->durtime['hours'] * HOURSECS + $formdata->durtime['minutes'] * MINSECS; $now = time(); $sessions = array(); if (isset($formdata->addmultiply)) { $startdate = $formdata->sessiondate; $starttime = $startdate - usergetmidnight($startdate); $enddate = $formdata->sessionenddate + DAYSECS; // because enddate in 0:0am if ($enddate < $startdate) { return NULL; } $days = (int) ceil(($enddate - $startdate) / DAYSECS); // Getting first day of week $sdate = $startdate; $dinfo = usergetdate($sdate); if ($CFG->calendar_startwday === '0') { //week start from sunday $startweek = $startdate - $dinfo['wday'] * DAYSECS; //call new variable } else { $wday = $dinfo['wday'] === 0 ? 7 : $dinfo['wday']; $startweek = $startdate - ($wday - 1) * DAYSECS; } $wdaydesc = array(0 => 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'); while ($sdate < $enddate) { if ($sdate < $startweek + WEEKSECS) { $dinfo = usergetdate($sdate); if (key_exists($wdaydesc[$dinfo['wday']], $formdata->sdays)) { $sess->sessdate = usergetmidnight($sdate) + $starttime; $sess->duration = $duration; $sess->descriptionitemid = $formdata->sdescription['itemid']; $sess->description = $formdata->sdescription['text']; $sess->descriptionformat = $formdata->sdescription['format']; $sess->timemodified = $now; fill_groupid($formdata, $sessions, $sess); } $sdate += DAYSECS; } else { $startweek += WEEKSECS * $formdata->period; $sdate = $startweek; } } } else { $sess->sessdate = $formdata->sessiondate; $sess->duration = $duration; $sess->descriptionitemid = $formdata->sdescription['itemid']; $sess->description = $formdata->sdescription['text']; $sess->descriptionformat = $formdata->sdescription['format']; $sess->timemodified = $now; fill_groupid($formdata, $sessions, $sess); } return $sessions; }
public function test_usergetdate() { global $USER, $CFG, $DB; $this->resetAfterTest(); $this->setAdminUser(); $USER->timezone = 2; // Set the timezone to a known state. $ts = 1261540267; // The time this function was created. $arr = usergetdate($ts, 1); // Specify the timezone as an argument. $arr = array_values($arr); list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr; $this->assertSame(7, $seconds); $this->assertSame(51, $minutes); $this->assertSame(4, $hours); $this->assertSame(23, $mday); $this->assertSame(3, $wday); $this->assertSame(12, $mon); $this->assertSame(2009, $year); $this->assertSame(356, $yday); $this->assertSame('Wednesday', $weekday); $this->assertSame('December', $month); $arr = usergetdate($ts); // Gets the timezone from the $USER object. $arr = array_values($arr); list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr; $this->assertSame(7, $seconds); $this->assertSame(51, $minutes); $this->assertSame(5, $hours); $this->assertSame(23, $mday); $this->assertSame(3, $wday); $this->assertSame(12, $mon); $this->assertSame(2009, $year); $this->assertSame(356, $yday); $this->assertSame('Wednesday', $weekday); $this->assertSame('December', $month); }
function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG = 'NAME') { global $CFG; $openlog = false; // loop through time fields in $TAGS foreach ($TAGS as $TAG) { // check $TAG has a sensible value if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) { if ($openlog == false) { $openlog = true; // only come through here once // open file for writing $course_dir = "{$CFG->dataroot}/{$restore->course_id}/backupdata"; check_dir_exists($course_dir, true); $restorelog = fopen("{$course_dir}/restorelog.html", "a"); // start output for this record $msg = new stdClass(); $msg->recordtype = $recordtype; $msg->recordname = $xml[$NAMETAG][0]['#']; fwrite($restorelog, get_string("backupdaterecordtype", "moodle", $msg)); } // write old date to $restorelog $value = $xml[$TAG][0]['#']; $date = usergetdate($value); $msg = new stdClass(); $msg->TAG = $TAG; $msg->weekday = $date['weekday']; $msg->mday = $date['mday']; $msg->month = $date['month']; $msg->year = $date['year']; fwrite($restorelog, get_string("backupdateold", "moodle", $msg)); // write new date to $restorelog $value += $restore->course_startdateoffset; $date = usergetdate($value); $msg = new stdClass(); $msg->TAG = $TAG; $msg->weekday = $date['weekday']; $msg->mday = $date['mday']; $msg->month = $date['month']; $msg->year = $date['year']; fwrite($restorelog, get_string("backupdatenew", "moodle", $msg)); // update $value in $xml tree for calling module $xml[$TAG][0]['#'] = "{$value}"; } } // close the restore log, if it was opened if ($openlog) { fclose($restorelog); } }
/** * Print the message history between two users * * @param object $user1 the current user * @param object $user2 the other user * @param string $search search terms to highlight * @param int $messagelimit maximum number of messages to return * @param string $messagehistorylink the html for the message history link or false * @param bool $viewingnewmessages are we currently viewing new messages? */ function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) { global $OUTPUT, $PAGE; $PAGE->requires->yui_module( array('moodle-core_message-toolbox'), 'M.core_message.toolbox.deletemsg.init', array(array()) ); echo $OUTPUT->box_start('center', 'message_user_pictures'); echo $OUTPUT->box_start('user'); echo $OUTPUT->box_start('generalbox', 'user1'); echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID)); echo html_writer::tag('div', fullname($user1), array('class' => 'heading')); echo $OUTPUT->box_end(); echo $OUTPUT->box_end(); $imgattr = array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => '', 'width' => 16, 'height' => 16); echo $OUTPUT->box(html_writer::empty_tag('img', $imgattr), 'between'); echo $OUTPUT->box_start('user'); echo $OUTPUT->box_start('generalbox', 'user2'); // Show user picture with link is real user else without link. if (core_user::is_real_user($user2->id)) { echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID)); } else { echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false)); } echo html_writer::tag('div', fullname($user2), array('class' => 'heading')); if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) { $script = null; $text = true; $icon = false; $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon); $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon); $useractionlinks = $strcontact.' | '.$strblock; echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks')); } echo $OUTPUT->box_end(); echo $OUTPUT->box_end(); echo $OUTPUT->box_end(); if (!empty($messagehistorylink)) { echo $messagehistorylink; } /// Get all the messages and print them if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) { $tablecontents = ''; $current = new stdClass(); $current->mday = ''; $current->month = ''; $current->year = ''; $messagedate = get_string('strftimetime'); $blockdate = get_string('strftimedaydate'); $messagenumber = 0; foreach ($messages as $message) { $messagenumber++; if ($message->notification) { $notificationclass = ' notification'; } else { $notificationclass = null; } $date = usergetdate($message->timecreated); if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) { $current->mday = $date['mday']; $current->month = $date['month']; $current->year = $date['year']; $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday'])); $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading')); $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align'); } if ($message->useridfrom == $user1->id) { $formatted_message = message_format_message($message, $messagedate, $search, 'me'); $side = 'left'; } else { $formatted_message = message_format_message($message, $messagedate, $search, 'other'); $side = 'right'; } // Check if it is a read message or not. if (isset($message->timeread)) { $type = 'message_read'; } else { $type = 'message'; } if (message_can_delete_message($message, $user1->id)) { $usergroup = optional_param('usergroup', MESSAGE_VIEW_UNREAD_MESSAGES, PARAM_ALPHANUMEXT); $viewing = optional_param('viewing', $usergroup, PARAM_ALPHANUMEXT); $deleteurl = new moodle_url('/message/index.php', array('user1' => $user1->id, 'user2' => $user2->id, 'viewing' => $viewing, 'deletemessageid' => $message->id, 'deletemessagetype' => $type, 'sesskey' => sesskey())); $deleteicon = $OUTPUT->action_icon($deleteurl, new pix_icon('t/delete', get_string('delete'))); $deleteicon = html_writer::tag('div', $deleteicon, array('class' => 'deleteicon accesshide')); $formatted_message .= $deleteicon; } $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left messagecontent $side $notificationclass", 'id' => 'message_' . $messagenumber)); } echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory')); } else { echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory')); } }
/** * Shows a time either as a date (if it falls exactly on the day) or * a full date and time, according to user's timezone. * * @param int $time Time * @param bool $until True if this date should be treated as the second of * an inclusive pair - if so the time will be shown unless date is 23:59:59. * Without this the date shows for 0:00:00. * @return string Date */ private function show_time($time, $until) { // Break down the time into fields $userdate = usergetdate($time); // Handle the 'inclusive' second date if ($until) { $dateonly = $userdate['hours'] == 23 && $userdate['minutes'] == 59 && $userdate['seconds'] == 59; } else { $dateonly = $userdate['hours'] == 0 && $userdate['minutes'] == 0 && $userdate['seconds'] == 0; } return userdate($time, get_string($dateonly ? 'strftimedate' : 'strftimedatetime', 'langconfig')); }
/** * Given a time, return the GMT timestamp of the most recent midnight * for the current user. * * @package core * @category time * @param int $date Timestamp in GMT * @param float|int|string $timezone user timezone * @return int Returns a GMT timestamp */ function usergetmidnight($date, $timezone = 99) { $userdate = usergetdate($date, $timezone); // Time of midnight of this user's day, in GMT. return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone); }
/** * Adds all the standard elements to a form to edit the settings for an activity module. */ function standard_coursemodule_elements() { global $COURSE, $CFG, $DB; $mform =& $this->_form; $this->_outcomesused = false; if ($this->_features->outcomes) { if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) { $this->_outcomesused = true; $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades')); foreach ($outcomes as $outcome) { $mform->addElement('advcheckbox', 'outcome_' . $outcome->id, $outcome->get_name()); } } } if ($this->_features->rating) { require_once $CFG->dirroot . '/rating/lib.php'; $rm = new rating_manager(); $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating')); $permission = CAP_ALLOW; $rolenamestring = null; if (!empty($this->_cm)) { $context = context_module::instance($this->_cm->id); $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/' . $this->_cm->modname . ':rate')); $rolenamestring = implode(', ', $rolenames); } else { $rolenamestring = get_string('capabilitychecknotavailable', 'rating'); } $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring); $mform->addHelpButton('rolewarning', 'rolewarning', 'rating'); $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating'), $rm->get_aggregate_types()); $mform->setDefault('assessed', 0); $mform->addHelpButton('assessed', 'aggregatetype', 'rating'); $mform->addElement('modgrade', 'scale', get_string('scale'), false); $mform->disabledIf('scale', 'assessed', 'eq', 0); $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating')); $mform->disabledIf('ratingtime', 'assessed', 'eq', 0); $mform->addElement('date_time_selector', 'assesstimestart', get_string('from')); $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0); $mform->disabledIf('assesstimestart', 'ratingtime'); $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to')); $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0); $mform->disabledIf('assesstimefinish', 'ratingtime'); } //doing this here means splitting up the grade related settings on the lesson settings page //$this->standard_grading_coursemodule_elements(); $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form')); if ($this->_features->groups) { $options = array(NOGROUPS => get_string('groupsnone'), SEPARATEGROUPS => get_string('groupsseparate'), VISIBLEGROUPS => get_string('groupsvisible')); $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS); $mform->addHelpButton('groupmode', 'groupmode', 'group'); } if ($this->_features->groupings or $this->_features->groupmembersonly) { //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly $options = array(); $options[0] = get_string('none'); if ($groupings = $DB->get_records('groupings', array('courseid' => $COURSE->id))) { foreach ($groupings as $grouping) { $options[$grouping->id] = format_string($grouping->name); } } $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options); $mform->addHelpButton('groupingid', 'grouping', 'group'); $mform->setAdvanced('groupingid'); } if ($this->_features->groupmembersonly) { $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group')); $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group'); $mform->setAdvanced('groupmembersonly'); } $mform->addElement('modvisible', 'visible', get_string('visible')); if (!empty($this->_cm)) { $context = context_module::instance($this->_cm->id); if (!has_capability('moodle/course:activityvisibility', $context)) { $mform->hardFreeze('visible'); } } if ($this->_features->idnumber) { $mform->addElement('text', 'cmidnumber', get_string('idnumbermod')); $mform->addHelpButton('cmidnumber', 'idnumbermod'); } if (!empty($CFG->enableavailability)) { // String used by conditions $strnone = get_string('none', 'condition'); // Conditional availability // Available from/to defaults to midnight because then the display // will be nicer where it tells users when they can access it (it // shows only the date and not time). $date = usergetdate(time()); $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']); // From/until controls $mform->addElement('header', 'availabilityconditionsheader', get_string('availabilityconditions', 'condition')); $mform->addElement('date_time_selector', 'availablefrom', get_string('availablefrom', 'condition'), array('optional' => true, 'defaulttime' => $midnight)); $mform->addHelpButton('availablefrom', 'availablefrom', 'condition'); $mform->addElement('date_time_selector', 'availableuntil', get_string('availableuntil', 'condition'), array('optional' => true, 'defaulttime' => $midnight)); // Conditions based on grades $gradeoptions = array(); $items = grade_item::fetch_all(array('courseid' => $COURSE->id)); $items = $items ? $items : array(); foreach ($items as $id => $item) { // Do not include grades for current item if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance && $this->_cm->modname == $item->itemmodule && $item->itemtype == 'mod') { continue; } $gradeoptions[$id] = $item->get_name(); } asort($gradeoptions); $gradeoptions = array(0 => $strnone) + $gradeoptions; $grouparray = array(); $grouparray[] =& $mform->createElement('select', 'conditiongradeitemid', '', $gradeoptions); $grouparray[] =& $mform->createElement('static', '', '', ' ' . get_string('grade_atleast', 'condition') . ' '); $grouparray[] =& $mform->createElement('text', 'conditiongrademin', '', array('size' => 3)); $grouparray[] =& $mform->createElement('static', '', '', '% ' . get_string('grade_upto', 'condition') . ' '); $grouparray[] =& $mform->createElement('text', 'conditiongrademax', '', array('size' => 3)); $grouparray[] =& $mform->createElement('static', '', '', '%'); $group = $mform->createElement('group', 'conditiongradegroup', get_string('gradecondition', 'condition'), $grouparray); // Get version with condition info and store it so we don't ask // twice if (!empty($this->_cm)) { $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE); $this->_cm = $ci->get_full_course_module(); $count = count($this->_cm->conditionsgrade) + 1; $fieldcount = count($this->_cm->conditionsfield) + 1; } else { $count = 1; $fieldcount = 1; } $this->repeat_elements(array($group), $count, array(), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true); $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition'); // Conditions based on user fields $operators = condition_info::get_condition_user_field_operators(); $useroptions = condition_info::get_condition_user_fields(); asort($useroptions); $useroptions = array(0 => $strnone) + $useroptions; $grouparray = array(); $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions); $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators); $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue'); $mform->setType('conditionfieldvalue', PARAM_RAW); $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray); $this->repeat_elements(array($group), $fieldcount, array(), 'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true); $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition'); // Conditions based on completion $completion = new completion_info($COURSE); if ($completion->is_enabled()) { $completionoptions = array(); $modinfo = get_fast_modinfo($COURSE); foreach ($modinfo->cms as $id => $cm) { // Add each course-module if it: // (a) has completion turned on // (b) is not the same as current course-module if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) { $completionoptions[$id] = $cm->name; } } asort($completionoptions); $completionoptions = array(0 => $strnone) + $completionoptions; $completionvalues = array(COMPLETION_COMPLETE => get_string('completion_complete', 'condition'), COMPLETION_INCOMPLETE => get_string('completion_incomplete', 'condition'), COMPLETION_COMPLETE_PASS => get_string('completion_pass', 'condition'), COMPLETION_COMPLETE_FAIL => get_string('completion_fail', 'condition')); $grouparray = array(); $grouparray[] =& $mform->createElement('select', 'conditionsourcecmid', '', $completionoptions); $grouparray[] =& $mform->createElement('select', 'conditionrequiredcompletion', '', $completionvalues); $group = $mform->createElement('group', 'conditioncompletiongroup', get_string('completioncondition', 'condition'), $grouparray); $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion) + 1; $this->repeat_elements(array($group), $count, array(), 'conditioncompletionrepeats', 'conditioncompletionadds', 2, get_string('addcompletions', 'condition'), true); $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition'); } // Do we display availability info to students? $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'), array(CONDITION_STUDENTVIEW_SHOW => get_string('showavailability_show', 'condition'), CONDITION_STUDENTVIEW_HIDE => get_string('showavailability_hide', 'condition'))); $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW); } // Conditional activities: completion tracking section if (!isset($completion)) { $completion = new completion_info($COURSE); } if ($completion->is_enabled()) { $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion')); // Unlock button for if people have completed it (will // be removed in definition_after_data if they haven't) $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion')); $mform->registerNoSubmitButton('unlockcompletion'); $mform->addElement('hidden', 'completionunlocked', 0); $mform->setType('completionunlocked', PARAM_INT); $mform->addElement('select', 'completion', get_string('completion', 'completion'), array(COMPLETION_TRACKING_NONE => get_string('completion_none', 'completion'), COMPLETION_TRACKING_MANUAL => get_string('completion_manual', 'completion'))); $mform->setDefault('completion', $this->_features->defaultcompletion ? COMPLETION_TRACKING_MANUAL : COMPLETION_TRACKING_NONE); $mform->addHelpButton('completion', 'completion', 'completion'); // Automatic completion once you view it $gotcompletionoptions = false; if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) { $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'), get_string('completionview_desc', 'completion')); $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC); $gotcompletionoptions = true; } // Automatic completion once it's graded if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) { $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'), get_string('completionusegrade_desc', 'completion')); $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC); $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion'); $gotcompletionoptions = true; } // Automatic completion according to module-specific rules $this->_customcompletionelements = $this->add_completion_rules(); foreach ($this->_customcompletionelements as $element) { $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC); } $gotcompletionoptions = $gotcompletionoptions || count($this->_customcompletionelements) > 0; // Automatic option only appears if possible if ($gotcompletionoptions) { $mform->getElement('completion')->addOption(get_string('completion_automatic', 'completion'), COMPLETION_TRACKING_AUTOMATIC); } // Completion expected at particular date? (For progress tracking) $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional' => true)); $mform->addHelpButton('completionexpected', 'completionexpected', 'completion'); $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE); } $this->standard_hidden_coursemodule_elements(); }
/** * Ensures the date for the calendar is correct and either sets it to now * or throws a moodle_exception if not * * @param bool $defaultonow use current time * @throws moodle_exception * @return bool validation of checkdate */ public function checkdate($defaultonow = true) { if (!checkdate($this->month, $this->day, $this->year)) { if ($defaultonow) { $now = usergetdate(time()); $this->day = intval($now['mday']); $this->month = intval($now['mon']); $this->year = intval($now['year']); return true; } else { throw new moodle_exception('invaliddate'); } } return true; }
/** *Prints form items with the names $hour and $minute * * @param string $hour fieldname * @param string ? $minute fieldname * @param $currenttime A default timestamp in GMT * @param int $step minute spacing * @param boolean $return */ function print_time_selector($hour, $minute, $currenttime = 0, $step = 5, $return = false) { if (!$currenttime) { $currenttime = time(); } $currentdate = usergetdate($currenttime); if ($step != 1) { $currentdate['minutes'] = ceil($currentdate['minutes'] / $step) * $step; } for ($i = 0; $i <= 23; $i++) { $hours[$i] = sprintf("%02d", $i); } for ($i = 0; $i <= 59; $i += $step) { $minutes[$i] = sprintf("%02d", $i); } // Build or print result $result = ''; // Note: There should probably be a fieldset around these fields as they are // clearly grouped. However this causes problems with display. See Mozilla // bug 474415 $result .= '<label class="accesshide" for="menu' . $hour . '">' . get_string('hour', 'form') . '</label>'; $result .= choose_from_menu($hours, $hour, $currentdate['hours'], '', '', '0', true); $result .= '<label class="accesshide" for="menu' . $minute . '">' . get_string('minute', 'form') . '</label>'; $result .= choose_from_menu($minutes, $minute, $currentdate['minutes'], '', '', '0', true); if ($return) { return $result; } else { echo $result; } }
function exercise_restore_mods($mod, $restore) { global $CFG; $status = true; //Get record from backup_ids $data = backup_getid($restore->backup_unique_code, $mod->modtype, $mod->id); if ($data) { //Now get completed xmlized object $info = $data->info; // if necessary, write to restorelog and adjust date/time fields if ($restore->course_startdateoffset) { restore_log_date_changes('Exercise', $restore, $info['MOD']['#'], array('DEADLINE')); } //traverse_xmlize($info); //Debug //print_object ($GLOBALS['traverse_array']); //Debug //$GLOBALS['traverse_array']=""; //Debug //Now, build the exercise record structure $exercise->course = $restore->course_id; $exercise->name = backup_todb($info['MOD']['#']['NAME']['0']['#']); $exercise->nelements = backup_todb($info['MOD']['#']['NELEMENTS']['0']['#']); $exercise->phase = backup_todb($info['MOD']['#']['PHASE']['0']['#']); $exercise->gradingstrategy = backup_todb($info['MOD']['#']['GRADINGSTRATEGY']['0']['#']); $exercise->usemaximum = backup_todb($info['MOD']['#']['USEMAXIMUM']['0']['#']); $exercise->assessmentcomps = backup_todb($info['MOD']['#']['ASSESSMENTCOMPS']['0']['#']); $exercise->anonymous = backup_todb($info['MOD']['#']['ANONYMOUS']['0']['#']); $exercise->maxbytes = backup_todb($info['MOD']['#']['MAXBYTES']['0']['#']); $exercise->deadline = backup_todb($info['MOD']['#']['DEADLINE']['0']['#']); $date = usergetdate($exercise->deadline); fwrite($restorelog_file, "<br/>The Exercise - " . $exercise->name . " <br/>"); fwrite($restorelog_file, "The DEADLINE was " . $date['weekday'] . ", " . $date['mday'] . " " . $date['month'] . " " . $date['year'] . ""); $exercise->deadline += $restore->course_startdateoffset; $date = usergetdate($exercise->deadline); fwrite($restorelog_file, " the DEADLINE is now " . $date['weekday'] . ", " . $date['mday'] . " " . $date['month'] . " " . $date['year'] . "<br/>"); $exercise->timemodified = backup_todb($info['MOD']['#']['TIMEMODIFIED']['0']['#']); $exercise->grade = backup_todb($info['MOD']['#']['GRADE']['0']['#']); $exercise->gradinggrade = backup_todb($info['MOD']['#']['GRADINGGRADE']['0']['#']); $exercise->showleaguetable = backup_todb($info['MOD']['#']['SHOWLEAGUETABLE']['0']['#']); $exercise->usepassword = backup_todb($info['MOD']['#']['USEPASSWORD']['0']['#']); $exercise->password = backup_todb($info['MOD']['#']['PASSWORD']['0']['#']); //The structure is equal to the db, so insert the exercise $newid = insert_record("exercise", $exercise); //Do some output if (!defined('RESTORE_SILENTLY')) { echo "<li>" . get_string("modulename", "exercise") . " \"" . format_string(stripslashes($exercise->name), true) . "\"</li>"; } backup_flush(300); if ($newid) { //We have the newid, update backup_ids backup_putid($restore->backup_unique_code, $mod->modtype, $mod->id, $newid); //We have to restore the exercise_elements table now (course level table) $status = exercise_elements_restore($newid, $info, $restore); //restore the teacher submissions and optionally the student submissions $status = exercise_submissions_restore($mod->id, $newid, $info, $restore); } else { $status = false; } } else { $status = false; } return $status; }
function schedule_inc_backup_next_execution($backup_course, $incremental_config, $now, $timezone) { $result = -1; //Get today's midnight GMT $midnight = usergetmidnight($now, $timezone); //Get today's day of week (0=Sunday...6=Saturday) $date = usergetdate($now, $timezone); $dayofweek = $date['wday']; //Get number of days (from today) to execute backups $scheduled_days = substr($incremental_config->backup_inc_weekdays, $dayofweek) . $incremental_config->backup_inc_weekdays; $daysfromtoday = strpos($scheduled_days, "1"); //If some day has been found if ($daysfromtoday !== false) { //Calculate distance $dist = $daysfromtoday * 86400 + $incremental_config->backup_inc_hour * 3600 + $incremental_config->backup_inc_minute * 60; //Minutes distance $result = $midnight + $dist; } //If that time is past, call the function recursively to obtain the next valid day if ($result > 0 && $result < time()) { $result = schedule_inc_backup_next_execution($backup_course, $incremental_config, $now + 86400, $timezone); } return $result; }
public function test_usergetdate() { global $USER, $CFG, $DB; $this->resetAfterTest(); // Check if forcetimezone is set then save it and set it to use user timezone. $cfgforcetimezone = null; if (isset($CFG->forcetimezone)) { $cfgforcetimezone = $CFG->forcetimezone; $CFG->forcetimezone = 99; // Get user default timezone. } $this->setAdminUser(); $userstimezone = $USER->timezone; $USER->timezone = 2; // Set the timezone to a known state. // The string version of date comes from server locale setting and does // not respect user language, so it is necessary to reset that. $oldlocale = setlocale(LC_TIME, '0'); setlocale(LC_TIME, 'en_AU.UTF-8'); $ts = 1261540267; // The time this function was created. $arr = usergetdate($ts, 1); // Specify the timezone as an argument. $arr = array_values($arr); list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr; $this->assertSame(7, $seconds); $this->assertSame(51, $minutes); $this->assertSame(4, $hours); $this->assertSame(23, $mday); $this->assertSame(3, $wday); $this->assertSame(12, $mon); $this->assertSame(2009, $year); $this->assertSame(356, $yday); $this->assertSame('Wednesday', $weekday); $this->assertSame('December', $month); $arr = usergetdate($ts); // Gets the timezone from the $USER object. $arr = array_values($arr); list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr; $this->assertSame(7, $seconds); $this->assertSame(51, $minutes); $this->assertSame(5, $hours); $this->assertSame(23, $mday); $this->assertSame(3, $wday); $this->assertSame(12, $mon); $this->assertSame(2009, $year); $this->assertSame(356, $yday); $this->assertSame('Wednesday', $weekday); $this->assertSame('December', $month); // Set the timezone back to what it was. $USER->timezone = $userstimezone; // Restore forcetimezone if changed. if (!is_null($cfgforcetimezone)) { $CFG->forcetimezone = $cfgforcetimezone; } setlocale(LC_TIME, $oldlocale); }
$repeats = optional_param('repeats', 0, PARAM_INT); if ($confirm and confirm_sesskey()) { // Kill it and redirect to day view if (($event = get_record('event', 'id', $eventid)) !== false) { if ($event->repeatid && $repeats) { delete_records('event', 'repeatid', $event->repeatid); add_to_log($event->courseid, 'calendar', 'delete all', '', $event->name); } else { delete_records('event', 'id', $eventid); add_to_log($event->courseid, 'calendar', 'delete', '', $event->name); } } echo '</td></tr></table>'; redirect(CALENDAR_URL . 'view.php?view=day&course=' . $urlcourse . '&cal_d=' . $_REQUEST['d'] . '&cal_m=' . $_REQUEST['m'] . '&cal_y=' . $_REQUEST['y']); } else { $eventtime = usergetdate($event->timestart); $m = $eventtime['mon']; $d = $eventtime['mday']; $y = $eventtime['year']; if ($event->repeatid) { $fetch = get_record_sql('SELECT 1, COUNT(id) AS repeatcount FROM ' . $CFG->prefix . 'event WHERE repeatid = ' . $event->repeatid); $repeatcount = $fetch->repeatcount; } else { $repeatcount = 0; } // Display confirmation form echo '<div class="header">' . get_string('deleteevent', 'calendar') . ': ' . $event->name . '</div>'; echo '<h2>' . get_string('confirmeventdelete', 'calendar') . '</h2>'; if ($repeatcount > 1) { echo '<p>' . get_string('youcandeleteallrepeats', 'calendar', $repeatcount) . '</p>'; }
/** * Called by HTML_QuickForm whenever form event is made on this element * * @param string $event Name of event * @param mixed $arg event arguments * @param object $caller calling object * @return bool */ function onQuickFormEvent($event, $arg, &$caller) { switch ($event) { case 'updateValue': // constant values override both default and submitted ones // default values are overriden by submitted $value = $this->_findValue($caller->_constantValues); if (null === $value) { // if no boxes were checked, then there is no value in the array // yet we don't want to display default value in this case if ($caller->isSubmitted()) { $value = $this->_findValue($caller->_submitValues); } else { $value = $this->_findValue($caller->_defaultValues); } } $requestvalue = $value; if ($value == 0) { $value = $this->_options['defaulttime']; if (!$value) { $value = time(); } } if (!is_array($value)) { $currentdate = usergetdate($value, $this->_options['timezone']); // Round minutes to the previous multiple of step. $currentdate['minutes'] -= $currentdate['minutes'] % $this->_options['step']; $value = array('minute' => $currentdate['minutes'], 'hour' => $currentdate['hours'], 'day' => $currentdate['mday'], 'month' => $currentdate['mon'], 'year' => $currentdate['year']); // If optional, default to off, unless a date was provided if ($this->_options['optional']) { $value['enabled'] = $requestvalue != 0; } } else { $value['enabled'] = isset($value['enabled']); } if (null !== $value) { $this->setValue($value); } break; case 'createElement': if ($arg[2]['optional']) { // When using the function addElement, rather than createElement, we still // enter this case, making this check necessary. if ($this->_usedcreateelement) { $caller->disabledIf($arg[0] . '[day]', $arg[0] . '[enabled]'); $caller->disabledIf($arg[0] . '[month]', $arg[0] . '[enabled]'); $caller->disabledIf($arg[0] . '[year]', $arg[0] . '[enabled]'); $caller->disabledIf($arg[0] . '[hour]', $arg[0] . '[enabled]'); $caller->disabledIf($arg[0] . '[minute]', $arg[0] . '[enabled]'); } else { $caller->disabledIf($arg[0], $arg[0] . '[enabled]'); } } return parent::onQuickFormEvent($event, $arg, $caller); break; case 'addElement': $this->_usedcreateelement = false; return parent::onQuickFormEvent($event, $arg, $caller); break; default: return parent::onQuickFormEvent($event, $arg, $caller); } }
/** *Prints form items with the names $hour and $minute * * @param string $hour fieldname * @param string ? $minute fieldname * @param $currenttime A default timestamp in GMT * @param int $step minute spacing * @param boolean $return */ function cm_print_time_selector($hour, $minute, $currenttime = 0, $step = 5, $return = false) { if (!$currenttime) { $currenttime = time(); } $currentdate = usergetdate($currenttime); // was cm_usergetdate if ($step != 1) { $currentdate['minutes'] = ceil($currentdate['minutes'] / $step) * $step; } for ($i = 0; $i <= 23; $i++) { $hours[$i] = sprintf("%02d", $i); } for ($i = 0; $i <= 59; $i += $step) { $minutes[$i] = sprintf("%02d", $i); } return cm_choose_from_menu($hours, $hour, $currentdate['hours'], '', '', '0', $return) . cm_choose_from_menu($minutes, $minute, $currentdate['minutes'], '', '', '0', $return); }
/** * Works out the next time the automated backup should be run. * * @param mixed $timezone user timezone * @param int $now timestamp, should not be in the past, most likely time() * @return int timestamp of the next execution at server time */ public static function calculate_next_automated_backup($timezone, $now) { $result = 0; $config = get_config('backup'); $autohour = $config->backup_auto_hour; $automin = $config->backup_auto_minute; // Gets the user time relatively to the server time. $date = usergetdate($now, $timezone); $usertime = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']); $diff = $now - $usertime; // Get number of days (from user's today) to execute backups. $automateddays = substr($config->backup_auto_weekdays, $date['wday']) . $config->backup_auto_weekdays; $daysfromnow = strpos($automateddays, "1"); // Error, there are no days to schedule the backup for. if ($daysfromnow === false) { return 0; } // Checks if the date would happen in the future (of the user). $userresult = mktime($autohour, $automin, 0, $date['mon'], $date['mday'] + $daysfromnow, $date['year']); if ($userresult <= $usertime) { // If not, we skip the first scheduled day, that should fix it. $daysfromnow = strpos($automateddays, "1", 1); $userresult = mktime($autohour, $automin, 0, $date['mon'], $date['mday'] + $daysfromnow, $date['year']); } // Now we generate the time relative to the server. $result = $userresult + $diff; // If that time is past, call the function recursively to obtain the next valid day. if ($result <= $now) { // Checking time() in here works, but makes PHPUnit Tests extremely hard to predict. // $now should never be earlier than time() anyway... $result = self::calculate_next_automated_backup($timezone, $now + DAYSECS); } return $result; }
/** * Works out the next time the automated backup should be run. * * @param mixed $timezone * @param int $now * @return int */ public static function calculate_next_automated_backup($timezone, $now) { $result = -1; $config = get_config('backup'); $midnight = usergetmidnight($now, $timezone); $date = usergetdate($now, $timezone); //Get number of days (from today) to execute backups $automateddays = substr($config->backup_auto_weekdays, $date['wday']) . $config->backup_auto_weekdays; $daysfromtoday = strpos($automateddays, "1"); if (empty($daysfromtoday)) { $daysfromtoday = 1; } //If some day has been found if ($daysfromtoday !== false) { //Calculate distance $dist = $daysfromtoday * 86400 + $config->backup_auto_hour * 3600 + $config->backup_auto_minute * 60; //Minutes distance $result = $midnight + $dist; } //If that time is past, call the function recursively to obtain the next valid day if ($result > 0 && $result < time()) { $result = self::calculate_next_automated_backup($timezone, $result); } return $result; }