function execute($finalelements, $data)
 {
     if ($this->report->type != 'sql') {
         return $finalelements;
     }
     $filter_starttime = optional_param('filter_starttime', 0, PARAM_RAW);
     $filter_endtime = optional_param('filter_endtime', 0, PARAM_RAW);
     if (!$filter_starttime || !$filter_endtime) {
         return $finalelements;
     }
     $filter_starttime = make_timestamp($filter_starttime['year'], $filter_starttime['month'], $filter_starttime['day']);
     $filter_endtime = make_timestamp($filter_endtime['year'], $filter_endtime['month'], $filter_endtime['day']);
     $operators = array('<', '>', '<=', '>=');
     if (preg_match("/%%FILTER_STARTTIME:([^%]+)%%/i", $finalelements, $output)) {
         list($field, $operator) = split(':', $output[1]);
         if (!in_array($operator, $operators)) {
             print_error('nosuchoperator');
         }
         $replace = ' AND ' . $field . ' ' . $operator . ' ' . $filter_starttime;
         $finalelements = str_replace('%%FILTER_STARTTIME:' . $output[1] . '%%', $replace, $finalelements);
     }
     if (preg_match("/%%FILTER_ENDTIME:([^%]+)%%/i", $finalelements, $output)) {
         list($field, $operator) = split(':', $output[1]);
         if (!in_array($operator, $operators)) {
             print_error('nosuchoperator');
         }
         $replace = ' AND ' . $field . ' ' . $operator . ' ' . $filter_endtime;
         $finalelements = str_replace('%%FILTER_ENDTIME:' . $output[1] . '%%', $replace, $finalelements);
     }
     $finalelements = str_replace('%STARTTIME%%', $filter_starttime, $finalelements);
     $finalelements = str_replace('%ENDTIME%%', $filter_endtime, $finalelements);
     return $finalelements;
 }
 /**
  */
 public function setHtml()
 {
     $html = array();
     if ($result = $this->getRecords()) {
         foreach ($result as $key => $value) {
             $value['msgtext'] = preg_replace('~(https?:/){[^}]+}/~', '$1/', $value['msgtext']);
             list($title, $message, $login) = $this->mark(array((string) $value['title'], (string) $value['msgtext'], (string) $value['login']));
             if ($title == '') {
                 $title = '<Без темы>';
             }
             if (empty($value['reply_to']) || is_null($value['reply_to'])) {
                 $link = '/blogs/view.php?tr=' . $value['thread_id'] . '&ord=new';
             } else {
                 $link = '/blogs/view.php?tr=' . $value['thread_id'] . '&ord=new&openlevel=' . $value['id'] . '&ord=new#o' . $value['id'];
             }
             $html[$key] = '<a href="' . $link . '" style="font-weight: bold;" class="blue">' . $title . '</a>';
             $html[$key] .= '<div style="margin-top: 4px;">' . reformat($message, 80, 0, 1) . '</div>';
             $html[$key] .= '<div class="little" style="margin-top: 4px;"><span class="topic">Закладка:</span> <a href="/blogs/viewgroup.php?gr=' . $value['id_gr'] . '&ord=new">' . $value['group_name'] . '</a> - комментарий - ';
             if ($value['fromuser_id'] > 0) {
                 $html[$key] .= '[<a href="/users/' . $value['login'] . '/" title="' . $value['uname'] . ' ' . $value['usurname'] . '" class="black">' . $login . '</a>]';
             } else {
                 $html[$key] .= '[' . $login . ']';
             }
             //$html[$key] .= '- [' . dateFormat("dd.mm YYYY | H:M", $value['post_time']) . ']</div>';
             $html[$key] .= '- [' . strftime('%d.%m.%Y | %H:%M', make_timestamp($value['post_time'])) . ']</div>';
         }
     }
     $this->html = $html;
 }
 /**
  */
 public function setHtml()
 {
     $html = array();
     if ($result = $this->getRecords('is_pro DESC, post_time DESC')) {
         $i = 0;
         foreach ($result as $key => $value) {
             list($name, $descr, $login) = $this->mark(array((string) $value['name'], (string) $value['descr'], (string) $value['login']));
             if ($value['is_text'] == 't') {
                 $html[$key] .= '<div style="width:200px;">';
                 $html[$key] .= '<div style="text-align:left;padding-top:4px;"><a href="/users/' . $value['login'] . '/viewproj.php?prjid=' . $value['id'] . '" target="_blank" class="blue" style="font-weight: bold;">' . $name . '</a></div>';
                 $html[$key] .= '<div style="text-align:left;padding-top:2px;">' . reformat($descr, 36, 0, 1) . '</div>';
                 $html[$key] .= '</div>';
             } else {
                 $html[$key] .= '<div style="width:200px;">';
                 if ($value['prof_show_preview'] == 't' && $value['is_pro'] == 't') {
                     $html[$key] .= '<div style="text-align:left;"><a href="/users/' . $value['login'] . '/viewproj.php?prjid=' . $value['id'] . '" target="_blank">' . view_preview($value['login'], $value['prev_pict'], "upload", $align) . '</a></div>';
                 }
                 $html[$key] .= '<div style="text-align:left;padding-top:4px;"><a href="/users/' . $value['login'] . '/viewproj.php?prjid=' . $value['id'] . '" target="_blank" class="blue" style="font-weight: bold;">' . $name . '</a></div>';
                 $html[$key] .= '<div style="text-align:left;padding-top:4px;">' . reformat($descr, 36, 0, 1) . '</div>';
             }
             $html[$key] .= '<div class="little" style="margin-top: 4px;">Автор: ';
             if ($value['user_id'] > 0) {
                 $html[$key] .= '[<a href="/users/' . $value['login'] . '/" title="' . $value['uname'] . ' ' . $value['usurname'] . '" class="black">' . $login . '</a>]';
             } else {
                 $html[$key] .= '[' . $login . ']';
             }
             $html[$key] .= ' - [' . strftime("%d.%m.%Y | %H:%M", make_timestamp($value['post_time'])) . ']</div>';
             $i++;
         }
     }
     $this->html = $html;
 }
 public function display_results($rids = false, $sort = '', $anonymous = false)
 {
     $output = '';
     if (is_array($rids)) {
         $prtotal = 1;
     } else {
         if (is_int($rids)) {
             $prtotal = 0;
         }
     }
     if ($rows = $this->get_results($rids, $anonymous)) {
         foreach ($rows as $row) {
             // Count identical answers (case insensitive).
             $this->text = $row->response;
             if (!empty($this->text)) {
                 $dateparts = preg_split('/-/', $this->text);
                 $this->text = make_timestamp($dateparts[0], $dateparts[1], $dateparts[2]);
                 // Unix timestamp.
                 $textidx = clean_text($this->text);
                 $this->counts[$textidx] = !empty($this->counts[$textidx]) ? $this->counts[$textidx] + 1 : 1;
             }
         }
         $output .= \mod_questionnaire\response\display_support::mkreslistdate($this->counts, count($rids), $this->question->precise, $prtotal);
     } else {
         $output .= '<p class="generaltable">&nbsp;' . get_string('noresponsedata', 'questionnaire') . '</p>';
     }
     return $output;
 }
Example #5
0
function update_questionbank()
{
    global $USER, $FULLME;
    $myurl = new moodle_url($FULLME);
    $myurl->param('first', 'second');
    //print_object($myurl->get_query_string());
    //notice('die please');
    $qid = optional_param('qid', null);
    $theQuestion = optional_param('question', null);
    if (empty($theQuestion)) {
        return;
    }
    $question = get_record('memorybank_bank', 'id', $qid);
    print_object($question);
    $question->question = optional_param('question', null);
    $question->answer = optional_param('answer', null);
    $question->reference = optional_param('reference', null);
    $question->initialgrade = optional_param('initialgrade', 4);
    $question->category = optional_param('category', 0);
    $question->visible = optional_param('visible', 0);
    $initviewtime = optional_param('initviewtime', 0);
    $question->initviewtime = make_timestamp($initviewtime['year'], $initviewtime['month'], $initviewtime['day'], $initviewtime['hour'], $initviewtime['minute']);
    $question->modifiedby = $USER->id;
    $question->timemodified = time();
    print_object($question);
    update_record('memorybank_bank', $question);
}
 function execute($data, $row, $user, $courseid, $starttime = 0, $endtime = 0)
 {
     global $DB, $CFG;
     $stat = '--';
     $filter_starttime = optional_param('filter_starttime', 0, PARAM_RAW);
     $filter_endtime = optional_param('filter_endtime', 0, PARAM_RAW);
     // Do not apply filters in timeline report (filters yet applied)
     if ($starttime && $endtime) {
         $filter_starttime = 0;
         $filter_endtime = 0;
     }
     if ($filter_starttime and $filter_endtime) {
         $filter_starttime = make_timestamp($filter_starttime['year'], $filter_starttime['month'], $filter_starttime['day']);
         $filter_endtime = make_timestamp($filter_endtime['year'], $filter_endtime['month'], $filter_endtime['day']);
     }
     $starttime = $filter_starttime ? $filter_starttime : $starttime;
     $endtime = $filter_endtime ? $filter_endtime : $endtime;
     $extrasql = "";
     switch ($data->stat) {
         case 'activityview':
             $total = 'SUM(stat1)';
             $stattype = 'activity';
             $extrasql = " AND roleid IN (" . implode(',', $data->roles) . ")";
             break;
         case 'activitypost':
             $total = 'SUM(stat2)';
             $stattype = 'activity';
             $extrasql = " AND roleid IN (" . implode(',', $data->roles) . ")";
             break;
         case 'activeenrolments':
             $total = 'stat2';
             $stattype = 'enrolments';
             $extrasql = " ORDER BY timeend DESC LIMIT 1";
             break;
         case 'totalenrolments':
         default:
             $total = 'stat1';
             $stattype = 'enrolments';
             $extrasql = " ORDER BY timeend DESC LIMIT 1";
     }
     $sql = "SELECT {$total} as total FROM {stats_daily} WHERE stattype = ? AND courseid = ?";
     $params = array($stattype, $row->id);
     if ($starttime and $endtime) {
         $starttime = usergetmidnight($starttime) + 24 * 60 * 60;
         $endtime = usergetmidnight($endtime) + 24 * 60 * 60;
         $sql .= " AND timeend >= ? AND timeend <= ?";
         $params = array_merge($params, array($starttime, $endtime));
     }
     $sql .= $extrasql;
     if ($res = $DB->get_records_sql($sql, $params)) {
         $res = array_shift($res);
         if ($res->total != NULL) {
             return $res->total;
         } else {
             return 0;
         }
     }
     return $stat;
 }
Example #7
0
 public function execute()
 {
     global $CFG, $DB, $PAGE;
     require_once $CFG->dirroot . '/enrol/locallib.php';
     require_once $CFG->dirroot . '/group/lib.php';
     $options = $this->expandedOptions;
     $arguments = $this->arguments;
     //find role id for given role
     $role = $DB->get_record('role', array('shortname' => $options['role']), '*', MUST_EXIST);
     if ($options['cshortname']) {
         $course = $DB->get_record("course", array("shortname" => $options['cshortname']), '*', MUST_EXIST);
     } else {
         $course = $DB->get_record('course', array('id' => $arguments[0]), '*', MUST_EXIST);
         array_shift($arguments);
     }
     $context = context_course::instance($course->id);
     $manager = new course_enrolment_manager($PAGE, $course);
     $instances = $manager->get_enrolment_instances();
     //find the manual one
     foreach ($instances as $instance) {
         if ($instance->enrol == 'manual') {
             break;
         }
     }
     if ($instance->enrol != 'manual') {
         die("No manual enrolment instance for the course\n");
     }
     $plugins = $manager->get_enrolment_plugins();
     //only one manual enrolment in a course
     if (!isset($plugins['manual'])) {
         die("No manual enrolment plugin for the course\n");
     }
     $plugin = $plugins['manual'];
     $today = time();
     $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
     //get userid from firstname AND lastname
     //check, if firstname and lastname set
     if ($options['firstname'] and $options['lastname']) {
         $user = $DB->get_record('user', array('firstname' => $options['firstname'], 'lastname' => $options['lastname']), '*', MUST_EXIST);
         if (!$user) {
             cli_problem("User '{$user}' not found");
         } else {
             $plugin->enrol_user($instance, $user->id, $role->id, $today, 0);
         }
     }
     foreach ($arguments as $argument) {
         if ($options['id']) {
             $user = $DB->get_record('user', array('id' => $argument), '*', MUST_EXIST);
         } else {
             $user = $DB->get_record('user', array('username' => $argument), '*', MUST_EXIST);
         }
         if (!$user) {
             cli_problem("User '{$user}' not found");
             continue;
         }
         $plugin->enrol_user($instance, $user->id, $role->id, $today, 0);
     }
 }
 function definition()
 {
     global $CFG, $USER, $DB, $COURSE;
     $mform =& $this->_form;
     // Don't forget the underscore!
     //check reportend make sure that if $this->userid != $USER->id that they have
     //the correct capability TODO
     /*
     $canmanage = false;
     if(has_capability('block/timetracker:manageworkers',$this->context)){
         $canmanage = true;
     }
     */
     //$userinfo = $DB->get_record('block_timetracker_workerinfo',
     //    array('id'=>$this->userid));
     /*
     $index  = new moodle_url($CFG->wwwroot.'/blocks/timetracker/index.php',
         array('id'=>$this->courseid,'userid'=>$this->userid));
     */
     $index = new moodle_url($CFG->wwwroot . 'blocks/timetracker/');
     /*
     if(!$canmanage && $USER->id != $userinfo->mdluserid){
         redirect($nextpage,'You do not have permission to generate this report.',1);
     }
     */
     $categoryinfo = $DB->get_record('course_categories', array('id' => $this->catid));
     if (!$categoryinfo) {
         $mform->addElement('header', 'general', 'Report Generator');
     } else {
         $mform->addElement('header', 'general', 'Report Generator for ' . $categoryinfo->name);
     }
     $now = time();
     if ($this->reportstart == 0 || $this->reportend == 0) {
         $starttime = usergetdate($now);
         $starttime_mid = make_timestamp($starttime['year'], $starttime['mon'] - 1, $starttime['mday']);
         $this->reportstart = $starttime_mid;
         $endtime = usergetdate($now);
         $endtime_mid = make_timestamp($endtime['year'], $endtime['mon'], $endtime['mday']);
         $this->reportend = $endtime_mid;
     }
     $buttonarray = array();
     $buttonarray[] =& $mform->createElement('submit', 'conflicts', 'Conflicts');
     $buttonarray[] =& $mform->createElement('submit', 'earningsactive', 'Earnings - active workers only');
     $buttonarray[] =& $mform->createElement('submit', 'earningsall', 'Earnings - all workers');
     $mform->addElement('html', 'Please provide a date and time range for the report(s) you
             wish to generate.');
     $mform->addElement('date_selector', 'reportstart', 'Start Date: ', array('optional' => false, 'step' => 1));
     $mform->setDefault('reportstart', $this->reportstart);
     $mform->addElement('date_selector', 'reportend', 'End Date: ', array('optional' => false, 'step' => 1));
     $mform->setDefault('reportend', $this->reportend);
     $mform->addElement('hidden', 'catid', $this->catid);
     //$mform->addElement('hidden','userid', $this->userid);
     $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
     $mform->closeHeaderBefore('buttonar');
 }
    function get_all_elements() {
        $elements = array();

        $components = cr_unserialize($this->config->components);

        $config = (isset($components['timeline']['config'])) ? $components['timeline']['config'] : new stdclass();

        if (isset($config->timemode)) {

            $daysecs = 60 * 60 * 24;

            if ($config->timemode == 'previous') {
                $config->starttime = gmmktime() - $config->previousstart * $daysecs;
                $config->endtime = gmmktime() - $config->previousend * $daysecs;
                if (isset($config->forcemidnight)) {
                    $config->starttime = usergetmidnight($config->starttime);
                    $config->endtime = usergetmidnight($config->endtime) + ($daysecs - 1);
                }
            }

            $filter_starttime = optional_param('filter_starttime', 0, PARAM_RAW);
            $filter_endtime = optional_param('filter_endtime', 0, PARAM_RAW);

            if ($filter_starttime and $filter_endtime) {
                $filter_starttime = make_timestamp($filter_starttime['year'], $filter_starttime['month'], $filter_starttime['day']);
                $filter_endtime = make_timestamp($filter_endtime['year'], $filter_endtime['month'], $filter_endtime['day']);

                $config->starttime = usergetmidnight($filter_starttime);
                $config->endtime = usergetmidnight($filter_endtime) + 24 * 60 * 60;
            }


            for ($i = $config->starttime; $i < $config->endtime; $i += $config->interval * $daysecs) {
                $row = new stdclass();
                $row->id = $i;
                $row->starttime = $i;
                $row->endtime = $row->starttime + ($config->interval * $daysecs - 1);
                if ($row->endtime > $config->endtime)
                    $row->endtime = $config->endtime;
                $this->timeline[$row->starttime] = $row;
                $elements[] = $row->starttime;
            }

            if ($config->ordering == 'desc')
                rsort($elements);
        }

        return $elements;
    }
Example #10
0
 /**
  * Return the content of this block.
  *
  * @return stdClass the content
  */
 public function get_content()
 {
     global $CFG;
     $calm = optional_param('cal_m', 0, PARAM_INT);
     $caly = optional_param('cal_y', 0, PARAM_INT);
     $time = optional_param('time', 0, PARAM_INT);
     require_once $CFG->dirroot . '/calendar/lib.php';
     if ($this->content !== null) {
         return $this->content;
     }
     // If a day, month and year were passed then convert it to a timestamp. If these were passed then we can assume
     // the day, month and year are passed as Gregorian, as no where in core should we be passing these values rather
     // than the time. This is done for BC.
     if (!empty($calm) && !empty($caly)) {
         $time = make_timestamp($caly, $calm, 1);
     } else {
         if (empty($time)) {
             $time = time();
         }
     }
     $this->content = new stdClass();
     $this->content->text = '';
     $this->content->footer = '';
     // [pj] To me it looks like this if would never be needed, but Penny added it
     // when committing the /my/ stuff. Reminder to discuss and learn what it's about.
     // It definitely needs SOME comment here!
     $courseid = $this->page->course->id;
     $issite = $courseid == SITEID;
     if ($issite) {
         // Being displayed at site level. This will cause the filter to fall back to auto-detecting
         // the list of courses it will be grabbing events from.
         $filtercourse = calendar_get_default_courses();
     } else {
         // Forcibly filter events to include only those from the particular course we are in.
         $filtercourse = array($courseid => $this->page->course);
     }
     list($courses, $group, $user) = calendar_set_filters($filtercourse);
     if ($issite) {
         // For the front page.
         $this->content->text .= calendar_get_mini($courses, $group, $user, false, false, 'frontpage', $courseid, $time);
         // No filters for now.
     } else {
         // For any other course.
         $this->content->text .= calendar_get_mini($courses, $group, $user, false, false, 'course', $courseid, $time);
         $this->content->text .= '<h3 class="eventskey">' . get_string('eventskey', 'calendar') . '</h3>';
         $this->content->text .= '<div class="filters calendar_filters">' . calendar_filter_controls($this->page->url) . '</div>';
     }
     return $this->content;
 }
Example #11
0
 /**
  * Validate that log files are archived for a variety of import and
  * export plugins, for a variety of configured log paths
  *
  * @param string $plugintype One of 'import' or 'export'
  * @param string $plugin The import plugin to associate log files to
  * @param string $logfilelocation The logfilelocation setting value to use
  * @dataProvider importpluginprovider
  */
 public function test_logfilesarchived($plugintype, $plugin, $logfilelocation)
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . '/local/datahub/fileplugins/log/log.class.php';
     require_once $CFG->libdir . '/filestorage/zip_archive.php';
     // Clean-up any existing log & zip files.
     self::cleanup_log_files();
     self::cleanup_zip_files();
     // Set up the log path.
     set_config('logfilelocation', $logfilelocation, $plugin);
     $format = get_string('logfile_timestamp', 'local_datahub');
     $USER->timezone = 99;
     // Create some log files to be zipped by the cron job.
     // Way earlier then any real existing files!
     $starttime = make_timestamp(1971, 1, 3);
     $filenames = array();
     for ($i = 0; $i < 10; ++$i) {
         $filenames[$i] = rlip_log_file_name($plugintype, $plugin, $logfilelocation, 'user', false, $starttime + $i * 3600);
         // Write out a line to the logfile.
         $logfile = new rlip_fileplugin_log($filenames[$i]);
         $logfile->open(RLIP_FILE_WRITE);
         $logfile->write(array('test entry'));
         $logfile->close();
     }
     // Call cron job that zips the specified day's log files.
     $zipfiles = rlip_compress_logs_cron('bogus', 0, $starttime);
     $this->assertTrue(!empty($zipfiles));
     // Was a zip file created?.
     // Verify that the compressed file exists.
     $exists = file_exists($zipfiles[0]);
     $this->assertTrue($exists);
     // Open zip_archive and verify all logs included.
     $zip = new zip_archive();
     $result = $zip->open($zipfiles[0]);
     $this->assertTrue($result);
     $this->assertEquals(10, $zip->count());
     $zip->close();
     // Verify that the log files created are gone....
     for ($i = 0; $i < 10; ++$i) {
         $exists = file_exists($filenames[$i]);
         $this->assertFalse($exists);
     }
     // Validate that the zip file name corresponds to the plugin.
     // E.g. pugin is 'dhimport_version1' and file name starts with 'import_version1_'.
     $parts = explode('/', $zipfiles[0]);
     $this->assertStringStartsWith($plugin . '_', 'dh' . $parts[count($parts) - 1]);
     // Delete the test zip.
     @unlink($zipfiles[0]);
 }
 /**
  * If timestamp is in YYYY-MM-DD or YYYY-MM-DD-HH-MM-SS format, then convert it to timestamp.
  *
  * @param string|int $datetime datetime to be converted.
  * @param stdClass $datarecord The object that will be used to save the record
  * @return int timestamp
  * @since Moodle 2.5
  */
 public function edit_save_data_preprocess($datetime, $datarecord)
 {
     // If timestamp then explode it to check if year is within field limit.
     $isstring = strpos($datetime, '-');
     if (empty($isstring)) {
         $datetime = date('Y-m-d-H-i-s', $datetime);
     }
     $datetime = explode('-', $datetime);
     // Bound year with start and end year.
     $datetime[0] = min(max($datetime[0], $this->field->param1), $this->field->param2);
     if (!empty($this->field->param3) && count($datetime) == 6) {
         return make_timestamp($datetime[0], $datetime[1], $datetime[2], $datetime[3], $datetime[4], $datetime[5]);
     } else {
         return make_timestamp($datetime[0], $datetime[1], $datetime[2]);
     }
 }
 /**
  */
 public function setHtml()
 {
     $html = array();
     if ($result = $this->getRecords()) {
         foreach ($result as $key => $value) {
             $is_articles = $value['id'] % 2;
             $id = ($value['id'] - $is_articles) / 2;
             list($title, $login, $uname, $usurname, $message) = $this->mark(array((string) $value['title'], (string) $value['login'], (string) $value['uname'], (string) $value['usurname'], (string) strip_tags($value['msgtext'])));
             $html[$key] = '';
             if ($is_articles) {
                 $link = '/articles/?id=' . $id;
                 if ($value['logo']) {
                     $logo = '<img src="' . WDCPREFIX . '/about/articles/' . $value['logo'] . '" width="50" hspace="0"/>';
                 }
                 $title = '<a href="' . $link . '" style="font-weight: bold;" class="blue">' . ($title ? $title : '<Без заголовка>') . '</a>';
                 $footer = '<div class="little" style="margin-top: 4px;"><span class="topic">Статьи:</span> <a href="' . $link . '">' . $value['title'] . '</a> - [' . strftime("%d.%m.%Y | %H:%M", make_timestamp($value['post_time'])) . ']</div>';
             } else {
                 $link = '/interview/?id=' . $id;
                 $logo = '<img src="' . WDCPREFIX . '/users/' . $value['login'] . '/upload/' . $value['logo'] . '" width="50"/>';
                 $footer = '<div class="little" style="margin-top: 4px;"><span class="topic">Интервью:</span> <a href="' . $link . '">' . $uname . ' ' . $usurname . '</a> - [<a href="/users/' . $value['login'] . '">' . $login . '</a>]</div>';
             }
             if ($logo) {
                 $logo = '<a href="' . $link . '">' . $logo . '</a>';
             }
             $html[$key] .= '<table cellpadding="0" cellspacing="0" width="100%">';
             $html[$key] .= '<col style="width:58px"/>';
             $html[$key] .= '<col />';
             $html[$key] .= '<tr valign="top">';
             $html[$key] .= '<td>';
             $html[$key] .= $logo;
             $html[$key] .= '</td>';
             $html[$key] .= '<td>';
             $html[$key] .= '<div>' . $title . '</div>';
             $html[$key] .= '<div>' . $message . '</div>';
             $html[$key] .= '</td>';
             $html[$key] .= '</tr>';
             $html[$key] .= '<tr valign="top">';
             $html[$key] .= '<td colspan="2">';
             $html[$key] .= $footer;
             $html[$key] .= '</td>';
             $html[$key] .= '</tr>';
             $html[$key] .= '</table>';
         }
     }
     $this->html = $html;
 }
Example #14
0
function webquest_update_instance($webquest)
{
    $webquest->timemodified = time();
    $webquest->id = $webquest->instance;
    //Encode password if necessary
    if (!empty($webquest->password)) {
        $webquest->password = md5($webquest->password);
    } else {
        unset($webquest->password);
    }
    $webquest->submissionstart = make_timestamp($webquest->submissionstartyear, $webquest->submissionstartmonth, $webquest->submissionstartday, $webquest->submissionstarthour, $webquest->submissionstartminute);
    $webquest->submissionend = make_timestamp($webquest->submissionendyear, $webquest->submissionendmonth, $webquest->submissionendday, $webquest->submissionendhour, $webquest->submissionendminute);
    if (!webquest_check_dates($webquest)) {
        return get_string('invaliddates', 'webquest');
    }
    return update_record("webquest", $webquest);
}
Example #15
0
 /**
  * If timestamp is in YYYY-MM-DD or YYYY-MM-DD-HH-MM-SS format, then convert it to timestamp.
  *
  * @param string|int $datetime datetime to be converted.
  * @param stdClass $datarecord The object that will be used to save the record
  * @return int timestamp
  * @since Moodle 2.5
  */
 public function edit_save_data_preprocess($datetime, $datarecord)
 {
     if (!$datetime) {
         return 0;
     }
     if (is_numeric($datetime)) {
         $datetime = userdate($datetime, '%Y-%m-%d-%H-%M-%S');
     }
     $datetime = explode('-', $datetime);
     // Bound year with start and end year.
     $datetime[0] = min(max($datetime[0], $this->field->param1), $this->field->param2);
     if (!empty($this->field->param3) && count($datetime) == 6) {
         return make_timestamp($datetime[0], $datetime[1], $datetime[2], $datetime[3], $datetime[4], $datetime[5]);
     } else {
         return make_timestamp($datetime[0], $datetime[1], $datetime[2]);
     }
 }
function skype_add_instance($skype)
{
    // Given an object containing all the necessary data,
    // (defined by the form in mod.html) this function
    // will create a new instance and return the id number
    // of the new instance.
    $skype->timemodified = time();
    if (!empty($skype->timerestrict) and $skype->timerestrict) {
        $skype->timeopen = make_timestamp($skype->openyear, $skype->openmonth, $skype->openday, $skype->openhour, $skype->openminute, 0);
        $skype->timeclose = make_timestamp($skype->closeyear, $skype->closemonth, $skype->closeday, $skype->closehour, $skype->closeminute, 0);
    } else {
        $skype->timeopen = 0;
        $skype->timeclose = 0;
    }
    //insert answers
    if (!($skype->id = insert_record("skype", $skype))) {
        error("Could not add new instance");
    }
    return $skype->id;
}
Example #17
0
 function update_content($recordid, $value, $name = '')
 {
     $names = explode('_', $name);
     $name = $names[2];
     // day month or year
     $this->{$name} = $value;
     if ($this->day and $this->month and $this->year) {
         // All of them have been collected now
         $content = new object();
         $content->fieldid = $this->field->id;
         $content->recordid = $recordid;
         $content->content = make_timestamp($this->year, $this->month, $this->day, 12, 0, 0, 0, false);
         if ($oldcontent = get_record('data_content', 'fieldid', $this->field->id, 'recordid', $recordid)) {
             $content->id = $oldcontent->id;
             return update_record('data_content', $content);
         } else {
             return insert_record('data_content', $content);
         }
     }
 }
/**
*
*/
function get_session_data(&$form)
{
    if (!($form->rangestart = optional_param('rangestart', '', PARAM_INT))) {
        $year = required_param('startyear', PARAM_INT);
        $month = required_param('startmonth', PARAM_INT);
        $day = required_param('startday', PARAM_INT);
        $form->rangestart = make_timestamp($year, $month, $day);
        $form->starthour = required_param('starthour', PARAM_INT);
        $form->startminute = required_param('startminute', PARAM_INT);
        $form->timestart = make_timestamp($year, $month, $day, $form->starthour, $form->startminute);
    }
    if (!($form->rangeend = optional_param('rangeend', '', PARAM_INT))) {
        $year = required_param('endyear', PARAM_INT);
        $month = required_param('endmonth', PARAM_INT);
        $day = required_param('endday', PARAM_INT);
        $form->rangeend = make_timestamp($year, $month, $day);
        $form->endhour = required_param('endhour', PARAM_INT);
        $form->endminute = required_param('endminute', PARAM_INT);
        $form->timeend = make_timestamp($year, $month, $day, $form->endhour, $form->endminute);
    }
    $form->monday = optional_param('monday', 0, PARAM_INT);
    $form->tuesday = optional_param('tuesday', 0, PARAM_INT);
    $form->wednesday = optional_param('wednesday', 0, PARAM_INT);
    $form->thursday = optional_param('thursday', 0, PARAM_INT);
    $form->friday = optional_param('friday', 0, PARAM_INT);
    $form->saturday = optional_param('saturday', 0, PARAM_INT);
    $form->sunday = optional_param('sunday', 0, PARAM_INT);
    $form->forcewhenoverlap = required_param('forcewhenoverlap', PARAM_INT);
    $form->exclusivity = required_param('exclusivity', PARAM_INT);
    $form->reuse = required_param('reuse', PARAM_INT);
    $form->divide = optional_param('divide', 0, PARAM_INT);
    $form->duration = optional_param('duration', 15, PARAM_INT);
    $form->teacherid = required_param('teacherid', PARAM_INT);
    $form->appointmentlocation = optional_param('appointmentlocation', '', PARAM_CLEAN);
    $form->emailfrom = required_param('emailfrom', PARAM_CLEAN);
    $form->displayfrom = required_param('displayfrom', PARAM_CLEAN);
}
 protected static function get_enrolperiod()
 {
     $today = time();
     $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
     if ($today <= strtotime('June 15')) {
         // 1 semestre -  31 julio
         // 1 vacaciones - 31 julio
         $timeend = strtotime("July 31");
     } else {
         if ($today >= strtotime('June 16') and $today <= strtotime('December 15')) {
             // 2 semestre - 31 Enero próximo año
             // 2 vacaciones - 31 enero próximo año
             $january31 = strtotime("January 31");
             $timeend = strtotime("+1 year", $january31);
         } else {
             // December 16 and December 31
             // 1 semestre -  31 julio próximo año
             // 1 vacaciones - 31 julio próximo año
             $july31 = strtotime("July 31");
             $timeend = strtotime("+1 year", $july31);
         }
     }
     return array('timestart' => $today, 'timeend' => $timeend);
 }
Example #20
0
$strexistingusers = get_string('existingusers', 'role');
$straction = get_string('assignroles', 'role');
$strroletoassign = get_string('roletoassign', 'role');
$strsearch = get_string('search');
$strshowall = get_string('showall');
$strparticipants = get_string('participants');
$strsearchresults = get_string('searchresults');
$unlimitedperiod = get_string('unlimited');
$defaultperiod = $course->enrolperiod;
for ($i = 1; $i <= 365; $i++) {
    $seconds = $i * 86400;
    $periodmenu[$seconds] = get_string('numdays', '', $i);
}
$timeformat = get_string('strftimedate');
$today = time();
$today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
// MDL-12420, preventing course start date showing up as an option at system context and front page roles.
if ($course->startdate > 0) {
    $basemenu[0] = get_string('startdate') . ' (' . userdate($course->startdate, $timeformat) . ')';
}
if ($course->enrollable != 2 || ($course->enrolstartdate == 0 || $course->enrolstartdate <= $today) && ($course->enrolenddate == 0 || $course->enrolenddate > $today)) {
    $basemenu[3] = get_string('today') . ' (' . userdate($today, $timeformat) . ')';
}
if ($course->enrollable == 2) {
    if ($course->enrolstartdate > 0) {
        $basemenu[4] = get_string('courseenrolstartdate') . ' (' . userdate($course->enrolstartdate, $timeformat) . ')';
    }
    if ($course->enrolenddate > 0) {
        $basemenu[5] = get_string('courseenrolenddate') . ' (' . userdate($course->enrolenddate, $timeformat) . ')';
    }
}
 /**
  * Output a timestamp. Give it the name of the group.
  *
  * @param array $submitValues values submitted.
  * @param bool $assoc specifies if returned array is associative
  * @return array
  */
 function exportValue(&$submitValues, $assoc = false)
 {
     $value = null;
     $valuearray = array();
     foreach ($this->_elements as $element) {
         $thisexport = $element->exportValue($submitValues[$this->getName()], true);
         if ($thisexport != null) {
             $valuearray += $thisexport;
         }
     }
     if (count($valuearray)) {
         if ($this->_options['optional']) {
             // If checkbox is on, the value is zero, so go no further
             if (empty($valuearray['enabled'])) {
                 $value[$this->getName()] = 0;
                 return $value;
             }
         }
         $valuearray = $valuearray + array('year' => 1970, 'month' => 1, 'day' => 1, 'hour' => 0, 'minute' => 0);
         $value[$this->getName()] = make_timestamp($valuearray['year'], $valuearray['month'], $valuearray['day'], $valuearray['hour'], $valuearray['minute'], 0, $this->_options['timezone'], true);
         return $value;
     } else {
         return null;
     }
 }
Example #22
0
 /**
  * Gets the enrolment selector control for this table and initialises its
  * JavaScript
  *
  * @return single_button|url_select
  */
 public function get_enrolment_selector()
 {
     global $CFG;
     static $count = 0;
     $instances = $this->manager->get_enrolment_instances();
     $plugins = $this->manager->get_enrolment_plugins();
     $manuals = array();
     // print enrol link or selection
     $links = array();
     foreach ($instances as $instance) {
         $plugin = $plugins[$instance->enrol];
         if ($link = $plugin->get_manual_enrol_link($instance)) {
             $links[$instance->id] = $link;
             $manuals[$instance->id] = $instance;
         }
     }
     if (!empty($links)) {
         $arguments = array();
         $count++;
         if (count($links) == 1) {
             $control = new single_button(reset($links), get_string('enrolusers', 'enrol_manual'), 'get');
             $control->class = 'singlebutton enrolusersbutton instance' . $count;
             $control->formid = 'manuallyenrol_single_' + $count;
             $arguments[] = array('id' => key($links), 'name' => $plugins[$instances[key($links)]->enrol]->get_instance_name($instances[key($links)]));
         } else {
             if (count($links) > 1) {
                 $inames = $this->manager->get_enrolment_instance_names();
                 $options = array();
                 foreach ($links as $i => $link) {
                     $options[$link->out(false)] = $inames[$i];
                     $arguments[] = array('id' => $i, 'name' => $plugins[$instances[$i]->enrol]->get_instance_name($instances[$i]));
                 }
                 $control = new url_select($options, '', array('' => get_string('enrolusers', 'enrol_manual') . '...'));
                 $control->class = 'singlebutton enrolusersbutton instance' . $count;
                 $control->formid = 'manuallyenrol_select_' + $count;
             }
         }
         $course = $this->manager->get_course();
         $timeformat = get_string('strftimedatefullshort');
         $today = time();
         $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
         $startdateoptions = array();
         if ($course->startdate > 0) {
             $startdateoptions[2] = get_string('coursestart') . ' (' . userdate($course->startdate, $timeformat) . ')';
         }
         $startdateoptions[3] = get_string('today') . ' (' . userdate($today, $timeformat) . ')';
         if ($count == 1) {
             $instance = reset($manuals);
             $this->moodlepage->requires->strings_for_js(array('ajaxoneuserfound', 'ajaxxusersfound', 'ajaxnext25', 'enrol', 'enrolmentoptions', 'enrolusers', 'errajaxfailedenrol', 'errajaxsearch', 'none', 'usersearch', 'unlimitedduration', 'startdatetoday', 'durationdays', 'enrolperiod', 'finishenrollingusers', 'recovergrades'), 'enrol');
             $this->moodlepage->requires->string_for_js('assignroles', 'role');
             $this->moodlepage->requires->string_for_js('startingfrom', 'moodle');
             $modules = array('moodle-enrol-enrolmentmanager', 'moodle-enrol-enrolmentmanager-skin');
             $function = 'M.enrol.enrolmentmanager.init';
             $arguments = array('instances' => $arguments, 'courseid' => $course->id, 'ajaxurl' => '/enrol/ajax.php', 'url' => $this->moodlepage->url->out(false), 'optionsStartDate' => $startdateoptions, 'defaultRole' => $instance->roleid, 'disableGradeHistory' => $CFG->disablegradehistory);
             $this->moodlepage->requires->yui_module($modules, $function, array($arguments));
         }
         return $control;
     }
     return null;
 }
Example #23
0
 /**
  * Returns a button to manually enrol users through the manual enrolment plugin.
  *
  * By default the first manual enrolment plugin instance available in the course is used.
  * If no manual enrolment instances exist within the course then false is returned.
  *
  * This function also adds a quickenrolment JS ui to the page so that users can be enrolled
  * via AJAX.
  *
  * @param course_enrolment_manager $manager
  * @return enrol_user_button
  */
 public function get_manual_enrol_button(course_enrolment_manager $manager)
 {
     global $CFG;
     $instance = null;
     $instances = array();
     foreach ($manager->get_enrolment_instances() as $tempinstance) {
         if ($tempinstance->enrol == 'manual') {
             if ($instance === null) {
                 $instance = $tempinstance;
             }
             $instances[] = array('id' => $tempinstance->id, 'name' => $this->get_instance_name($tempinstance));
         }
     }
     if (empty($instance)) {
         return false;
     }
     if (!($manuallink = $this->get_manual_enrol_link($instance))) {
         return false;
     }
     $button = new enrol_user_button($manuallink, get_string('enrolusers', 'enrol_manual'), 'get');
     $button->class .= ' enrol_manual_plugin';
     $startdate = $manager->get_course()->startdate;
     $startdateoptions = array();
     $timeformat = get_string('strftimedatefullshort');
     if ($startdate > 0) {
         $startdateoptions[2] = get_string('coursestart') . ' (' . userdate($startdate, $timeformat) . ')';
     }
     $today = time();
     $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
     $startdateoptions[3] = get_string('today') . ' (' . userdate($today, $timeformat) . ')';
     $defaultduration = $instance->enrolperiod > 0 ? $instance->enrolperiod / 86400 : '';
     $modules = array('moodle-enrol_manual-quickenrolment', 'moodle-enrol_manual-quickenrolment-skin');
     $arguments = array('instances' => $instances, 'courseid' => $instance->courseid, 'ajaxurl' => '/enrol/manual/ajax.php', 'url' => $manager->get_moodlepage()->url->out(false), 'optionsStartDate' => $startdateoptions, 'defaultRole' => $instance->roleid, 'defaultDuration' => $defaultduration, 'disableGradeHistory' => $CFG->disablegradehistory, 'recoverGradesDefault' => '');
     if ($CFG->recovergradesdefault) {
         $arguments['recoverGradesDefault'] = ' checked="checked"';
     }
     $function = 'M.enrol_manual.quickenrolment.init';
     $button->require_yui_module($modules, $function, array($arguments));
     $button->strings_for_js(array('ajaxoneuserfound', 'ajaxxusersfound', 'ajaxnext25', 'enrol', 'enrolmentoptions', 'enrolusers', 'errajaxfailedenrol', 'errajaxsearch', 'none', 'usersearch', 'unlimitedduration', 'startdatetoday', 'durationdays', 'enrolperiod', 'finishenrollingusers', 'recovergrades'), 'enrol');
     $button->strings_for_js('assignroles', 'role');
     $button->strings_for_js('startingfrom', 'moodle');
     return $button;
 }
Example #24
0
function calendar_top_controls($type, $data)
{
    global $CFG, $CALENDARDAYS, $THEME;
    $content = '';
    if (!isset($data['d'])) {
        $data['d'] = 1;
    }
    // Ensure course id passed if relevant
    // Required due to changes in view/lib.php mainly (calendar_session_vars())
    $courseid = '';
    if (!empty($data['id'])) {
        $courseid = '&amp;course=' . $data['id'];
    }
    if (!checkdate($data['m'], $data['d'], $data['y'])) {
        $time = time();
    } else {
        $time = make_timestamp($data['y'], $data['m'], $data['d']);
    }
    $date = usergetdate($time);
    $data['m'] = $date['mon'];
    $data['y'] = $date['year'];
    //Accessibility: calendar block controls, replaced <table> with <div>.
    //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
    //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
    switch ($type) {
        case 'frontpage':
            list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
            list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
            $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide = true);
            $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
            $content .= "\n" . '<div class="calendar-controls">' . $prevlink;
            $content .= '<span class="hide"> | </span><span class="current"><a href="' . calendar_get_link_href(CALENDAR_URL . 'view.php?view=month' . $courseid . '&amp;', 1, $data['m'], $data['y']) . '">' . userdate($time, get_string('strftimemonthyear')) . '</a></span>';
            $content .= '<span class="hide"> | </span>' . $nextlink . "\n";
            $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
            break;
        case 'course':
            list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
            list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
            $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id=' . $data['id'] . '&amp;', 0, $nextmonth, $nextyear, $accesshide = true);
            $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id=' . $data['id'] . '&amp;', 0, $prevmonth, $prevyear, true);
            $content .= "\n" . '<div class="calendar-controls">' . $prevlink;
            $content .= '<span class="hide"> | </span><span class="current"><a href="' . calendar_get_link_href(CALENDAR_URL . 'view.php?view=month' . $courseid . '&amp;', 1, $data['m'], $data['y']) . '">' . userdate($time, get_string('strftimemonthyear')) . '</a></span>';
            $content .= '<span class="hide"> | </span>' . $nextlink . "\n";
            $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
            break;
        case 'upcoming':
            $content .= '<div style="text-align: center;"><a href="' . CALENDAR_URL . 'view.php?view=upcoming"' . $courseid . '>' . userdate($time, get_string('strftimemonthyear')) . "</a></div>\n";
            break;
        case 'display':
            $content .= '<div style="text-align: center;"><a href="' . calendar_get_link_href(CALENDAR_URL . 'view.php?view=month' . $courseid . '&amp;', 1, $data['m'], $data['y']) . '">' . userdate($time, get_string('strftimemonthyear')) . "</a></div>\n";
            break;
        case 'month':
            list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
            list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
            $prevdate = make_timestamp($prevyear, $prevmonth, 1);
            $nextdate = make_timestamp($nextyear, $nextmonth, 1);
            $content .= "\n" . '<div class="calendar-controls">';
            $content .= calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month' . $courseid . '&amp;', 1, $prevmonth, $prevyear);
            $content .= '<span class="hide"> | </span><span class="current">' . userdate($time, get_string('strftimemonthyear')) . "</span>\n";
            $content .= '<span class="hide"> | </span>' . calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month' . $courseid . '&amp;', 1, $nextmonth, $nextyear);
            $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
            break;
        case 'day':
            $data['d'] = $date['mday'];
            // Just for convenience
            $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
            $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
            $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
            $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
            $content .= "\n" . '<div class="calendar-controls">';
            $content .= calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
            // Get the format string
            $text = get_string('strftimedaydate');
            /*
            // Regexp hackery to make a link out of the month/year part
            $text = ereg_replace('(%B.+%Y|%Y.+%B|%Y.+%m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
            $text = ereg_replace('(F.+Y|Y.+F|Y.+m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
            */
            // Replace with actual values and lose any day leading zero
            $text = userdate($time, $text);
            // Print the actual thing
            $content .= '<span class="hide"> | </span><span class="current">' . $text . '</span>';
            $content .= '<span class="hide"> | </span>' . calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
            $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
            break;
    }
    return $content;
}
 public function test_make_timestamp()
 {
     global $USER, $CFG, $DB;
     $this->resetAfterTest();
     $this->setAdminUser();
     $testvalues = array(array('usertimezone' => 'America/Moncton', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => '0.0', 'applydst' => false, 'expectedoutput' => '1309514400'), array('usertimezone' => 'America/Moncton', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => '99', 'applydst' => false, 'expectedoutput' => '1309528800'), array('usertimezone' => 'America/Moncton', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => '99', 'applydst' => true, 'expectedoutput' => '1309525200'), array('usertimezone' => 'America/Moncton', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => 'America/Moncton', 'applydst' => true, 'expectedoutput' => '1309525200'), array('usertimezone' => '2', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => '99', 'applydst' => true, 'expectedoutput' => '1309507200'), array('usertimezone' => '-2', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => '99', 'applydst' => true, 'expectedoutput' => '1309521600'), array('usertimezone' => '-10', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => '2', 'applydst' => true, 'expectedoutput' => '1309507200'), array('usertimezone' => '-10', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => '-2', 'applydst' => true, 'expectedoutput' => '1309521600'), array('usertimezone' => '-10', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => 'random/time', 'applydst' => true, 'expectedoutput' => '1309485600'), array('usertimezone' => '14', 'year' => '2011', 'month' => '7', 'day' => '1', 'hour' => '10', 'minutes' => '00', 'seconds' => '00', 'timezone' => '99', 'applydst' => true, 'expectedoutput' => '1309485600'));
     // Check if forcetimezone is set then save it and set it to use user timezone.
     $cfgforcetimezone = null;
     if (isset($CFG->forcetimezone)) {
         $cfgforcetimezone = $CFG->forcetimezone;
         $CFG->forcetimezone = 99;
         // Get user default timezone.
     }
     // Store user default timezone to restore later.
     $userstimezone = $USER->timezone;
     // The string version of date comes from server locale setting and does
     // not respect user language, so it is necessary to reset that.
     $oldlocale = setlocale(LC_TIME, '0');
     setlocale(LC_TIME, 'en_AU.UTF-8');
     // Set default timezone to Australia/Perth, else time calculated
     // Will not match expected values. Before that save system defaults.
     $systemdefaulttimezone = date_default_timezone_get();
     date_default_timezone_set('Australia/Perth');
     // Test make_timestamp with all testvals and assert if anything wrong.
     foreach ($testvalues as $vals) {
         $USER->timezone = $vals['usertimezone'];
         $actualoutput = make_timestamp($vals['year'], $vals['month'], $vals['day'], $vals['hour'], $vals['minutes'], $vals['seconds'], $vals['timezone'], $vals['applydst']);
         // On different systems case of AM PM changes so compare case insensitive.
         $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
         $actualoutput = core_text::strtolower($actualoutput);
         $this->assertSame($vals['expectedoutput'], $actualoutput, "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},\n                Please check if timezones are updated (Site adminstration -> location -> update timezone)");
     }
     // Restore user timezone back to what it was.
     $USER->timezone = $userstimezone;
     // Restore forcetimezone.
     if (!is_null($cfgforcetimezone)) {
         $CFG->forcetimezone = $cfgforcetimezone;
     }
     // Restore system default values.
     date_default_timezone_set($systemdefaulttimezone);
     setlocale(LC_TIME, $oldlocale);
 }
Example #26
0
    /**
     * @method add_users Assigns the manager to a costcenter
     * @param array $userids
     * @param int $costcenterid  Cost centerid
     */
    public function add_users($userids, $costcenterid) {
        global $CFG, $DB, $OUTPUT, $USER;

        //$department = new department ();
        $currenturl = "{$CFG->wwwroot}/local/costcenter/index.php";
        if (empty($userids)) {
            /* ---nothing to do--- */
            return;
        }
        $userids = array_reverse($userids);
        foreach ($userids as $userid) {
            $manager = new stdClass();
            $manager->userid = $userid;
            $manager->costcenterid = $costcenterid;
            $manager->roleid = $DB->get_field('role','id',array('archetype' => 'manager'));
            $today = time();
            $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
            $manager->timecreated = $today ;
            $manager->usermodified = $USER->id;
            
            $userdata = new stdClass();
            $userdata->costcenterid = $costcenterid;
            $userdata->userid = $userid;
            $userdata->timecreated = $today;
            $userdata->timemodified = $today;
            $userdata->usermodified = $USER->id;
            $userdata->supervisorid = 0;
            $userdata->reportingmanagerid = 0;
            
            $costcenter = $DB->get_record('local_costcenter', array('id' => $costcenterid));
            $checkexist = $DB->get_record('local_costcenter_permissions', array('userid' => $userid, 'costcenterid' => $costcenterid));
          
            if ($checkexist) {
                $this->set_confirmation(get_string('alreadyassigned', 'local_costcenter', array('costcenter' => $costcenter->fullname)), $currenturl);
            } else {
                $permission_id = $DB->insert_record('local_costcenter_permissions', $manager);
                //if(!$DB->record_exists('local_userdata',array('userid'=>$userid)))
                //$DB->insert_record('local_userdata', $userdata);
            }
            if ($permission_id) {
                $conf = new object();
                $conf->username = $DB->get_field('user', 'username', array('id' => $userid));
                $conf->costcentername = $DB->get_field('local_costcenter', 'fullname', array('id' => $costcenterid));
                $message = get_string('msg_add_reg_schl', 'local_costcenter', $conf);
                $userfrom = $DB->get_record('user', array('id' => $USER->id));
                $userto = $DB->get_record('user', array('id' => $userid));
                $message_post_message = message_post_message($userfrom, $userto, $message, FORMAT_HTML);
            }
        }
        if ($permission_id) {
            $this->set_confirmation(get_string('assignedsuccess', 'local_costcenter'), $currenturl, array('style' => 'notifysuccess'));
        } else {
            $this->set_confirmation(get_string('assignedfailed', 'local_costcenter'), $currenturl, array('style' => 'notifyproblem'));
        }
    }
 public function init_start_end_date()
 {
     global $CFG;
     // HOURSECS solves issue for weeks view with Daylight saving time and clocks adjusting by one hour backward.
     $date = usergetdate($this->curdate + HOURSECS);
     $mday = $date['mday'];
     $wday = $date['wday'] - $CFG->calendar_startwday;
     if ($wday < 0) {
         $wday += 7;
     }
     $mon = $date['mon'];
     $year = $date['year'];
     switch ($this->view) {
         case ATT_VIEW_DAYS:
             $this->startdate = make_timestamp($year, $mon, $mday);
             $this->enddate = make_timestamp($year, $mon, $mday + 1);
             break;
         case ATT_VIEW_WEEKS:
             $this->startdate = make_timestamp($year, $mon, $mday - $wday);
             $this->enddate = make_timestamp($year, $mon, $mday + 7 - $wday) - 1;
             break;
         case ATT_VIEW_MONTHS:
             $this->startdate = make_timestamp($year, $mon);
             $this->enddate = make_timestamp($year, $mon + 1);
             break;
         case ATT_VIEW_ALLPAST:
             $this->startdate = 1;
             $this->enddate = time();
             break;
         case ATT_VIEW_ALL:
             $this->startdate = 0;
             $this->enddate = 0;
             break;
     }
 }
Example #28
0
/**
 * Given date/time components return the equivalent GMT timestamp for specified
 * date/time in user's timezone.
 *
 * @param int $hour            the hour in specified or user's timezone (0-23)
 * @param int $minute          the minute in specified or user's timezone (0-59)
 * @param int $second          the second in specified or user's timezone (0-59)
 * @param int $month           the month in specified or user's timezone (1-12)
 * @param int $day             the day in specified or user's timezone (0-31)
 * @param int $year            the year in specified or user's timezone
 * @param int|string $timezone the timezone the specified time is relative to.
 * @return int the GMT timestamp in specified or user's timezone
 */
function pm_timestamp($hour = null, $minute = null, $second = null, $month = null, $day = null, $year = null, $timezone = 99)
{
    if ($hour === null) {
        $hour = gmdate('H');
    }
    if ($minute === null) {
        $minute = gmdate('i');
    }
    if ($second === null) {
        $second = gmdate('s');
    }
    if ($month === null) {
        $month = gmdate('n');
    }
    if ($day === null) {
        $day = gmdate('j');
    }
    if ($year === null) {
        $year = gmdate('Y');
    }
    return make_timestamp($year, $month, $day, $hour, $minute, $second, $timezone);
}
Example #29
0
function workshop_update_instance($workshop)
{
    // Given an object containing all the necessary data,
    // (defined by the form in mod.html) this function
    // will update an existing instance with new data.
    global $CFG;
    $workshop->timemodified = time();
    $workshop->submissionstart = make_timestamp($workshop->submissionstartyear, $workshop->submissionstartmonth, $workshop->submissionstartday, $workshop->submissionstarthour, $workshop->submissionstartminute);
    $workshop->assessmentstart = make_timestamp($workshop->assessmentstartyear, $workshop->assessmentstartmonth, $workshop->assessmentstartday, $workshop->assessmentstarthour, $workshop->assessmentstartminute);
    $workshop->submissionend = make_timestamp($workshop->submissionendyear, $workshop->submissionendmonth, $workshop->submissionendday, $workshop->submissionendhour, $workshop->submissionendminute);
    $workshop->assessmentend = make_timestamp($workshop->assessmentendyear, $workshop->assessmentendmonth, $workshop->assessmentendday, $workshop->assessmentendhour, $workshop->assessmentendminute);
    $workshop->releasegrades = make_timestamp($workshop->releaseyear, $workshop->releasemonth, $workshop->releaseday, $workshop->releasehour, $workshop->releaseminute);
    if (!workshop_check_dates($workshop)) {
        return get_string('invaliddates', 'workshop');
    }
    // set the workshop's type
    $wtype = 0;
    // 3 phases, no grading grades
    if ($workshop->includeself or $workshop->ntassessments) {
        $wtype = 1;
    }
    // 3 phases with grading grades
    if ($workshop->nsassessments) {
        $wtype = 2;
    }
    // 5 phases with grading grades
    $workshop->wtype = $wtype;
    // encode password if necessary
    if (!empty($workshop->password)) {
        $workshop->password = md5($workshop->password);
    } else {
        unset($workshop->password);
    }
    $workshop->id = $workshop->instance;
    if ($returnid = update_record("workshop", $workshop)) {
        $dates = array('submissionstart' => $workshop->submissionstart, 'submissionend' => $workshop->submissionend, 'assessmentstart' => $workshop->assessmentstart, 'assessmentend' => $workshop->assessmentend);
        $moduleid = get_field('modules', 'id', 'name', 'workshop');
        foreach ($dates as $type => $date) {
            if ($event = get_record('event', 'modulename', 'workshop', 'instance', $workshop->id, 'eventtype', $type)) {
                $event->name = get_string($type . 'event', 'workshop', $workshop->name);
                $event->description = $workshop->description;
                $event->eventtype = $type;
                $event->timestart = $date;
                update_event($event);
            } else {
                if ($date) {
                    $event = NULL;
                    $event->name = get_string($type . 'event', 'workshop', $workshop->name);
                    $event->description = $workshop->description;
                    $event->courseid = $workshop->course;
                    $event->groupid = 0;
                    $event->userid = 0;
                    $event->modulename = 'workshop';
                    $event->instance = $workshop->instance;
                    $event->eventtype = $type;
                    $event->timestart = $date;
                    $event->timeduration = 0;
                    $event->visible = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $workshop->id);
                    add_event($event);
                }
            }
        }
    }
    if (time() > $workshop->assessmentstart) {
        // regrade all the submissions...
        set_field("workshop_submissions", "nassessments", 0, "workshopid", $workshop->id);
        workshop_grade_assessments($workshop);
    }
    return $returnid;
}
 /**
  * Takes a record and transform it into an appropriate format
  * This method is set up as a hook to be implented by actual report class
  *
  * @uses $CFG
  * @param   stdClass  $record         The current report record
  * @param   string    $export_format  The format being used to render the report
  *
  * @return  stdClass                  The reformatted record
  */
 function transform_record($record, $export_format)
 {
     global $CFG;
     //$this->err_dump($record, 'transform_record($record, '. $export_format .')');
     // Total time column from seconds to hours[:minutes]
     if ($this->segment == 'noseg') {
         $record->gcslabel = $export_format == php_report::$EXPORT_FORMAT_PDF ? "�������" : '';
         $totaltime = 0;
         if (!empty($record->mcourse_id)) {
             $sql = "SELECT SUM(duration) as sum\n                        FROM {$CFG->prefix}etl_user_activity\n                       WHERE courseid = {$record->mcourse_id}\n                         AND userid = {$record->user_id}\n                         AND hour >= {$this->startdate}";
             if (!empty($this->enddate)) {
                 $sql .= " AND hour <= {$this->enddate}";
             }
             //print_object($sql);
             $trecs = get_records_sql($sql);
             if (!empty($trecs)) {
                 //$this->err_dump($trecs, '$trecs');
                 foreach ($trecs as $rec) {
                     if (!empty($rec->sum)) {
                         $totaltime += $rec->sum;
                     }
                 }
             }
         }
     } else {
         if ($this->segment == 'years') {
             $totaltime = 0;
             if (!empty($record->mcourse_id)) {
                 $startdate = make_timestamp($record->year);
                 foreach ($this->months as $month) {
                     $enddate = $this->add_month($startdate);
                     // TBD: $this->next_month($startdate);
                     $sql = "SELECT SUM(duration) as sum\n                              FROM {$CFG->prefix}etl_user_activity\n                             WHERE courseid = {$record->mcourse_id}\n                               AND userid = {$record->user_id}\n                               AND hour >= {$startdate}\n                               AND hour < {$enddate}";
                     //print_object($sql);
                     $trecs = get_records_sql($sql);
                     $curtime = 0;
                     if (!empty($trecs)) {
                         //$this->err_dump($trecs, '$trecs');
                         foreach ($trecs as $rec) {
                             if (!empty($rec->sum)) {
                                 $curtime += $rec->sum;
                             }
                         }
                     }
                     $record->{$month} = $this->format_time(get_string('time_format', $this->langfile), $curtime);
                     $totaltime += $curtime;
                     $startdate = $enddate;
                 }
             }
         } else {
             if ($this->segment == 'months') {
                 $totaltime = 0;
                 if (!empty($record->mcourse_id)) {
                     $startdate = make_timestamp($record->year, $record->month);
                     $nextmonth = $this->add_month($startdate);
                     foreach ($this->weeks as $wk) {
                         $enddate = $wk == 'week4' ? $nextmonth : $this->add_week($startdate);
                         $sql = "SELECT SUM(duration) as sum\n                              FROM {$CFG->prefix}etl_user_activity\n                             WHERE courseid = {$record->mcourse_id}\n                               AND userid = {$record->user_id}\n                               AND hour >= {$startdate}\n                               AND hour < {$enddate}";
                         //print_object($sql);
                         $trecs = get_records_sql($sql);
                         $curtime = 0;
                         if (!empty($trecs)) {
                             //$this->err_dump($trecs, '$trecs');
                             foreach ($trecs as $rec) {
                                 if (!empty($rec->sum)) {
                                     $curtime += $rec->sum;
                                 }
                             }
                         }
                         $totaltime += $curtime;
                         $record->{$wk} = $this->format_time(get_string('time_format', $this->langfile), $curtime);
                         $startdate = $enddate;
                     }
                     if (!empty($record->month)) {
                         $sparam = new stdClass();
                         $sparam->int_month = $record->month;
                         $sparam->str_month = get_string($this->months[$record->month - 1], $this->langfile);
                         $record->month = get_string('month_format', $this->langfile, $sparam);
                     }
                 }
             } else {
                 // 'weeks'
                 $totaltime = 0;
                 if (!empty($record->mcourse_id)) {
                     $startdate = make_timestamp($record->year);
                     while (date('w', $startdate) != 0) {
                         // off a day depending on TZ
                         // week must start on a sunday
                         $startdate = $this->add_day($startdate);
                         // TBD: $this->next_day($startdate);
                     }
                     for ($i = 1; $i < $record->week; ++$i) {
                         $startdate = $this->add_week($startdate);
                     }
                     foreach ($this->wkdays as $day) {
                         $enddate = $this->add_day($startdate);
                         // TBD: $this->next_day($startdate);
                         $sql = "SELECT SUM(duration) as sum\n                              FROM {$CFG->prefix}etl_user_activity\n                             WHERE courseid = {$record->mcourse_id}\n                               AND userid = {$record->user_id}\n                               AND hour >= {$startdate}\n                               AND hour < {$enddate}";
                         //print_object($sql);
                         $trecs = get_records_sql($sql);
                         $curtime = 0;
                         if (!empty($trecs)) {
                             //$this->err_dump($trecs, '$trecs');
                             foreach ($trecs as $rec) {
                                 if (!empty($rec->sum)) {
                                     $curtime += $rec->sum;
                                 }
                             }
                         }
                         $totaltime += $curtime;
                         $record->{$day} = $this->format_time(get_string('time_format', $this->langfile), $curtime);
                         $startdate = $enddate;
                     }
                 }
             }
         }
     }
     if (empty($record->year)) {
         $record->year = get_string('no_time_logged', $this->langfile, strtolower(get_string('seg_years', $this->langfile)));
     }
     if (empty($record->year) || empty($record->month)) {
         $record->month = get_string('no_time_logged', $this->langfile, strtolower(get_string('seg_months', $this->langfile)));
     }
     if (empty($record->year) || empty($record->week)) {
         $record->week = get_string('no_time_logged', $this->langfile, strtolower(get_string('seg_weeks', $this->langfile)));
     }
     if ($this->xformrec != $record) {
         // required since table_report::get_data()
         // calls transform_record() twice for 1st record!
         $this->grouptotal += $totaltime;
         $this->xformrec = clone $record;
     }
     $totaltime_fmt = $export_format == php_report::$EXPORT_FORMAT_CSV ? 'time_format' : 'totaltime_format';
     $record->totaltime = $this->format_time(get_string($totaltime_fmt, $this->langfile), $totaltime);
     // Below must reassign AFTER time since above requires u.id (user_id)
     $record->user_id = fullname($record);
     return $record;
 }