本文整理汇总了PHP中file_mime_type函数的典型用法代码示例。如果您正苦于以下问题:PHP file_mime_type函数的具体用法?PHP file_mime_type怎么用?PHP file_mime_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了file_mime_type函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: qrdecode
function qrdecode($file)
{
$url = 'http://zxing.org/w/decode';
$args = array('full' => 'true');
$files = array('f' => array('name' => basename($file), 'tmp_name' => $file, 'type' => file_mime_type($file)));
$response = sendpost($url, $args, $files, false);
// DON'T encode data in base64
if (!$response or $response[0] != 200) {
return false;
}
if (!preg_match('#<tr><td>Parsed Result</td><td><pre.*>(.*)</pre></td></tr>#', $response[2], $r)) {
// extract data - adapt when response format changes
return false;
}
return strip_tags($r[1]);
}
示例2: download
function download($lang, $arglist = false)
{
$node_id = $download_name = false;
if (is_array($arglist)) {
if (isset($arglist[0])) {
$node_id = $arglist[0];
}
if (isset($arglist[1])) {
$download_name = $arglist[1];
}
}
if (!$node_id) {
return run('error/badrequest', $lang);
}
if (!$download_name) {
return run('error/badrequest', $lang);
}
$sqllang = db_sql_arg($lang, false);
$sqlname = db_sql_arg($download_name, true);
$tabnodecontent = db_prefix_table('node_content');
$tabcontentdownload = db_prefix_table('content_download');
$sql = "SELECT cd.path FROM {$tabnodecontent} nc JOIN {$tabcontentdownload} cd ON nc.content_type='download' AND cd.content_id=nc.content_id AND cd.locale={$sqllang} WHERE nc.node_id={$node_id} AND cd.name={$sqlname}";
$r = db_query($sql);
if (!$r) {
return run('error/notfound', $lang);
}
$path = $r[0]['path'];
$filepath = ROOT_DIR . DIRECTORY_SEPARATOR . $path;
if (!file_exists($filepath)) {
return run('error/internalerror', $lang);
}
$filename = $download_name;
$filesize = filesize($filepath);
$filetype = file_mime_type($filepath);
if (!$filetype) {
$filetype = 'application/octet-stream';
}
header('HTTP/1.1 200 OK');
// make sure status code is OK in case URL pointed to a file not found like an image
header('Content-Description: File Transfer');
header("Content-Type: {$filetype}");
header("Content-Disposition: attachment; filename={$filename}");
header("Content-Length: {$filesize}");
readfile($filepath);
return false;
}
示例3: import_next_user
function import_next_user($filename, $username, $authinstance)
{
global $ADDEDUSERS, $FAILEDUSERS;
log_debug('adding user ' . $username . ' from ' . $filename);
$authobj = get_record('auth_instance', 'id', $authinstance);
$institution = new Institution($authobj->institution);
$date = time();
$nicedate = date('Y/m/d h:i:s', $date);
$niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $username);
$uploaddir = get_config('dataroot') . 'import/' . $niceuser . '-' . $date . '/';
check_dir_exists($uploaddir);
// Unzip the file
$archive = new ZipArchive();
if ($archive->open($filename) && $archive->extractTo($uploaddir)) {
// successfully extracted
$archive->close();
} else {
$FAILEDUSERS[$username] = get_string('unzipfailed', 'admin', hsc($filename));
return;
}
$leap2afilename = $uploaddir . 'leap2a.xml';
if (!is_file($leap2afilename)) {
$FAILEDUSERS[$username] = get_string('noleap2axmlfiledetected', 'admin');
log_debug($FAILEDUSERS[$username]);
return;
}
// If the username is already taken, append something to the end
while (get_record('usr', 'username', $username)) {
$username .= "_";
}
$user = (object) array('authinstance' => $authinstance, 'username' => $username, 'firstname' => 'Imported', 'lastname' => 'User', 'password' => get_random_key(6), 'passwordchange' => 1);
db_begin();
try {
$user->id = create_user($user, array(), $institution, $authobj);
} catch (EmailException $e) {
// Suppress any emails (e.g. new institution membership) sent out
// during user creation, becuase the user doesn't have an email
// address until we've imported them from the Leap2A file.
log_debug("Failed sending email during user import");
}
$niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $user->username);
$record = (object) array('token' => '', 'usr' => $user->id, 'queue' => (int) (!PluginImport::import_immediately_allowed()), 'ready' => 0, 'expirytime' => db_format_timestamp(time() + 60 * 60 * 24), 'format' => 'leap', 'data' => array('importfile' => $filename, 'importfilename' => $filename, 'importid' => $niceuser . time(), 'mimetype' => file_mime_type($filename)), 'loglevel' => PluginImportLeap::LOG_LEVEL_VERBOSE, 'logtargets' => LOG_TARGET_FILE, 'profile' => true);
$tr = new LocalImporterTransport($record);
$tr->extract_file();
$importer = PluginImport::create_importer(null, $tr, $record);
unset($record, $tr);
try {
$importer->process();
log_info("Imported user account {$user->id} from Leap2A file, see" . $importer->get('logfile') . 'for a full log');
} catch (ImportException $e) {
log_info("Leap2A import failed: " . $e->getMessage());
$FAILEDUSERS[$username] = get_string("leap2aimportfailed");
db_rollback();
}
db_commit();
if (empty($FAILEDUSERS[$username])) {
// Reload the user details, as various fields are changed by the
// importer when importing (e.g. firstname/lastname)
$newuser = get_record('usr', 'id', $user->id);
$newuser->clearpasswd = $user->password;
$ADDEDUSERS[] = $newuser;
}
return;
}
示例4: xmldb_artefact_file_upgrade
function xmldb_artefact_file_upgrade($oldversion = 0)
{
$status = true;
if ($oldversion < 2009033000) {
if (!get_record('artefact_config', 'plugin', 'file', 'field', 'uploadagreement')) {
insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'uploadagreement', 'value' => 1));
insert_record('artefact_config', (object) array('plugin' => 'file', 'field' => 'usecustomagreement', 'value' => 1));
}
}
if ($oldversion < 2009091700) {
execute_sql("DELETE FROM {artefact_file_files} WHERE artefact IN (SELECT id FROM {artefact} WHERE artefacttype = 'folder')");
}
if ($oldversion < 2009091701) {
$table = new XMLDBTable('artefact_file_files');
$key = new XMLDBKey('artefactpk');
$key->setAttributes(XMLDB_KEY_PRIMARY, array('artefact'));
add_key($table, $key);
$table = new XMLDBTable('artefact_file_image');
$key = new XMLDBKey('artefactpk');
$key->setAttributes(XMLDB_KEY_PRIMARY, array('artefact'));
add_key($table, $key);
}
if ($oldversion < 2009092300) {
insert_record('artefact_installed_type', (object) array('plugin' => 'file', 'name' => 'archive'));
// update old files
if (function_exists('zip_open')) {
$files = get_records_select_array('artefact_file_files', "filetype IN ('application/zip', 'application/x-zip')");
if ($files) {
$checked = array();
foreach ($files as $file) {
$path = get_config('dataroot') . 'artefact/file/originals/' . $file->fileid % 256 . '/' . $file->fileid;
$zip = zip_open($path);
if (is_resource($zip)) {
$checked[] = $file->artefact;
zip_close($zip);
}
}
if (!empty($checked)) {
set_field_select('artefact', 'artefacttype', 'archive', "artefacttype = 'file' AND id IN (" . join(',', $checked) . ')', array());
}
}
}
}
if ($oldversion < 2010012702) {
if ($records = get_records_sql_array("SELECT * FROM {artefact_file_files} WHERE filetype='application/octet-stream'", array())) {
require_once 'file.php';
foreach ($records as &$r) {
$path = get_config('dataroot') . 'artefact/file/originals/' . $r->fileid % 256 . '/' . $r->fileid;
set_field('artefact_file_files', 'filetype', file_mime_type($path), 'fileid', $r->fileid, 'artefact', $r->artefact);
}
}
}
if ($oldversion < 2011052500) {
// Set default quota to 50MB
set_config_plugin('artefact', 'file', 'defaultgroupquota', 52428800);
}
if ($oldversion < 2011070700) {
// Create an images folder for everyone with a profile icon
$imagesdir = get_string('imagesdir', 'artefact.file');
$imagesdirdesc = get_string('imagesdirdesc', 'artefact.file');
execute_sql("\n INSERT INTO {artefact} (artefacttype, container, owner, ctime, mtime, atime, title, description, author)\n SELECT 'folder', 1, owner, current_timestamp, current_timestamp, current_timestamp, ?, ?, owner\n FROM {artefact} WHERE owner IS NOT NULL AND artefacttype = 'profileicon'\n GROUP BY owner", array($imagesdir, $imagesdirdesc));
// Put profileicons into the images folder and update the description
$profileicondesc = get_string('uploadedprofileicon', 'artefact.file');
if (is_postgres()) {
execute_sql("\n UPDATE {artefact}\n SET parent = f.folderid, description = ?\n FROM (\n SELECT owner, MAX(id) AS folderid\n FROM {artefact}\n WHERE artefacttype = 'folder' AND title = ? AND description = ?\n GROUP BY owner\n ) f\n WHERE artefacttype = 'profileicon' AND {artefact}.owner = f.owner", array($profileicondesc, $imagesdir, $imagesdirdesc));
} else {
execute_sql("\n UPDATE {artefact}, (\n SELECT owner, MAX(id) AS folderid\n FROM {artefact}\n WHERE artefacttype = 'folder' AND title = ? AND description = ?\n GROUP BY owner\n ) f\n SET parent = f.folderid, description = ?\n WHERE artefacttype = 'profileicon' AND {artefact}.owner = f.owner", array($imagesdir, $imagesdirdesc, $profileicondesc));
}
}
if ($oldversion < 2011082200) {
// video file type
if (!get_record('artefact_installed_type', 'plugin', 'file', 'name', 'video')) {
insert_record('artefact_installed_type', (object) array('plugin' => 'file', 'name' => 'video'));
}
// update existing records
$videotypes = get_records_sql_array('
SELECT DISTINCT description
FROM {artefact_file_mime_types}
WHERE mimetype ' . db_ilike() . ' \'%video%\'', array());
if ($videotypes) {
$mimetypes = array();
foreach ($videotypes as $type) {
$mimetypes[] = $type->description;
}
$files = get_records_sql_array('
SELECT *
FROM {artefact_file_files}
WHERE filetype IN (
SELECT mimetype
FROM {artefact_file_mime_types}
WHERE description IN (' . join(',', array_map('db_quote', array_values($mimetypes))) . ')
)', array());
if ($files) {
$checked = array();
foreach ($files as $file) {
$checked[] = $file->artefact;
}
if (!empty($checked)) {
set_field_select('artefact', 'artefacttype', 'video', "artefacttype = 'file' AND id IN (" . join(',', $checked) . ')', array());
}
//.........这里部分代码省略.........
示例5: make_thumb
function make_thumb($name, $path, $thumbs_dir)
{
$height = 200;
$width = 200;
$exlong = $extiny = false;
$return = array('generated' => false);
if (file_mime_type(ABSPATH . '/' . $path) == 'image/svg+xml') {
$svg = file_get_contents(ABSPATH . '/' . $path);
if (preg_match('/<svg.*?width="([\\d.]+)(em|ex|px|in|cm|mm|pt|pc|%)?".*?height="([\\d.]+)(em|ex|px|in|cm|mm|pt|pc|%)?".*?>/', $svg, $match)) {
$width = $match[1];
$height = $match[3];
} else {
if (preg_match('/<svg.*?height="([\\d.]+)(em|ex|px|in|cm|mm|pt|pc|%)?".*?width="([\\d.]+)(em|ex|px|in|cm|mm|pt|pc|%)?".*?>/', $svg, $match)) {
$width = $match[3];
$height = $match[1];
} else {
$width = $height = 200;
}
}
$ratio = $width / $height;
$exlong = $ratio > 3 || $ratio < 0.33;
if ($ratio < 0.33 || $ratio >= 1 && $ratio <= 3) {
$width = 200;
$height = $width / $ratio;
} else {
if ($ratio >= 0.33 && $ratio < 1 || $ratio > 3) {
$height = 200;
$width = $height * $ratio;
}
}
$return['width'] = $width;
$return['height'] = $height;
} else {
if (!($imgInfo = getimagesize(ABSPATH . '/' . $path))) {
return $return;
}
$notype = false;
list($width_orig, $height_orig, $type) = $imgInfo;
switch ($type) {
case IMAGETYPE_GIF:
$readf = "imagecreatefromgif";
$writef = "imagegif";
break;
case IMAGETYPE_JPEG:
$readf = "imagecreatefromjpeg";
$writef = "imagejpeg";
break;
case IMAGETYPE_PNG:
$readf = "imagecreatefrompng";
$writef = "imagepng";
break;
default:
$notype = true;
}
$ratio_orig = $width_orig / $height_orig;
$exlong = $ratio_orig < 0.33 || $ratio_orig > 3;
$extiny = $width_orig < 67 || $height_orig < 67;
if ($height_orig <= $height && $width_orig <= $width || $extiny || $exlong && ($height_orig <= $height || $width_orig <= $width)) {
$return['width'] = $width_orig;
$return['height'] = $height_orig;
} else {
if ($ratio_orig < 0.33 || $ratio_orig >= 1 && $ratio_orig <= 3) {
$height = $width / $ratio_orig;
} else {
if ($ratio_orig >= 0.33 && $ratio_orig < 1 || $ratio_orig > 3) {
$width = $height * $ratio_orig;
}
}
$return['width'] = $width;
$return['height'] = $height;
if ($notype || !($image_p = imagecreatetruecolor($width, $height))) {
return $return;
}
$image = $readf(ABSPATH . '/' . $path);
// Create alpha channel for png
if ($type == IMAGETYPE_PNG) {
if (!imagealphablending($image_p, false) || !imagesavealpha($image_p, true) || !($transparent = imagecolorallocatealpha($image_p, 255, 255, 255, 127)) || !imagefill($image_p, 0, 0, $transparent)) {
return $return;
}
}
// Make transparent for gif
if ($type == IMAGETYPE_GIF) {
$transparent_index = imagecolortransparent($image);
if ($transparent_index != -1) {
$bgcolor = imagecolorsforindex($image, $transparent_index);
$bgcolor = imagecolorallocate($image_p, $bgcolor['red'], $bgcolor['green'], $bgcolor['blue']);
$bgcolor_index = imagecolortransparent($image_p, $bgcolor);
imagefill($image_p, 0, 0, $bgcolor_index);
}
}
// Resize image
if (!imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig)) {
return $return;
}
if (!$writef($image_p, ABSPATH . "/{$thumbs_dir}/{$name}")) {
return $return;
}
imagedestroy($image);
imagedestroy($image_p);
$return['generated'] = true;
//.........这里部分代码省略.........
示例6: prepare_files
/**
* retrieves the files from the remote host
*/
public function prepare_files()
{
if (empty($this->importer)) {
throw new ImportException(null, 'Failed to initialise XMLRPC file retrieval - no importer object');
}
$this->prepare_tempdir();
$this->token = $this->importer->get('token');
require_once get_config('docroot') . 'api/xmlrpc/client.php';
$client = new Client();
try {
$client->set_method('portfolio/mahara/lib.php/fetch_file')->add_param($this->token)->send($this->host->wwwroot);
} catch (XmlrpcClientException $e) {
throw new ImportException($this->importer, 'Failed to retrieve zipfile from remote server: ' . $e->getMessage());
}
if (!($filecontents = base64_decode($client->response))) {
throw new ImportException($this->importer, 'Failed to retrieve zipfile from remote server');
}
$this->importfilename = 'import.zip';
$this->importfile = $this->tempdir . $this->importfilename;
if (!file_put_contents($this->tempdir . $this->importfilename, $filecontents)) {
throw new ImportException($this->importer, 'Failed to write out the zipfile to local temporary storage');
}
// detect the filetype and bail if it's not a zip file
safe_require('artefact', 'file');
require_once 'file.php';
$ziptypes = PluginArtefactFile::get_mimetypes_from_description('zip');
$this->mimetype = file_mime_type($this->tempdir . $this->importfilename);
if (!in_array($this->mimetype, $ziptypes)) {
throw new ImportException($this->importer, 'Not a valid zipfile - mimetype was ' . $this->mimetype);
}
}
示例7: new_file
/**
* Test file type and return a new Image or File.
*/
public static function new_file($path, $data)
{
require_once 'file.php';
if (is_image_file($path)) {
// If it's detected as an image, overwrite the browser mime type
$imageinfo = getimagesize($path);
$data->filetype = $imageinfo['mime'];
$data->width = $imageinfo[0];
$data->height = $imageinfo[1];
return new ArtefactTypeImage(0, $data);
}
$data->guess = file_mime_type($path, "foo.{$data->oldextension}");
// The guessed mimetype tends to be more accurate than what the browser tells us.
// Use the guess, unless it failed to find a match.
// But if it failed to find a match *and* there is no browser-supplied mimetype,
// then just use the guess.
if ($data->guess != 'application/octet-stream' || empty($data->filetype)) {
$data->filetype = $data->guess;
}
foreach (array('video', 'audio', 'archive') as $artefacttype) {
$classname = 'ArtefactType' . ucfirst($artefacttype);
if (call_user_func_array(array($classname, 'is_valid_file'), array($path, &$data))) {
return new $classname(0, $data);
}
}
return new ArtefactTypeFile(0, $data);
}
示例8: addfontform_validate
function addfontform_validate(Pieform $form, $values)
{
global $USER, $SESSION;
require_once 'file.php';
require_once 'uploadmanager.php';
$foldername = preg_replace(Skin::FONTNAME_FILTER_CHARACTERS, '', $values['fonttitle']);
if (!$foldername) {
$form->set_error('fonttitle', get_string('invalidfonttitle', 'skin'));
}
// If we are uploading a zip file we need to extract things before we can validate them
if (!empty($values['fontfileZip'])) {
safe_require('artefact', 'file');
$ziptypes = PluginArtefactFile::get_mimetypes_from_description('zip');
$zipmimetype = file_mime_type($values['fontfileZip']['name']);
$zipmimetype = $zipmimetype || (substr($values['fontfileZip']['name'], -4) == '.zip' ? 'application/zip' : null);
if (in_array($zipmimetype, $ziptypes)) {
// we are dealing with a zip file
// First pass it through the virus checker
$um = new upload_manager('fontfileZip');
if ($error = $um->preprocess_file()) {
$form->set_error('fontfileZip', $error);
}
$zip = new ZipArchive();
if ($zip->open($values['fontfileZip']['tmp_name'])) {
$check = uploadfiles_info();
for ($i = 0; $i < $zip->numFiles; $i++) {
$fontname = dirname($zip->getNameIndex($i));
$filename = basename($zip->getNameIndex($i));
if (empty($fontname) || $fontname == '.') {
$fontname = substr($values['fontfileZip']['name'], 0, -1 * strlen('.zip'));
}
// Check that all the needed files exist in the zip file
foreach ($check as $key => $item) {
if (end(explode('.', $zip->getNameIndex($i))) == $item['suffix']) {
$check[$key]['found'] = true;
}
}
}
// now examine our $check array to make sure at least one of each of the required files was found
foreach ($check as $key => $item) {
if ($item['required'] == true && $item['found'] == false) {
$form->set_error('fontfileZip', get_string('fontfilemissing', 'skin', $item['suffix']));
}
}
} else {
$form->set_error('fontfileZip', get_string('archivereadingerror', 'skin'));
}
} else {
$form->set_error('fontfileZip', get_string('notvalidzipfile', 'skin'));
}
} else {
foreach (uploadfiles_info() as $inputname => $details) {
$um = new upload_manager($inputname, false, null, !$details['required']);
if ($error = $um->preprocess_file()) {
$form->set_error($inputname, $error);
}
if (!$um->optionalandnotsupplied && $details['suffix']) {
$reqext = ".{$details['suffix']}";
$fileext = substr($values[$inputname]['name'], -1 * strlen($reqext));
if ($fileext != $reqext) {
$form->set_error($inputname, get_string('notvalidfontfile', 'skin', strtoupper($details['suffix'])));
}
}
}
}
}
示例9: attach_linked_file
/**
* Attaches a file to a blogpost entry that was just linked directly, rather than having a Leap2a entry
* See http://wiki.leapspecs.org/2A/files
*
* @param SimpleXMLElement $blogpostentry
* @param SimpleXMLElement $blogpostlink
* @param PluginImportLeap $importer
*/
private static function attach_linked_file($blogpostentry, $blogpostlink, PluginImportLeap $importer)
{
$importer->trace($blogpostlink);
$pathname = urldecode((string) $blogpostlink['href']);
$dir = dirname($importer->get('filename'));
$pathname = $dir . DIRECTORY_SEPARATOR . $pathname;
if (!file_exists($pathname)) {
return false;
}
// Note: this data is passed (eventually) to ArtefactType->__construct,
// which calls strtotime on the dates for us
require_once 'file.php';
$data = (object) array('title' => (string) $blogpostentry->title . ' ' . get_string('attachment', 'artefact.blog'), 'owner' => $importer->get('usr'), 'filetype' => file_mime_type($pathname));
return ArtefactTypeFile::save_file($pathname, $data, $importer->get('usrobj'), true);
}
示例10: get_image_size
function get_image_size($file)
{
$geterror = false;
if (file_mime_type($file) == 'image/svg+xml') {
$svg = file_get_contents($file);
if (preg_match('/<svg.+width="(\\d+\\.?\\d*)(em|ex|px|in|cm|mm|pt|pc|%)?".+height="(\\d+\\.?\\d*)(em|ex|px|in|cm|mm|pt|pc|%)?"/', $svg, $matches)) {
$width = $matches[1];
$height = $matches[3];
} else {
if (preg_match('/<svg.+height="(\\d+\\.?\\d*)(em|ex|px|in|cm|mm|pt|pc|%)?".+width="(\\d+\\.?\\d*)(em|ex|px|in|cm|mm|pt|pc|%)?"/', $svg, $matches)) {
$width = $matches[3];
$height = $matches[1];
} else {
$width = 200;
$height = 200;
}
}
$ratio = $width / $height;
if ($ratio < 0.33 || $ratio >= 1 && $ratio <= 3) {
$width = 200;
$height = $width / $ratio;
} else {
if ($ratio >= 0.33 && $ratio < 1 || $ratio > 3) {
$height = 200;
$width = $height * $ratio;
}
}
} else {
if (!($imgInfo = @getimagesize($file))) {
list($width, $height) = array(200, 200);
$geterror = true;
} else {
list($width, $height, , ) = $imgInfo;
}
}
return array($width, $height, $geterror);
}
示例11: save_uploaded_file
/**
* Processes a newly uploaded file, copies it to disk, and creates
* a new artefact object.
* Takes the name of a file input.
* Returns false for no errors, or a string describing the error.
*/
public static function save_uploaded_file($inputname, $data)
{
require_once 'uploadmanager.php';
$um = new upload_manager($inputname);
if ($error = $um->preprocess_file()) {
throw new UploadException($error);
}
$size = $um->file['size'];
if (!empty($data->owner)) {
global $USER;
if ($data->owner == $USER->get('id')) {
$owner = $USER;
$owner->quota_refresh();
} else {
$owner = new User();
$owner->find_by_id($data->owner);
}
if (!$owner->quota_allowed($size)) {
throw new QuotaExceededException(get_string('uploadexceedsquota', 'artefact.file'));
}
}
$data->size = $size;
if ($um->file['type'] == 'application/octet-stream') {
// the browser wasn't sure, so use file_mime_type to guess
require_once 'file.php';
$data->filetype = file_mime_type($um->file['tmp_name']);
} else {
$data->filetype = $um->file['type'];
}
$data->oldextension = $um->original_filename_extension();
$f = self::new_file($um->file['tmp_name'], $data);
$f->commit();
$id = $f->get('id');
// Save the file using its id as the filename, and use its id modulo
// the number of subdirectories as the directory name.
if ($error = $um->save_file(self::get_file_directory($id), $id)) {
$f->delete();
throw new UploadException($error);
} else {
if (isset($owner)) {
$owner->quota_add($size);
$owner->commit();
}
}
return $id;
}
示例12: genPostdata
private function genPostdata()
{
if (count($this->files) == 0 && !$this->multipart) {
if (count($this->posts) != 0) {
$query = '';
foreach ($this->posts as $post) {
$query .= rawurlencode($post['key']) . '=' . rawurlencode($post['value']) . '&';
}
$query = substr($query, 0, -1);
if ($this->method == 'POST') {
$this->setHeader(array('name' => 'Content-Type', 'value' => 'application/x-www-form-urlencoded'));
$this->postdata = $query;
} else {
if ($this->query == '') {
$this->query = '?' . $query;
} else {
$this->query .= '&' . $query;
}
}
}
} else {
// 设置分割标识
srand((double) microtime() * 1000000);
$boundary = '---------------------------' . substr(md5(rand(0, 32000)), 0, 10);
$this->setHeader(array('name' => 'Content-Type', 'value' => 'multipart/form-data; boundary=' . $boundary));
$this->postdata = '--' . $boundary . HTTPRequest::HTTP_EOL;
if (count($this->posts) != 0) {
foreach ($this->posts as $post) {
$this->postdata .= 'Content-Disposition: form-data; name="' . $post['key'] . '"' . HTTPRequest::HTTP_EOL . HTTPRequest::HTTP_EOL;
$this->postdata .= $post['value'] . HTTPRequest::HTTP_EOL;
$this->postdata .= '--' . $boundary . HTTPRequest::HTTP_EOL;
}
}
foreach ($this->files as $file) {
if (file_exists($file['path'])) {
$this->postdata .= 'Content-Disposition: form-data; name="' . $file['name'] . '"; filename="' . $file['filename'] . '"' . HTTPRequest::HTTP_EOL;
$mime = file_mime_type($file['path']);
if ($mime) {
$this->postdata .= 'Content-Type: ' . $mime . HTTPRequest::HTTP_EOL;
}
$this->postdata .= HTTPRequest::HTTP_EOL;
$contents = file_get_contents($file['path']);
$this->postdata .= $contents . HTTPRequest::HTTP_EOL;
$this->postdata .= '--' . $boundary . HTTPRequest::HTTP_EOL;
}
}
$this->postdata = substr($this->postdata, 0, -2) . '--' . HTTPRequest::HTTP_EOL;
$this->setHeader(array('name' => 'Content-Length', 'value' => strlen($this->postdata)));
}
}
示例13: emailhtml
function emailhtml($text, $html, $css, $to, $subject, $sender = false)
{
global $mailer, $webmaster, $sitename;
if (!$sender) {
$sender = $webmaster;
}
$textheader = $textbody = $htmlheader = $htmlbody = false;
if ($text) {
$textheader = 'Content-Type: text/plain; charset=utf-8';
$textbody = <<<_SEP_
{$text}
_SEP_;
}
$related = false;
if ($html) {
$related = array();
if (preg_match_all('#<img[^>]+src="([^"]*)"[^>]*>#is', $html, $matches)) {
$pattern = array();
$replacement = array();
foreach ($matches[1] as $url) {
if ($url[0] != '/') {
continue;
}
if (array_key_exists($url, $related)) {
continue;
}
$fname = ROOT_DIR . $url;
$filetype = file_mime_type($fname, false);
if (!$filetype or strpos($filetype, 'image') !== 0) {
continue;
}
$data = file_get_contents($fname);
if (get_magic_quotes_runtime()) {
$data = stripslashes($data);
}
if (!$data) {
continue;
}
$base64 = chunk_split(base64_encode($data));
$cid = md5(uniqid('cid', true));
$qfname = preg_quote($url);
$pattern[] = '#(<img[^>]+src=)"' . $qfname . '"([^>]*>)#is';
$replacement[] = '${1}"cid:' . $cid . '"${2}';
$related[$url] = array(basename($fname), $filetype, $cid, $base64);
}
$html = preg_replace($pattern, $replacement, $html);
}
$title = htmlspecialchars($sitename, ENT_COMPAT, 'UTF-8');
$htmlheader = 'Content-Type: text/html; charset=utf-8';
$htmlbody = <<<_SEP_
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>{$title}</title>
<style type="text/css">
{$css}
</style>
</head>
<body>
{$html}
</body>
</html>
_SEP_;
}
$headers = <<<_SEP_
From: {$sender}
Return-Path: {$sender}
X-Mailer: {$mailer}
_SEP_;
$body = '';
if ($related) {
if ($textbody) {
$sep = md5(uniqid('sep', true));
$body .= <<<_SEP_
Content-Type: multipart/alternative; boundary="{$sep}"
--{$sep}
{$textheader}
{$textbody}
--{$sep}
{$htmlheader}
{$htmlbody}
--{$sep}--
_SEP_;
} else {
$body .= <<<_SEP_
{$htmlheader}
{$htmlbody}
_SEP_;
}
$sep = md5(uniqid('sep', true));
//.........这里部分代码省略.........
示例14: adduser_validate
function adduser_validate(Pieform $form, $values)
{
global $USER, $TRANSPORTER;
$authobj = AuthFactory::create($values['authinstance']);
$institution = $authobj->institution;
// Institutional admins can only set their own institutions' authinstances
if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) {
$form->set_error('authinstance', get_string('notadminforinstitution', 'admin'));
return;
}
$institution = new Institution($authobj->institution);
// Don't exceed max user accounts for the institution
if ($institution->isFull()) {
$form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin'));
return;
}
$username = $values['username'];
$firstname = $values['firstname'];
$lastname = $values['lastname'];
$email = $values['email'];
$password = $values['password'];
if (method_exists($authobj, 'is_username_valid') && !$authobj->is_username_valid($username)) {
$form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
}
if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', strtolower($username))) {
$form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
}
if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
$form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type));
}
if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') {
$form->set_error('firstname', null);
$form->set_error('lastname', null);
$form->set_error('email', null);
if (!$values['leap2afile']) {
$form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
return;
}
if ($values['leap2afile']['type'] == 'application/octet-stream') {
require_once 'file.php';
$mimetype = file_mime_type($values['leap2afile']['tmp_name']);
} else {
$mimetype = $values['leap2afile']['type'];
}
$date = time();
$niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $values['username']);
safe_require('import', 'leap');
$fakeimportrecord = (object) array('data' => array('importfile' => $values['leap2afile']['tmp_name'], 'importfilename' => $values['leap2afile']['name'], 'importid' => $niceuser . '-' . $date, 'mimetype' => $mimetype));
$TRANSPORTER = new LocalImporterTransport($fakeimportrecord);
try {
$TRANSPORTER->extract_file();
PluginImportLeap::validate_transported_data($TRANSPORTER);
} catch (Exception $e) {
$form->set_error('leap2afile', $e->getMessage());
}
} else {
if (!$form->get_error('firstname') && !preg_match('/\\S/', $firstname)) {
$form->set_error('firstname', $form->i18n('rule', 'required', 'required'));
}
if (!$form->get_error('lastname') && !preg_match('/\\S/', $lastname)) {
$form->set_error('lastname', $form->i18n('rule', 'required', 'required'));
}
if (!$form->get_error('email')) {
require_once 'phpmailer/class.phpmailer.php';
if (!$form->get_error('email') && !PHPMailer::ValidateAddress($email)) {
$form->set_error('email', get_string('invalidemailaddress', 'artefact.internal'));
}
if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) {
$form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
}
}
}
}
示例15: adduser_validate
function adduser_validate(Pieform $form, $values)
{
global $USER, $TRANSPORTER;
$authobj = AuthFactory::create($values['authinstance']);
$institution = $authobj->institution;
// Institutional admins can only set their own institutions' authinstances
if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) {
$form->set_error('authinstance', get_string('notadminforinstitution', 'admin'));
return;
}
$institution = new Institution($authobj->institution);
// Don't exceed max user accounts for the institution
if ($institution->isFull()) {
$institution->send_admin_institution_is_full_message();
$form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin'));
return;
}
$username = $values['username'];
$firstname = sanitize_firstname($values['firstname']);
$lastname = sanitize_lastname($values['lastname']);
$email = sanitize_email($values['email']);
$password = $values['password'];
if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
$maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled');
$maxquota = get_config_plugin('artefact', 'file', 'maxquota');
if ($maxquotaenabled && $values['quota'] > $maxquota) {
$form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota)));
}
}
if (method_exists($authobj, 'is_username_valid_admin')) {
if (!$authobj->is_username_valid_admin($username)) {
$form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal'));
}
} else {
if (method_exists($authobj, 'is_username_valid')) {
if (!$authobj->is_username_valid($username)) {
$form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
}
}
}
if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) {
$form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
}
if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
$form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type));
}
if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') {
$form->set_error('firstname', null);
$form->set_error('lastname', null);
$form->set_error('email', null);
if (!$values['leap2afile'] && ($_FILES['leap2afile']['error'] == UPLOAD_ERR_INI_SIZE || $_FILES['leap2afile']['error'] == UPLOAD_ERR_FORM_SIZE)) {
$form->reply(PIEFORM_ERR, array('message' => get_string('uploadedfiletoobig'), 'goto' => '/admin/users/add.php'));
$form->set_error('leap2afile', get_string('uploadedfiletoobig'));
return;
} else {
if (!$values['leap2afile']) {
$form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
return;
}
}
if ($values['leap2afile']['type'] == 'application/octet-stream') {
require_once 'file.php';
$mimetype = file_mime_type($values['leap2afile']['tmp_name']);
} else {
$mimetype = trim($values['leap2afile']['type'], '"');
}
$date = time();
$niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $values['username']);
safe_require('import', 'leap');
$fakeimportrecord = (object) array('data' => array('importfile' => $values['leap2afile']['tmp_name'], 'importfilename' => $values['leap2afile']['name'], 'importid' => $niceuser . '-' . $date, 'mimetype' => $mimetype));
$TRANSPORTER = new LocalImporterTransport($fakeimportrecord);
try {
$TRANSPORTER->extract_file();
PluginImportLeap::validate_transported_data($TRANSPORTER);
} catch (Exception $e) {
$form->set_error('leap2afile', $e->getMessage());
}
} else {
if (!$form->get_error('firstname') && empty($firstname)) {
$form->set_error('firstname', $form->i18n('rule', 'required', 'required'));
}
if (!$form->get_error('lastname') && empty($lastname)) {
$form->set_error('lastname', $form->i18n('rule', 'required', 'required'));
}
if (!$form->get_error('email')) {
if (!$form->get_error('email') && empty($email)) {
$form->set_error('email', get_string('invalidemailaddress', 'artefact.internal'));
}
if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) {
$form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
}
}
}
}