Пример #1
0
function expect_times($expected, $times, $testCase)
{
    $totalDuration = 0;
    for ($run = 0; $run < $times; $run++) {
        $testResult = expect($expected, $testCase);
        if (!$testResult->success) {
            print "Run " . $run . " failed";
            print_result($testResult);
            break;
        }
        $totalDuration += $testResult->duration;
    }
    $averageDuration = $totalDuration / $times;
    print "Average duration: " . format_duration($averageDuration) . " \n";
}
Пример #2
0
/**
 * Print the details of a session
 *
 * @param object $session         Record from facetoface_sessions
 * @param boolean $showcapacity   Show the capacity (true) or only the seats available (false)
 * @param boolean $calendaroutput Whether the output should be formatted for a calendar event
 * @param boolean $return         Whether to return (true) the html or print it directly (true)
 * @param boolean $hidesignup     Hide any messages relating to signing up
 */
function facetoface_print_session($session, $showcapacity, $calendaroutput=false, $return=false, $hidesignup=false) {
    global $CFG, $DB;

    $table = new html_table();
    $table->summary = get_string('sessionsdetailstablesummary', 'facetoface');
    $table->attributes['class'] = 'generaltable f2fsession';
    $table->align = array('right', 'left');
    if ($calendaroutput) {
        $table->tablealign = 'left';
    }

    $customfields = facetoface_get_session_customfields();
    $customdata = $DB->get_records('facetoface_session_data', array('sessionid' => $session->id), '', 'fieldid, data');
    foreach ($customfields as $field) {
        $data = '';
        if (!empty($customdata[$field->id])) {
            if (CUSTOMFIELD_TYPE_MULTISELECT == $field->type) {
                $values = explode(CUSTOMFIELD_DELIMITER, format_string($customdata[$field->id]->data));
                $data = implode(html_writer::empty_tag('br'), $values);
            }
            else {
                $data = format_string($customdata[$field->id]->data);
            }
        }
        $table->data[] = array(str_replace(' ', '&nbsp;', format_string($field->name)), $data);
    }

    $strdatetime = str_replace(' ', '&nbsp;', get_string('sessiondatetime', 'facetoface'));
    if ($session->datetimeknown) {
        $html = '';
        foreach ($session->sessiondates as $date) {
            if (!empty($html)) {
                $html .= html_writer::empty_tag('br');
            }
            $sessionobj = facetoface_format_session_times($date->timestart, $date->timefinish, $date->sessiontimezone);
            if ($sessionobj->startdate == $sessionobj->enddate) {
                $html .= $sessionobj->startdate . ', ';
            } else {
                $html .= $sessionobj->startdate . ' - ' . $sessionobj->enddate . ', ';
            }
            $html .= $sessionobj->starttime . ' - ' . $sessionobj->endtime . ' ' . $sessionobj->timezone;
        }
        $table->data[] = array($strdatetime, $html);
    } else {
        $table->data[] = array($strdatetime, html_writer::tag('i', get_string('wait-listed', 'facetoface')));
    }

    $signupcount = facetoface_get_num_attendees($session->id);
    $placesleft = $session->capacity - $signupcount;

    if ($showcapacity) {
        if ($session->allowoverbook) {
            $table->data[] = array(get_string('capacity', 'facetoface'), get_string('capacityallowoverbook', 'facetoface', $session->capacity));
        } else {
            $table->data[] = array(get_string('capacity', 'facetoface'), $session->capacity);
        }
    }
    elseif (!$calendaroutput) {
        $table->data[] = array(get_string('seatsavailable', 'facetoface'), max(0, $placesleft));
    }

    // Display requires approval notification
    $facetoface = $DB->get_record('facetoface', array('id' => $session->facetoface));

    if ($facetoface->approvalreqd) {
        $table->data[] = array('', get_string('sessionrequiresmanagerapproval', 'facetoface'));
    }

    // Display waitlist notification
    if (!$hidesignup && $session->allowoverbook && $placesleft < 1) {
        $table->data[] = array('', get_string('userwillbewaitlisted', 'facetoface'));
    }

    if (!empty($session->duration)) {
        $table->data[] = array(get_string('duration', 'facetoface'), format_duration($session->duration));
    }

    // Display room information
    $session->room = $DB->get_record('facetoface_room', array('id' => $session->roomid));
    if (!empty($session->room)) {
        $roomstring = '';
        $roomstring = isset($session->room->name) ? format_string($session->room->name) . ', '. html_writer::empty_tag('br') : '';
        $roomstring .= isset($session->room->building) ? format_string($session->room->building) . ', ' . html_writer::empty_tag('br') : '';
        $roomstring .= isset($session->room->address) ? format_string($session->room->address) . html_writer::empty_tag('br') : '';

        $systemcontext = context_system::instance();
        $editoroptions = array(
            'noclean'  => false,
            'maxfiles' => EDITOR_UNLIMITED_FILES,
            'context'  => $systemcontext,
        );

        $session->room->descriptionformat = FORMAT_HTML;
        $session->room = file_prepare_standard_editor($session->room, 'description', $editoroptions, $systemcontext, 'facetoface', 'room', $session->room->id);

        $roomstring .= $session->room->description_editor['text'];

        $table->data[] = array(get_string('room', 'facetoface'), $roomstring);
    }

    if (!empty($session->normalcost)) {
        $table->data[] = array(get_string('normalcost', 'facetoface'), format_string($session->normalcost));
    }
    if (!empty($session->discountcost)) {
        $table->data[] = array(get_string('discountcost', 'facetoface'), format_string($session->discountcost));
    }

    // Display trainers.
    $courseid = $DB->get_field('facetoface', 'course', array('id' => $session->facetoface));
    $coursecontext = context_course::instance($courseid);

    if (!empty($session->details)) {
        if ($cm = get_coursemodule_from_instance('facetoface', $facetoface->id, $courseid)) {
            $context = context_module::instance($cm->id);
            $session->details = file_rewrite_pluginfile_urls($session->details, 'pluginfile.php', $context->id, 'mod_facetoface', 'session', $session->id);
        }
        $details = format_text($session->details, FORMAT_HTML);
        $table->data[] = array(get_string('details', 'facetoface'), $details);
    }

    $trainerroles = facetoface_get_trainer_roles($coursecontext);

    if ($trainerroles) {
        // Get trainers.
        $trainers = facetoface_get_trainers($session->id);

        foreach ($trainerroles as $role => $rolename) {
            $rolename = $rolename->localname;

            if (empty($trainers[$role])) {
                continue;
            }

            $trainer_names = array();
            foreach ($trainers[$role] as $trainer) {
                $trainer_url = new moodle_url('/user/view.php', array('id' => $trainer->id));
                $trainer_names[] = html_writer::link($trainer_url, fullname($trainer));
            }

            $table->data[] = array($rolename, implode(', ', $trainer_names));
        }
    }

    return html_writer::table($table, $return);
}
Пример #3
0
function duration($seconds)
{
    $data = format_duration($seconds);
    $data2 = array();
    foreach ($data as $unit => $amount) {
        $data2[] = $amount . ' ' . $unit;
    }
    return implode(', ', $data2);
}
Пример #4
0
/**
 * Print the details of a session
 *
 * @param object $session         Record from facetoface_sessions
 * @param boolean $showcapacity   Show the capacity (true) or only the seats available (false)
 * @param boolean $calendaroutput Whether the output should be formatted for a calendar event
 * @param boolean $return         Whether to return (true) the html or print it directly (true)
 * @param boolean $hidesignup     Hide any messages relating to signing up
 */
function facetoface_print_session($session, $showcapacity, $calendaroutput = false, $return = false, $hidesignup = false)
{
    global $CFG, $DB;
    $table = new html_table();
    $table->summary = get_string('sessionsdetailstablesummary', 'facetoface');
    $table->attributes['class'] = 'generaltable f2fsession';
    $table->align = array('right', 'left');
    if ($calendaroutput) {
        $table->tablealign = 'left';
    }
    $customfields = facetoface_get_session_customfields();
    $customdata = $DB->get_records('facetoface_session_data', array('sessionid' => $session->id), '', 'fieldid, data');
    foreach ($customfields as $field) {
        $data = '';
        if (!empty($customdata[$field->id])) {
            if (CUSTOMFIELD_TYPE_MULTISELECT == $field->type) {
                $values = explode(CUSTOMFIELD_DELIMITER, format_string($customdata[$field->id]->data));
                $data = implode(html_writer::empty_tag('br'), $values);
            } else {
                $data = format_string($customdata[$field->id]->data);
            }
        }
        $table->data[] = array(str_replace(' ', '&nbsp;', format_string($field->name)), $data);
    }
    $strdatetime = str_replace(' ', '&nbsp;', get_string('sessiondatetime', 'facetoface'));
    if ($session->datetimeknown) {
        $html = '';
        foreach ($session->sessiondates as $date) {
            if (!empty($html)) {
                $html .= html_writer::empty_tag('br');
            }
            $timestart = userdate($date->timestart, get_string('strftimedatetime'));
            $timefinish = userdate($date->timefinish, get_string('strftimedatetime'));
            $html .= "{$timestart} &ndash; {$timefinish}";
        }
        $table->data[] = array($strdatetime, $html);
    } else {
        $table->data[] = array($strdatetime, html_writer::tag('i', get_string('wait-listed', 'facetoface')));
    }
    $signupcount = facetoface_get_num_attendees($session->id);
    $placesleft = $session->capacity - $signupcount;
    if ($showcapacity) {
        if ($session->allowoverbook) {
            $table->data[] = array(get_string('capacity', 'facetoface'), $session->capacity . ' (' . strtolower(get_string('allowoverbook', 'facetoface')) . ')');
        } else {
            $table->data[] = array(get_string('capacity', 'facetoface'), $session->capacity);
        }
    } else {
        if (!$calendaroutput) {
            $table->data[] = array(get_string('seatsavailable', 'facetoface'), max(0, $placesleft));
        }
    }
    // Display requires approval notification.
    $facetoface = $DB->get_record('facetoface', array('id' => $session->facetoface));
    if ($facetoface->approvalreqd) {
        $table->data[] = array('', get_string('sessionrequiresmanagerapproval', 'facetoface'));
    }
    // Display waitlist notification.
    if (!$hidesignup && $session->allowoverbook && $placesleft < 1) {
        $table->data[] = array('', get_string('userwillbewaitlisted', 'facetoface'));
    }
    if (!empty($session->duration)) {
        $table->data[] = array(get_string('duration', 'facetoface'), format_duration($session->duration));
    }
    if (!empty($session->normalcost)) {
        $table->data[] = array(get_string('normalcost', 'facetoface'), format_cost($session->normalcost));
    }
    if (!empty($session->discountcost)) {
        $table->data[] = array(get_string('discountcost', 'facetoface'), format_cost($session->discountcost));
    }
    if (!empty($session->details)) {
        $details = clean_text($session->details, FORMAT_HTML);
        $table->data[] = array(get_string('details', 'facetoface'), $details);
    }
    // Display trainers.
    $trainerroles = facetoface_get_trainer_roles();
    if ($trainerroles) {
        // Get trainers.
        $trainers = facetoface_get_trainers($session->id);
        foreach ($trainerroles as $role => $rolename) {
            $rolename = $rolename->name;
            if (empty($trainers[$role])) {
                continue;
            }
            $trainernames = array();
            foreach ($trainers[$role] as $trainer) {
                $trainerurl = new moodle_url('/user/view.php', array('id' => $trainer->id));
                $trainernames[] = html_writer::link($trainerurl, fullname($trainer));
            }
            $table->data[] = array($rolename, implode(', ', $trainernames));
        }
    }
    return html_writer::table($table, $return);
}
Пример #5
0
function format_datetime_ago($datetime)
{
    $dt = new DateTime($datetime);
    $seconds_ago = time() - (int) $dt->format('U');
    return format_duration($seconds_ago) . " ago";
}
Пример #6
0
function rip_youtube_data($record)
{
    $media = $record['media$group'];
    $title = $media['media$title']['$t'];
    $description = substr($media['media$description']['$t'], 0, 100);
    $duration = $media['yt$duration']['seconds'];
    $thumbs = array();
    // w:h => array( file, file, file)
    $largest = array(0, '', 0, 0);
    $smallest = array(3000 * 3000, '', 3000, 3000);
    // Ok, hacky, sosumi
    foreach ($media['media$thumbnail'] as $thumb) {
        if (!isset($thumbs["{$thumb['width']}x{$thumb['height']}"])) {
            $thumbs["{$thumb['width']}x{$thumb['height']}"] = array();
            if ($thumb['width'] * $thumb['height'] > $largest[0]) {
                $largest = array($thumb['width'] * $thumb['height'], $thumb['width'] . 'x' . $thumb['height'], $thumb['width'], $thumb['height']);
            }
            if ($thumb['width'] * $thumb['height'] < $smallest[0]) {
                $smallest = array($thumb['width'] * $thumb['height'], $thumb['width'] . 'x' . $thumb['height'], $thumb['width'], $thumb['height']);
            }
        }
        $thumbs["{$thumb['width']}x{$thumb['height']}"][$thumb['time']] = $thumb['url'];
    }
    // Find the main image link
    $mainImage = $thumbs[$largest[1]];
    $mainImage = array_pop($mainImage);
    // Find the thumb image link
    $thumbImage = $thumbs[$smallest[1]];
    $thumbImage = array_pop($thumbImage);
    $embed = NULL;
    foreach ($media['media$content'] as $vid) {
        if ($vid['type'] == 'application/x-shockwave-flash') {
            $embed = $vid['url'];
            break;
        }
    }
    // Final image to pass to manager (use query param to record the embed url)
    $combinedImage = $mainImage . '?x-shockwave-flash=' . rawurlencode($embed) . '&x-tn=' . rawurlencode($thumbImage);
    return array('title' => $title, 'description' => $description, 'duration' => format_duration($duration), 'mainImage' => $mainImage, 'thumbImage' => $thumbImage, 'combinedImage' => $combinedImage, 'smallest' => $smallest, 'largest' => $largest, 'thumbs' => $thumbs, 'embed' => $embed);
}
 private function calc_bossdkp($key, $times, $standby, $standby1 = 0)
 {
     $bossdkp = 0;
     foreach ($this->raids[$key]['bosskills'] as $b => $bosskill) {
         //absolute bossdkp
         if ($times !== false) {
             foreach ($times as $time) {
                 if (!isset($time['standby']) && !$standby || (isset($time['standby']) and $standby == $time['standby'])) {
                     if ($time['join'] < $bosskill['time'] and $time['leave'] > $bosskill['time']) {
                         $bossdkp += $bosskill['bonus'];
                         break;
                     }
                 }
             }
         } else {
             $bossdkp += $bosskill['bonus'];
         }
         //timed bossdkp
         $kill_before = isset($this->raids[$key]['bosskills'][$b - 1]['time']) ? $this->raids[$key]['bosskills'][$b - 1]['time'] : NULL;
         $kill_after = isset($this->raids[$key]['bosskills'][$b + 1]['time']) ? $this->raids[$key]['bosskills'][$b + 1]['time'] : NULL;
         $temp = $this->get_bosskill_raidtime($this->raids[$key]['begin'], $this->raids[$key]['end'], $bosskill['time'], $kill_before, $kill_after);
         $in_boss = format_duration($this->in_raid($temp, $times, $standby1));
         $bossdkp += $this->calc_timebossdkp($bosskill['timebonus'], $in_boss);
     }
     return $bossdkp;
 }
Пример #8
0
/**
 * Subsitute the placeholders in message templates for the actual data
 *
 * Expects the following parameters in the $data object:
 * - datetimeknown
 * - details
 * - discountcost
 * - duration
 * - normalcost
 * - sessiondates
 *
 * @access  public
 * @param   string  $msg            Email message
 * @param   string  $facetofacename F2F name
 * @param   obj     $user           The subject of the message
 * @param   obj     $data           Session data
 * @param   int     $sessionid      Session ID
 * @return  string
 */
function facetoface_message_substitutions($msg, $coursename, $facetofacename, $user, $data, $sessionid) {
    global $CFG, $DB;

    if (empty($msg)) {
        return '';
    }

    if ($data->datetimeknown) {
        // Scheduled session
        $alldates = '';
        foreach ($data->sessiondates as $date) {
            if ($alldates != '') {
                $alldates .= "\n";
            }
            $startdate = userdate($date->timestart, get_string('strftimedate'), $date->sessiontimezone);
            $finishdate = userdate($date->timefinish, get_string('strftimedate'), $date->sessiontimezone);
            if ($startdate == $finishdate) {
                $alldates .= $startdate . ', ';
            } else {
                $alldates .= $startdate . ' - ' . $finishdate . ', ';
            }
            $starttime = userdate($date->timestart, get_string('strftimetime'), $date->sessiontimezone);
            $finishtime = userdate($date->timefinish, get_string('strftimetime'), $date->sessiontimezone);
            $timestr = $starttime . ' - ' . $finishtime . ' ' . $date->sessiontimezone;
            $alldates .= $timestr;
        }

        $startdate = userdate($data->sessiondates[0]->timestart, get_string('strftimedate'), $date->sessiontimezone);
        $finishdate = userdate($data->sessiondates[0]->timefinish, get_string('strftimedate'), $date->sessiontimezone);
        $sessiondate = ($startdate == $finishdate) ? $startdate : $startdate . ' - ' . $finishdate;
        $starttime = userdate($data->sessiondates[0]->timestart, get_string('strftimetime'), $date->sessiontimezone);
        $finishtime = userdate($data->sessiondates[0]->timefinish, get_string('strftimetime'), $date->sessiontimezone);

    } else {
        // Wait-listed session
        $startdate   = get_string('unknowndate', 'facetoface');
        $finishdate  = get_string('unknowndate', 'facetoface');
        $sessiondate = get_string('unknowndate', 'facetoface');
        $alldates    = get_string('unknowndate', 'facetoface');
        $starttime   = get_string('unknowntime', 'facetoface');
        $finishtime  = get_string('unknowntime', 'facetoface');
    }

    $msg = str_replace(get_string('placeholder:coursename', 'facetoface'), $coursename, $msg);
    $msg = str_replace(get_string('placeholder:facetofacename', 'facetoface'), $facetofacename, $msg);
    $msg = str_replace(get_string('placeholder:firstname', 'facetoface'), $user->firstname, $msg);
    $msg = str_replace(get_string('placeholder:lastname', 'facetoface'), $user->lastname, $msg);
    $msg = str_replace(get_string('placeholder:cost', 'facetoface'), facetoface_cost($user->id, $sessionid, $data), $msg);
    $msg = str_replace(get_string('placeholder:alldates', 'facetoface'), $alldates, $msg);
    $msg = str_replace(get_string('placeholder:sessiondate', 'facetoface'), $sessiondate, $msg);
    $msg = str_replace(get_string('placeholder:startdate', 'facetoface'), $startdate, $msg);
    $msg = str_replace(get_string('placeholder:finishdate', 'facetoface'), $finishdate, $msg);
    $msg = str_replace(get_string('placeholder:starttime', 'facetoface'), $starttime, $msg);
    $msg = str_replace(get_string('placeholder:finishtime', 'facetoface'), $finishtime, $msg);
    $msg = str_replace(get_string('placeholder:duration', 'facetoface'), format_duration($data->duration), $msg);

    // add placeholders that somehow have been forgetten since moodle
    $roomnull = 'N/A';  // Displayed if empty.

    // Defaults if values are empty
    $strlocation = $roomnull;
    $strvenue = $roomnull;
    $strroom = $roomnull;

    if ($room = facetoface_get_session_room($sessionid)) {
        $strlocation = isset($room->address) ? $room->address : $roomnull;
        $strvenue = isset($room->building) ? $room->building : $roomnull;
        $strroom = isset($room->name) ? $room->name : $roomnull;
    }

    $msg = str_replace(get_string('placeholder:location', 'facetoface'), $strlocation, $msg);
    $msg = str_replace(get_string('placeholder:venue', 'facetoface'), $strvenue, $msg);
    $msg = str_replace(get_string('placeholder:room', 'facetoface'), $strroom, $msg);

    if (empty($data->details)) {
        $msg = str_replace(get_string('placeholder:details', 'facetoface'), '', $msg);
    } else {
        $msg = str_replace(get_string('placeholder:details', 'facetoface'), html_to_text($data->details), $msg);
    }

    // Replace more meta data
    $attendees_url = new moodle_url('/mod/facetoface/attendees.php', array('s' => $sessionid, 'action' => 'approvalrequired'));
    $link = html_writer::link($attendees_url, $attendees_url, array('title' => get_string('attendees', 'facetoface')));
    $msg = str_replace(get_string('placeholder:attendeeslink', 'facetoface'), $link, $msg);

    if (strstr($msg, get_string('placeholder:reminderperiod', 'facetoface'))) {
        // Handle the legacy reminderperiod placeholder.
        $reminderperiod = $DB->get_field('facetoface_notification', 'MAX(scheduleamount)',
            array('facetofaceid' => $data->facetoface, 'conditiontype' => MDL_F2F_CONDITION_BEFORE_SESSION,
            'scheduleunit' => MDL_F2F_SCHEDULE_UNIT_DAY, 'status' => 1), IGNORE_MULTIPLE);
        $reminderperiod = empty($reminderperiod) ? 0 : $reminderperiod;
        $msg = str_replace(get_string('placeholder:reminderperiod', 'facetoface'), $reminderperiod, $msg);
    }

    // Custom session fields (they look like "session:shortname" in the templates)
    $customfields = facetoface_get_session_customfields();
    $customdata = $DB->get_records('facetoface_session_data', array('sessionid' => $sessionid), '', 'fieldid, data');
    foreach ($customfields as $field) {
        $placeholder = "[session:{$field->shortname}]";
        $value = '';
        if (!empty($customdata[$field->id])) {
            if (CUSTOMFIELD_TYPE_MULTISELECT == $field->type) {
                $value = str_replace(CUSTOMFIELD_DELIMITER, ', ', $customdata[$field->id]->data);
            } else {
                $value = $customdata[$field->id]->data;
            }
        }

        $msg = str_replace($placeholder, $value, $msg);
    }

    return $msg;
}
Пример #9
0
 public function test_format_duration()
 {
     // ISSUES:
     // Expects a space after hour/s but not minute/s.
     // Minutes > 59 are not being converted to hour values.
     // Negative values are not interpreted correctly.
     // Test for positive single hour value.
     $this->assertEqual(format_duration('1:00'), '1 hour ');
     $this->assertEqual(format_duration('1.00'), '1 hour ');
     // Test for positive multiple hours value.
     $this->assertEqual(format_duration('3:00'), '3 hours ');
     $this->assertEqual(format_duration('3.00'), '3 hours ');
     // Test for positive single minute value.
     $this->assertEqual(format_duration('0:01'), '1 minute');
     $this->assertEqual(format_duration('0.1'), '6 minutes');
     // Test for positive minutes value.
     $this->assertEqual(format_duration('0:30'), '30 minutes');
     $this->assertEqual(format_duration('0.50'), '30 minutes');
     // Test for out of range minutes value.
     $this->assertEqual(format_duration('9:70'), '');
     // Test for zero value.
     $this->assertEqual(format_duration('0:00'), '');
     $this->assertEqual(format_duration('0.00'), '');
     // Test for negative hour value.
     $this->assertEqual(format_duration('-1:00'), '');
     $this->assertEqual(format_duration('-1.00'), '');
     // Test for negative multiple hours value.
     $this->assertEqual(format_duration('-7:00'), '');
     $this->assertEqual(format_duration('-7.00'), '');
     // Test for negative single minute value.
     $this->assertEqual(format_duration('-0:01'), '');
     $this->assertEqual(format_duration('-0.01'), '');
     // Test for negative multiple minutes value.
     $this->assertEqual(format_duration('-0:33'), '');
     $this->assertEqual(format_duration('-0.33'), '');
     // Test for negative hours & minutes value.
     $this->assertEqual(format_duration('-5:42'), '');
     $this->assertEqual(format_duration('-5.42'), '');
     // Test for invalid characters value.
     $this->assertEqual(format_duration('invalid_string'), '');
 }
Пример #10
0
/**
 * Returns information about an Audio/Video file.
 * 
 * @param string $file_name Audio/Video file
 * @return dictionary FALSE on error or a dictionary of audio/video properties
 * with the following keys otherwise:
 * <ul>
 *   <li>width</li>
 *   <li>height</li>
 *   <li>dar (display aspect ratio)</li>
 *   <li>duration (formated as [HH:]mm:ss)</li>
 *   <li>size (in bytes)</li>
 * </ul>
 */
function get_av_info($file_name)
{
    $h = popen('avprobe -show_streams -show_format "' . $file_name . '" 2> /dev/null', 'r');
    $tag = NULL;
    $codec_type = NULL;
    while (($r = fgets($h, 512)) !== FALSE) {
        // Match tags.
        if (preg_match('/^\\[FORMAT\\]/', $r)) {
            $tag = 'FORMAT';
            continue;
        }
        if (preg_match('/^\\[STREAM\\]/', $r)) {
            $tag = 'STREAM';
            continue;
        }
        if ($tag == 'FORMAT') {
            // Size
            if (preg_match('/^size=/', $r)) {
                $size = intval(_parse_value($r));
            }
        }
        if ($tag == 'STREAM') {
            // Width
            if (preg_match('/^width=/', $r)) {
                $width = intval(_parse_value($r));
            }
            // Height
            if (preg_match('/^height=/', $r)) {
                $height = intval(_parse_value($r));
            }
            // DAR
            if (preg_match('/^display_aspect_ratio=/', $r)) {
                $dar = _parse_value($r);
            }
            // Codec Type
            if (preg_match('/^codec_type=/', $r)) {
                $codec_type = _parse_value($r);
            }
            // Duration
            if (preg_match('/^duration=/', $r) && strcmp($codec_type, 'video') == 0) {
                $duration = format_duration(floatval(_parse_value($r)));
            }
        }
    }
    if (pclose($h) > 0) {
        return FALSE;
    }
    return array('width' => $width, 'height' => $height, 'dar' => $dar, 'duration' => $duration, 'size' => $size);
    //	return array('width'=> 1440, 'height'=> 1080, 'dar'=> '16:9',
    //			'duration'=> '00:10', 'size'=> 5568748);
}
Пример #11
0
function get_all_torrents($params)
{
    $torrents_only = get_param($params, 'torrents_only', false);
    $for_html = get_param($params, 'for_html', false);
    $view = get_param($params, 'view', 'main');
    global $disk_usage_dir;
    global $tracker_highlight, $tracker_highlight_default;
    global $can_hide_unhide, $date_added_format;
    $show_hidden = $can_hide_unhide && get_user_setting('show_hidden') == 'yes';
    $torrents = rtorrent_multicall('d', 'main', array('get_base_path', 'get_chunk_size', 'get_chunks_hashed', 'get_complete', 'get_completed_chunks', 'get_connection_current', 'get_directory', 'get_down_rate', 'get_down_total', 'get_hash', 'get_hashing', 'get_message', 'get_name', 'get_peers_complete', 'get_peers_connected', 'get_peers_not_connected', 'get_priority', 'get_priority_str', 'get_ratio', 'get_size_chunks', 'get_state', 'get_state_changed', 'get_tied_to_file', 'get_up_rate', 'is_active', 'is_hash_checked', 'is_hash_checking', 'is_multi_file', 'is_open', 'is_private'), 'hash', true);
    if ($response === false) {
        return false;
    }
    if (!is_array($_SESSION['persistent'])) {
        $_SESSION['persistent'] = array();
    }
    $total_down_rate = 0;
    $total_up_rate = 0;
    $torrents_count_all = count($torrents);
    $torrents_count_superhidden = 0;
    $torrents_count_visible = 0;
    $index = 0;
    foreach ($torrents as $hash => $t) {
        $total_down_rate += $t['down_rate'];
        $total_up_rate += $t['up_rate'];
        if (is_array($_SESSION['tags'][$hash])) {
            $t['tags'] = $_SESSION['tags'][$hash];
            if (in_array('_hidden', $_SESSION['tags'][$hash])) {
                if ($show_hidden) {
                    $torrents_count_superhidden++;
                } else {
                    unset($torrents[$hash]);
                    continue;
                }
            }
        } else {
            $t['tags'] = array();
        }
        $t['completed_bytes'] = $t['completed_chunks'] * $t['chunk_size'];
        $t['size_bytes'] = $t['size_chunks'] * $t['chunk_size'];
        $t['up_total'] = $t['size_bytes'] * $t['ratio'] / 1000;
        $t['percent_complete'] = $t['completed_bytes'] / $t['size_bytes'] * 100;
        $t['bytes_remaining'] = $t['size_bytes'] - $t['completed_bytes'];
        if ($t['message'] == 'Tracker: [Tried all trackers.]') {
            $t['message'] = '';
        }
        if ($t['is_active'] == 0) {
            $t['status'] = 'Stopped';
        }
        if ($t['complete'] == 1) {
            $t['status'] = 'Complete';
        }
        if ($t['is_active'] == 1 && $t['connection_current'] == 'leech') {
            $t['status'] = 'Leeching';
        }
        if ($t['is_active'] == 1 && $t['complete'] == 1) {
            $t['status'] = 'Seeding';
        }
        if ($t['hashing'] > 0) {
            $t['status'] = 'Hashing';
            $t['percent_complete'] = $t['chunks_hashed'] / $t['size_chunks'] * 100;
        }
        if ($t['complete'] == 1) {
            $t['status_class'] = 'complete';
        } else {
            $t['status_class'] = 'incomplete';
        }
        if ($t['is_active'] == 1) {
            $t['status_class'] .= 'active';
        } else {
            $t['status_class'] .= 'inactive';
        }
        if ($t['down_rate'] > 0) {
            $t['eta'] = ($t['size_bytes'] - $t['completed_bytes']) / $t['down_rate'];
        } else {
            $t['eta'] = 0;
        }
        $t['start_stop_cmd'] = $t['is_active'] == 1 ? 'stop' : 'start';
        # Format peers_summary to keep the sorting routine as simple as possible
        $t['peers_summary'] = sprintf('%03d,%03d,%03d', $t['peers_connected'], $t['peers_not_connected'], $t['peers_complete']);
        $t['is_transferring'] = $t['down_rate'] + $t['up_rate'] ? 1 : 0;
        if (is_array($_SESSION['persistent'][$hash])) {
            $s = $_SESSION['persistent'][$hash];
        } else {
            $s = array();
            $s['tracker_hostname'] = tracker_hostname($hash);
            $s['tracker_color'] = $tracker_highlight_default;
            if (is_array($tracker_highlight)) {
                foreach ($tracker_highlight as $highlight) {
                    foreach ($highlight as $this_url) {
                        if (stristr($s['tracker_hostname'], $this_url) !== false) {
                            $s['tracker_color'] = $highlight[0];
                        }
                    }
                }
            }
            $fn = $t['tied_to_file'];
            if (function_exists('get_local_torrent_path')) {
                $fn = get_local_torrent_path($fn);
            }
            $s['date_added'] = 0;
            if (file_exists($fn)) {
                $s['date_added'] = filemtime($fn);
            } else {
                if (preg_match('@^[a-f0-9]{40}.meta$@i', $t['name'])) {
                    // For magnet links, rTorrent creates a "TORRENT_HASH.meta" file and
                    // sets it as "tied_to_file" when the download starts.  The file still
                    // exists before then though, and it can be found at the torrent's
                    // base_path.
                    $fn = $t['base_path'];
                    if (file_exists($fn)) {
                        $s['date_added'] = filemtime($fn);
                    }
                }
            }
            $_SESSION['persistent'][$hash] = $s;
        }
        $t['tracker_hostname'] = $s['tracker_hostname'];
        $t['tracker_color'] = $s['tracker_color'];
        $t['date_added'] = $s['date_added'];
        // unset items that are only needed for setting other items
        unset($t['chunk_size']);
        unset($t['chunks_hashed']);
        unset($t['connection_current']);
        unset($t['hashing']);
        unset($t['size_chunks']);
        if ($for_html) {
            $t['server_index'] = $index++;
            $t['server_visible'] = true;
            switch ($view) {
                case 'main':
                    // (Always visible)
                    break;
                case 'started':
                    $t['server_visible'] = !!$t['state'];
                    break;
                case 'stopped':
                    $t['server_visible'] = !$t['state'];
                    break;
                case 'active':
                    $t['server_visible'] = !!$t['is_transferring'];
                    break;
                case 'inactive':
                    $t['server_visible'] = !$t['is_transferring'];
                    break;
                case 'complete':
                    $t['server_visible'] = !!$t['complete'];
                    break;
                case 'incomplete':
                    $t['server_visible'] = !$t['complete'];
                    break;
                case 'seeding':
                    $t['server_visible'] = !!$t['complete'] && !!$t['state'];
                    break;
            }
            if ($t['server_visible']) {
                $torrents_count_visible++;
            }
            // unset items that aren't needed by the HTML templates
            unset($t['base_path']);
            unset($t['directory']);
            unset($t['is_active']);
            unset($t['is_hash_checked']);
            unset($t['is_hash_checking']);
            unset($t['is_multi_file']);
            unset($t['is_open']);
            unset($t['is_private']);
            unset($t['priority']);
            unset($t['state_changed']);
            unset($t['tied_to_file']);
            // set some string values for the HTML templates
            $t['date_added_str'] = $t['date_added'] ? date($date_added_format, $t['date_added']) : '';
            $t['eta_str'] = format_duration($t['eta']);
            $t['percent_complete_str'] = round($t['percent_complete'], 1) . '%';
            $t['percent_complete_width'] = round($t['percent_complete'] / 2);
            $t['tags_str'] = implode('|', $t['tags']);
            $t['bytes_remaining_str'] = format_bytes($t['bytes_remaining'], '&nbsp;', '');
            $t['size_bytes_str'] = format_bytes($t['size_bytes'], '&nbsp;', '');
            $t['down_rate_str'] = format_bytes($t['down_rate'], '&nbsp;', '/s');
            $t['up_rate_str'] = format_bytes($t['up_rate'], '&nbsp;', '/s');
            $t['up_total_str'] = format_bytes($t['up_total'], '&nbsp;', '');
            $t['ratio_str'] = number_format($t['ratio'] / 1000, 2);
        }
        $torrents[$hash] = $t;
    }
    if ($torrents_only) {
        return $torrents;
    }
    if (isset($disk_usage_dir)) {
        $df_output = rtorrent_xmlrpc('execute_capture', array('sh', '-c', "BLOCKSIZE=1 df \"{$disk_usage_dir}\""));
        if ($df_output) {
            $df_output = explode("\n", $df_output);
            $df_output = $df_output[1];
            // Filesystem [1B-blocks Used Available] Use% Mounted on
            if (preg_match('@\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+@', $df_output, $matches)) {
                $disk_total = $matches[1];
                $disk_free = $matches[3];
            }
        }
    }
    if ($disk_total > 0) {
        $disk_percent = $disk_free / $disk_total * 100;
    } else {
        // avoid divide by zero error if getting total space fails
        $disk_percent = 0;
    }
    $data = array('torrents' => $torrents, 'global' => array('torrents_count_visible' => $torrents_count_visible, 'torrents_count_all' => $torrents_count_all, 'torrents_count_superhidden' => $torrents_count_superhidden, 'total_down_rate' => format_bytes($total_down_rate, '0 B/s', '/s'), 'total_up_rate' => format_bytes($total_up_rate, '0 B/s', '/s'), 'total_down_limit' => format_bytes(rtorrent_xmlrpc('get_download_rate'), 'unlim', '/s'), 'total_up_limit' => format_bytes(rtorrent_xmlrpc('get_upload_rate'), 'unlim', '/s'), 'show_disk_free' => isset($disk_usage_dir) && $disk_total, 'disk_free' => format_bytes($disk_free), 'disk_total' => format_bytes($disk_total), 'disk_percent' => round($disk_percent, 2)));
    return $data;
}
Пример #12
0
 public function index($event_name = "")
 {
     $rid = intval($event_name);
     if (empty($rid)) {
         @header('Location:/' . $this->activity_name . '/home');
     }
     $this->load->model('live_programs_model', 'live_programs_m');
     $this->load->model('api/member_model', 'member_m');
     $this->load->model('space/comment_model', 'comment_m');
     $program = $this->live_programs_m->get_program($rid);
     //房间不存在
     if (empty($program)) {
         @header('Location:/' . $this->activity_name . '/home');
     }
     $this->data['uid'] = $program['uid'];
     $this->data['user'] = $this->member_m->get_user(array('uid', 'username'), array('uid' => $program['uid']));
     //获取赛票工具列表
     //$this->data['tools_list'] = $this->tools_list();
     //相关节目推荐
     $archive_list = $this->live_programs_m->recommended();
     foreach ($archive_list as $k => $v) {
         $v['pic_name'] = "/public/data/images/video/cut/187x140_" . $v['pic_name'];
         $v['record_time'] = friendly_date($v['record_time']) . "之前";
         $v['duration'] = format_duration($v['duration']);
         $v['views'] = $v['views'] . "人围观";
         $archive_list[$k] = $v;
     }
     $this->data['recommend_list'] = $archive_list;
     echo "<!--";
     var_export($archive_list);
     echo "-->";
     //由谁推荐过
     $this->data['program'] = $program;
     $stream_name = $program['stream'];
     //问题和建议
     $comments = array();
     if ($program['is_live'] == 0) {
         $this->data['program'] = $program;
         $stream_url = "/public/data/video/VIDEO0002.mp4";
         $this->data['stream_url'] = $stream_url;
         $comments = $this->comment_m->get_items(0);
         $this->data['comments'] = $comments;
         $data = $this->init_pre_data($program);
         //$data = array();
         $this->data['data'] = base64_encode(json_encode($data));
         //尚未开始
         $this->data['seo']['title'] = $program['name'] . ":直播尚未开始-,酷Live";
         $this->data['seo']['description'] = $program['desc'];
         $this->data['seo']['keywords'] = $program['tags'] . ",直播";
         $this->load->view('spree/live_pre.tpl', $this->data);
     } else {
         if ($program['is_live'] == 1) {
             //正在进行中
             $this->data['live_url'] = array('rtmp' => 'rtmp://' . $this->live_config['pub_server'] . ':' . $this->live_config['pub_port'] . '/' . $this->live_config['pub_stream'] . '/' . $stream_name, 'hls' => 'http://' . $this->live_config['hls_server'] . ':' . $this->live_config['hls_port'] . '/' . $this->live_config['hls_stream'] . '/' . $stream_name . '_hls.m3u8');
             $comments = $this->comment_m->get_items(1);
             $this->data['comments'] = $comments;
             $data = $this->init_ing_data($program, $rtmp = $this->data['live_url']['rtmp'], $hls = $this->data['live_url']['hls']);
             //$data = array();
             $this->data['data'] = base64_encode(json_encode($data));
             $this->data['seo']['title'] = "直播Live" - $program['name'] . "-酷Live";
             $this->data['seo']['description'] = $program['desc'];
             $this->data['seo']['keywords'] = $program['tags'] . ",直播,酷Live";
             $this->load->view('spree/live_ing.tpl', $this->data);
         } else {
             //直播存档
             $this->load->model('video_model', 'video_m');
             $video = $this->video_m->get_archive_video($rid);
             $video['pic_name'] = "/public/data/images/video/cut/187x140_" . $video['pic_name'];
             $video['flv_url'] = "http://coollive.labake.cn/public/data/video/live/" . $program['stream'] . ".flv";
             $comments = $this->comment_m->get_items(2);
             $this->data['comments'] = $comments;
             $this->data['program']['video'] = $video;
             $data = $this->init_archive_data($program);
             //$data = array();
             $this->data['data'] = base64_encode(json_encode($data));
             $this->data['seo']['title'] = $program['name'] . "-酷Live";
             $this->data['seo']['description'] = $program['desc'];
             $this->data['seo']['keywords'] = $program['tags'] . ",直播,回放,酷Live";
             $this->load->view('spree/live_archive.tpl', $this->data);
         }
     }
 }
Пример #13
0
    function test_format_duration() {
        /* ISSUES:
         * expects a space after hour/s but not minute/s
         * minutes > 59 are not being converted to hour values
         * negative values are not interpreted correctly
         */

        // Test - for positive single hour value.
        $this->assertEquals(format_duration('1:00'), '1 hour ');
        $this->assertEquals(format_duration('1.00'), '1 hour ');

        // Test - for positive multiple hours value.
        $this->assertEquals(format_duration('3:00'), '3 hour(s) ');
        $this->assertEquals(format_duration('3.00'), '3 hour(s) ');

        // Test - for positive single minute value.
        $this->assertEquals(format_duration('0:01'), '1 minute');
        $this->assertEquals(format_duration('0.1'), '6 minute(s)');

        // Test - for positive minutes value.
        $this->assertEquals(format_duration('0:30'), '30 minute(s)');
        $this->assertEquals(format_duration('0.50'), '30 minute(s)');

        // Test - for out of range minutes value.
        $this->assertEquals(format_duration('9:70'), '');

        // Test - for zero value.
        $this->assertEquals(format_duration('0:00'), '');
        $this->assertEquals(format_duration('0.00'), '');

        // Test - for negative hour value.
        $this->assertEquals(format_duration('-1:00'), '');
        $this->assertEquals(format_duration('-1.00'), '');

        // Test - for negative multiple hours value.
        $this->assertEquals(format_duration('-7:00'), '');
        $this->assertEquals(format_duration('-7.00'), '');

        // Test - for negative single minute value.
        $this->assertEquals(format_duration('-0:01'), '');
        $this->assertEquals(format_duration('-0.01'), '');

        // Test - for negative multiple minutes value.
        $this->assertEquals(format_duration('-0:33'), '');
        $this->assertEquals(format_duration('-0.33'), '');

        // Test - for negative hours & minutes value.
        $this->assertEquals(format_duration('-5:42'), '');
        $this->assertEquals(format_duration('-5.42'), '');

        // Test - for invalid characters value.
        $this->assertEquals(format_duration('invalid_string'), '');

        $this->resetAfterTest(true);
    }
Пример #14
0
 public function testFormatDuration()
 {
     $this->assertSame('1 day', format_duration('2015-05-15 11:22:22', '2015-05-16 11:22:22'));
     $this->assertSame('2 days', format_duration('2015-05-15 11:22:22', '2015-05-17 11:22:22'));
     $this->assertSame('1 day 1 hour', format_duration('2015-05-15 11:22:22', '2015-05-16 12:22:22'));
     $this->assertSame('1 day 2 hours', format_duration('2015-05-15 11:22:22', '2015-05-16 13:22:22'));
     $this->assertSame('2 days 1 hour', format_duration('2015-05-15 11:22:22', '2015-05-17 12:22:22'));
     $this->assertSame('2 days 2 hours', format_duration('2015-05-15 11:22:22', '2015-05-17 13:22:22'));
     $this->assertSame('1 day 1 hour 1 minute', format_duration('2015-05-15 11:22:22', '2015-05-16 12:23:22'));
     $this->assertSame('1 day 1 hour 2 minutes', format_duration('2015-05-15 11:22:22', '2015-05-16 12:24:22'));
     $this->assertSame('1 day 2 hours 1 minute', format_duration('2015-05-15 11:22:22', '2015-05-16 13:23:22'));
     $this->assertSame('1 day 1 minute', format_duration('2015-05-15 11:22:22', '2015-05-16 11:23:22'));
     $this->assertSame('1 day 2 minutes', format_duration('2015-05-15 11:22:22', '2015-05-16 11:24:22'));
     $this->assertSame('2 days 2 minutes', format_duration('2015-05-15 11:22:22', '2015-05-17 11:24:22'));
     $this->assertSame('1 day 2 hours 1 minute', format_duration('2015-05-15 11:22:22', '2015-05-16 13:23:25'));
     $this->assertSame('1 day', format_duration('2015-05-15 11:22:22', '2015-05-16 11:22:25'));
     $this->assertSame('1 second', format_duration('2015-05-15 11:22:22', '2015-05-15 11:22:23'));
     $this->assertSame('5 seconds', format_duration('2015-05-15 11:22:22', '2015-05-15 11:22:27'));
     $this->assertSame('1 hour', format_duration('2015-05-15 11:22:22', '2015-05-15 12:22:22'));
     $this->assertSame('2 hours', format_duration('2015-05-15 11:22:22', '2015-05-15 13:22:22'));
     $this->assertSame('1 hour 1 minute', format_duration('2015-05-15 11:22:22', '2015-05-15 12:23:22'));
     $this->assertSame('1 hour 1 minute', format_duration('2015-05-15 11:22:22', '2015-05-15 12:23:26'));
     $this->assertSame('2 hours 1 minute', format_duration('2015-05-15 11:22:22', '2015-05-15 13:23:59'));
     $this->assertSame('1 minute', format_duration('2015-05-15 11:22:22', '2015-05-15 11:23:22'));
     $this->assertSame('2 minutes', format_duration('2015-05-15 11:22:22', '2015-05-15 11:24:22'));
     $this->assertSame('2 minutes', format_duration('2015-05-15 11:22:22', '2015-05-15 11:24:46'));
     $this->assertSame('2 minutes 24 seconds', format_duration('2015-05-15 11:22:22', '2015-05-15 11:24:46', true));
     $this->assertSame('1 minute', format_duration('2015-05-15 11:22:22', '2015-05-15 11:23:22', true));
     $this->assertSame('1 second', format_duration('2015-05-15 11:22:22', '2015-05-15 11:22:23', true));
     $this->assertSame('5 seconds', format_duration('2015-05-15 11:22:22', '2015-05-15 11:22:27', true));
     $this->assertSame('1 day 2 hours 1 minute 3 seconds', format_duration('2015-05-15 11:22:22', '2015-05-16 13:23:25', true));
     $this->assertSame('1 day 3 seconds', format_duration('2015-05-15 11:22:22', '2015-05-16 11:22:25', true));
 }
Пример #15
0
 $xtpl->table_add_category("DEP");
 $xtpl->table_add_category("DONE?");
 $xtpl->table_add_category("OK?");
 $rows = 0;
 while ($t = $db->find("transactions", $whereCond, "t_id DESC", $limit)) {
     $rows++;
     $m = $db->findByColumnOnce("members", "m_id", $t["t_m_id"]);
     $s = $db->findByColumnOnce("servers", "server_id", $t["t_server"]);
     if ($_SESSION["is_admin"]) {
         $xtpl->table_td('<a href="?page=transactions&filter=yes&details=1&id=' . $t["t_id"] . '">' . $t["t_id"] . '</a>');
     } else {
         $xtpl->table_td($t["t_id"]);
     }
     $xtpl->table_td(strftime("%Y-%m-%d %H:%M", $t["t_time"]));
     $xtpl->table_td(format_duration($t["t_end"] ? $t["t_end"] - $t["t_time"] : 0), false, true);
     $xtpl->table_td(format_duration($t["t_end"] - $t["t_real_start"]), false, true);
     $xtpl->table_td("{$m["m_id"]} {$m["m_nick"]}");
     $xtpl->table_td($s ? "{$s["server_id"]} {$s["server_name"]}" : '---');
     $xtpl->table_td($t["t_vps"] == 0 ? _("--Every--") : "<a href='?page=adminvps&action=info&veid={$t["t_vps"]}'>{$t["t_vps"]}</a>");
     if ($_SESSION["is_admin"]) {
         $xtpl->table_td('<a href="?page=transactions&filter=yes&details=1&type=' . $t["t_type"] . '">' . $t["t_type"] . '</a>' . ' ' . transaction_label($t["t_type"]));
     } else {
         $xtpl->table_td("{$t["t_type"]}" . ' ' . transaction_label($t["t_type"]));
     }
     $xtpl->table_td('<a href="?page=transactions&filter=yes&details=1&id=' . $t["t_depends_on"] . '">' . $t["t_depends_on"] . '</a>');
     $xtpl->table_td($t["t_done"]);
     $xtpl->table_td($t["t_success"]);
     if ($_SESSION["is_admin"] && !$t["t_success"]) {
         $xtpl->table_td('<a href="?page=transactions&action=redo&id=' . $t["t_id"] . '"><img src="template/icons/vps_restart.png"  title="' . _("Redo transaction") . '"/></a>');
     }
     if ($t["t_done"] == 1 && $t["t_success"] == 1) {
Пример #16
0
<dl>
	<dt>UTF Codepoint</dt>
	<dd><?php 
echo $char;
?>
</dd>
	
	<dt>Number of segments</dt>
	<dd><?php 
echo $segments;
?>
</dd>
	
	<dt>Age</dt>
	<dd><?php 
echo format_duration($age);
?>
</dd>
	
	<dt>Status</dt>
	<dd><?php 
echo $status;
?>
</dd>
	
	<dt>Fitness</dt>
	<dd><?php 
echo $fitness;
?>
</dd>
</dl>