public function __construct() { Validator::extend('skinmimes', function ($attribute, $value, $parameters) { $allowed = array('audio/mpeg', 'image/jpeg', 'application/ogg', 'audio/wave', 'audio/aiff', 'image/png', 'text/plain'); $mime = new MimeReader($value->getRealPath()); return in_array($mime->get_type(), $allowed); }); }
public function test1() { $msg = 'Date: Sun, 06 Nov 2011 10:09:58 +0100 From: =?iso-8859-1?Q?Tommy <*****@*****.**> Subject: Emailing: Bok2.txt To: tekstfiler <*****@*****.**> MIME-version: 1.0 X-Mailer: Microsoft Office Outlook 12.0 Content-type: multipart/mixed; boundary="Boundary_(ID_vPoI7CFh//8avI2MqJP0jQ)" Content-language: no Thread-index: AcycY2pawb1JDhc+RfewhS8ZTdEfxg== This is a multi-part message in MIME format. --Boundary_(ID_vPoI7CFh//8avI2MqJP0jQ) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT Your message is ready to be sent with the following file or link attachments: Bok2.txt Note: To protect against computer viruses, e-mail programs may prevent sending or receiving certain types of file attachments. Check your e-mail security settings to determine how attachments are handled. --Boundary_(ID_vPoI7CFh//8avI2MqJP0jQ) Content-type: text/plain; name=Bok2.txt Content-transfer-encoding: 7BIT Content-disposition: attachment; filename=Bok2.txt sak_referanse;sak_ref2;Status_Hovedstol;Status_Dato 22;6310;0;20111028 23;7605;-998;20111028 24;3872;-200;20111028 51;8111;-1947;20111028 55;6730;-1547;20111031 58;6499;-1547;20111031 59;6527;0;20111031 66;6350;0;20111031 67;5841;-500;20111031 --Boundary_(ID_vPoI7CFh//8avI2MqJP0jQ)--'; $mime = new MimeReader(); $mime->parseMail($msg); $mail = $mime->getAsEMail(0); d($mail); //TODO: make MimeReader static class }
/** * @param $callback function that is called with parsed mail header + attachments */ function getMail($callback = '', $timeout = 30) { if (!$this->connect()) { echo "ERROR: IMAP connection to " . $this->server . ":" . $this->port . " failed\n"; return false; } $folders = imap_listmailbox($this->handle, '{' . $this->server . ':' . $this->port . '}', '*'); $msginfo = imap_mailboxmsginfo($this->handle); //dp('found '.$msginfo->Nmsgs.' messages in mailbox'); $this->tot_mails = $msginfo->Nmsgs; for ($i = 1; $i <= $this->tot_mails; $i++) { //dp("Downloading ".$i." of ".$this->tot_mails." ..."); //XXX hack because retarded imap_fetchbody() dont allow to fetch the whole message $fp = fopen('php://temp', 'w'); imap_savebody($this->handle, $fp, $i); rewind($fp); $msg = stream_get_contents($fp); fclose($fp); $mime = new MimeReader(); $mime->parseMail($msg); $this->emails[] = $mime->getAsEMail($i); } if (!function_exists($callback)) { throw new \Exception('ERROR callback function ' . $callback . ' not found'); } call_user_func($callback, $this->emails, $this); }
/** * Handles incoming SIP messages * * @param $peer client address to send to * @param $msg the raw SIP message * @return true if message was handled */ function handle_message($peer, $msg) { $pos = strpos($msg, "\r\n\r\n"); $head = explode("\r\n", trim(substr($msg, 0, $pos)), 2); $mime = mimeParseHeader($head[1]); $body = trim(substr($msg, $pos)); $tmp = explode(' ', $head[0]); //INVITE sip:xxx@10.10.10.240 SIP/2.0 if ($tmp[2] != 'SIP/2.0') { //XXX return error code! echo "ERROR: Unsupported SIP version: " . $tmp[2] . "\n"; return false; } switch ($tmp[0]) { case 'INVITE': $sip_type = SIP_INVITE; break; case 'ACK': $sip_type = SIP_ACK; break; case 'BYE': $sip_type = SIP_BYE; break; case 'OPTIONS': $sip_type = SIP_OPTIONS; break; case 'CANCEL': $sip_type = SIP_CANCEL; break; case 'REGISTER': $sip_type = SIP_REGISTER; break; default: echo "Unknown SIP command: " . $tmp[0] . "\n"; return false; } switch ($sip_type) { case SIP_INVITE: //echo "Recieved SIP INVITE from ".$peer."\n"; //Send "100 TRYING" response $res = $this->send_message(SIP_TRYING, $peer, $mime); //Send "180 RINGING" response $res = $this->send_message(SIP_RINGING, $peer, $mime); //Send "200 OK" response if ($mime['Content-Type'] != 'application/sdp') { echo "ERROR: DIDNT GET SDP FROM CLIENT INVITE MSG\n"; //FIXME how to handle. hangup? break; } echo "Forwarding SIP media streams to IP: " . $this->dst_ip . "\n"; $port = $this->allocate_port($peer); $res_sdp = generate_sdp($body, $this->dst_ip, $port); $res = $this->send_message(SIP_OK, $peer, $mime, $res_sdp); echo "SDP FROM CALLER:\n" . $body . "\n\n"; echo "SDP TO CALLER & STREAMING SERVER:\n" . $res_sdp . "\n"; $sdp_file = '/tmp/sip_tmp.sdp'; file_put_contents($sdp_file, $res_sdp); //NOTE: playback live stream locally with VLC: //exec('/home/ml/scripts/compile/vlc-git/vlc -vvv '.$sdp_file); exec('ffplay ' . $sdp_file); //XXX dump rtp stream (command not working!!!) //exec('ffmpeg -i '.$sdp_file.' -vcodec copy -f raw /tmp/out.h263'); break; case SIP_BYE: echo "Recieved SIP BYE from " . $peer . "\n"; //Send "200 OK" response $res = $this->send_message(SIP_OK, $peer, $mime); $this->free_port($peer); break; case SIP_ACK: //echo "Recieved SIP ACK from ".$peer."\n"; //we dont send a response on this message break; case SIP_OPTIONS: //FIXME more parameters should be set in the OK response (???) echo "Recieved SIP OPTIONS from " . $peer . "\n"; $res = $this->send_message(SIP_OK, $peer, $mime); break; //We are acting a SIP Registrar //We are acting a SIP Registrar case SIP_REGISTER: echo "Recieved SIP REGISTER from " . $peer . "\n"; if (empty($mime['Authorization'])) { //FIXME sip bindings (how does that work?!) RFC 3261: 10.3 echo "Sending auth request!\n"; $res = $this->send_message(SIP_UNAUTHORIZED, $peer, $mime); break; } $pos = strpos($mime['Authorization'], ' '); $auth_type = substr($mime['Authorization'], 0, $pos); $auth_response = substr($mime['Authorization'], $pos + 1); if ($auth_type != "Digest") { //FIXME: send error code! 400 Bad request (???) echo "ERROR: SIP/2.0 only support Digest authentication\n"; break; } //RFC 2617: "3.2.2.1 Request-Digest" $chal = MimeReader::parseAuthRequest($auth_response); if ($chal['algorithm'] != "MD5" || $chal['realm'] != $this->auth_realm || $chal['nonce'] != $this->get_nonce($peer) || $chal['opaque'] != md5($this->auth_opaque) || empty($chal['username'])) { //FIXME: send error code! 400 Bad request (???) echo "ERROR: Authentication details for user " . $chal['username'] . " is invalid!\n"; break; } $check = $this->auth_default_handler($chal['username'], $this->auth_realm, $chal['uri'], $chal['nonce'], $chal['response']); if ($check) { echo "DEBUG: Authentication of user " . $chal['username'] . " SUCCESSFUL!\n"; $res = $this->send_message(SIP_OK, $peer, $mime); } else { //FIXME: send error code! 403 Forbidden (???) echo "ERROR: Authentication of user " . $chal['username'] . " FAILED!\n"; } break; case SIP_CANCEL: echo "Recieved SIP CANCEL from " . $peer . "\n"; //FIXME what should we respond? break; default: echo "Unknown SIP message type\n"; return false; } return true; }
/** * Deletes a file. * * Called when this component receives an HTTP DELETE request to * /file/$a/$b/$c/$file. * * @param string $hash The hash of the file which should be deleted. */ public function deleteFile($callName, $input, $params = array()) { $path = array(self::getBaseDir(), $params['a'], $params['b'], $params['c'], $params['file']); $filePath = implode('/', array_slice($path, 0)); if (strlen($filePath) > 0 && file_exists($this->config['DIR']['files'] . '/' . $filePath)) { // after the successful deletion, we want to return the file data $file = new File(); $file->setAddress($filePath); $file->setFileSize(filesize($this->config['DIR']['files'] . '/' . $filePath)); $file->setHash(sha1_file($this->config['DIR']['files'] . '/' . $filePath)); $file->setMimeType(MimeReader::get_mime($this->config['DIR']['files'] . '/' . $filePath)); // removes the file unlink($this->config['DIR']['files'] . '/' . $filePath); // the removing/unlink process failed, if the file still exists. if (file_exists($this->config['DIR']['files'] . '/' . $filePath)) { return Model::isProblem(new File()); } // the file is removed return Model::isCreated($file); } else { // file does not exist return Model::isProblem(new File()); } }
/** * Processes a submissions * * Called when this component receives an HTTP POST request to * /submission(/). */ public function postSubmission() { $this->app->response->setStatus(201); $body = $this->app->request->getBody(); $submissions = Submission::decodeSubmission($body); // always been an array $arr = true; if (!is_array($submissions)) { $submissions = array($submissions); $arr = false; } $res = array(); foreach ($submissions as $submission) { $fail = false; $process = new Process(); $process->setRawSubmission($submission); $eid = $submission->getExerciseId(); // load processor data from database $result = Request::routeRequest('GET', '/process/exercise/' . $eid, array(), '', $this->_processorDb, 'process'); $processors = null; if ($result['status'] >= 200 && $result['status'] <= 299) { $processors = Process::decodeProcess($result['content']); } else { if ($result['status'] != 404) { $submission->addMessage("Interner Fehler"); $res[] = $submission; $this->app->response->setStatus(409); continue; } } $result2 = Request::routeRequest('GET', '/exercisefiletype/exercise/' . $eid, array(), '', $this->_getExerciseExerciseFileType, 'exercisefiletype'); $exerciseFileTypes = null; if ($result2['status'] >= 200 && $result2['status'] <= 299) { $exerciseFileTypes = ExerciseFileType::decodeExerciseFileType($result2['content']); if (!is_array($exerciseFileTypes)) { $exerciseFileTypes = array($exerciseFileTypes); } $filePath = null; if ($submission->getFile() != null) { $file = $submission->getFile()->getBody(true); if ($file !== null) { $fileHash = sha1($file); $filePath = '/tmp/' . $fileHash; if ($submission->getFile()->getDisplayName() != null) { LProcessor::generatepath($filePath); file_put_contents($filePath . '/' . $submission->getFile()->getDisplayName(), $file); $filePath .= '/' . $submission->getFile()->getDisplayName(); } else { LProcessor::generatepath($filePath); file_put_contents($filePath . '/tmp', $file); $filePath .= '/tmp'; } } } // check file type if ($filePath != null) { $found = false; $types = array(); $mimeType = MimeReader::get_mime($filePath); $foundExtension = isset(pathinfo($filePath)['extension']) ? pathinfo($filePath)['extension'] : '-'; foreach ($exerciseFileTypes as $type) { $types[] = $type->getText(); $type = explode(' ', str_replace('*', '', $type->getText())); //echo MimeReader::get_mime($filePath); if (strpos($mimeType, $type[0]) !== false && (!isset($type[1]) || '.' . $foundExtension == $type[1])) { $found = true; break; } } if (!$found && count($exerciseFileTypes) > 0) { $submission->addMessage("falscher Dateityp \nGefunden: " . $mimeType . " ." . $foundExtension . "\nErlaubt: " . implode(',', $types)); $res[] = $submission; $this->app->response->setStatus(409); unlink($filePath); continue; } unlink($filePath); } } else { if ($result2['status'] != 404) { $submission->addMessage("Interner Fehler"); $res[] = $submission; $this->app->response->setStatus(409); continue; } } // process submission if ($processors !== null) { if (!is_array($processors)) { $processors = array($processors); } foreach ($processors as $pro) { $component = $pro->getTarget(); if ($process->getExercise() === null) { $process->setExercise($pro->getExercise()); } $process->setParameter($pro->getParameter()); $process->setAttachment($pro->getAttachment()); $process->setTarget($pro->getTarget()); $process->setWorkFiles($pro->getWorkFiles()); //echo Process::encodeProcess($process)."_______";// return; $result = Request::post($component->getAddress() . '/process', array(), Process::encodeProcess($process)); //echo $result['content'].'_______'; if ($result['status'] >= 200 && $result['status'] <= 299) { $process = Process::decodeProcess($result['content']); } else { $fail = true; $submission->addMessage("Beim Verarbeiten der Einsendung ist ein Fehler aufgetreten"); if (isset($result['content'])) { $content = Process::decodeProcess($result['content']); $submission->setStatus($content->getStatus()); $submission->addMessages($content->getMessages()); } break; } } } if ($fail) { if (isset($submission)) { $submission->setFile(null); } $res[] = $submission; $this->app->response->setStatus(409); continue; } // upload submission $uploadSubmission = $process->getSubmission(); if ($uploadSubmission === null) { $uploadSubmission = $process->getRawSubmission(); if ($uploadSubmission->getFile() != null) { $file = $uploadSubmission->getFile(); if ($file->getDisplayName() == null) { $file->setDisplayName($submission->getExerciseName()); } } } if ($uploadSubmission !== null) { ///echo Submission::encodeSubmission($uploadSubmission);return; $result = Request::routeRequest('POST', '/submission', array(), Submission::encodeSubmission($uploadSubmission), $this->_submission, 'submission'); //var_dump($result);return; // checks the correctness of the query if ($result['status'] >= 200 && $result['status'] <= 299) { $queryResult = Submission::decodeSubmission($result['content']); $uploadSubmission->setId($queryResult->getId()); $uploadSubmission->setFile($queryResult->getFile()); if ($process->getMarking() !== null) { $process->getMarking()->setSubmission($queryResult); } } else { $uploadSubmission->addMessage("Beim Speichern der Einsendung ist ein Fehler aufgetreten."); //var_dump($uploadSubmission); return; if (isset($result['content'])) { $content = Submission::decodeSubmission($result['content']); $uploadSubmission->setStatus($content->getStatus()); $uploadSubmission->addMessages($content->getMessages()); } $uploadSubmission->setStatus(409); $res[] = $uploadSubmission; $this->app->response->setStatus(409); continue; } } // upload marking if ($process->getMarking() !== null) { //echo Marking::encodeMarking($process->getMarking()); $result = Request::routeRequest('POST', '/marking', array(), Marking::encodeMarking($process->getMarking()), $this->_marking, 'marking'); // checks the correctness of the query if ($result['status'] >= 200 && $result['status'] <= 299) { $queryResult = Marking::decodeMarking($result['content']); } else { $uploadSubmission->addMessage("Beim Speichern der Korrektur ist ein Fehler aufgetreten"); if (isset($result['content'])) { $content = Marking::decodeMarking($result['content']); $uploadSubmission->addMessages($content->getMessages()); } $res[] = $uploadSubmission; $this->app->response->setStatus(409); continue; } } $rr = $process->getSubmission(); if ($rr === null) { $rr = $process->getRawSubmission(); } $res[] = $rr; } if (!$arr && count($res) == 1) { $this->app->response->setBody(Submission::encodeSubmission($res[0])); } else { $this->app->response->setBody(Submission::encodeSubmission($res)); } }
include_once dirname(__FILE__) . '/../Assistants/Language.php'; include_once dirname(__FILE__) . '/../Assistants/MimeReader.php'; global $globalUserData; Authentication::checkRights(PRIVILEGE_LEVEL::TUTOR, $cid, $uid, $globalUserData); $langTemplate = 'TutorUpload_Controller'; Language::loadLanguageFile('de', $langTemplate, 'json', dirname(__FILE__) . '/'); if (isset($_POST['action']) && $_POST['action'] == 'TutorUpload') { if (isset($_FILES['MarkingFile'])) { $file = $_FILES['MarkingFile']; $error = $file['error']; if ($error == 0) { $filePath = $file['tmp_name']; $displayName = $file['name']; $type = $file["type"]; // checks file ending if (MimeReader::get_mime($filePath) == "application/zip") { // creates the JSON object containing the file $file = new File(); $file->setBody(Reference::createReference($filePath)); $file->setTimeStamp(time()); $file->setDisplayName($displayName); $file = File::encodeFile($file); // sends the JSON object to the logic $URI = $logicURI . "/tutor/user/{$uid}/course/{$cid}"; $error = http_post_data($URI, $file, true, $message); if ($message == "201" || $message == "200") { $successmsg = Language::Get('main', 'sucessFileUpload', $langTemplate); $notifications[] = MakeNotification('success', $successmsg); } else { $errors = @json_decode($error); if ($errors !== null) {
/** * Returns the mime type of a file * * @param string $file * @return mixed */ public static function mime($file) { // stop for invalid files if (!file_exists($file)) { return null; } // Fileinfo is prefered if available if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $file); finfo_close($finfo); return $mime; } // for older versions with mime_content_type go for that. if (function_exists('mime_content_type') && ($mime = @mime_content_type($file) !== false)) { return $mime; } // shell check try { $mime = system::execute('file', [$file, '-z', '-b', '--mime'], 'output'); $mime = trim(str::split($mime, ';')[0]); if (f::mimeToExtension($mime)) { return $mime; } } catch (Exception $e) { // no mime type detectable with shell $mime = null; } // Mime Sniffing $reader = new MimeReader($file); $mime = $reader->get_type(); if (!empty($mime) && f::mimeToExtension($mime)) { return $mime; } // guess the matching mime type by extension return f::extensionToMime(f::extension($file)); }
function _AUTH() { if (isset($this->ability['AUTH']['DIGEST-MD5'])) { //XXX: this implementation might be buggy in regards to charset (non latin1 letters in username / password) $this->write('AUTH DIGEST-MD5'); if ($this->status != 334) { echo "smtp->_AUTH() DIGEST-MD5 [" . $this->status . "]: " . $this->lastreply . ln(); return false; } //echo "challenge: ".base64_decode($this->lastreply)."\n"; $chal = MimeReader::parseAuthRequest(base64_decode($this->lastreply)); if (empty($chal['qop'])) { $chal['qop'] = 'auth'; } //default if ($chal['algorithm'] != 'md5-sess') { echo "smtp->_AUTH() DIGEST-MD5 unknown algorithm: " . $chal['algorithm'] . ln(); return false; } //RFC 2831 @ 2.1.2.1 $nc = '00000001'; //number of times same nonce has been used $cnonce = md5(mt_rand() . microtime()); $digest_uri = 'smtp/' . $this->servername; $a1 = md5($this->username . ':' . $chal['realm'] . ':' . $this->password, true) . ':' . $chal['nonce'] . ':' . $cnonce . (!empty($chal['authzid']) ? ':' . $chal['authzid'] : ''); $a2 = 'AUTHENTICATE:' . $digest_uri . ($chal['qop'] != 'auth' ? ':00000000000000000000000000000000' : ''); $response = md5(md5($a1) . ':' . $chal['nonce'] . ':' . $nc . ':' . $cnonce . ':' . $chal['qop'] . ':' . md5($a2)); $cmd = 'charset=' . $chal['charset'] . ',' . 'username="******",' . 'realm="' . $chal['realm'] . '",' . 'nonce="' . $chal['nonce'] . '",' . 'nc=' . $nc . ',' . 'cnonce="' . $cnonce . '",' . 'digest-uri="' . $digest_uri . '",' . 'response=' . $response . ',' . 'qop=' . $chal['qop']; $this->write(base64_encode($cmd)); if ($this->status != 334) { echo "smtp->_AUTH() DIGEST-MD5 challenge [" . $this->status . "]: " . $this->lastreply . ln(); return false; } //XXX validate server response, RFC 2831 @ 2.1.3 //echo "response: ".base64_decode($this->lastreply)."\n"; $this->write('NOOP'); //FIXME figure out why we need to send 1 more command to get the 235 status if ($this->status != 235) { echo "smtp->_AUTH() DIGEST-MD5 auth failed [" . $this->status . "]: " . $this->lastreply . ln(); return false; } return true; } if (isset($this->ability['AUTH']['CRAM-MD5'])) { $this->write('AUTH CRAM-MD5'); if ($this->status != 334) { echo "smtp->_AUTH() CRAM-MD5 [" . $this->status . "]: " . $this->lastreply . ln(); return false; } $digest = hash_hmac('md5', base64_decode($this->lastreply), $this->password); $this->write(base64_encode($this->username . ' ' . $digest)); if ($this->status != 235) { echo "smtp->_AUTH() CRAM-MD5 challenge [" . $this->status . "]: " . $this->lastreply . ln(); return false; } return true; } if (isset($this->ability['AUTH']['LOGIN'])) { $this->write('AUTH LOGIN'); if ($this->status != 334) { echo "smtp->_AUTH() LOGIN [" . $this->status . "]: " . $this->lastreply . ln(); return false; } $this->write(base64_encode($this->username)); if ($this->status != 334) { echo "smtp->_AUTH() LOGIN username [" . $this->status . "]: " . $this->lastreply . ln(); return false; } $this->write(base64_encode($this->password)); if ($this->status != 235) { echo "smtp->_AUTH() LOGIN password [" . $this->status . "]: " . $this->lastreply . ln(); return false; } return true; } //d($this->ability); //Defaults to "AUTH PLAIN" if the server is not ESMTP-capable (FIXME: verify with non-capable server) $this->write('AUTH PLAIN'); if ($this->status == 503) { return true; } //authentication not enabled if ($this->status != 334) { throw new \Exception("smtp->_AUTH() PLAIN [" . $this->status . "]: " . $this->lastreply); } $cmd = base64_encode(chr(0) . $this->username . chr(0) . $this->password); $this->write($cmd); if ($this->status != 235) { echo "smtp->_AUTH() PLAIN error [" . $this->status . "]: " . $this->lastreply . ln(); return false; } return true; }
/** * @name validateFile Comprueba un ARCHIVO que este en el DISCO * Si quieres comprobar archivos subidos puedes utilizar "validateUploadedFile" para agilizar la carga * @param string $file Path to file to validate * @param string/array $type Especifica el/los tipos de ficheros que se aceptan */ public function validateFile($file, $type = '', $testExtensions = true) { $mime = new MimeReader($file); return $this->validate($file, $mime->get_type(), $type, $testExtensions); }
<?php include '../mimereader.class.php'; $files = array('./image.jpg', './image.png', './image.gif', './image.bmp', './Test.pdf'); echo '<table>'; foreach ($files as $file) { $fp = fopen($file, 'r'); $buffer = fread($fp, 16); fclose($fp); echo '<tr><td>' . $file . '</td><td>'; $type = '<b>UNKNOWN</b>'; $reader = new MimeReader($file); echo $reader->get_type() . '</td></tr>'; } echo '</table>';