Example #1
0
 /**
  * Checks if we are allowed to turn on the 'default icon' option. You can
  * only have one of these for a given MIME type.
  *
  * @param string $mimetype MIME type
  * @param string $oldextension File extension name (before any change)
  */
 public static function is_defaulticon_allowed($mimetype, $oldextension = '')
 {
     $mimeinfo = get_mimetypes_array();
     if ($oldextension !== '') {
         unset($mimeinfo[$oldextension]);
     }
     foreach ($mimeinfo as $extension => $values) {
         if ($values['type'] !== $mimetype) {
             continue;
         }
         if (!empty($values['defaulticon'])) {
             return false;
         }
     }
     return true;
 }
Example #2
0
/**
 * Adds RSS Media Enclosures for "podcasting" by including attachments that
 * are specified in the item->attachments field.
 *
 * @param stdClass $item representing an RSS item
 * @return string RSS enclosure tags
 */
function rss_add_enclosures($item)
{
    global $CFG;
    $returnstring = '';
    // list of media file extensions and their respective mime types
    include_once $CFG->libdir . '/filelib.php';
    $mediafiletypes = get_mimetypes_array();
    // take into account attachments (e.g. from forum) - with these, we are able to know the file size
    if (isset($item->attachments) && is_array($item->attachments)) {
        foreach ($item->attachments as $attachment) {
            $extension = strtolower(substr($attachment->url, strrpos($attachment->url, '.') + 1));
            if (isset($mediafiletypes[$extension]['type'])) {
                $type = $mediafiletypes[$extension]['type'];
            } else {
                $type = 'document/unknown';
            }
            $returnstring .= "\n<enclosure url=\"{$attachment->url}\" length=\"{$attachment->length}\" type=\"{$type}\" />\n";
        }
    }
    return $returnstring;
}
Example #3
0
 /**
  * Tests for get_mimetype_for_sending function.
  */
 public function test_get_mimetype_for_sending()
 {
     // Without argument.
     $this->assertEquals('application/octet-stream', get_mimetype_for_sending());
     // Argument is null.
     $this->assertEquals('application/octet-stream', get_mimetype_for_sending(null));
     // Filename having no extension.
     $this->assertEquals('application/octet-stream', get_mimetype_for_sending('filenamewithoutextension'));
     // Test using the extensions listed from the get_mimetypes_array function.
     $mimetypes = get_mimetypes_array();
     foreach ($mimetypes as $ext => $info) {
         if ($ext === 'xxx') {
             $this->assertEquals('application/octet-stream', get_mimetype_for_sending('SampleFile.' . $ext));
         } else {
             $this->assertEquals($info['type'], get_mimetype_for_sending('SampleFile.' . $ext));
         }
     }
 }
/** determine the mimetype of a file
 *
 * This routine tries to discover the mimetype of a file.
 * First we try to determine the mimetype via the fileinfo extension.
 * If that doesn't work, we try the deprecated mime_content_type() function.
 * If that doesn't work, we try to shell out to file(1).
 * If that doesn't work, we resort to "guessing" the mimetype based
 * on the extension of the file or else we return the generic
 * 'application/octet-stream'.
 *
 * Note that in step 3 we shell out and try to execute the file(1) command.
 * The results are checked against a pattern to assert that we are
 * really dealing with a mime type. The pattern is described in RFC2616
 * (see sections 3.7 and 2.2):
 *
 *<pre>
 *      media-type     = type "/" subtype *( ";" parameter )
 *      type           = token
 *      subtype        = token
 *      token          = 1*&lt;any CHAR except CTLs or separators&gt;
 *      separators     = "(" | ")" | "&lt;" | "&gt;" | "@"
 *                     | "," | ";" | ":" | "\" | &lt;"&gt;
 *                     | "/" | "[" | "]" | "?" | "="
 *                     | "{" | "}" | SP | HT
 *      CHAR           = &lt;any US-ASCII character (octets 0 - 127)&gt;
 *      CTL            = &lt;any US-ASCII control character
 *                       (octets 0 - 31) and DEL (127)&gt;
 *      SP             = &lt;US-ASCII SP, space (32)&gt;
 *      HT             = &lt;US-ASCII HT, horizontal-tab (9)&gt;
 *      &lt;"&gt;            = &lt;US-ASCII double-quote mark (34)&gt;
 *</pre>
 *
 * This description means we should look for two tokens containing
 * letters a-z or A-Z, digits 0-9 and these special characters:
 * ! # $ % & ' * + - . ^ _ ` | or ~. That's it.
 *
 * Note that file(1) may return a mime type with additional parameters.
 * e.g. 'text/plain; charset=US-ASCII'. This fits the pattern, because
 * it starts with a token, a slash and another token.
 *
 * The optional parameter $name is used to determine the mimetype based
 * on the extension (as a last resort), even when the current name of the
 * file is meaningless, e.g. when uploading a file, the name of the file
 * (from $_FILES['file0']['tmp_name']) is something like '/tmp/php4r5dwfw',
 * even though $_FILES['file0']['name'] might read 'S6301234.JPG'.
 * If $name is not specified (i.e. is empty), we construct it from $path.
 *
 * @param string $path fully qualified path to the file to test
 * @param string $name name of the file, possibly different from $path
 * @return string mimetype of the file $path
 * @todo there is room for improvement here: 
 *       the code in step 1 and step 2 is largely untested
 */
function get_mimetype($path, $name = '')
{
    // 0 -- quick check for file of type 'image/*' (suppress annoying warning message from getimagesize())
    if (($imagesize = @getimagesize($path)) !== FALSE && is_array($imagesize) && isset($imagesize['mime'])) {
        $mimetype = $imagesize['mime'];
        // logger(sprintf('%d: %s(): path=%s name=%s mime=%s',0,__FUNCTION__,$path,$name,$mimetype),WLOG_DEBUG);
        return $mimetype;
    }
    // 1 -- try the finfo-route if it is available
    if (function_exists('finfo_open') && function_exists('finfo_file') && function_exists('finfo_close') && defined(FILEINFO_MIME)) {
        $finfo = finfo_open(FILEINFO_MIME);
        if ($finfo !== FALSE) {
            $mimetype = finfo_file($finfo, $path);
            $finfo_close($finfo);
            if ($mimetype !== FALSE) {
                // logger(sprintf('%d: %s(): path=%s name=%s mime=%s',1,__FUNCTION__,$path,$name,$mimetype),WLOG_DEBUG);
                return $mimetype;
            }
        }
    }
    // 2 -- now try the deprecated mime_content_type method
    if (function_exists('mime_content_type')) {
        $mimetype = mime_content_type($path);
        // logger(sprintf('%d: %s(): path=%s name=%s mime=%s',2,__FUNCTION__,$path,$name,$mimetype),WLOG_DEBUG);
        return $mimetype;
    }
    // 3 -- now try to shell out and use the file command
    $command = sprintf('file -b -i %s', escapeshellarg($path));
    // -b = brief output, -i = output mime type strings
    $dummy = array();
    $retval = 0;
    $mimetype = exec($command, $dummy, $retval);
    if ($retval == 0) {
        // now assert that the result looks like a mimetype and not an error message
        if (get_mediatype($mimetype) !== FALSE) {
            // logger(sprintf('%d: %s(): path=%s name=%s mime=%s',3,__FUNCTION__,$path,$name,$mimetype),WLOG_DEBUG);
            return $mimetype;
        }
    }
    // 4 -- take a wild guess; boldly assume that the file extension carries any meaning whatsoever
    $ext = strtolower(pathinfo(empty($name) ? $path : $name, PATHINFO_EXTENSION));
    $mimetypes = get_mimetypes_array();
    $mimetype = isset($mimetypes[$ext]) ? $mimetypes[$ext] : 'application/octet-stream';
    // logger(sprintf('%d: %s(): path=%s name=%s mime=%s',4,__FUNCTION__,$path,$name,$mimetype),WLOG_DEBUG);
    return $mimetype;
}
Example #5
0
 /**
  * Deletes a file type from the config list (or, for a standard one, marks it
  * as deleted).
  *
  * @param string $extension File extension without dot, e.g. 'doc'
  * @throws coding_exception If the extension does not exist, or otherwise invalid
  */
 public static function delete_type($extension)
 {
     // Extension must exist.
     $mimetypes = get_mimetypes_array();
     if (!array_key_exists($extension, $mimetypes)) {
         throw new coding_exception('Extension ' . $extension . ' not found');
     }
     // Get existing custom filetype list.
     $customs = self::get_custom_types();
     // Remove any entries for this extension.
     foreach ($customs as $key => $custom) {
         if ($custom->extension === $extension && empty($custom->deleted)) {
             unset($customs[$key]);
         }
     }
     // If it was a standard entry (doesn't have 'custom' set) then add a
     // deleted marker.
     if (empty($mimetypes[$extension]['custom'])) {
         $customs[] = (object) array('extension' => $extension, 'deleted' => true);
     }
     // Save and reset cache.
     self::set_custom_types($customs);
 }
Example #6
0
/**
* Adds RSS Media Enclosures for "podcasting" by examining links to media files,
* and attachments which are media files. Please note that the RSS that is
* produced cannot be strictly valid for the linked files, since we do not know
* the files' sizes and cannot include them in the "length" attribute. At
* present, the validity (and therefore the podcast working in most software)
* can only be ensured for attachments, and not for links.
* Note also that iTunes does some things very badly - one thing it does is
* refuse to download ANY of your files if you're using "file.php?file=blah"
* and can't use the more elegant "file.php/blah" slasharguments setting. It
* stops after ".php" and assumes the files are not media files, despite what
* is specified in the "type" attribute. Dodgy coding all round!
*
* @param    $item     object representing an RSS item
* @return   string    RSS enclosure tags
* @author   Hannes Gassert <*****@*****.**>
* @author   Dan Stowell
*/
function rss_add_enclosures($item)
{
    global $CFG;
    $returnstring = '';
    $rss_text = $item->description;
    // list of media file extensions and their respective mime types
    include_once $CFG->libdir . '/filelib.php';
    $mediafiletypes = get_mimetypes_array();
    // regular expression (hopefully) matching all links to media files
    $medialinkpattern = '@href\\s*=\\s*(\'|")(\\S+(' . implode('|', array_keys($mediafiletypes)) . '))\\1@Usie';
    // take into account attachments (e.g. from forum) - with these, we are able to know the file size
    if (isset($item->attachments) && is_array($item->attachments)) {
        foreach ($item->attachments as $attachment) {
            $extension = strtolower(substr($attachment->url, strrpos($attachment->url, '.') + 1));
            if (isset($mediafiletypes[$extension]['type'])) {
                $type = $mediafiletypes[$extension]['type'];
            } else {
                $type = 'document/unknown';
            }
            $returnstring .= "\n<enclosure url=\"{$attachment->url}\" length=\"{$attachment->length}\" type=\"{$type}\" />\n";
        }
    }
    if (!preg_match_all($medialinkpattern, $rss_text, $matches)) {
        return $returnstring;
    }
    // loop over matches of regular expression
    for ($i = 0; $i < count($matches[2]); $i++) {
        $url = htmlspecialchars($matches[2][$i]);
        $extension = strtolower($matches[3][$i]);
        if (isset($mediafiletypes[$extension]['type'])) {
            $type = $mediafiletypes[$extension]['type'];
        } else {
            $type = 'document/unknown';
        }
        // the rss_*_tag functions can't deal with methods, unfortunately
        $returnstring .= "\n<enclosure url='{$url}' type='{$type}' />\n";
    }
    return $returnstring;
}
Example #7
0
/**
 * Get information about a filetype based on the icon file.
 * @param string $element Desired information (usually 'icon')
 * @param string $icon Icon file path.
 * @return string Requested piece of information from array
 */
function mimeinfo_from_icon($element, $icon)
{
    static $mimeinfo;
    $mimeinfo = get_mimetypes_array();
    if (preg_match("/\\/(.*)/", $icon, $matches)) {
        $icon = $matches[1];
    }
    $info = $mimeinfo['xxx'][$element];
    // Default
    foreach ($mimeinfo as $values) {
        if ($values['icon'] == $icon) {
            if (isset($values[$element])) {
                $info = $values[$element];
            }
            //No break, for example for 'excel.gif' we don't want 'csv'!
        }
    }
    return $info;
}
Example #8
0
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * Display the custom file type settings page.
 *
 * @package tool_filetypes
 * @copyright 2014 The Open University
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require __DIR__ . '/../../../config.php';
require_once $CFG->libdir . '/adminlib.php';
admin_externalpage_setup('tool_filetypes');
// Page settings.
$title = get_string('pluginname', 'tool_filetypes');
$context = context_system::instance();
$PAGE->set_url(new \moodle_url('/admin/tool/filetypes/index.php'));
$PAGE->set_context($context);
$PAGE->set_pagelayout('admin');
$PAGE->set_title($SITE->fullname . ': ' . $title);
$renderer = $PAGE->get_renderer('tool_filetypes');
// Is it restricted because set in config.php?
$restricted = array_key_exists('customfiletypes', $CFG->config_php_settings);
// Display the page.
echo $renderer->header();
echo $renderer->edit_table(get_mimetypes_array(), core_filetypes::get_deleted_types(), $restricted);
echo $renderer->footer();
Example #9
0
 /**
  * Tests the get_mimetypes_array function.
  */
 public function test_get_mimetypes_array()
 {
     $mimeinfo = get_mimetypes_array();
     // Test example MIME type (doc).
     $this->assertEquals('application/msword', $mimeinfo['doc']['type']);
     $this->assertEquals('document', $mimeinfo['doc']['icon']);
     $this->assertEquals(array('document'), $mimeinfo['doc']['groups']);
     $this->assertFalse(isset($mimeinfo['doc']['string']));
     $this->assertFalse(isset($mimeinfo['doc']['defaulticon']));
     $this->assertFalse(isset($mimeinfo['doc']['customdescription']));
     // Check the less common fields using other examples.
     $this->assertEquals('image', $mimeinfo['png']['string']);
     $this->assertEquals(true, $mimeinfo['txt']['defaulticon']);
 }
 /**
  * Get the media mimetype
  *
  * Uses a built-in moodle mimetype helper
  * @return string
  */
 public function get_mimetype()
 {
     if (function_exists('get_mimetypes_array')) {
         $mimetypes =& get_mimetypes_array();
         $container = $this->get_primary_file_container();
         if (isset($mimetypes[$container])) {
             return $mimetypes[$container]['type'];
         }
     }
     return 'video/mp4';
 }
 /** try to make sure that the extension of file $name makes sense or matches the actual filetype
  *
  * this checks or changes the $name of the file in line with the
  * mimetype of the actual file (as established by get_mimetype()).
  *
  * The reason to do this is to make it harder to 'smuggle in' files
  * with deceptive filenames/extensions. Quite often the extension is
  * used to determine the type of the file, even by browsers that should
  * know better. By uploading a malicious .PDF using an innocuous extension
  * like .TXT, a browser may be tricked into rendering that .PDF inline.
  * By changing the extension from .TXT to .PDF we can mitigate that risk,
  * at least a little bit. (People somehow trust an extension even though
  * they should know better and file(1) says so...)
  *
  * Strategy is as follows. If the mimetype based on the $name matches the
  * actual mimetype, we can simply allow the name provided.
  *
  * If there is a difference, we try to find an extension that maps to the
  * same mimetype as that of the actual file. IOW: we put more trust in the
  * mimetype of the actual file than we do in the mimetype suggested by the
  * extension.
  *
  * @param string $path full path to the actual file (from $_FILES[$i]['tmp_name'])
  * @param string $name the requested name of the file to examine (from $_FILES[$i]['name'])
  * @param string $type the suggested filetype of the file (from $_FILES[$i]['type'])
  * @return string the sanitised name and extension based on the file type
  */
 function sanitise_filetype($path, $name, $type)
 {
     // 0 -- initialise: isolate the $filename and $ext
     if (strpos($name, '.') === FALSE) {
         // not a single dot -> filename without extension
         $filename = $name;
         $extension = '';
     } else {
         $components = explode('.', $name);
         $extension = array_pop($components);
         $filename = implode('.', $components);
         unset($components);
     }
     // 1 -- does actual file mimetype agree with the file extension?
     $type_path = get_mediatype(get_mimetype($path, $name));
     $ext = utf8_strtolower($extension);
     $mimetypes = get_mimetypes_array();
     $type_name = isset($mimetypes[$ext]) ? get_mediatype($mimetypes[$ext]) : 'application/octet-stream';
     if (strcmp($type_path, $type_name) == 0) {
         return $name;
     }
     // 2 -- No, we change the extension based on the actual mimetype of the file
     // 2A - lookup the first extension matching type, or use '' (which implies application/octet-stream)
     $new_extension = array_search($type_path, $mimetypes);
     if ($new_extension === FALSE || is_null($new_extension)) {
         $new_extension = '';
         logger(sprintf('%s.%s(): mimetype \'%s\' not recognised; using \'%s\' instead', __CLASS__, __FUNCTION__, $type_path, $mimetypes[$new_extension]));
     }
     // 2B - avoid tricks with double extensions (eg. upload of "malware.exe.txt")
     if ($new_extension == '') {
         if ($type_name == 'application/octet-stream') {
             // preserve original extension and case because the original
             // extension will yield 'application/octet-stream' when served via file.php,
             // i.e. there is no need to lose the extension if it yields the same mimetype anyway
             $new_name = $name;
         } elseif (strpos($filename, '.') === FALSE) {
             // filename has no dot =>
             // no part of existing filename can be mistaken for an extension =>
             // don't add anything at all
             $new_name = $filename;
         } else {
             // bare $filename already contains an extension =>
             // add '.bin' to force 'application/octet-stream'
             $new_name = $filename . '.bin';
         }
     } else {
         $new_name = $filename . '.' . $new_extension;
     }
     logger(sprintf('%s.%s(): namechange %s -> %s (%s)', __CLASS__, __FUNCTION__, $name, $new_name, $type_path), WLOG_DEBUG);
     return $new_name;
 }
Example #12
0
function generate_roster_file()
{
    global $cm, $iru, $COURSE, $USER;
    // Only teachers/admins can view iclicker that is not their own.
    if (!has_capability('mod/iclickerregistration:viewenrolled', context_module::instance($cm->id))) {
        echo json_encode(array("status" => "access denied"));
        return;
    }
    // RESOURCE LOCK.
    // For more info: https://docs.moodle.org/dev/Lock_API
    // Get an instance of the currently configured lock_factory.
    $resource = 'user: '******'mod_iclickerregistration');
    // ACQUIRE LOCK.
    $lock = $lockfactory->get_lock("{$resource}", 5);
    $allusers = $iru->get_all_users_left_join_iclickers(array("courseid" => $COURSE->id));
    $responsetext = "";
    foreach ($allusers as $iclickeruser) {
        $responsetext .= "{$iclickeruser->lastname}, {$iclickeruser->firstname}, {$iclickeruser->idnumber}\r\n";
    }
    $fs = get_file_storage();
    $fs->delete_area_files($cm->id, 'mod_iclickerregistration');
    $dummyfilename = 'roster.txt';
    $fs = get_file_storage();
    $filerecord = array('contextid' => $cm->id, 'component' => 'mod_iclickerregistration', 'filearea' => 'intro', 'itemid' => 0, 'filepath' => '/', 'filename' => $dummyfilename, 'timecreated' => time(), 'timemodified' => time());
    $file = $fs->create_file_from_string($filerecord, $responsetext);
    // RELEASE LOCK.
    $lock->release();
    if (!$file) {
        return false;
        // File don't exist.
    }
    // Force it to be csv. Otherwise, moodle throws an error for some reason.
    send_file($file, $dummyfilename, 0, true, false, false, get_mimetypes_array()['csv']['type']);
}
Example #13
0
/**
 * Get information about a filetype based on the icon file.
 * @param string $element Desired information (usually 'icon')
 * @param string $icon Icon file path.
 * @param boolean $all return all matching entries (defaults to false - last match)
 * @return string Requested piece of information from array
 */
function mimeinfo_from_icon($element, $icon, $all = false)
{
    $mimeinfo = get_mimetypes_array();
    if (preg_match("/\\/(.*)/", $icon, $matches)) {
        $icon = $matches[1];
    }
    $info = array($mimeinfo['xxx'][$element]);
    // Default
    foreach ($mimeinfo as $values) {
        if ($values['icon'] == $icon) {
            if (isset($values[$element])) {
                $info[] = $values[$element];
            }
            //No break, for example for 'excel.gif' we don't want 'csv'!
        }
    }
    if ($all) {
        return $info;
    }
    return array_pop($info);
    // Return last match (mimicking behaviour/comment inside foreach loop)
}
Example #14
0
 public function test_revert_type_to_default()
 {
     $this->resetAfterTest();
     // Delete and then revert.
     core_filetypes::delete_type('doc');
     $this->assertArrayNotHasKey('doc', get_mimetypes_array());
     core_filetypes::revert_type_to_default('doc');
     $this->assertArrayHasKey('doc', get_mimetypes_array());
     // Update and then revert.
     core_filetypes::update_type('asm', 'asm', 'text/plain', 'sourcecode', array(), '', 'An asm file');
     $types = get_mimetypes_array();
     $this->assertEquals('An asm file', $types['asm']['customdescription']);
     core_filetypes::revert_type_to_default('asm');
     $types = get_mimetypes_array();
     $this->assertArrayNotHasKey('customdescription', $types['asm']);
     // Test reverting a non-default type causes exception.
     try {
         core_filetypes::revert_type_to_default('frog');
         $this->fail();
     } catch (coding_exception $e) {
         $this->assertContains('not a default type', $e->getMessage());
         $this->assertContains('frog', $e->getMessage());
     }
 }
Example #15
0
 * Display the file type updating page.
 *
 * @package tool_filetypes
 * @copyright 2014 The Open University
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require __DIR__ . '/../../../config.php';
require_once $CFG->libdir . '/adminlib.php';
require_once 'edit_form.php';
admin_externalpage_setup('tool_filetypes');
$oldextension = optional_param('oldextension', '', PARAM_ALPHANUMEXT);
$mform = new tool_filetypes_form('edit.php', array('oldextension' => $oldextension));
$title = get_string('addfiletypes', 'tool_filetypes');
if ($oldextension) {
    // This is editing an existing filetype, load data to the form.
    $mimetypes = get_mimetypes_array();
    if (!array_key_exists($oldextension, $mimetypes)) {
        throw new moodle_exception('error_notfound', 'tool_filetypes');
    }
    $typeinfo = $mimetypes[$oldextension];
    $formdata = array('extension' => $oldextension, 'mimetype' => $typeinfo['type'], 'icon' => $typeinfo['icon'], 'oldextension' => $oldextension, 'description' => '', 'groups' => '', 'corestring' => '', 'defaulticon' => 0);
    if (!empty($typeinfo['customdescription'])) {
        $formdata['description'] = $typeinfo['customdescription'];
    }
    if (!empty($typeinfo['groups'])) {
        $formdata['groups'] = implode(', ', $typeinfo['groups']);
    }
    if (!empty($typeinfo['string'])) {
        $formdata['corestring'] = $typeinfo['string'];
    }
    if (!empty($typeinfo['defaulticon'])) {
Example #16
0
/**
 * Get information about a filetype based on the icon file.
 *
 * @param string $element Desired information (usually 'icon')
 * @param string $icon Icon file name without extension
 * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
 * @return string Requested piece of information from array
 */
function mimeinfo_from_icon($element, $icon, $all = false)
{
    $mimeinfo = get_mimetypes_array();
    if (preg_match("/\\/(.*)/", $icon, $matches)) {
        $icon = $matches[1];
    }
    // Try to get the extension
    $extension = '';
    if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon) - 1) {
        $extension = substr($icon, $cutat + 1);
    }
    $info = array($mimeinfo['xxx'][$element]);
    // Default
    foreach ($mimeinfo as $key => $values) {
        if ($values['icon'] == $icon) {
            if (isset($values[$element])) {
                $info[$key] = $values[$element];
            }
            //No break, for example for 'excel' we don't want 'csv'!
        }
    }
    if ($all) {
        if (count($info) > 1) {
            array_shift($info);
            // take off document/unknown if we have better options
        }
        return array_values($info);
        // Keep keys out when requesting all
    }
    // Requested only one, try to get the best by extension coincidence, else return the last
    if ($extension && isset($info[$extension])) {
        return $info[$extension];
    }
    return array_pop($info);
    // Return last match (mimicking behaviour/comment inside foreach loop)
}
Example #17
0
/**
 * Returns array of elements of type $element in type group(s)
 *
 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
 * @param string|array $groups one group or array of groups/extensions/mimetypes
 * @return array
 */
function file_get_typegroup($element, $groups)
{
    static $cached = array();
    if (!is_array($groups)) {
        $groups = array($groups);
    }
    if (!array_key_exists($element, $cached)) {
        $cached[$element] = array();
    }
    $result = array();
    foreach ($groups as $group) {
        if (!array_key_exists($group, $cached[$element])) {
            // retrieive and cache all elements of type $element for group $group
            $mimeinfo =& get_mimetypes_array();
            $cached[$element][$group] = array();
            foreach ($mimeinfo as $extension => $value) {
                $value['extension'] = '.' . $extension;
                if (empty($value[$element])) {
                    continue;
                }
                if (($group === '.' . $extension || $group === $value['type'] || !empty($value['groups']) && in_array($group, $value['groups'])) && !in_array($value[$element], $cached[$element][$group])) {
                    $cached[$element][$group][] = $value[$element];
                }
            }
        }
        $result = array_merge($result, $cached[$element][$group]);
    }
    return array_values(array_unique($result));
}
 function setup_elements(&$mform)
 {
     global $CFG, $COURSE;
     // Get extra settings
     if ($update = optional_param('update', 0, PARAM_INT)) {
         if (!($cm = get_record("course_modules", "id", $update))) {
             error("This course module doesn't exist");
         }
         $assignment_extra = get_record('assignment_peerreview', 'assignment', $cm->instance);
         if (record_exists('assignment_submissions', 'assignment', $cm->instance)) {
             $mform->addElement('html', '<div style="color:#ff6600;background:#ffff00;margin:5px 20px;padding:5px;text-align:center;font-weight:bold;">' . get_string('settingschangewarning', 'assignment_peerreview') . '</div>');
         }
     }
     // Submission format
     $submissionFormats = array();
     $submissionFormats[self::SUBMIT_DOCUMENT] = get_string('submissionformatdocument', 'assignment_peerreview');
     $submissionFormats[self::ONLINE_TEXT] = get_string('submissionformatonlinetext', 'assignment_peerreview');
     $mform->addElement('select', 'var3', get_string('submissionformat', 'assignment_peerreview'), $submissionFormats);
     $mform->setDefault('var3', self::SUBMIT_DOCUMENT);
     // Filesize restriction
     $choices = get_max_upload_sizes($CFG->maxbytes, $COURSE->maxbytes);
     $choices[0] = get_string('courseuploadlimit') . ' (' . display_size($COURSE->maxbytes) . ')';
     $mform->addElement('select', 'maxbytes', get_string('maximumsize', 'assignment_peerreview'), $choices);
     $mform->setDefault('maxbytes', $CFG->assignment_maxbytes);
     $mform->disabledIf('maxbytes', 'var3', 'eq', self::ONLINE_TEXT);
     // Get the list of file extensions and mime types
     $fileExtensions = array();
     require_once "{$CFG->dirroot}/lib/filelib.php";
     // for file types
     $mimeTypes = get_mimetypes_array();
     $longestExtension = max(array_map('strlen', array_keys($mimeTypes)));
     foreach ($mimeTypes as $extension => $mimeTypeAndIcon) {
         if ($extension != 'xxx') {
             $padding = '';
             for ($i = 0; $i < $longestExtension - strlen($extension); $i++) {
                 $padding .= '&nbsp;';
             }
             $fileExtensions[$extension] = $extension . $padding . ' (' . $mimeTypeAndIcon['type'] . ')';
         }
     }
     ksort($fileExtensions, SORT_STRING);
     // File type restrinction
     $attributes = array('style' => 'font-family:monospace;width:99%;');
     $mform->addElement('select', 'fileextension', get_string('fileextension', 'assignment_peerreview'), $fileExtensions, $attributes);
     $mform->setType('fileextension', PARAM_TEXT);
     $mform->setDefault('fileextension', isset($assignment_extra) ? $assignment_extra->fileextension : 'doc');
     $mform->disabledIf('fileextension', 'var3', 'eq', self::ONLINE_TEXT);
     // Value of each review
     $options = array();
     for ($i = 0; $i <= 50; $i++) {
         $options[$i] = "{$i}";
     }
     $mform->addElement('select', 'var1', get_string('valueofreview', 'assignment_peerreview'), $options);
     $mform->setDefault('var1', '10');
     $mform->setHelpButton('var1', array('valueofreview', get_string('valueofreview', 'assignment_peerreview'), 'assignment/type/peerreview/'));
     // Practice Review
     // $mform->addElement('selectyesno', 'var2', get_string('practicereview', 'assignment_peerreview'));
     // $mform->setDefault('var2', 'no');
     // $mform->setAdvanced('var2');
 }