/** * Render a single post * * @param \stdClass $cm The forum course module * @param \stdClass $discussion The post's discussion * @param \stdClass $post The post to render * @param bool $canreply * @param null|object $parent Optional, parent post * @param array $commands Override default post commands * @param int $depth Depth of the post * @return string */ public function post($cm, $discussion, $post, $canreply = false, $parent = null, $commands = array(), $depth = 0, $search = '') { global $USER, $CFG, $DB; $forum = hsuforum_get_cm_forum($cm); if (!hsuforum_user_can_see_post($forum, $discussion, $post, null, $cm)) { // Return a message about why you cannot see the post return "<div class='hsuforum-post-content-hidden'>" . get_string('forumbodyhidden', 'hsuforum') . "</div>"; } if ($commands === false) { $commands = array(); } else { if (empty($commands)) { $commands = $this->post_get_commands($post, $discussion, $cm, $canreply, false); } else { if (!is_array($commands)) { throw new coding_exception('$commands must be false, empty or populated array'); } } } $postuser = hsuforum_extract_postuser($post, $forum, context_module::instance($cm->id)); $postuser->user_picture->size = 100; // $post->breadcrumb comes from search btw. $data = new stdClass(); $data->id = $post->id; $data->discussionid = $discussion->id; $data->fullname = $postuser->fullname; $data->subject = property_exists($post, 'breadcrumb') ? $post->breadcrumb : $this->raw_post_subject($post); $data->message = $this->post_message($post, $cm, $search); $data->created = userdate($post->created, get_string('articledateformat', 'hsuforum')); $data->rawcreated = $post->created; $data->datetime = date(DATE_W3C, usertime($post->created)); $data->privatereply = $post->privatereply; $data->imagesrc = $postuser->user_picture->get_url($this->page)->out(); $data->userurl = $this->get_post_user_url($cm, $postuser); $data->unread = empty($post->postread) ? true : false; $data->permalink = new moodle_url('/mod/hsuforum/discuss.php#p' . $post->id, array('d' => $discussion->id)); $data->isreply = false; $data->parentfullname = ''; $data->parentuserurl = ''; $data->tools = implode(' ', $commands); $data->postflags = implode(' ', $this->post_get_flags($post, $cm, $discussion->id, false)); $data->depth = $depth; $data->revealed = false; if ($forum->anonymous && $postuser->id === $USER->id && $post->reveal) { $data->revealed = true; } if (!empty($post->children)) { $post->replycount = count($post->children); } $data->replycount = ''; // Only show reply count if replies and not first post if (!empty($post->replycount) && $post->replycount > 0 && $post->parent) { $data->replycount = hsuforum_xreplies($post->replycount); } // Mark post as read. if ($data->unread) { hsuforum_mark_post_read($USER->id, $post, $forum->id); } if (!empty($parent)) { $parentuser = hsuforum_extract_postuser($parent, $forum, context_module::instance($cm->id)); $data->parenturl = $CFG->wwwroot . '/mod/hsuforum/discuss.php?d=' . $parent->discussion . '#p' . $parent->id; $data->parentfullname = $parentuser->fullname; if (!empty($parentuser->user_picture)) { $parentuser->user_picture->size = 100; $data->parentuserurl = $this->get_post_user_url($cm, $parentuser); $data->parentuserpic = $this->output->user_picture($parentuser, array('link' => false, 'size' => 100, 'alttext' => false)); } } if ($depth > 0) { // Top level responses don't count. $data->isreply = true; } return $this->post_template($data); }
} // Merge Moodle users last - higher priority in linking than other contact type if (count($moodleUserGroups) > 0) { foreach ($moodleUserGroups as $userGroup) { $destinations += $userDAO->getUsersInGroup($userGroup, 'phone'); } } if (count($moodleUsers) > 0) { $destinations += $userDAO->getUsersById($moodleUsers, 'phone'); } // If there are valid destinations, send the message if (count($destinations) > 0) { $txttoolsAccount = $accountDAO->getTxttoolsAccountById($formData->txttoolsaccount); $thisUser = new MoodletxtBiteSizedUser($USER->id, $USER->username, $USER->firstname, $USER->lastname); if ($formData->schedule == 'schedule') { $scheduletime = usertime(gmmktime($formData->scheduletime['H'], $formData->scheduletime['i'], 0, $formData->scheduletime['M'], $formData->scheduletime['d'], $formData->scheduletime['Y'])); } else { $scheduletime = time(); } $outboundMessage = new MoodletxtOutboundMessage($txttoolsAccount, $thisUser, $formData->messageText, time(), MoodletxtOutboundMessage::$MESSAGE_CHARGE_TYPE_BULK, $scheduletime, $formData->suppressUnicode); $outboundMessage->setMessageRecipients($destinations); try { $connector = MoodletxtOutboundControllerFactory::getOutboundController(MoodletxtOutboundControllerFactory::$CONTROLLER_TYPE_XML); $outboundMessage->setSentSMSMessages($connector->sendMessage($outboundMessage)); $messageDAO->saveSentMessage($outboundMessage); $statsDAO->incrementUserOutboundStatsById($txttoolsAccount->getId(), $USER->id, 1); // Stub for later expansion $sentPageUrl = new moodle_url('/blocks/moodletxt/sent.php', array('course' => $courseId, 'instance' => $instanceId)); redirect($sentPageUrl, get_string('redirectmessagesent', 'block_moodletxt')); } catch (MoodletxtRemoteProcessingException $ex) { // Uh-oh, couldn't send! Display error, please
// CSS classes for each column in the table. $examstable->colclasses = array("exams_examname", null); $examstable->data[] = array(get_string("examname", "mod_emarking"), $exam->name); $details = html_writer::start_tag("div", array("class" => "printdetails")); if ($exam->headerqr) { $details .= html_writer::div($OUTPUT->pix_icon("qr-icon", get_string("headerqr", "mod_emarking"), "mod_emarking")); } if ($exam->printlist) { $details .= html_writer::div($OUTPUT->pix_icon("i/grades", get_string("printlist", "mod_emarking"))); } if ($exam->printrandom) { $details .= html_writer::div($OUTPUT->pix_icon("shuffle", get_string("printrandom", "mod_emarking"), "mod_emarking")); } $details .= emarking_enrolments_div($exam); $details .= html_writer::end_tag("div"); $examstable->data[] = array(get_string("examdate", "mod_emarking"), date("l jS F Y, g:ia", usertime($exam->examdate))); if ($usercangrade) { $examstatus = emarking_exam_status_string($exam); $examstable->data[] = array(get_string("comment", "mod_emarking"), $exam->comment); $examstable->data[] = array(get_string("status", "mod_emarking"), $examstatus); $examstable->data[] = array(get_string("details", "mod_emarking"), $details); $examstable->data[] = array(get_string("sent", "mod_emarking"), emarking_time_ago($exam->timecreated)); $originals = $exam->totalpages + $exam->extrasheets; $copies = $exam->totalstudents + $exam->extraexams; $totalsheets = $originals * $copies; $examstable->data[] = array(get_string('originals', 'mod_emarking'), $originals); $examstable->data[] = array(get_string('copies', 'mod_emarking'), $copies); $examstable->data[] = array(get_string('totalpagesprint', 'mod_emarking'), $totalsheets); $user = $DB->get_record("user", array("id" => $exam->requestedby)); $examstable->data[] = array(get_string('requestedby', 'mod_emarking'), $user->firstname . ' ' . $user->lastname); $examstable->data[] = array(get_string("multicourse", "mod_emarking"), $multicourse ? $multicourse : get_string("no"));
/** * Searches for courses using a substring match and optionally limits by category. * * @param string $query The substring to search for. * @param array $categoryquery Array of categories to search for. * @return array Matching courses or returns no matches found. */ function report_ncccscensus_course_search($query, $categoryquery) { global $DB; $time = usertime(time(), get_user_timezone()); $param = array($time, $time, "%{$query}%"); $categorysql = ""; if (is_array($categoryquery) && count($categoryquery) > 0) { $tempcategories = array(); foreach ($categoryquery as $category) { array_push($tempcategories, $category['id']); } $categories = $DB->get_in_or_equal($tempcategories); $categorysql = " AND category {$categories['0']} "; foreach ($categories[1] as $temp) { array_push($param, $temp); } } $sqlquery = 'SELECT DISTINCT c.id, c.fullname FROM {course} c, {enrol} e, {user_enrolments} ue WHERE'; $sqlquery .= ' e.courseid = c.id AND ue.enrolid = e.id '; $sqlquery .= ' AND ue.timestart < ? AND (ue.timeend > ? OR ue.timeend = 0)'; $sqlquery .= ' AND c.fullname LIKE ? ' . $categorysql; $courses = $DB->get_records_sql($sqlquery, $param); $results = array(); foreach ($courses as $course) { array_push($results, array('id' => $course->id, 'name' => $course->fullname)); } if (count($results) === 0) { array_push($results, array('name' => get_string('noresults', 'report_ncccscensus') . " {$query}")); } return $results; }
/** * Given date parts in user time produce a GMT timestamp. * * @param int $year The year part to create timestamp of * @param int $month The month part to create timestamp of * @param int $day The day part to create timestamp of * @param int $hour The hour part to create timestamp of * @param int $minute The minute part to create timestamp of * @param int $second The second part to create timestamp of * @param float $timezone ? * @param bool $applydst ? * @return int timestamp * @todo Finish documenting this function */ function make_timestamp($year, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = 99, $applydst = true) { $strtimezone = NULL; if (!is_numeric($timezone)) { $strtimezone = $timezone; } $timezone = get_user_timezone_offset($timezone); if (abs($timezone) > 13) { $time = mktime((int) $hour, (int) $minute, (int) $second, (int) $month, (int) $day, (int) $year); } else { $time = gmmktime((int) $hour, (int) $minute, (int) $second, (int) $month, (int) $day, (int) $year); $time = usertime($time, $timezone); if ($applydst) { $time -= dst_offset_on($time, $strtimezone); } } return $time; }
/** * this function handles the access policy to contents indexed as searchable documents. If this * function does not exist, the search engine assumes access is allowed. * When this point is reached, we already know that : * - user is legitimate in the surrounding context * - user may be guest and guest access is allowed to the module * - the function may perform local checks within the module information logic * @param string $path the access path to the module script code * @param string $itemtype the information subclassing (usefull for complex modules, defaults to 'standard') * @param int $this_id the item id within the information class denoted by itemtype. In databases, this id * points out an indexed data record page. * @param object $user the user record denoting the user who searches * @param int $group_id the current group used by the user when searching * @uses $CFG, $DB * @return true if access is allowed, false elsewhere */ function data_check_text_access($path, $itemtype, $this_id, $user, $group_id, $context_id) { global $CFG, $DB; // get the database object and all related stuff if ($itemtype == 'record') { $record = $DB->get_record('data_records', array('id' => $this_id)); } elseif ($itemtype == 'comment') { $comment = $DB->get_record('data_comments', array('id' => $this_id)); $record = $DB->get_record('data_records', array('id' => $comment->recordid)); } else { // we do not know what type of information is required return false; } $data = $DB->get_record('data', array('id' => $record->dataid)); $context = $DB->get_record('context', array('id' => $context_id)); $cm = $DB->get_record('course_modules', array('id' => $context->instanceid)); if (empty($cm)) { return false; } // Shirai 20090530 - MDL19342 - course module might have been delete if (!$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $context)) { if (!empty($CFG->search_access_debug)) { echo "search reject : hidden database "; } return false; } //group consistency check : checks the following situations about groups // trap if user is not same group and groups are separated $course = $DB->get_record('course', 'id', $data->course); if (isset($cm->groupmode) && empty($course->groupmodeforce)) { $groupmode = $cm->groupmode; } else { $groupmode = $course->groupmode; } if ($groupmode == SEPARATEGROUPS && !ismember($group_id) && !has_capability('moodle/site:accessallgroups', $context)) { if (!empty($CFG->search_access_debug)) { echo "search reject : separated group owned resource "; } return false; } //ownership check : checks the following situations about user // trap if user is not owner and has cannot see other's entries if ($itemtype == 'record') { if ($user->id != $record->userid && !has_capability('mod/data:viewentry', $context) && !has_capability('mod/data:manageentries', $context)) { if (!empty($CFG->search_access_debug)) { echo "search reject : not owned resource "; } return false; } } //approval check // trap if unapproved and has not approval capabilities // TODO : report a potential capability lack of : mod/data:approve $approval = $DB->get_field('data_records', 'approved', array('id' => $record->id)); if (!$approval && !has_capability('mod/data:manageentries', $context)) { if (!empty($CFG->search_access_debug)) { echo "search reject : unapproved resource "; } return false; } //minimum records to view check // trap if too few records // TODO : report a potential capability lack of : mod/data:viewhiddenentries $recordsAmount = $DB->count_records('data_records', array('dataid' => $data->id)); if ($data->requiredentriestoview > $recordsAmount && !has_capability('mod/data:manageentries', $context)) { if (!empty($CFG->search_access_debug)) { echo "search reject : not enough records to view "; } return false; } //opening periods check // trap if user has not capability to see hidden records and date is out of opening range // TODO : report a potential capability lack of : mod/data:viewhiddenentries $now = usertime(time()); if ($data->timeviewfrom > 0) { if ($now < $data->timeviewfrom && !has_capability('mod/data:manageentries', $context)) { if (!empty($CFG->search_access_debug)) { echo "search reject : still not open activity "; } return false; } } if ($data->timeviewto > 0) { if ($now > $data->timeviewto && !has_capability('mod/data:manageentries', $context)) { if (!empty($CFG->search_access_debug)) { echo "search reject : closed activity "; } return false; } } return true; }
/** * Write one date somewhere in the worksheet * @param integer $row Zero indexed row * @param integer $col Zero indexed column * @param string $date The date to write in UNIX timestamp format * @param mixed $format The XF format for the cell */ function write_date($row, $col, $date, $format=null) { /// Calculate the internal PEAR format $format = $this->MoodleExcelFormat2PearExcelFormat($format); /// Convert the date to Excel format $timezone = get_user_timezone_offset(); if ($timezone == 99) { // system timezone offset in seconds $offset = (int)date('Z'); } else { $offset = (int)($timezone * HOURSECS * 2); } $value = ((usertime($date) + $offset) / 86400) + 25569; /// Add the date safely to the PEAR Worksheet $this->pear_excel_worksheet->writeNumber($row, $col, $value, $format); }
function get_sessions_by_course($sessionids, $displayinfo, $waitlistedsessions) { global $DB, $activefilters, $hasvalue; if (empty($sessionids) && empty($waitlistedsessions)) { return array(); } // Add IDs of wait-listed sessions. foreach ($waitlistedsessions as $session) { // If no date has been selected then add the sessionid. if (!$hasvalue['timestart'] && !$hasvalue['timefinish']) { $sessionids[] = $session->id; } } list($insql, $params) = $DB->get_in_or_equal($sessionids); // If timestart/timefinish has a date, it uses that date. It uses the current month otherwise. $timestart = $hasvalue['timestart'] ? $activefilters['defaultfields']['unixtimestart'] : usertime($displayinfo->tstart); $timeend = $hasvalue['timefinish'] ? $activefilters['defaultfields']['unixtimefinish'] : usertime($displayinfo->tend); $params[] = $timestart; $params[] = $timeend; $sessions = $DB->get_records_sql("SELECT d.id, s.id AS sessionid, f.id AS facetofaceid, f.name, s.datetimeknown, d.timestart, d.timefinish, d.sessiontimezone FROM {facetoface} f JOIN {facetoface_sessions} s ON f.id = s.facetoface JOIN {facetoface_sessions_dates} d ON d.sessionid = s.id WHERE s.id {$insql} AND ((d.timestart >= ? AND d.timestart <= ?) OR s.datetimeknown = 0) ORDER BY f.name, d.timestart", $params); return $sessions; }
public static function process_gdoc($gdoc) { global $OUTPUT; if (isset($gdoc->explicitlyTrashed) && $gdoc->explicitlyTrashed) { return false; } $title = !empty($gdoc->originalFilename) ? $gdoc->originalFilename : $gdoc->title; $owner = !empty($gdoc->ownerNames) ? implode(', ', $gdoc->ownerNames) : ''; $download = null; if ($gdoc->mimeType == 'application/vnd.google-apps.drawing') { $download = self::get_link($gdoc); } else { if ($gdoc->mimeType == 'application/vnd.google-apps.spreadsheet') { if (isset($gdoc->exportLinks)) { $links = (array) $gdoc->exportLinks; $download = $links['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; $title .= '.xlsx'; } } else { if ($gdoc->mimeType == 'application/vnd.google-apps.fusiontable') { $download = $gdoc->alternateLink; } else { $download = !empty($gdoc->selfUrl) ? $gdoc->selfUrl : (!empty($gdoc->downloadUrl) ? $gdoc->downloadUrl : $gdoc->alternateLink); } } } $url = !empty($gdoc->downloadUrl) ? $gdoc->downloadUrl : ''; $size = (!empty($gdoc->fileSize) ? $gdoc->fileSize : (!empty($gdoc->quotaBytesUsed) ? $gdoc->quotaBytesUsed : 'Unknown')) . ' Bytes'; $thumb = !empty($gdoc->thumbnailLink) ? $gdoc->thumbnailLink : (string) $OUTPUT->pix_url(file_extension_icon($title, 32)); // todo: make sure there's nothing else out there reliant on the $source being the URL $file = array('title' => $title, 'url' => $url, 'source' => $gdoc->id, 'date' => usertime(strtotime($gdoc->modifiedDate)), 'thumbnail' => $thumb, 'author' => $owner, 'size' => $size, 'mimetype' => $gdoc->mimeType, 'webContentLink' => isset($gdoc->webContentLink) ? $gdoc->webContentLink : '', 'selfUrl' => isset($gdoc->selfUrl) ? $gdoc->selfUrl : '', 'downloadUrl' => isset($gdoc->downloadUrl) ? $gdoc->downloadUrl : '', 'alternateLink' => $gdoc->alternateLink, 'download' => $url); return $file; }
public function get_file_list($search = '') { global $CFG; $url = google_docs::DOCUMENTFEED_URL; if ($search) { $url .= '?q=' . urlencode($search); } $content = $this->google_curl->get($url); $xml = new SimpleXMLElement($content); $files = array(); foreach ($xml->entry as $gdoc) { // there doesn't seem to to be cleaner way of getting the id/type // than spliting this.. if (preg_match('/^http:\\/\\/docs.google.com\\/feeds\\/documents\\/private\\/full\\/([^%]*)%3A(.*)$/', $gdoc->id, $matches)) { $docid = $matches[2]; // FIXME: We're making hard-coded choices about format here. // If the repo api can support it, we could let the user // chose. switch ($matches[1]) { case 'document': $title = $gdoc->title . '.rtf'; $source = 'http://docs.google.com/feeds/download/documents/Export?docID=' . $docid . '&exportFormat=rtf'; break; case 'presentation': $title = $gdoc->title . '.ppt'; $source = 'http://docs.google.com/feeds/download/presentations/Export?docID=' . $docid . '&exportFormat=ppt'; break; case 'spreadsheet': $title = $gdoc->title . '.xls'; $source = 'http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=' . $docid . '&fmcmd=4'; break; } $files[] = array('title' => $title, 'url' => "{$gdoc->link[0]->attributes()->href}", 'source' => $source, 'date' => usertime(strtotime($gdoc->updated)), 'thumbnail' => $CFG->wwwroot . '/pix/f/' . mimeinfo('icon32', $title)); } } return $files; }
function validation($data, $files) { global $CFG, $COURSE, $USER, $DB; require_once $CFG->dirroot . "/mod/emarking/print/locallib.php"; if ($data["type"] < 0 || $data["type"] > 5) { return array("type" => get_string("markingtypemandatory", "mod_emarking")); } // Calculates context for validating permissions // If we have the module available, we use it, otherwise we fallback to course $ctx = context_course::instance($COURSE->id); if ($this->current && $this->current->coursemodule) { $cm = get_coursemodule_from_id('emarking', $this->current->module, $COURSE->id); if ($cm) { $ctx = context_module::instance($cm->id); } } $errors = array(); // Verify that we have enough markers if ($data['type'] == EMARKING_TYPE_MARKER_TRAINING) { // Get all users with permission to grade in emarking $markers = get_enrolled_users($ctx, 'mod/emarking:grade'); $totalmarkers = 0; foreach ($markers as $marker) { if (has_capability('mod/emarking:supervisegrading', $ctx, $marker)) { continue; } $totalmarkers++; } if ($totalmarkers < 2) { $errors['type'] = get_string('notenoughmarkersfortraining', 'mod_emarking'); return $errors; } return $errors; } // Get the exam if we are updating an emarking activity $exam = null; if (isset($data['exam']) && $data['exam'] > 0) { if (!($exam = $DB->get_record("emarking_exams", array("id" => $data["exam"])))) { $errors["exam"] = "Invalid data from form"; } } // If there is no associated exam yet if (!$exam) { // The exam date comes from the date selector $examdate = new DateTime(); $examdate->setTimestamp(usertime($data['examdate'])); // Day of week from 0 Sunday to 6 Saturday $examw = date("w", $examdate->getTimestamp()); // Hour of the day un 00 to 23 format $examh = date("H", $examdate->getTimestamp()); // If minimum days for printing is enabled if (isset($CFG->emarking_minimumdaysbeforeprinting) && $CFG->emarking_minimumdaysbeforeprinting > 0) { // Sundays are forbidden, saturdays from 6am to 4pm TODO: Move this settings to eMarking settings if ($examw == 0 || $examw == 6 && ($examh < 6 || $examh > 16)) { $errors['examdate'] = get_string('examdateinvaliddayofweek', 'mod_emarking'); } // User date. Important because the user sees a date selector based on her timezone settings, not the server's $date = usertime(time()); // Today is the date according to the user's timezone $today = new DateTime(); $today->setTimestamp($date); // We have a minimum difference otherwise we wouldn't be in this part of the code $mindiff = intval($CFG->emarking_minimumdaysbeforeprinting); // If today is saturday or sunday, demand for a bigger difference $todayw = date("w", $today->getTimestamp()); $todayw = $todayw ? $todayw : 7; if ($todayw > 5) { $mindiff += $todayw - 5; } // DateInterval calculated with diff $diff = $today->diff($examdate, false); // The difference using the invert from DateInterval so we know it is in the past $realdiff = $diff->days * ($diff->invert ? -1 : 1); // If the difference is not enough, show an error if ($realdiff < $mindiff) { $a = new stdClass(); $a->mindays = $mindiff; $errors['examdate'] = get_string('examdateinvalid', 'mod_emarking', $a); } } } // If there's no previous exam to associate, and we are creating a new // e-marking, we need the PDF file if ($data["exam"] == 0 && !$this->_instance) { // We get the draftid from the form $draftid = file_get_submitted_draft_itemid('exam_files'); $usercontext = context_user::instance($USER->id); $fs = get_file_storage(); $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid); $tempdir = emarking_get_temp_dir_path($COURSE->id); emarking_initialize_directory($tempdir, true); $numpagesprevious = -1; $exampdfs = array(); foreach ($files as $uploadedfile) { if ($uploadedfile->get_mimetype() !== 'application/pdf') { continue; } $filename = $uploadedfile->get_filename(); $filename = emarking_clean_filename($filename); $newfilename = $tempdir . '/' . $filename; $pdffile = emarking_get_path_from_hash($tempdir, $uploadedfile->get_pathnamehash()); // Executes pdftk burst to get all pages separated $numpages = emarking_pdf_count_pages($newfilename, $tempdir, false); if (!is_numeric($numpages) || $numpages < 1) { $errors["exam_files"] = get_string('invalidpdfnopages', 'mod_emarking'); return $errors; } if ($numpagesprevious >= 0 && $numpagesprevious != $numpages) { $errors["exam_files"] = get_string('invalidpdfnumpagesforms', 'mod_emarking'); return $errors; } $exampdfs[] = array('pathname' => $pdffile, 'filename' => $filename); } if (count($exampdfs) == 0) { $errors["exam_files"] = get_string('invalidpdfnopages', 'mod_emarking'); return $errors; } } // Validate the adjusted slope $adjustslope = isset($data['adjustslope']) ? $data['adjustslope'] : false; $adjustslopescore = isset($data['adjustslopescore']) ? $data['adjustslopescore'] : 0; $adjustslopegrade = isset($data['adjustslopegrade']) ? $data['adjustslopegrade'] : 0; $grademin = $data['grademin']; $grademax = $data['grade']; $regradesopendate = $data['regradesopendate']; $regradesclosedate = $data['regradesclosedate']; // Make sure the minimum score is not greater than the maximum score if ($grademin >= $grademax) { $errors['grademin'] = get_string('gradescheck', 'mod_emarking'); $errors['grade'] = get_string('gradescheck', 'mod_emarking'); } // If we are adjusting the slope if ($adjustslope) { // Make sure the grade is greater than the minimum grade if ($adjustslopegrade <= $grademin) { $errors['adjustslopegrade'] = get_string('adjustslopegrademustbegreaterthanmin', 'mod_emarking'); } // Make sure the grade is lower than the maximum grade if ($adjustslopegrade > $grademax) { $errors['adjustslopegrade'] = get_string('adjustslopegrademustbelowerthanmax', 'mod_emarking'); } // And that the score for adjusting is greater than 0 if ($adjustslopescore <= 0) { $errors['adjustslopescore'] = get_string('adjustslopescoregreaterthanzero', 'mod_emarking'); } } // Validate regrade dates if ($regradesopendate > $regradesclosedate) { $errors['regradesopendate'] = get_string('verifyregradedate', 'mod_emarking'); $errors['regradesclosedate'] = get_string('verifyregradedate', 'mod_emarking'); } // Validate custom marks $custommarks = isset($data['custommarks']) ? $data['custommarks'] : ''; $custommarks = str_replace('\\r\\n', '\\n', $custommarks); if (strlen($custommarks) > 0) { $parts = explode("\n", $custommarks); $linenumber = 0; foreach ($parts as $line) { $linenumber++; if (strlen(trim($line)) == 0) { continue; } $subparts = explode("#", $line); if (count($subparts) != 2) { if (!isset($errors['custommarks'])) { $errors['custommarks'] = get_string('invalidcustommarks', 'mod_emarking'); } $errors['custommarks'] .= "{$linenumber} "; } } } $qualitycontrol = isset($data['enablequalitycontrol']) ? $data['enablequalitycontrol'] : false; if ($data['type'] == EMARKING_TYPE_NORMAL && $qualitycontrol) { // Get all users with permission to grade in emarking // Get all users with permission to grade in emarking $markers = get_enrolled_users($ctx, 'mod/emarking:grade'); $totalmarkers = 0; foreach ($markers as $marker) { if (isset($data['marker-' . $marker->id])) { $totalmarkers++; } } if ($totalmarkers == 0) { $errors['markers'] = get_string('notenoughmarkersforqualitycontrol', 'mod_emarking'); } } if ($data["exam"] > 0 && $this->_instance) { $previousexam = $DB->get_record("emarking_exams", array("emarking" => $this->_instance)); if ($previousexam && $previousexam->id != $data["exam"]) { $errors["exam"] = "An exam is already assigned for this emarking activity"; } } return $errors; }
public function get_file_list($search = '', $repo = null) { // require_once('constants.php'); global $CFG, $OUTPUT; $url = get_morsle_url($search); if (array_key_exists('path', $search)) { $path = $search['path'] . '/'; unset($search['path']); } else { $path = null; } foreach ($search as $key => $param) { if ($key === 'q') { $param = urlencode($param); } $params[$key] = trim($param); } // $url .= '?' . implode_assoc('=', '&', $params); $content = twolegged($url, $params, 'GET'); // $content = $this->get($url, $params, null); $xml = new SimpleXMLElement($content->response); $files = array(); $repolink = "{$CFG->wwwroot}/repository/repository_ajax.php?action=list&p="; foreach ($xml->entry as $gdoc) { $docid = (string) $gdoc->children('http://schemas.google.com/g/2005')->resourceId; list($type, $docid) = explode(':', $docid); $title = (string) $gdoc->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 'folder': break; case 'document': $temptitle = 'temp.doc'; break; case 'presentation': $temptitle = 'temp.ppt'; break; case 'spreadsheet': $temptitle = 'temp.xls'; break; case 'pdf': $temptitle = 'temp.pdf'; break; default: $temptitle = $gdoc->title; } $source = (string) get_href_noentry($gdoc, GDOC_ALT_REL); // TODO: get this thumbnail working with the display $iconlink = '<img src="' . (string) get_href_noentry($gdoc, GDOC_THUMB_REL) . '" />'; if (!empty($source)) { if ($type == 'folder') { echo null; $files[] = array('title' => $title, 'url' => "{$gdoc->link[0]->attributes()->href}", 'source' => $source, 'date' => usertime(strtotime($gdoc->updated)), 'children' => array(), 'path' => base64_encode($docid . '|' . $path . $title), 'thumbnail' => (string) $OUTPUT->pix_url('f/folder-64')); } else { $files[] = array('title' => $title, 'url' => $source, 'source' => $source, 'date' => usertime(strtotime($gdoc->updated)), 'thumbnail' => (string) $OUTPUT->pix_url(file_extension_icon($temptitle, 64))); } } } return $files; }
function validation($data, $files) { global $CFG; $errors = array(); // The exam date comes from the date selector $examdate = new DateTime(); $examdate->setTimestamp(usertime($data['examdate'])); // Day of week from 0 Sunday to 6 Saturday $examw = date("w", $examdate->getTimestamp()); // Hour of the day un 00 to 23 format $examh = date("H", $examdate->getTimestamp()); // Sundays are forbidden, saturdays from 6am to 4pm TODO: Move this settings to eMarking settings if ($examw == 0 || $examw == 6 && ($examh < 6 || $examh > 16)) { $errors['examdate'] = get_string('examdateinvaliddayofweek', 'mod_emarking'); } // If minimum days for printing is enabled if (isset($CFG->emarking_minimumdaysbeforeprinting) && $CFG->emarking_minimumdaysbeforeprinting > 0) { // User date. Important because the user sees a date selector based on her timezone settings, not the server's $date = usertime(time()); // Today is the date according to the user's timezone $today = new DateTime(); $today->setTimestamp($date); // We have a minimum difference otherwise we wouldn't be in this part of the code $mindiff = intval($CFG->emarking_minimumdaysbeforeprinting); // If today is saturday or sunday, demand for a bigger difference $todayw = date("w", $today->getTimestamp()); $todayw = $todayw ? $todayw : 7; if ($todayw > 5) { $mindiff += $todayw - 5; } // DateInterval calculated with diff $diff = $today->diff($examdate, false); // The difference using the invert from DateInterval so we know it is in the past $realdiff = $diff->days * ($diff->invert ? -1 : 1); // If the difference is not enough, show an error if ($realdiff < $mindiff) { $a = new stdClass(); $a->mindays = $mindiff; $errors['examdate'] = get_string('examdateinvalid', 'mod_emarking', $a); } } // If print random order within groups if (isset($data['printrandom']) && $data['printrandom'] === '1') { $groups = groups_get_all_groups($data["course"]); if (count($groups) == 0) { $errors['printrandom'] = get_string('printrandominvalid', 'mod_emarking'); } } return $errors; }
/** * returns unix timestamp from a date string depending on the date format * * @param string $format e.g. "d/m/Y" - see date_parse_from_format for supported formats * @param string $date a date to be converted e.g. "12/06/12" * @return int unix timestamp (0 if fails to parse) */ function facetofaceb_date_parse_from_format($format, $date) { global $CFG; $tz = isset($CFG->timezone) ? $CFG->timezone : 99; $timezone = get_user_timezone_offset($tz); $dateArray = array(); $dateArray = date_parse_from_format($format, $date); if (is_array($dateArray) && isset($dateArray['error_count']) && $dateArray['error_count'] == 0) { if (abs($timezone) > 13) { $time = mktime($dateArray['hour'], $dateArray['minute'], $dateArray['second'], $dateArray['month'], $dateArray['day'], $dateArray['year']); } else { $time = gmmktime($dateArray['hour'], $dateArray['minute'], $dateArray['second'], $dateArray['month'], $dateArray['day'], $dateArray['year']); $time = usertime($time, $timezone); } return $time; } else { return 0; } }
private function get_exam_date_errors($data) { global $CFG; $errors = array(); if (!isset($data['examdate'])) { $a = new stdClass(); $a->mindays = 2; $errors['examdate'] = get_string('examdateinvalid', 'mod_emarking', $a); return $errors; } // The exam date comes from the date selector. $examdate = new DateTime(); $examdate->setTimestamp(usertime($data['examdate'])); // Day of week from 0 Sunday to 6 Saturday. $examw = date("w", $examdate->getTimestamp()); // Hour of the day un 00 to 23 format. $examh = date("H", $examdate->getTimestamp()); // We have a minimum difference otherwise we wouldn't be in this part of the code. if (isset($CFG->emarking_minimumdaysbeforeprinting) && $CFG->emarking_minimumdaysbeforeprinting > 0) { $mindiff = intval($CFG->emarking_minimumdaysbeforeprinting); } else { return $errors; } // Sundays are forbidden, saturdays from 6am to 4pm TODO: Move this settings to eMarking settings. if ($examw == 0 || $examw == 6 && ($examh < 6 || $examh > 16)) { $errors['examdate'] = get_string('examdateinvaliddayofweek', 'mod_emarking'); } // User date. Important because the user sees a date selector based on her timezone settings, not the server's. $date = usertime(time()); // Today is the date according to the user's timezone. $today = new DateTime(); $today->setTimestamp($date); // If today is saturday or sunday, demand for a bigger difference. $todayw = date("w", $today->getTimestamp()); $todayw = $todayw ? $todayw : 7; if ($todayw > 5) { $mindiff += $todayw - 5; } // DateInterval calculated with diff. $diff = $today->diff($examdate, false); // The difference using the invert from DateInterval so we know it is in the past. $realdiff = $diff->days * ($diff->invert ? -1 : 1); // If the difference is not enough, show an error. if ($realdiff < $mindiff) { $a = new stdClass(); $a->mindays = $mindiff; $errors['examdate'] = get_string('examdateinvalid', 'mod_emarking', $a); } return $errors; }
/** * Write one date somewhere in the worksheet * @param integer $row Zero indexed row * @param integer $col Zero indexed column * @param string $date The date to write in UNIX timestamp format * @param mixed $format The XF format for the cell */ function write_date($row, $col, $date, $format = null) { /// Calculate the internal PEAR format $format = $this->MoodleExcelFormat2PearExcelFormat($format); /// Convert the date to Excel format $timezone = get_user_timezone_offset(); $value = (usertime($date) + (int) ($timezone * HOURSECS * 2)) / 86400 + 25569; /// Add the date safely to the PEAR Worksheet $this->pear_excel_worksheet->writeNumber($row, $col, $value, $format); }
/** * Displays a month in detail * * @param calendar_information $calendar * @return string */ public function show_month_detailed(calendar_information $calendar, moodle_url $returnurl = null) { global $CFG; if (empty($returnurl)) { $returnurl = $this->page->url; } $date = usergetdate(time()); $display = new stdClass(); $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday()); $display->maxwday = $display->minwday + 6; $display->thismonth = $date['mon'] == $calendar->month; $display->maxdays = calendar_days_in_month($calendar->month, $calendar->year); $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, $calendar->month, 1, $calendar->year); // This is GMT $display->tend = gmmktime(23, 59, 59, $calendar->month, $display->maxdays, $calendar->year); // 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, $calendar->month, 1, $calendar->year); $display->tend = mktime(23, 59, 59, $calendar->month, $display->maxdays, $calendar->year); $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), $calendar->users, $calendar->groups, $calendar->courses); if (!empty($events)) { foreach ($events as $eventid => $event) { $event = new calendar_event($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, $calendar->month, $calendar->year, $eventsbyday, $durationbyday, $typesbyday, $calendar->courses); $output = html_writer::start_tag('div', array('class' => 'header')); if (calendar_user_can_add_event($calendar->course)) { $output .= $this->add_event_button($calendar->course->id, null, $calendar->month, $calendar->year); } $output .= get_string('detailedmonthview', 'calendar') . ': ' . $this->course_filter_selector($returnurl); $output .= html_writer::end_tag('div', array('class' => 'header')); // Controls $output .= html_writer::tag('div', calendar_top_controls('month', array('id' => $calendar->courseid, 'm' => $calendar->month, 'y' => $calendar->year)), array('class' => 'controls')); $days = calendar_get_days(); $table = new html_table(); $table->attributes = array('class' => 'calendarmonth calendartable'); $table->data = array(); $header = new html_table_row(); $header->attributes = array('class' => 'weekdays'); $header->cells = array(); 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 $cell = new html_table_cell(get_string($days[$i % 7], 'calendar')); $cell->header = true; $header->cells[] = $cell; } // For the table display. $week is the row; $dayweek is the column. $week = 1; $dayweek = $startwday; // Create an array of all the week days. $wdays = array(0 => '<strong>' . get_string('sunday', 'calendar') . '</strong>', 1 => '<strong>' . get_string('monday', 'calendar') . '</strong>', 2 => '<strong>' . get_string('tuesday', 'calendar') . '</strong>', 3 => '<strong>' . get_string('wednesday', 'calendar') . '</strong>', 4 => '<strong>' . get_string('thursday', 'calendar') . '</strong>', 5 => '<strong>' . get_string('friday', 'calendar') . '</strong>', 6 => '<strong>' . get_string('saturday', 'calendar') . '</strong>'); // Loop only if the day offset is greater than 0. // This loop involves shifting the days around until the desired start day // is at the start of the array. $daycount = 0; while ($display->minwday > $daycount++) { $wdays_end = array_shift($wdays); array_push($wdays, $wdays_end); } // Now we set the (modified) array to the table header to be displayed. $table->head = $wdays; $row = new html_table_row(array()); // Paddding (the first week may have blank days in the beginning) for ($i = $display->minwday; $i < $startwday; ++$i) { $cell = new html_table_cell(' '); $cell->attributes = array('class' => 'nottoday'); $row->cells[] = $cell; } // Now display all the calendar $weekend = CALENDAR_DEFAULT_WEEKEND; if (isset($CFG->calendar_weekend)) { $weekend = intval($CFG->calendar_weekend); } for ($calendar->day = 1; $calendar->day <= $display->maxdays; ++$calendar->day, ++$dayweek) { if ($dayweek > $display->maxwday) { // We need to change week (table row) $table->data[] = $row; $row = new html_table_row(array()); $dayweek = $display->minwday; ++$week; } // Reset vars $cell = new html_table_cell(); $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', array('view' => 'day', 'course' => $calendar->courseid)), $calendar->day, $calendar->month, $calendar->year); $cellclasses = array(); if ($weekend & 1 << $dayweek % 7) { // Weekend. This is true no matter what the exact range is. $cellclasses[] = 'weekend'; } // Special visual fx if an event is defined if (isset($eventsbyday[$calendar->day])) { if (count($eventsbyday[$calendar->day]) == 1) { $title = get_string('oneevent', 'calendar'); } else { $title = get_string('manyevents', 'calendar', count($eventsbyday[$calendar->day])); } $cell->text = html_writer::tag('div', html_writer::link($dayhref, $calendar->day, array('title' => $title)), array('class' => 'day')); } else { $cell->text = html_writer::tag('div', $calendar->day, array('class' => 'day')); } // Special visual fx if an event spans many days $durationclass = false; if (isset($typesbyday[$calendar->day]['durationglobal'])) { $durationclass = 'duration_global'; } else { if (isset($typesbyday[$calendar->day]['durationcourse'])) { $durationclass = 'duration_course'; } else { if (isset($typesbyday[$calendar->day]['durationgroup'])) { $durationclass = 'duration_group'; } else { if (isset($typesbyday[$calendar->day]['durationuser'])) { $durationclass = 'duration_user'; } } } } if ($durationclass) { $cellclasses[] = 'duration'; $cellclasses[] = $durationclass; } // Special visual fx for today if ($display->thismonth && $calendar->day == $calendar->day) { $cellclasses[] = 'today'; } else { $cellclasses[] = 'nottoday'; } $cell->attributes = array('class' => join(' ', $cellclasses)); if (isset($eventsbyday[$calendar->day])) { $cell->text .= html_writer::start_tag('ul', array('class' => 'events-new')); foreach ($eventsbyday[$calendar->day] as $eventindex) { // If event has a class set then add it to the event <li> tag $attributes = array(); if (!empty($events[$eventindex]->class)) { $attributes['class'] = $events[$eventindex]->class; } $dayhref->set_anchor('event_' . $events[$eventindex]->id); $link = html_writer::link($dayhref, format_string($events[$eventindex]->name, true)); $cell->text .= html_writer::tag('li', $link, $attributes); } $cell->text .= html_writer::end_tag('ul'); } if (isset($durationbyday[$calendar->day])) { $cell->text .= html_writer::start_tag('ul', array('class' => 'events-underway')); foreach ($durationbyday[$calendar->day] as $eventindex) { $cell->text .= html_writer::tag('li', '[' . format_string($events[$eventindex]->name, true) . ']', array('class' => 'events-underway')); } $cell->text .= html_writer::end_tag('ul'); } $row->cells[] = $cell; } // Paddding (the last week may have blank days at the end) for ($i = $dayweek; $i <= $display->maxwday; ++$i) { $cell = new html_table_cell(' '); $cell->attributes = array('class' => 'nottoday'); $row->cells[] = $cell; } $table->data[] = $row; $output .= html_writer::table($table); // OK, now for the filtering display $output .= $this->filter_selection_table($calendar); return $output; }
function definition() { global $DB, $CFG; // Verifies that the global configurated logo exists, and if it's new it copies it // to a normal space within Moodle's filesystem emarking_verify_logo(); $mform = $this->_form; $instance = $this->_customdata; $cmid = $instance['cmid']; $courseid = $instance['courseid']; $examid = $instance['examid']; // Multicourse // Get the course record to get the shortname $course = $DB->get_record('course', array('id' => $courseid)); $exam = $DB->get_record('emarking_exams', array('id' => $examid)); // Exam id goes hidden $mform->addElement('hidden', 'id', $examid); $mform->setType('id', PARAM_INT); // Course module id goes hidden as well $mform->addElement('hidden', 'cm', $cmid); $mform->setType('cm', PARAM_INT); // Course id goes hidden as well $mform->addElement('hidden', 'course', $courseid); $mform->setType('course', PARAM_INT); // Exam totalpages goes hidden as well $mform->addElement('hidden', 'totalpages'); $mform->setType('totalpages', PARAM_INT); $mform->addElement('header', 'exam_title', get_string('examinfo', 'mod_emarking')); $mform->addElement('static', 'coursename', get_string('course'), $course->fullname); // Exam name $mform->addElement('text', 'name', get_string('examname', 'mod_emarking')); $mform->addRule('name', get_string('required'), 'required', null, 'client'); $mform->addRule('name', get_string('maximumchars', '', 50), 'maxlength', 50, 'client'); $mform->setType('name', PARAM_TEXT); $mform->addHelpButton('name', 'examname', 'mod_emarking'); $date = new DateTime(); $date->setTimestamp(usertime(time())); $date->modify('+2 days'); $date->modify('+10 minutes'); // Exam date $mform->addElement('date_time_selector', 'examdate', get_string('examdate', 'mod_emarking'), array('startyear' => date('Y'), 'stopyear' => date('Y') + 1, 'step' => 5, 'defaulttime' => $date->getTimestamp(), 'optional' => false), $instance['options']); $mform->addRule('examdate', get_string('filerequiredpdf', 'mod_emarking'), 'required', null, 'client'); $mform->addHelpButton('examdate', 'examdate', 'mod_emarking'); // Exam PDF file $mform->addElement('filemanager', 'exam_files', get_string('pdffile', 'mod_emarking'), null, array('subdirs' => 0, 'maxbytes' => 0, 'maxfiles' => 10, 'accepted_types' => array('.pdf'), 'return_types' => FILE_INTERNAL)); //if ($examid == 0) //se omite el if, ya que al editar el examen emite error $mform->addRule('exam_files', get_string('filerequiredtosendnewprintorder', 'mod_emarking'), 'required', null, 'client'); $mform->setType('exam_files', PARAM_FILE); $mform->addHelpButton('exam_files', 'pdffile', 'mod_emarking'); // eMarking configuration $mform->addElement('header', 'emarking_title', get_string('emarking', 'mod_emarking')); // Personalized header (using QR) $mform->addElement('checkbox', 'headerqr', get_string('headerqr', 'mod_emarking')); // $mform->addElement('hidden','headerqr'); $mform->setType('headerqr', PARAM_BOOL); $mform->addHelpButton('headerqr', 'headerqr', 'mod_emarking'); $mform->setDefault('headerqr', true); // Enrolment methods to include in printing $enrolcheckboxes = array(); $enrolavailables = array(); $enrolments = enrol_get_instances($courseid, true); $flag = 0; foreach ($enrolments as $enrolment) { if ($enrolment->enrol == "meta") { if ($flag == 0) { $flag = 1; $enrolavailables[] = $enrolment->enrol; $enrolcheckboxes[] = $mform->createElement('checkbox', $enrolment->enrol, null, get_string('enrol' . $enrolment->enrol, 'mod_emarking'), 'checked'); } } else { $enrolavailables[] = $enrolment->enrol; $enrolcheckboxes[] = $mform->createElement('checkbox', $enrolment->enrol, null, get_string('enrol' . $enrolment->enrol, 'mod_emarking'), 'checked'); } } $mform->addGroup($enrolcheckboxes, 'enrolments', get_string('includestudentsinexam', 'mod_emarking'), array('<br/>'), true); if ($CFG->emarking_enrolincludes && strlen($CFG->emarking_enrolincludes) > 1) { $enrolincludes = explode(",", $CFG->emarking_enrolincludes); foreach ($enrolincludes as $enroldefault) { if (in_array($enroldefault, $enrolavailables)) { $mform->setDefault("enrolments[{$enroldefault}]", true); } } } if ($CFG->emarking_enableprintingrandom) { // Print Random $mform->addElement('checkbox', 'printrandom', get_string('printrandom', 'mod_emarking')); $mform->setType('printrandom', PARAM_BOOL); $mform->addHelpButton('printrandom', 'printrandom', 'mod_emarking'); $mform->setDefault('printrandom', false); } if ($CFG->emarking_enableprintinglist) { // Print Random $mform->addElement('checkbox', 'printlist', get_string('printlist', 'mod_emarking')); $mform->setType('printlist', PARAM_BOOL); $mform->addHelpButton('printlist', 'printlist', 'mod_emarking'); $mform->setDefault('printlist', false); } // Copy center instructions $mform->addElement('header', 'exam_title', get_string('copycenterinstructions', 'mod_emarking')); // Numbers from 0 to 14 for extra exams and sheets $numberarray = array(); for ($j = 0; $j < 3; $j++) { $numberarray[$j] = $j; } // Extra sheets per student $mform->addElement('select', 'extrasheets', get_string('extrasheets', 'mod_emarking'), $numberarray, null); $mform->addHelpButton('extrasheets', 'extrasheets', 'mod_emarking'); // Extra students $mform->addElement('select', 'extraexams', get_string('extraexams', 'mod_emarking'), $numberarray, null); $mform->addHelpButton('extraexams', 'extraexams', 'mod_emarking'); // print double sided // $mform->addElement('checkbox','printdoublesided',get_string('printdoublesided', 'mod_emarking'))); $mform->addElement('hidden', 'printdoublesided'); $mform->setType('printdoublesided', PARAM_BOOL); // $mform->addHelpButton('printdoublesided', 'printdoublesided', 'mod_emarking'); $mform->setDefault('printdoublesided', false); // Obtain parallel courses if ($seccionesparalelas = emarking_get_parallel_courses($course, null, $CFG->emarking_parallelregex)) { // Add a checkbox for each parallel course $checkboxes = array(); foreach ($seccionesparalelas as $cid => $course) { $checkboxes[] = $mform->createElement('checkbox', $course->shortname, null, $course->fullname, 'checked'); } // If there's any parallel course we add the multicourse option if (count($checkboxes) > 0) { $mform->addGroup($checkboxes, 'multisecciones', get_string('multicourse', 'mod_emarking'), array('<br/>'), true); $mform->addHelpButton('multisecciones', 'multicourse', 'mod_emarking'); if ($examid == 0) { $mform->addElement('button', 'selectall', get_string('selectall', 'mod_emarking'), array('onClick' => 'selectAllCheckboxes(this.form,true);')); $mform->addElement('button', 'deselectall', get_string('selectnone', 'mod_emarking'), array('onClick' => 'selectAllCheckboxes(this.form,false);')); } else { foreach ($seccionesparalelas as $cid => $course) { $selected = false; if ($examid > 0 && ($parallel = $DB->get_record('emarking_exams', array('file' => $exam->file, 'course' => $cid)))) { $selected = true; } $mform->setType("multisecciones[{$course->shortname}]", PARAM_BOOL); if ($selected) { $mform->setDefault("multisecciones[{$course->shortname}]", true); } } } } $this->extraScript .= "<script>function selectAllCheckboxes(form,checked) { " . "for (var i = 0; i < form.elements.length; i++ ) { " . " if (form.elements[i].type == 'checkbox' && form.elements[i].id.indexOf('multiseccion') > 0) { " . " form.elements[i].checked = checked; " . " } " . "} " . "}</script>"; } $mform->addElement('hidden', 'action', 'uploadfile'); $mform->setType('action', PARAM_ALPHA); // buttons $this->add_action_buttons(true, get_string('submit')); }
/** * 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; } 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' => usertime(strtotime($gdoc->updated)), 'thumbnail' => (string) $OUTPUT->pix_url(file_extension_icon($title, 32))); } return $files; }
function certificate_date_report($user) { global $certificate; $certdate = usertime($user->timecreated); $datestrings = array("%DD", "%dd", "%ss", "%MS", "%YY", "%yy", "%mm", "%MM"); $datereplace = array(date('d', $certdate), date('j', $certdate), date('S', $certdate), userdate($certdate, "%B"), strftime('%Y', $certdate), strftime('%y', $certdate), date('n', $certdate), date('m', $certdate)); $certificatedate = str_replace($datestrings, $datereplace, $certificate->datefmt) . ", " . strftime('%X', $certdate); return $certificatedate; }
public function test_usertime() { // This is a useless bad hack, it needs to be completely eliminated. $time = gmmktime(1, 1, 1, 3, 1, 2015); $this->assertSame($time - 60 * 60 * 1, usertime($time, '1')); $this->assertSame($time - 60 * 60 * -1, usertime($time, '-1')); $this->assertSame($time - 60 * 60 * 1, usertime($time, 'Europe/Prague')); $this->assertSame($time - 60 * 60 * 8, usertime($time, 'Australia/Perth')); $this->assertSame($time - 60 * 60 * 12, usertime($time, 'Pacific/Auckland')); $this->assertSame($time - 60 * 60 * -5, usertime($time, 'America/New_York')); $time = gmmktime(1, 1, 1, 5, 1, 2015); $this->assertSame($time - 60 * 60 * 1, usertime($time, '1')); $this->assertSame($time - 60 * 60 * -1, usertime($time, '-1')); $this->assertSame($time - 60 * 60 * 1, usertime($time, 'Europe/Prague')); $this->assertSame($time - 60 * 60 * 8, usertime($time, 'Australia/Perth')); $this->assertSame($time - 60 * 60 * 12, usertime($time, 'Pacific/Auckland')); $this->assertSame($time - 60 * 60 * -5, usertime($time, 'America/New_York')); }
public function get_listing($path = '', $page = '', $query = null) { global $CFG, $USER, $OUTPUT, $COURSE, $DB; require_once "{$CFG->dirroot}/google/constants.php"; require_once 'course_constants.php'; $ret = array(); $ret['dynload'] = true; $user = build_user(); $course = $COURSE; // $user = $USER->email; // TODO: uncomment $useraccount = $USER->email; $user = $useraccount; $deptstr = get_string('departmentaccountstring', 'repository_morsle'); // get departmental folder if exists $shortname = is_number(substr($course->shortname, 0, 5)) ? substr($course->shortname, 6) : $course->shortname; $morsleaccount = strtolower($course->shortname . '@' . $this->domain); // SPLIT INTO DEPARTMENTAL CODES $dept = explode("-", $shortname); if (defined($dept[0])) { $deptstr = CONSTANT($dept[0]) . $deptstr; $deptshortstr = strtolower(substr($deptstr, 0, 6)); $deptaccount = strtolower($deptstr . '@' . $this->domain); } else { $deptstr = 'nodept'; $deptshortstr = 'nodept'; $deptaccount = 'nodept'; } // get course level folders or documents $maxfiles = get_config('morsle', 'maxfilesreturned'); // get a docid if available $path = base64_decode($path); if ($path == '') { $root_path = null; $pathleftover = null; $search_path = null; } elseif ($path == $deptstr) { $root_path = $deptstr; $pathleftover = null; $search_path = null; } elseif (strpos($path, '|')) { list($docid, $pathleftover) = explode('|', $path); $search_path = 'folder%3A' . $docid; $root_path = strtolower(substr($pathleftover, 0, 6)); } else { $root_path = strtolower(substr($path, 0, 6)); $pathleftover = $path; $search_path = null; } // handle a search instance if ($query !== null) { $root_path = 'queryi'; } switch ($root_path) { case null: // empty: get only the readonly and writeable folders plus any files and user folder and (if available) department folder $user = $morsleaccount; $search = array('xoauth_requestor_id' => $user, 'showfolders' => 'true', 'folder' => 'folder%3Aroot', 'max-results' => $maxfiles); if ($search_path !== null) { // looking for another folder's contents $search['folder'] = $search_path; } $mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored // unset($search['repo_id']); $mdocs = new morsle_docs($mauth); $ret['list'] = $mdocs->get_file_list($search, $this); // get user level folders or documents $user = $useraccount; $title = get_string('useraccountstring', 'repository_morsle') . $user; $url = DOCUMENTFEED_URL; $ret['list'][] = array('title' => $title, 'url' => $url, 'source' => $url, 'date' => usertime(strtotime(time())), 'children' => array(), 'path' => base64_encode('User Files'), 'thumbnail' => (string) $OUTPUT->pix_url('f/folder-64')); // check to see if we even have a departmental account for this department but don't show the departmental collection if we're already in it indicated by $wdir // TODO: this needs to change if we eliminate morsle table, but if the read-only or writeable folders get renamed then we need the table // department account if exists $conditions = " shortname = '{$deptstr}' "; $user = $deptaccount; $title = get_string('deptaccountstring', 'repository_morsle') . $user; if (strpos($path, $deptstr) === false && ($is_morsle_dept = $DB->get_record_select('morsle_active', $conditions))) { $ret['list'][] = array('title' => $deptstr, 'url' => $url, 'source' => $url, 'date' => usertime(strtotime(time())), 'children' => array(), 'path' => base64_encode($deptstr), 'thumbnail' => (string) $OUTPUT->pix_url('f/folder-64')); } $ret['path'][]['name'] = 'Morsle Files'; break; case 'queryi': case 'user f': // user account google files $search = array('xoauth_requestor_id' => $user, 'path' => $pathleftover, 'showfolders' => 'true', 'repo_id' => 5, 'max-results' => $maxfiles); if ($search_path !== null) { // looking for another folder's contents $search['folder'] = $search_path; } if ($query !== null) { $search['q'] = $query; } $mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored unset($search['repo_id']); $mdocs = new morsle_docs($mauth); $ret['list'] = $mdocs->get_file_list($search, $this); $ret['path'][]['name'] = $pathleftover; break; case '/': // TODO: what does this get $search = array('xoauth_requestor_id' => $user, 'folder' => $search_path, 'repo_id' => 5, 'max-results' => $maxfiles); $mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored unset($search['repo_id']); $mdocs = new morsle_docs($mauth); $ret['list'] = $mdocs->get_file_list($search, $this); break; case $deptstr: // department account google files, if we got here it means department files exist $user = $deptaccount; $search = array('xoauth_requestor_id' => $user, 'path' => $pathleftover, 'showfolders' => 'true', 'repo_id' => 5, 'max-results' => $maxfiles); if ($search_path !== null) { // looking for another folder's contents $search['folder'] = $search_path; } $mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored unset($search['repo_id']); $mdocs = new morsle_docs($mauth); $ret['list'] = $mdocs->get_file_list($search, $this); $ret['path'][]['name'] = $pathleftover; break; case 'morsle': // only way we'd get here is if the read-only or writeable folder got clicked $user = $morsleaccount; $search = array('xoauth_requestor_id' => $user, 'path' => 'Morsle Files', 'max-results' => $maxfiles); if ($search_path !== null) { // looking for another folder's contents $search['folder'] = $search_path; } $mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored unset($search['repo_id']); $mdocs = new morsle_docs($mauth); $ret['list'] = $mdocs->get_file_list($search); $ret['path'][]['name'] = $pathleftover; break; default: // empty: get only the readonly and writeable folders user folder and (if available) department folder $user = $morsleaccount; // list($title, $domain) = explode('@',$user); $search = array('xoauth_requestor_id' => $user, 'showfolders' => 'true', 'max-results' => $maxfiles); if ($search_path !== null) { // looking for another folder's contents $search['folder'] = $search_path; } $mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored // unset($search['repo_id']); $mdocs = new morsle_docs($mauth); $ret['list'] = $mdocs->get_file_list($search, $this); // check to see if we even have a departmental account for this department but don't show the departmental collection if we're already in it indicated by $wdir // TODO: this needs to change if we eliminate morsle table $conditions = " shortname = '{$deptstr}' "; $user = $deptaccount; $title = get_string('deptaccountstring', 'repository_morsle') . $user; if (strpos($path, $deptstr) === false && ($is_morsle_dept = $DB->get_record_select('morsle_active', $conditions))) { $ret['list'][] = array('title' => $deptstr, 'url' => $url, 'source' => $url, 'date' => usertime(strtotime(time())), 'children' => array(), 'path' => base64_encode($deptstr), 'thumbnail' => (string) $OUTPUT->pix_url('f/folder-64')); } $ret['path'][]['name'] = 'Morsle Files'; } return $ret; }
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>'; }
public function get_file_list($search = '') { global $CFG, $OUTPUT; $url = google_docs::DOCUMENTFEED_URL; if ($search) { $url .= '?q=' . urlencode($search); } $content = $this->google_curl->get($url); $xml = new SimpleXMLElement($content); $files = array(); 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': $title = (string) $gdoc->title; $source = (string) $gdoc->content[0]->attributes()->src; break; } if (!empty($source)) { $files[] = array('title' => $title, 'url' => "{$gdoc->link[0]->attributes()->href}", 'source' => $source, 'date' => usertime(strtotime($gdoc->updated)), 'thumbnail' => (string) $OUTPUT->pix_url(file_extension_icon($title, 32))); } } return $files; }
/** * Return standard meta data for module * * @param cm_info $mod * @param string $timeopenfld * @param string $timeclosefld * @param string $keyfield * @param string $submissiontable * @param string $submittedonfld * @param string $submitstrkey * @param bool $isgradeable * @param string $submitselect - sql to further filter submission row select statement - e.g. st.status='finished' * @return bool | \theme_snap\activity_meta */ protected static function std_meta(\cm_info $mod, $timeopenfld, $timeclosefld, $keyfield, $submissiontable, $submittedonfld, $submitstrkey, $isgradeable = false, $submitselect = '') { global $USER; $courseid = $mod->course; // Create meta data object. $meta = new \theme_snap\activity_meta(); $meta->submitstrkey = $submitstrkey; $meta->submittedstr = get_string($submitstrkey, 'theme_snap'); $meta->notsubmittedstr = get_string('not' . $submitstrkey, 'theme_snap'); if (get_string_manager()->string_exists($mod->modname . 'draft', 'theme_snap')) { $meta->draftstr = get_string($mod->modname . 'draft', 'theme_snap'); } else { $meta->drafstr = get_string('draft', 'theme_snap'); } if (get_string_manager()->string_exists($mod->modname . 'reopened', 'theme_snap')) { $meta->reopenedstr = get_string($mod->modname . 'reopened', 'theme_snap'); } else { $meta->reopenedstr = get_string('reopened', 'theme_snap'); } // If module is not visible to the user then don't bother getting meta data. if (!$mod->uservisible) { return $meta; } $activitydates = self::instance_activity_dates($courseid, $mod, $timeopenfld, $timeclosefld); $meta->timeopen = $activitydates->timeopen; $meta->timeclose = $activitydates->timeclose; // TODO: use activity specific "teacher" capabilities. if (has_capability('mod/assign:grade', \context_course::instance($courseid))) { $meta->isteacher = true; // Teacher - useful teacher meta data. $methodnsubmissions = $mod->modname . '_num_submissions'; $methodnungraded = $mod->modname . '_num_submissions_ungraded'; if (method_exists('theme_snap\\activity', $methodnsubmissions)) { $meta->numsubmissions = call_user_func('theme_snap\\activity::' . $methodnsubmissions, $courseid, $mod->instance); } if (method_exists('theme_snap\\activity', $methodnungraded)) { $meta->numrequiregrading = call_user_func('theme_snap\\activity::' . $methodnungraded, $courseid, $mod->instance); } } else { // Student - useful student meta data - only display if activity is available. if (empty($activitydates->timeopen) || usertime($activitydates->timeopen) <= time()) { $submissionrow = self::get_submission_row($courseid, $mod, $submissiontable, $keyfield, $submitselect); if (!empty($submissionrow)) { if ($submissionrow->status) { switch ($submissionrow->status) { case 'draft': $meta->draft = true; break; case 'reopened': $meta->reopened = true; break; case 'submitted': $meta->submitted = true; break; } } else { $meta->submitted = true; $meta->timesubmitted = !empty($submissionrow->{$submittedonfld}) ? $submissionrow->{$submittedonfld} : null; } // If submitted on field uses modified field then fall back to timecreated if modified is 0. if (empty($meta->timesubmitted) && ($submittedonfld = 'timemodified')) { if (isset($submissionrow->timemodified)) { $meta->timesubmitted = $submissionrow->timemodified; } else { $meta->timesubmitted = $submissionrow->timecreated; } } } } $graderow = false; if ($isgradeable) { $graderow = self::grade_row($courseid, $mod); } if ($graderow) { $gradeitem = \grade_item::fetch(array('itemtype' => 'mod', 'itemmodule' => $mod->modname, 'iteminstance' => $mod->instance)); $grade = new \grade_grade(array('itemid' => $gradeitem->id, 'userid' => $USER->id)); $coursecontext = \context_course::instance($courseid); $canviewhiddengrade = has_capability('moodle/grade:viewhidden', $coursecontext); if (!$grade->is_hidden() || $canviewhiddengrade) { $meta->grade = true; } } } return $meta; }
/** * Get the module meta data for a specific module. * * @param cm_info $mod * * @return string */ protected function module_meta_html(cm_info $mod) { global $COURSE, $CFG; $content = ''; if (is_guest(context_course::instance($COURSE->id))) { return ''; } // Do we have an activity function for this module for returning meta data? // @todo - check module lib.php for a meta function (won't work for core mods but will for ours if we wish). $methodname = $mod->modname . '_meta'; if (method_exists('theme_snap\\activity', $methodname)) { $meta = call_user_func('theme_snap\\activity::' . $methodname, $mod); } else { // Can't get meta data for this module. return ''; } $content .= '<div class="module-meta">'; if ($meta->isteacher) { // Teacher - useful teacher meta data. if (!empty($meta->timeclose)) { $dueinfo = get_string('due', 'theme_snap'); $dueclass = 'label-info'; $content .= '<span class="label ' . $dueclass . '">' . $dueinfo . ' ' . userdate($meta->timeclose, get_string('strftimedate', 'langconfig') . '</span>'); } $engagementmeta = array(); $gradedlabel = "info"; // Below, !== false means we get 0 out of x submissions. if (!$meta->submissionnotrequired && $meta->numsubmissions !== false) { $engagementmeta[] = get_string('xofy' . $meta->submitstrkey, 'theme_snap', (object) array('completed' => $meta->numsubmissions, 'participants' => \theme_snap\local::course_participant_count($COURSE->id))); } if ($meta->numrequiregrading) { $gradedlabel = "warning"; $engagementmeta[] = get_string('xungraded', 'theme_snap', $meta->numrequiregrading); } $link = $CFG->wwwroot . '/mod/' . $mod->modname . '/view.php?action=grading&id=' . $mod->id . '&tsort=timesubmitted&filter=require_grading'; $content .= '<a href="' . s($link) . '"><span class="label label-' . $gradedlabel . '">' . implode(', ', $engagementmeta) . '</span></a>'; } else { // Student - useful student meta data. if (!empty($meta->timeopen) && $meta->timeopen > time()) { // Todo - spit out a 'submissions allowed form' tag. $content .= '</div>'; return $content; } // Note, due date is rendered seperately for students as it has a warning class if overdue. if (!empty($meta->timeclose)) { if (empty($meta->submissionnotrequired) && empty($meta->timesubmitted) && time() > usertime($meta->timeclose)) { $dueinfo = get_string('overdue', 'theme_snap'); $dueclass = 'label-danger'; } else { $dueinfo = get_string('due', 'theme_snap'); $dueclass = 'label-info'; } $content .= '<span class="label ' . $dueclass . '">' . $dueinfo . ' ' . userdate($meta->timeclose, get_string('strftimedate', 'langconfig') . '</span>'); } // Feedback meta. if (!empty($meta->grade)) { // Note - the link that a module takes you to would be better off defined by a function in // theme/snap/activity - for now its just hard coded. $url = new \moodle_url('/grade/report/user/index.php', ['id' => $COURSE->id]); if (in_array($mod->modname, ['quiz', 'assign'])) { $url = new \moodle_url('/mod/' . $mod->modname . '/view.php?id=' . $mod->id); } $content .= '<a href="' . $url->out() . '"><span class="label label-info">' . get_string('feedbackavailable', 'theme_snap') . '</span></a>'; } // Submission CTA. if (empty($meta->submissionnotrequired)) { $content .= '<a class="assignment_stage" href="' . $CFG->wwwroot . '/mod/' . $mod->modname . '/view.php?id=' . $mod->id . '">'; if ($meta->submitted) { if (empty($meta->timesubmitted)) { $submittedonstr = ''; } else { $submittedonstr = ' ' . userdate($meta->timesubmitted, get_string('strftimedate', 'langconfig')); } $content .= '<span class="label label-success">' . $meta->submittedstr . $submittedonstr . '</span>'; } else { $warningstr = $meta->draft ? $meta->draftstr : $meta->notsubmittedstr; $warningstr = $meta->reopened ? $meta->reopenedstr : $warningstr; $content .= '<span class="label label-warning">' . $warningstr . '</span>'; } $content .= '</a>'; } } $content .= '</div>'; return $content; }
/** * Given date parts in user time produce a GMT timestamp. * * @package core * @category time * @param int $year The year part to create timestamp of * @param int $month The month part to create timestamp of * @param int $day The day part to create timestamp of * @param int $hour The hour part to create timestamp of * @param int $minute The minute part to create timestamp of * @param int $second The second part to create timestamp of * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset. * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone} * @param bool $applydst Toggle Daylight Saving Time, default true, will be * applied only if timezone is 99 or string. * @return int GMT timestamp */ function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) { // Save input timezone, required for dst offset check. $passedtimezone = $timezone; $timezone = get_user_timezone_offset($timezone); if (abs($timezone) > 13) { // Server time. $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year); } else { $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year); $time = usertime($time, $timezone); // Apply dst for string timezones or if 99 then try dst offset with user's default timezone. if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) { $time -= dst_offset_on($time, $passedtimezone); } } return $time; }
/** * Defines forms elements */ public function definition() { global $COURSE, $DB, $CFG, $USER; $mform = $this->_form; $instance = $this->_customdata; $context = $instance['context']; $cmid = $instance['id']; $emarking = $instance['emarking']; $mform->addElement('hidden', 'id', $cmid); $mform->setType('id', PARAM_INT); $mform->addElement('hidden', 'type', $emarking->type); $mform->setType('type', PARAM_INT); // Today. $date = new DateTime(); $date->setTimestamp(usertime(time())); // Students can see peers answers. $ynoptions = array(0 => get_string('no'), 1 => get_string('yespeerisanonymous', 'mod_emarking')); $mform->addElement('select', 'peervisibility', get_string('viewpeers', 'mod_emarking'), $ynoptions); $mform->addHelpButton('peervisibility', 'viewpeers', 'mod_emarking'); $mform->setDefault('peervisibility', 0); $mform->setType('peervisibility', PARAM_INT); $mform->disabledIf('peervisibility', 'type', 'eq', '2'); // Expected pages for submissions. $mform->addElement('hidden', 'totalpages', 0); $mform->setType('totalpages', PARAM_INT); // Anonymous eMarking setting. $anonymousoptions = array(0 => get_string('studentanonymous_markervisible', 'mod_emarking'), 1 => get_string('studentanonymous_markeranonymous', 'mod_emarking'), 2 => get_string('studentvisible_markervisible', 'mod_emarking'), 3 => get_string('studentvisible_markeranonymous', 'mod_emarking')); if (has_capability('mod/emarking:manageanonymousmarking', $context)) { $mform->addElement('select', 'anonymous', get_string('anonymous', 'mod_emarking'), $anonymousoptions); $mform->addHelpButton('anonymous', 'anonymous', 'mod_emarking'); } else { $mform->addElement('hidden', 'anonymous'); } $mform->setDefault('anonymous', 0); $mform->setType('anonymous', PARAM_INT); $mform->disabledIf('anonymous', 'type', 'eq', '2'); // Justice perception eMarking setting. $justiceoptions = array(EMARKING_JUSTICE_DISABLED => get_string('justicedisabled', 'mod_emarking'), EMARKING_JUSTICE_PER_SUBMISSION => get_string('justicepersubmission', 'mod_emarking'), EMARKING_JUSTICE_PER_CRITERION => get_string('justicepercriterion', 'mod_emarking')); $mform->addElement('select', 'justiceperception', get_string('justiceperception', 'mod_emarking'), $justiceoptions); $mform->addHelpButton('justiceperception', 'justiceperception', 'mod_emarking'); $mform->setDefault('justiceperception', 0); $mform->setType('justiceperception', PARAM_INT); $mform->disabledIf('justiceperception', 'type', 'eq', '2'); $mform->addElement('checkbox', 'linkrubric', get_string('linkrubric', 'mod_emarking')); $mform->addHelpButton('linkrubric', 'linkrubric', 'mod_emarking'); $mform->addElement('checkbox', 'collaborativefeatures', get_string('collaborativefeatures', 'mod_emarking')); $mform->addHelpButton('collaborativefeatures', 'collaborativefeatures', 'mod_emarking'); // Custom marks. if (has_capability('mod/emarking:managespecificmarks', $context)) { $mform->addElement('textarea', 'custommarks', get_string('specificmarks', 'mod_emarking'), array('rows' => 5, 'cols' => 100, 'class' => 'smalltext')); $mform->addHelpButton('custommarks', 'specificmarks', 'mod_emarking'); } else { $mform->addElement('hidden', 'custommarks'); } $mform->setDefault('custommarks', ''); $mform->setType('custommarks', PARAM_TEXT); $mform->setAdvanced('custommarks'); $mform->disabledIf('custommarks', 'type', 'eq', '2'); // Due date settings. $mform->addElement('checkbox', 'qualitycontrol', get_string('enablequalitycontrol', 'mod_emarking')); $mform->addHelpButton('qualitycontrol', 'enablequalitycontrol', 'mod_emarking'); $mform->setAdvanced('qualitycontrol'); $mform->disabledIf('qualitycontrol', 'type', 'eq', '2'); // Get all users with permission to grade in emarking. $markers = get_enrolled_users($context, 'mod/emarking:grade'); $chkmarkers = array(); foreach ($markers as $marker) { $chkmarkers[] = $mform->createElement('checkbox', 'marker-' . $marker->id, null, $marker->firstname . " " . $marker->lastname); } // Add markers group as checkboxes. $mform->addGroup($chkmarkers, 'markers', get_string('markersqualitycontrol', 'mod_emarking'), array('<br />'), false); $mform->addHelpButton('markers', 'markersqualitycontrol', 'mod_emarking'); $mform->setType('markers', PARAM_INT); $mform->disabledIf('markers', 'qualitycontrol'); $mform->setAdvanced('markers'); $mform->disabledIf('markers', 'type', 'eq', '2'); // Due date settings. $mform->addElement('checkbox', 'enableduedate', get_string('enableduedate', 'mod_emarking')); $mform->setAdvanced('enableduedate'); $mform->addElement('date_time_selector', 'markingduedate', get_string('markingduedate', 'mod_emarking'), array('startyear' => date('Y'), 'stopyear' => date('Y') + 1, 'step' => 5, 'defaulttime' => $date->getTimestamp(), 'optional' => false), null); $mform->addHelpButton('markingduedate', 'markingduedate', 'mod_emarking'); $mform->setAdvanced('markingduedate'); $mform->disabledIf('markingduedate', 'enableduedate'); // Regrade settings, dates and enabling. $mform->addElement('checkbox', 'regraderestrictdates', get_string('regraderestrictdates', 'mod_emarking')); $mform->addHelpButton('regraderestrictdates', 'regraderestrictdates', 'mod_emarking'); $mform->setAdvanced('regraderestrictdates'); $mform->disabledIf('regraderestrictdates', 'type', 'eq', '2'); $mform->addElement('date_time_selector', 'regradesopendate', get_string('regradesopendate', 'mod_emarking'), array('startyear' => date('Y'), 'stopyear' => date('Y') + 1, 'step' => 5, 'defaulttime' => $date->getTimestamp(), 'optional' => false), null); $mform->addHelpButton('regradesopendate', 'regradesopendate', 'mod_emarking'); $mform->setAdvanced('regradesopendate'); $mform->disabledIf('regradesopendate', 'regraderestrictdates'); $mform->disabledIf('regradesopendate', 'type', 'eq', '2'); $date->modify('+2 months'); $mform->addElement('date_time_selector', 'regradesclosedate', get_string('regradesclosedate', 'mod_emarking'), array('startyear' => date('Y'), 'stopyear' => date('Y') + 1, 'step' => 5, 'defaulttime' => $date->getTimestamp(), 'optional' => false), null); $mform->addHelpButton('regradesclosedate', 'regradesclosedate', 'mod_emarking'); $mform->setAdvanced('regradesclosedate'); $mform->disabledIf('regradesclosedate', 'regraderestrictdates'); $mform->disabledIf('regradesclosedate', 'type', 'eq', '2'); // Buttons. $this->add_action_buttons(true, get_string('submit')); }
function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) { global $CFG, $USER; $display = new stdClass(); $display->minwday = get_user_preferences('calendar_startwday', CALENDAR_STARTING_WEEKDAY); $display->maxwday = $display->minwday + 6; $content = ''; if (!empty($cal_month) && !empty($cal_year)) { $thisdate = usergetdate(time()); // Date and time the user sees at his location if ($cal_month == $thisdate['mon'] && $cal_year == $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($cal_month, 1, $cal_year)) { $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']); $display->thismonth = true; } else { $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year); $display->thismonth = false; } } } else { $date = usergetdate(time()); // Date and time the user sees at his location $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); 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 } 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 = dayofweek(1, $m, $y); // Align the starting weekday to fall in our display range // This is simple, not foolproof. if ($startwday < $display->minwday) { $startwday += 7; } // TODO: THIS IS TEMPORARY CODE! // [pj] I was just reading through this and realized that I when writing this code I was probably // asking for trouble, as all these time manipulations seem to be unnecessary and a simple // make_timestamp would accomplish the same thing. So here goes a test: //$test_start = make_timestamp($y, $m, 1); //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59); //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) { //notify('Failed assertion in calendar/lib.php line 126; display->tstart = '.$display->tstart.', dst_offset = '.dst_offset_on($display->tstart).', usertime = '.usertime($display->tstart).', make_t = '.$test_start); //} //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) { //notify('Failed assertion in calendar/lib.php line 130; display->tend = '.$display->tend.', dst_offset = '.dst_offset_on($display->tend).', usertime = '.usertime($display->tend).', make_t = '.$test_end); //} // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ! $events = calendar_get_events(usertime($display->tstart) - dst_offset_on($display->tstart), usertime($display->tend) - dst_offset_on($display->tend), $users, $groups, $courses); // Set event course class for course events 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]); } } } } // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra // arguments to this function. $morehref = ''; if (!empty($courses)) { $courses = array_diff($courses, array(SITEID)); if (count($courses) == 1) { $morehref = '&course=' . reset($courses); } } // We want to have easy access by day, since the display is on a per-day basis. // Arguments passed by reference. //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday); calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses); //Accessibility: added summary and <abbr> elements. ///global $CALENDARDAYS; appears to be broken. $days_title = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'); $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear'))); $summary = get_string('tabledata', 'access', $summary); $content .= '<table class="minicalendar" summary="' . $summary . '">'; // Begin table $content .= '<tr class="weekdays">'; // Header row: day names // Print out the names of the weekdays $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'); 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 $content .= '<th scope="col"><abbr title="' . get_string($days_title[$i % 7], 'calendar') . '">' . get_string($days[$i % 7], 'calendar') . "</abbr></th>\n"; } $content .= '</tr><tr>'; // End of day names; prepare for day numbers // For the table display. $week is the row; $dayweek is the column. $dayweek = $startwday; // Paddding (the first week may have blank days in the beginning) for ($i = $display->minwday; $i < $startwday; ++$i) { $content .= '<td class="dayblank"> </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) $content .= '</tr><tr>'; $dayweek = $display->minwday; } // Reset vars $cell = ''; if (CALENDAR_WEEKEND & 1 << $dayweek % 7) { // Weekend. This is true no matter what the exact range is. $class = 'weekend day'; } else { // Normal working day. $class = 'day'; } // Special visual fx if an event is defined if (isset($eventsbyday[$day])) { $dayhref = calendar_get_link_href(CALENDAR_URL . 'view.php?view=day' . $morehref . '&', $day, $m, $y); // OverLib popup $popupcontent = ''; foreach ($eventsbyday[$day] as $eventid) { if (!isset($events[$eventid])) { continue; } $event = $events[$eventid]; if (!empty($event->modulename)) { $popupicon = $CFG->modpixpath . '/' . $event->modulename . '/icon.gif'; $popupalt = $event->modulename; } else { if ($event->courseid == SITEID) { // Site event $popupicon = $CFG->pixpath . '/c/site.gif'; $popupalt = ''; } else { if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event $popupicon = $CFG->pixpath . '/c/course.gif'; $popupalt = ''; } else { if ($event->groupid) { // Group event $popupicon = $CFG->pixpath . '/c/group.gif'; $popupalt = ''; } else { if ($event->userid) { // User event $popupicon = $CFG->pixpath . '/c/user.gif'; $popupalt = ''; } } } } } $popupcontent .= '<div><img class="icon" src="' . $popupicon . '" alt="' . $popupalt . '" /><a href="' . $dayhref . '#event_' . $event->id . '">' . format_string($event->name, true) . '</a></div>'; } //Accessibility: functionality moved to calendar_get_popup. if ($display->thismonth && $day == $d) { $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent); } else { $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent); } // Class and cell content if (isset($typesbyday[$day]['startglobal'])) { $class .= ' event_global'; } else { if (isset($typesbyday[$day]['startcourse'])) { $class .= ' event_course'; } else { if (isset($typesbyday[$day]['startgroup'])) { $class .= ' event_group'; } else { if (isset($typesbyday[$day]['startuser'])) { $class .= ' event_user'; } } } } $cell = '<a href="' . $dayhref . '" ' . $popup . '>' . $day . '</a>'; } else { $cell = $day; } 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'; } } } } // If event has a class set then add it to the table day <td> tag // Note: only one colour for minicalendar if (isset($eventsbyday[$day])) { foreach ($eventsbyday[$day] as $eventid) { if (!isset($events[$eventid])) { continue; } $event = $events[$eventid]; if (!empty($event->class)) { $class .= ' ' . $event->class; } break; } } // Special visual fx for today //Accessibility: hidden text for today, and popup. if ($display->thismonth && $day == $d) { $class .= ' today'; $today = get_string('today', 'calendar') . ' ' . userdate(time(), get_string('strftimedayshort')); if (!isset($eventsbyday[$day])) { $class .= ' eventnone'; $popup = calendar_get_popup(true, false); $cell = '<a href="#" ' . $popup . '>' . $day . '</a>'; } $cell = get_accesshide($today . ' ') . $cell; } // Just display it if (!empty($class)) { $class = ' class="' . $class . '"'; } $content .= '<td' . $class . '>' . $cell . "</td>\n"; } // Paddding (the last week may have blank days at the end) for ($i = $dayweek; $i <= $display->maxwday; ++$i) { $content .= '<td class="dayblank"> </td>'; } $content .= '</tr>'; // Last row ends $content .= '</table>'; // Tabular display of days ends return $content; }
/** * this function handles the access policy to contents indexed as searchable documents. If this * function does not exist, the search engine assumes access is allowed. * When this point is reached, we already know that : * - user is legitimate in the surrounding context * - user may be guest and guest access is allowed to the module * - the function may perform local checks within the module information logic * @param path the access path to the module script code * @param itemtype the information subclassing (usefull for complex modules, defaults to 'standard') * @param this_id the item id within the information class denoted by itemtype. In databases, this id * points out an indexed data record page. * @param user the user record denoting the user who searches * @param group_id the current group used by the user when searching * @return true if access is allowed, false elsewhere */ function data_check_text_access($path, $itemtype, $this_id, $user, $group_id, $context_id) { global $CFG; // get the database object and all related stuff if ($itemtype == 'record') { $record = get_record('data_records', 'id', $this_id); } elseif ($itemtype == 'comment') { $comment = get_record('data_comments', 'id', $this_id); $record = get_record('data_records', 'id', $comment->recordid); } else { // we do not know what type of information is required return false; } $data = get_record('data', 'id', $record->dataid); $course = get_record('course', 'id', $data->course); $module_context = get_record('context', 'id', $context_id); $cm = get_record('course_modules', 'id', $module_context->instanceid); if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $module_context)) { return false; } //group consistency check : checks the following situations about groups // trap if user is not same group and groups are separated $current_group = get_current_group($course->id); if (groupmode($course) == SEPARATEGROUPS && !groups_is_member($group_id) && !has_capability('moodle/site:accessallgroups', $module_context)) { return false; } //ownership check : checks the following situations about user // trap if user is not owner and has cannot see other's entries if ($itemtype == 'record') { if ($user->id != $record->userid && !has_capability('mod/data:viewentry', $module_context) && !has_capability('mod/data:manageentries', $module_context)) { return false; } } //approval check // trap if unapproved and has not approval capabilities // TODO : report a potential capability lack of : mod/data:approve $approval = get_field('data_records', 'approved', 'id', $record->id); if (!$approval && !isteacher($data->course) && !has_capability('mod/data:manageentries', $module_context)) { return false; } //minimum records to view check // trap if too few records // TODO : report a potential capability lack of : mod/data:viewhiddenentries $recordsAmount = count_records('data_records', 'dataid', $data->id); if ($data->requiredentriestoview > $recordsAmount && !isteacher($data->course) && !has_capability('mod/data:manageentries', $module_context)) { return false; } //opening periods check // trap if user has not capability to see hidden records and date is out of opening range // TODO : report a potential capability lack of : mod/data:viewhiddenentries $now = usertime(time()); if ($data->timeviewfrom > 0) { if ($now < $data->timeviewfrom && !isteacher($data->course) && !has_capability('mod/data:manageentries', $module_context)) { return false; } } if ($data->timeviewto > 0) { if ($now > $data->timeviewto && !isteacher($data->course) && !has_capability('mod/data:manageentries', $module_context)) { return false; } } return true; }