protected function zip_upload($fobject, $name, $data, $action, $item) { $res = array(); $mtype = MIME::type_for_file($fobject->original_name); if ($mtype->type == 'application/zip;zip') { $zip = new ZipArchive(); $ro = $zip->open($fobject->path); if ($ro === true) { $dir = CMS::temp_dir() . '/' . $fobject->name; $dir_object = IO_FS::mkdir($dir, null, true); if ($dir_object) { $zip->extractTo($dir); $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)); foreach ($objects as $k => $object) { $base = trim($object->getBasename($object->getExtension()), '. '); if ('' !== $base) { $upload = Net_HTTP::Upload($object->getPathname(), $object->getFilename(), array('name' => $object->getFilename(), 'type' => MIME::type_for_file($object->getPathname())->type, 'tmp_name' => $object->getPathname(), 'error' => 0, 'size' => $object->getSize())); $res[] = $this->upload_file($upload, $name, $data, $action, $item); } } $dir_object->rm(); } $zip->close(); } } return $res; }
public static function get() { if (!self::$instance) { self::$instance = new self(); } return self::$instance; }
public function sendfile($path, $cb, $pri = EIO_PRI_DEFAULT) { $req = $this; try { $this->header('Content-Type: ' . MIME::get($path)); } catch (RequestHeadersAlreadySent $e) { } if ($this->conn->sendfileCap) { $req->ensureSentHeaders(); $req->conn->onWriteOnce(function ($conn) use($req, $path, $cb, $pri) { FS::sendfile($req->conn->fd, $path, $cb, 0, null, $pri); }); return; } $first = true; FS::readfileChunked($path, $cb, function ($file, $chunk) use($req, &$first) { // readed chunk if ($first) { try { $req->header('Content-Length: ' . $file->stat['st_size']); } catch (RequestHeadersAlreadySent $e) { } $first = false; } $req->out($chunk); }); }
/** * Constructor. * * @param string $sender Sender of the iTip reply. * @param string $recipient Recipient of the iTip reply. * @param MIME_Headers $headers Reply headers. * @param MIME_Message $body Reply body. */ public function __construct($sender, $recipient, MIME_Headers $headers, MIME_Message $body) { $this->_sender = $sender; $this->_recipient = MIME::encodeAddress($recipient); $this->_headers = $headers; $this->_body = $body; }
public static function getMIMEMediaReg() { if (MIME::$MIMEMediaReg == "") { MIME::$MIMEMediaReg = "/" . join("|", array_map(function ($item) { return preg_replace("/\\./", "\\.", $item) . "\$"; }, array_keys(MIME::$MIMEMediaTable))) . "/"; } return MIME::$MIMEMediaReg; }
public static function add($extension, $type = null) { if (is_array($extension)) { self::$map = array_merge(self::$map, $extension); } elseif ($type === null) { throw new Error_IllegalArgument(); } else { self::$map[$extension] = $type; } }
static function init() { //return if already done if (MIME::$class_init) { return; } //populate the types list with data MIME::$mime_types = array('txt' => 'text/plain', 'html' => 'text/html', 'htm' => 'text/html', 'php' => 'text/plain', 'css' => 'text/css', 'js' => 'application/x-javascript', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'bmp' => 'image/bmp', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'doc' => 'application/msword', 'docx' => 'application/msword', 'xls' => 'application/excel', 'xlsx' => 'application/excel', 'ppt' => 'application/powerpoint', 'pptx' => 'application/powerpoint', 'pdf' => 'application/pdf', 'wmv' => 'application/octet-stream', 'mpg' => 'video/mpeg', 'mov' => 'video/quicktime', 'mp4' => 'video/quicktime', 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'dmg' => 'application/x-apple-diskimage', 'exe' => 'application/octet-stream'); //set init state to true MIME::$class_init = true; }
function edit($args = null) { $answer = array(); $answer["success"]["fields"] = array(); if (empty($_SESSION["user"]) || empty($_SESSION["user"]["id"])) { //$answer["error"]["field"] = "auth"; $answer["error"]["msg"] = "Вы не авторизованы!"; return $answer; } $user = new UserCustomer(); if (!$user->load(array("id" => $_SESSION["user"]["id"]))) { //$answer["error"]["field"] = null; $answer["error"]["msg"] = Common::echoLastError(); return $answer; } $validate_fields = array(); if (isset($_POST["validate_fields"])) { $validate_fields = $_POST["validate_fields"]; } $required_fields = array(); if (isset($_POST["required_fields"])) { $required_fields = $_POST["required_fields"]; } //считываем фамилию $user->surname = readPostField($answer, "surname", $validate_fields, $required_fields); if ($user->surname === null) { return $answer; } //считываем имя $user->name = readPostField($answer, "name", $validate_fields, $required_fields); if ($user->name === null) { return $answer; } //считываем отчество $user->second_name = readPostField($answer, "second_name", $validate_fields, $required_fields); if ($user->second_name === null) { return $answer; } //считываем пол $user->sex = readPostField($answer, "sex", $validate_fields, $required_fields); if ($user->sex === null) { return $answer; } //считываем дату рождения $user->birthday = readPostField($answer, "birthday", $validate_fields, $required_fields); if ($user->birthday === null) { return $answer; } //$user->write(); //если указана фотография if (!empty($_POST["photo_data"])) { //парсим ее в MIME $photo = new MIME(); $photo_data = json_decode($_POST["photo_data"]); $photo->parseString($photo_data->image); //считываем область выделения и проверяем, установлена ли она $selection = $photo_data->selection; if (empty($selection) || empty($selection->width) || empty($selection->height)) { //если не установлена, то берем максимально большую область по размерам картинки $photo_size = $photo->imageSize(); if ($photo_size === false) { $answer["error"] = array("field" => "photo", "Не удалось сохранить фотографию (" . Common::getLastErrorMsg() . ")"); return $answer; } $selection->x1 = 0; $selection->y1 = 0; if ($photo_size["width"] <= $photo_size["height"]) { $selection->width = $photo_size["width"]; $selection->height = $photo_size["width"]; } else { $selection->width = $photo_size["height"]; $selection->height = $photo_size["height"]; } } //удаляем старую фотку, если есть $file_name = $user->photo; if (!empty($file_name) && file_exists($file_name)) { unlink($file_name); } //и сохраняем новую картинку с изменением размеров $file_name = $photo->saveToFile(User::$user_photo_dir . $user->id, array("x1" => 0, "y1" => 0, "width" => 200, "height" => 200), array("x1" => $selection->x1, "y1" => $selection->y1, "width" => $selection->width, "height" => $selection->height)); if ($file_name === false) { $answer["error"] = array("field" => "photo", "msg" => "Не удалось сохранить фотографию (" . Common::getLastErrorMsg() . ")"); return $answer; } $user->photo = $file_name; $answer["success"]["fields"][] = "photo"; } //считываем телефоны $phones = readPostField($answer, "phone", $validate_fields, $required_fields); if ($phones === null) { return $answer; } $user->phones = array(); foreach ($phones as $phone) { $phone_data = explode(',', $phone); if (count($phone_data) != 2) { $answer["error"] = array("field" => "phone", "msg" => "Телефоны указаны некорректно"); array_pop($answer["success"]["fields"]); return $answer; } $user->phones[] = array("phone" => preg_replace('/[^0-9]/', '', $phone_data[1]), "type" => $phone_data[0]); } //считываем jabber $user->jabber = readPostField($answer, "jabber", $validate_fields, $required_fields); if ($user->jabber === null) { return $answer; } //считываем skype $user->skype = readPostField($answer, "skype", $validate_fields, $required_fields); if ($user->skype === null) { return $answer; } /*$old_pwd = readPostField($answer,"old_pwd",$validate_fields,$required_fields); if($old_pwd === null) return $answer; if(!empty($old_pwd)) { $pwd1 = $_POST["pwd1"]; $pwd2 = $_POST["pwd2"]; $pwd_strong = 0; $error = Users::validatePassword($pwd1,$pwd2,$pwd_strong); if($error !== Users::ERROR_NOT) { //в случае ошибки возвращаем текст ошибки //если пароли отличаются или второй пароль пустой, указываем фокус на второй пароль if(($error === Users::ERROR_PWD_DIFFERENT)||(($error === Users::ERROR_PWD_EMPTY)&&(!empty($pwd1)))) { $answer["error"]["field"] = "pwd2"; array_push($answer["success"]["fields"],"pwd"); } else $answer["error"]["field"] = "pwd"; array_pop($answer["success"]["fields"]); return $answer; } }*/ //если нужна была только валидация, выходим if (!isset($_POST["submit"]) || !$_POST["submit"]) { return $answer; } //сохраняем if (!$user->save()) { $answer["error"] = array("field" => "submit", "msg" => Common::echoLastErrorMsg()); return $answer; } //указываем об успешности опреации и выходим $answer["success"]["msg"] = "Данные успешно сохранены"; $answer["success"]["fields"][] = "submit"; return $answer; }
/* Purpose: - set 'text/plain' and 'text/html' version of message - send mail directly to client (without MTA support) - add attachment - embed image into HTML - print result */ // manage errors error_reporting(E_ALL); // php errors define('DISPLAY_XPM4_ERRORS', true); // display XPM4 errors // path to 'MAIL.php' file from XPM4 package require_once '../MAIL.php'; // get ID value (random) for the embed image $id = MIME::unique(); // initialize MAIL class $m = new MAIL(); // set from address and name $m->From('*****@*****.**', 'My Name'); // add to address and name $m->AddTo('*****@*****.**', 'Client Name'); // set subject $m->Subject('Hello World!'); // set text/plain version of message $m->Text('Text version of message.'); // set text/html version of message $m->Html('<b>HTML</b> version of <u>message</u>.<br><i>Powered by</i> <img src="cid:' . $id . '">'); // add attachment ('text/plain' file) $m->Attach('source file', 'text/plain'); $f = 'xpertmailer.gif';
function send_email($goingto, $toname, $sbj, $messg) { global $Config; define('DISPLAY_XPM4_ERRORS', true); // display XPM4 errors $core_em = $Config->get('site_email'); // If email type "0" (SMTP) if ($Config->get('email_type') == 0) { require_once 'core/mail/SMTP.php'; // path to 'SMTP.php' file from XPM4 package $f = '' . $core_em . ''; // from mail address $t = '' . $goingto . ''; // to mail address // standard mail message RFC2822 $m = 'From: ' . $f . "\r\n" . 'To: ' . $t . "\r\n" . 'Subject: ' . $sbj . "\r\n" . 'Content-Type: text/plain' . "\r\n\r\n" . '' . $messg . ''; $h = explode('@', $t); // get client hostname $c = SMTP::MXconnect($h[1]); // connect to SMTP server (direct) from MX hosts list $s = SMTP::Send($c, array($t), $m, $f); // send mail // print result if ($s) { output_message('success', 'Mail Sent!'); } else { output_message('error', print_r($_RESULT)); } SMTP::Disconnect($c); // disconnect } elseif ($Config->get('email_type') == 1) { require_once 'core/mail/MIME.php'; // path to 'MIME.php' file from XPM4 package // compose message in MIME format $mess = MIME::compose($messg); // send mail $send = mail($goingto, $sbj, $mess['content'], 'From: ' . $core_em . '' . "\n" . $mess['header']); // print result echo $send ? output_message('success', 'Mail Sent!') : output_message('error', 'Error!'); } elseif ($Config->get('email_type') == 2) { require_once 'core/mail/MAIL.php'; // path to 'MAIL.php' file from XPM4 package $m = new MAIL(); // initialize MAIL class $m->From($core_em); // set from address $m->AddTo($goingto); // add to address $m->Subject($sbj); // set subject $m->Html($messg); // set html message // connect to MTA server 'smtp.hostname.net' port '25' with authentication: 'username'/'password' if ($Config->get('email_use_secure') == 1) { $c = $m->Connect($Config->get('email_smtp_host'), $Config->get('email_smtp_port'), $Config->get('email_smtp_user'), $Config->get('email_smtp_pass'), $Config->get('email_smtp_secure')) or die(print_r($m->Result)); } else { $c = $m->Connect($Config->get('email_smtp_host'), $Config->get('email_smtp_port'), $Config->get('email_smtp_user'), $Config->get('email_smtp_pass')) or die(print_r($m->Result)); } // send mail relay using the '$c' resource connection echo $m->Send($c) ? output_message('success', 'Mail Sent!') : output_message('error', 'Error! Please check your config and make sure you inserted your MTA info correctly.'); $m->Disconnect(); // disconnect from server // print_r($m->History); // optional, for debugging } }
function _renderVarDisplay_email($form, $var, $vars) { $display_email = $email = $var->getValue($vars); if ($var->type->strip_domain && strpos($email, '@') !== false) { $display_email = str_replace(array('@', '.'), array(' (at) ', ' (dot) '), $email); } if ($var->type->link_compose) { $email_val = trim($email); // Format the address according to RFC822. $mailbox_host = explode('@', $email_val); if (!isset($mailbox_host[1])) { $mailbox_host[1] = ''; } $name = $var->type->link_name; require_once 'Horde/MIME.php'; $address = MIME::rfc822WriteAddress($mailbox_host[0], $mailbox_host[1], $name); // Get rid of the trailing @ (when no host is included in // the email address). $address = str_replace('@>', '>', $address); try { $mail_link = $GLOBALS['registry']->call('mail/compose', array(array('to' => addslashes($address)))); } catch (Horde_Exception $e) { $mail_link = 'mailto:' . urlencode($address); } return Horde::link($mail_link, $email_val) . htmlspecialchars($display_email) . '</a>'; } else { return nl2br(htmlspecialchars($display_email)); } }
/** * Creates a docman file */ function createDocmanFile($sessionKey, $group_id, $parent_id, $title, $description, $ordering, $status, $obsolescence_date, $permissions, $metadata, $file_size, $file_name, $mime_type, $content, $chunk_offset, $chunk_size, $author, $date, $owner, $create_date, $update_date) { $content = base64_decode($content); //ignore mime type coming from the client, guess it instead //Write the content of the file into a temporary file //The best accurate results are got when the file has the real extension, therefore use the filename $tmp = tempnam(ForgeConfig::get('tmp_dir'), 'Mime-detect'); $tmpname = $tmp . '-' . basename($file_name); file_put_contents($tmpname, $content); $mime_type = MIME::instance()->type($tmpname); //remove both files created by tempnam() and file_put_contents() unlink($tmp); unlink($tmpname); $extraParams = array('chunk_offset' => $chunk_offset, 'chunk_size' => $chunk_size, 'file_size' => $file_size, 'file_name' => $file_name, 'mime_type' => $mime_type, 'upload_content' => $content, 'date' => $date, 'author' => _getUserIdByUserName($author)); return _createDocmanDocument($sessionKey, $group_id, $parent_id, $title, $description, $ordering, $status, $obsolescence_date, PLUGIN_DOCMAN_ITEM_TYPE_FILE, $permissions, $metadata, $owner, $create_date, $update_date, $extraParams); }
/** * Устанавливает заголовок письма в multipart с указанным типом и границей * * @param string $type * @param string $boundary * * @return Mail_Message_Message */ public function multipart($type = 'mixed', $boundary = null) { $this->body = new ArrayObject(); $this->head['Content-Type'] = array('Multipart/' . ucfirst(strtolower($type)), 'boundary' => $boundary ? $boundary : MIME::boundary()); return $this; }
public function content_type() { return MIME::for_file($this); }
public function autoindex($dir) { $this->onWakeup(); Daemon::$req = $this; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Index of /</title> <style type="text/css"> a, a:active {text-decoration: none; color: blue;} a:visited {color: #48468F;} a:hover, a:focus {text-decoration: underline; color: red;} body {background-color: #F5F5F5;} h2 {margin-bottom: 12px;} table {margin-left: 12px;} th, td { font: 90% monospace; text-align: left;} th { font-weight: bold; padding-right: 14px; padding-bottom: 3px;} td {padding-right: 14px;} td.s, th.s {text-align: right;} div.list { background-color: white; border-top: 1px solid #646464; border-bottom: 1px solid #646464; padding-top: 10px; padding-bottom: 14px;} div.foot { font: 90% monospace; color: #787878; padding-top: 4px;} </style> </head> <body> <pre class="header">Welcome!</pre><h2>Index of /</h2> <div class="list"> <table summary="Directory Listing" cellpadding="0" cellspacing="0"> <thead> <tr> <th class="n">Name</th> <th class="t">Type</th> </tr> </thead> <tbody> <tr> <td class="n"><a href="../">Parent Directory</a>/</td> <td class="t">Directory</td> </tr> <?php foreach ($dir['dents'] as $item) { $type = $item['type'] === EIO_DT_DIR ? 'Directory' : MIME::get($path); ?> <tr> <td class="n"><a href="<?php echo htmlspecialchars($item['name']) . ($type == 'Directory' ? '/' : ''); ?> "><?php echo htmlspecialchars($item['name']); ?> </a></td> <td class="t"><?php echo $type; ?> </td> </tr> <?php } ?> </tbody> </table> </div> <?php if ($this->upstream->config->expose->value) { ?> <div class="foot">phpDaemon/<?php echo Daemon::$version; ?> </div><?php } ?> </body> </html><?php }
protected function infer_mime_type() { return \MIME::for_file($this->file); }
/** * Returns mime-type of the file * * @return String * * @see plugins/webdav/lib/Sabre/DAV/Sabre_DAV_File#getContentType() */ function getContentType() { if (file_exists($this->getFileLocation()) && filesize($this->getFileLocation())) { $mime = MIME::instance(); return $mime->type($this->getFileLocation()); } }
function announce() { $module = $this->options['module']; if (!isset($this->notes)) { print "NOT announcing release, RELEASE_NOTES missing.\n"; return; } if (!empty($this->options['noannounce'])) { print "NOT announcing release on freshmeat.net\n"; } else { print "Announcing release on freshmeat.net\n"; $fm = Horde_RPC::request('xmlrpc', 'http://freshmeat.net/xmlrpc/', 'login', array('username' => $this->options['fm']['user'], 'password' => $this->options['fm']['password'])); if ($this->_fmVerify($fm)) { $fm = Horde_RPC::request('xmlrpc', 'http://freshmeat.net/xmlrpc/', 'publish_release', array('SID' => $fm['SID'], 'project_name' => $this->notes['fm']['project'], 'branch_name' => $this->notes['fm']['branch'], 'version' => $this->sourceVersionString, 'changes' => $this->notes['fm']['changes'], 'release_focus' => (int) $this->notes['fm']['focus'], 'url_changelog' => $this->oldVersion ? "http://cvs.horde.org/diff.php/{$module}/docs/CHANGES?r1={$this->oldChangelogVersion}&r2={$this->changelogVersion}&ty=h" : '', 'url_tgz' => "ftp://ftp.horde.org/pub/{$module}/{$this->tarballName}")); $this->_fmVerify($fm); } } $ml = $module; if ($ml == 'accounts' || $ml == 'forwards' || $ml == 'passwd' || $ml == 'vacation') { $ml = 'sork'; } $to = "announce@lists.horde.org, {$ml}@lists.horde.org"; if (!$this->latest) { $to .= ', i18n@lists.horde.org'; } if (!empty($this->options['noannounce'])) { print "NOT announcing release on {$to}\n"; return; } print "Announcing release to {$to}\n"; // Building headers $subject = $this->notes['name'] . ' ' . $this->sourceVersionString; if ($this->latest) { $subject .= ' (final)'; } $headers = array('From' => $this->options['ml']['from'], 'To' => $to, 'Subject' => $subject); // Building message text $body = $this->notes['ml']['changes']; if ($this->oldVersion) { $body .= "\n\n" . sprintf('The full list of changes (from version %s) can be viewed here:', $this->oldSourceVersionString) . "\n\n" . sprintf('http://cvs.horde.org/diff.php/%s/docs/CHANGES?r1=%s&r2=%s&ty=h', $module, $this->oldChangelogVersion, $this->changelogVersion); } $body .= "\n\n" . sprintf('The %s %s distribution is available from the following locations:', $this->notes['name'], $this->sourceVersionString) . "\n\n" . sprintf(' ftp://ftp.horde.org/pub/%s/%s', $module, $this->tarballName) . "\n" . sprintf(' http://ftp.horde.org/pub/%s/%s', $module, $this->tarballName); if ($this->makeDiff) { $body .= "\n\n" . sprintf('Patches against version %s are available at:', $this->oldSourceVersionString) . "\n\n" . sprintf(' ftp://ftp.horde.org/pub/%s/patches/%s.gz', $module, $this->patchName) . "\n" . sprintf(' http://ftp.horde.org/pub/%s/patches/%s.gz', $module, $this->patchName); } $body .= "\n\n" . 'Or, for quicker access, download from your nearest mirror:' . "\n\n" . ' http://www.horde.org/mirrors.php' . "\n\n" . 'MD5 sums for the packages are as follows:' . "\n\n" . ' ' . $this->tarballMD5[0] . "\n" . ' ' . $this->patchMD5[0] . "\n\n" . 'Have fun!' . "\n\n" . 'The Horde Team.'; // Building and sending message $message =& new MIME_Message('lists.horde.org'); $part =& new MIME_Part('text/plain', $body, 'iso-8859-1'); $message->addPart($part); $headers = $message->encode($headers, 'iso-8859-1'); $msg = $message->toString(); if (substr($msg, -1) != "\n") { $msg .= "\n"; } require_once 'Mail.php'; $mailer =& Mail::factory($this->options['mailer']['type'], $this->options['mailer']['params']); $result = $mailer->send(MIME::encodeAddress($to), $headers, $msg); if (is_a($result, 'PEAR_Error')) { print $result->getMessage() . "\n"; } }
/** * Sends a file download, invoking the browser's "Save As..." dialog. * * Exits after sending. Unlike the HTTP extension version, this function * also sends Content-Type, Content-Disposition, and "no-cache" headers. * * @param string $file Filepath to file to send. * @param string $filetype File type to send as, default is * 'application/octet-stream'. * @param string $filename Optional name to show to user - defaults to * basename($file). * @return void * @throws RuntimeException if headers already sent, or file is unreadable. */ public function sendFile($file, $filetype = 'download', $filename = null) { if (headers_sent($_file, $_line)) { throw new RuntimeException("Cannot send file - output started in '{$_file}' on line '{$_line}'."); } if (!file_exists($file) || !is_readable($file)) { throw new RuntimeException("Cannot send unknown or unreadable file {$file}."); } if (!isset($filename)) { $filename = basename($file); } header('Expires: 0'); header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); $this->sendContentType(MIME::get(strtolower($filetype), 'application/octet-stream')); $this->sendContentDisposition('attachment', $filename); // invalid without Content-Length header('Content-Length: ' . filesize($file)); header('Content-Transfer-Encoding: binary'); header('Connection: close'); readfile($file); exit; }
/** * Sends the email specified by $emailId to all recipients. * @param integer $emailId The id of the email message. * @param string $emailTable Optional the name of the table containing the email messages. * @param string $joinTable Optional the name of the table corresponding to a single recipient of the given email. * @param string $recipientsTable The name of the table where the recipients originated from. * @param string $emailColumn The name of the column that stored the email address. */ function sendMail($emailId, $emailTable = null, $joinTable = null, $recipientsTable = null, $emailColumn = null) { require_once dirname(__FILE__) . '/../lib/XPM/MIME.php'; if (isset($emailTable)) { $this->emailTable = $emailTable; } if (isset($joinTable)) { $this->joinTable = $joinTable; } if (isset($recipientsTable)) { $this->recipientsTable = $recipientsTable; } if (isset($emailColumn)) { $this->emailColumn = $emailColumn; } $app =& Dataface_Application::getInstance(); $conf =& $app->_conf; if (@$conf['_mail']['func']) { $mail_func = $conf['_mail']['func']; } else { $mail_func = 'mail'; } $emailTableObj =& Dataface_Table::loadTable($this->emailTable); $emailTableObj->addRelationship('recipients', array('__sql__' => 'select * from `' . $this->recipientsTable . '` r inner join `' . $this->joinTable . '` j on `r`.`' . $this->emailColumn . '` = j.recipient_email inner join `' . $this->emailTable . '` e on e.id = j.messageid where e.id=\'' . addslashes($emailId) . '\'')); $email = df_get_record($this->emailTable, array('id' => $emailId)); if (!$email) { return PEAR::raiseError("Failed to send email because no message with id {$emailId} could be found.", DATAFACE_E_ERROR); } $recipients = $email->getRelatedRecordObjects('recipients', 0, 500, 'sent=0'); foreach ($recipients as $recipient) { $values = $recipient->strvals(); $keys = array(); foreach ($values as $key => $val) { $keys[] = '/%' . $key . '%/'; } $values = array_values($values); $content = preg_replace($keys, $values, $recipient->strval('content')); $opt_out_url = df_absolute_url(DATAFACE_SITE_HREF . '?-action=email_opt_out&email=' . urlencode($recipient->val('recipient_email'))); $html_content = $content .= <<<END \t\t\t<hr /> <p>If you don't want to receive email updates from us, you can opt out of our mailing list by clicking <a href="{$opt_out_url}">here</a> .</p> END; $content .= <<<END ------------------------------------------------------------------ If you don't want to receive email updates from us, you can opt out of our mailing list by going to {$opt_out_url} . END; $headers = array(); if ($email->strval('from')) { $headers[] = "From: " . $email->strval('from'); $headers[] = "Reply-to: " . $email->strval('from'); } if (@$app->_conf['mail_host']) { $headers[] = 'Message-ID: <' . md5(uniqid(time())) . '@' . $app->_conf['mail_host'] . '>'; } //$headers[] = "Content-Type: text/plain; charset=".$app->_conf['oe']; $joinRecord = $recipient->toRecord($this->joinTable); if (!trim($recipient->val('recipient_email'))) { $joinRecord->setValue('success', 0); $joinRecord->setValue('sent', 1); $joinRecord->save(); unset($joinRecord); unset($recipient); continue; } // path to 'MIME.php' file from XPM4 package // get ID value (random) for the embed image $id = MIME::unique(); // set text/plain version of message $text = MIME::message(htmlspecialchars_decode(strip_tags(preg_replace(array('/<br[^>]*>/i', '/<div[^>]*>/i', '/<p[^>]*>/i', '/<table[^>]*>/i'), array("\r\n", "\r\n", "\r\n", "\r\n"), $content))), 'text/plain'); // set text/html version of message $html = MIME::message($html_content, 'text/html'); // add attachment with name 'file.txt' //$at[] = MIME::message('source file', 'text/plain', 'file.txt', 'ISO-8859-1', 'base64', 'attachment'); //$file = 'xpertmailer.gif'; // add inline attachment '$file' with name 'XPM.gif' and ID '$id' //$at[] = MIME::message(file_get_contents($file), FUNC::mime_type($file), 'XPM.gif', null, 'base64', 'inline', $id); // compose mail message in MIME format $mess = MIME::compose($text, $html); if (!$email->val('ignore_blacklist') and $this->isBlackListed($recipient->val('recipient_email'))) { echo "\nEmail address '" . $recipient->val('recipient_email') . "' is black listed so we do not send email to this address..."; $joinRecord->setValue('success', 0); $joinRecord->setValue('sent', 1); } else { if ($mail_func($recipient->strval('recipient_email'), $email->strval('subject'), $mess['content'], implode("\r\n", $headers) . "\r\n" . $mess['header'])) { $joinRecord->setValue('success', 1); $joinRecord->setValue('sent', 1); echo "Successfully sent email to " . $recipient->val('recipient_email'); //echo "Successfully sent email to {$recipient->strval('recipient_email')}" ; //exit; } else { $joinRecord->setValue('success', 0); $joinRecord->setValue('sent', 1); $this->messages[] = "Failed to send email to " . $email->val('recipient_email'); //echo "Failed to send"; //exit; } } $joinRecord->setValue('date_sent', date('Y-m-d H:i:s')); $joinRecord->save(); unset($joinRecord); unset($recipient); } }
function nulluhr() { global $db; update_all_ranks(); $db->query('DELETE FROM ' . DB_PRE . 'ecp_messages WHERE fromdel = 1 AND del = 1'); $result = $db->query('SELECT ID FROM ' . DB_PRE . 'ecp_user WHERE (ondelete < ' . time() . ' AND ondelete != 0) OR (status = 0 AND registerdate < ' . (time() - DELETE_UNAKTIV * 86400) . ')'); while ($row = mysql_fetch_assoc($result)) { delete_user($row['ID']); } $result = $db->query('SELECT ID, money FROM ' . DB_PRE . 'ecp_user LEFT JOIN ' . DB_PRE . 'ecp_ranks ON (rID = rankID)'); while ($row = mysql_fetch_assoc($result)) { if ($row['money'] != '') { $db->query('UPDATE ' . DB_PRE . 'ecp_user_stats SET money = money + ' . $row['money'] . ' WHERE userID = ' . $row['ID']); } } if (BACKUP_AKTIV) { $last = $db->result(DB_PRE . 'ecp_stats', 'lastdbbackup', '1'); if (BACKUP_CYCLE == 'day' or $last + (BACKUP_CYCLE == 'month' ? 2592000 : 604800) < time()) { $backup_obj = new MySQL_Backup(); $backup_obj->server = MYSQL_HOST; $backup_obj->username = MYSQL_USER; $backup_obj->password = MYSQL_PASS; $backup_obj->database = MYSQL_DATABASE; $backup_obj->tables = array(); $backup_obj->drop_tables = true; $backup_obj->struct_only = false; $backup_obj->comments = true; $backup_obj->fname_format = 'd_m_y__H_i_s'; $string = get_random_string(8, 2); if ($backup_obj->Execute(MSB_SAVE, 'uploads/forum/' . $string . '.sql.gz', true)) { $m = new XMail(); // set from address and name $m->From(SITE_EMAIL); // add to address and name $m->AddTo(BACKUP_EMAIL); // set subject $m->Subject(BACKUP_AUTO); // set text/plain version of message $m->Text(DATE . ': ' . date('d.m.Y H:i:s')); // add attachment ('text/plain' file) $m->Attach(date('Y_m_d') . '.sql.gz', 'application/x-gzip'); $f = 'uploads/forum/' . $string . '.sql.gz'; $id = MIME::unique(); // add inline attachment '$f' file with ID '$id' $m->Attach(file_get_contents($f), FUNC::mime_type($f), null, null, null, 'attachment', $id); if (SMTP_AKTIV) { $c = $m->Connect(SMTP_HOST, (int) SMTP_PORT, SMTP_USER, SMTP_PASS, 'tls', 10, 'localhost', null, 'plain'); //or die(print_r($m->Result)); } if ($m->Send(SMTP_AKTIV ? $c : null)) { $db->query('UPDATE ' . DB_PRE . 'ecp_stats SET lastdbbackup = ' . strtotime('today 00:00:00')); } unlink('uploads/forum/' . $string . '.sql.gz'); } } } $result = $db->query('SELECT attachID, strname FROM ' . DB_PRE . 'ecp_forum_attachments WHERE (tID = 0 OR bID = 0) AND uploadzeit < ' . (time() - 1000)); while ($row = $db->fetch_assoc()) { @unlink('upload/forum/' . $row['attachID'] . '_' . $row['strname']); } $db->query('DELETE FROM ' . DB_PRE . 'ecp_forum_attachments WHERE (tID = 0 OR bID = 0) AND uploadzeit < ' . (time() - 1000)); // Buchungen durchf�hren $buchresult = $db->query('SELECT `ID`, `verwendung`, `intervall`, `betrag`, `nextbuch`, `tagmonat` FROM ' . DB_PRE . 'ecp_clankasse_auto WHERE nextbuch <= \'' . time() . '\''); while ($row = mysql_fetch_assoc($buchresult)) { $db->query('INSERT INTO ' . DB_PRE . 'ecp_clankasse_transaktion (`geld`, `verwendung`, `datum`, `userID`) VALUES (-' . $row['betrag'] . ', \'' . mysql_real_escape_string($row['verwendung']) . '\', ' . time() . ', 0)'); $db->query('UPDATE ' . DB_PRE . 'ecp_clankasse SET kontostand = kontostand - ' . $row['betrag']); switch ($row['tagmonat']) { case 1: $nextdate = strtotime('+ ' . (int) $row['intervall'] . ' month'); break; case 15: $nextdate = strtotime('+ ' . (int) $row['intervall'] . ' month'); break; case 28: $nextdate = strtotime('+ ' . (int) $row['intervall'] . ' month'); } $db->query('UPDATE ' . DB_PRE . 'ecp_clankasse_auto SET `nextbuch` = \'' . $nextdate . '\''); } $db->query('DELETE FROM ' . DB_PRE . 'ecp_forum_search WHERE datum < ' . (time() - 86400)); $result = $db->query('SELECT COUNT(sID) as anzahl, sID FROM ' . DB_PRE . 'ecp_server_stats GROUP BY sID'); while ($row = mysql_fetch_assoc($result)) { if ($row['anzahl'] > SERVER_MAX_LOG) { $db->query('DELETE FROM ' . DB_PRE . 'ecp_server_stats WHERE sID = ' . $row['sID'] . ' ORDER BY datum ASC LIMIT ' . ($row['anzahl'] - SERVER_MAX_LOG)); } } }
/** * This function takes in an array of the address objects generated by the message headers and turns them into an * associative array. * * @param array $addresses * @return array */ protected function processAddressObject($addresses) { $outputAddresses = array(); if (is_array($addresses)) { foreach ($addresses as $address) { if (property_exists($address, 'mailbox') && $address->mailbox != 'undisclosed-recipients') { $currentAddress = array(); $currentAddress['address'] = $address->mailbox . '@' . $address->host; if (isset($address->personal)) { $currentAddress['name'] = MIME::decode($address->personal, self::$charset); } $outputAddresses[] = $currentAddress; } } } return $outputAddresses; }
/** * @param $text */ protected function setFileName($text) { $this->filename = MIME::decode($text, Message::$charset); }
public function getMimeType() { if (!$this->object) { return NULL; } if (!$this->mime_type) { $mime = new MIME(Config::MIME_CACHE_PATH); $this->mime_type = $mime->bufferGetType($this->object->data, $this->getName()); } return $this->mime_type; }
// from mail address $to = '*****@*****.**'; // to mail address $subj = 'Hello World!'; // mail subject $text = 'Text version of message.'; // text/plain version of message $html = '<b>HTML</b> version of <u>message</u>.'; // text/html version of message // CONFIGURATION ------------------ // set text/plain version of message $msg1 = MIME::message($text, 'text/plain'); // set text/html version of message $msg2 = MIME::message($html, 'text/html'); // compose message in MIME format $mess = MIME::compose($msg1, $msg2); // standard mail message RFC2822 $body = 'From: ' . $from . "\r\n" . 'To: ' . $to . "\r\n" . 'Subject: ' . $subj . "\r\n" . $mess['header'] . "\r\n\r\n" . $mess['content']; // get client hostname $expl = explode('@', $to); // connect to SMTP server (direct) from MX hosts list $conn = SMTP::mxconnect($expl[1]) or die(print_r($_RESULT)); // send mail $sent = SMTP::send($conn, array($to), $body, $from); // print result if ($sent) { echo 'Sent !'; } else { print_r($_RESULT); } // disconnect from SMTP server
/** * Возвращает MIME-тип файла * * @return string */ protected function get_mime_type() { return $this->mime_type ? $this->mime_type : ($this->mime_type = MIME::type_for_file($this->original_name)); }
/* Purpose: - set Text and HTML version of message - add attachment - embed image into HTML */ // manage errors error_reporting(E_ALL); // php errors define('DISPLAY_XPM4_ERRORS', true); // display XPM4 errors //define('LOG_XPM4_ERRORS', serialize(array('type' => 1, 'destination' => '*****@*****.**', 'headers' => 'From: xpm4@domain.tld'))); // <- send mail //define('LOG_XPM4_ERRORS', serialize(array('type' => 3, 'destination' => '/var/tmp/XPM4.log'))); // <- append file // path to 'MIME.php' file from XPM4 package require_once '../MIME.php'; // get ID value (random) for the embed image $id = MIME::unique(); // set text/plain version of message $text = MIME::message('Text version of message.', 'text/plain'); // set text/html version of message $html = MIME::message('<b>HTML</b> version of <u>message</u>.<br><i>Powered by</i> <img src="cid:' . $id . '">', 'text/html'); // add attachment with name 'file.txt' $at[] = MIME::message('source file', 'text/plain', 'file.txt', 'ISO-8859-1', 'base64', 'attachment'); $file = 'xpertmailer.gif'; // add inline attachment '$file' with name 'XPM.gif' and ID '$id' $at[] = MIME::message(file_get_contents($file), FUNC::mime_type($file), 'XPM.gif', null, 'base64', 'inline', $id); // compose mail message in MIME format $mess = MIME::compose($text, $html, $at); // send mail $send = mail('*****@*****.**', 'Hello World!', $mess['content'], 'From: me@myaddress.net' . "\n" . $mess['header']); // print result echo $send ? 'Sent !' : 'Error !';
/** * Кодирует текст * * @param string $text */ public function encode($text) { return MIME::encode_qp($text, $this->length); }
/** * Check that the From header is not trying to impersonate a valid * user that is not $sasluser. * * @param string $sasluser The current, authenticated user. * @param string $sender Sender address * @param string $fromhdr From header * @param string $client_addr Client IP * * @return mixed A PEAR_Error in case of an error, true if From * can be accepted, false if From must be rejected, * or a string with a corrected From header that * makes From acceptable */ function _verify_sender($sasluser, $sender, $fromhdr, $client_addr) { global $conf; if (isset($conf['kolab']['filter']['email_domain'])) { $domains = $conf['kolab']['filter']['email_domain']; } else { $domains = 'localhost'; } if (!is_array($domains)) { $domains = array($domains); } if (isset($conf['kolab']['filter']['local_addr'])) { $local_addr = $conf['kolab']['filter']['local_addr']; } else { $local_addr = '127.0.0.1'; } if (empty($client_addr)) { $client_addr = $local_addr; } if (isset($conf['kolab']['filter']['verify_subdomains'])) { $verify_subdomains = $conf['kolab']['filter']['verify_subdomains']; } else { $verify_subdomains = true; } if (isset($conf['kolab']['filter']['reject_forged_from_header'])) { $reject_forged_from_header = $conf['kolab']['filter']['reject_forged_from_header']; } else { $reject_forged_from_header = false; } if (isset($conf['kolab']['filter']['kolabhosts'])) { $kolabhosts = $conf['kolab']['filter']['kolabhosts']; } else { $kolabhosts = 'localhost'; } if (isset($conf['kolab']['filter']['privileged_networks'])) { $privnetworks = $conf['kolab']['filter']['privileged_networks']; } else { $privnetworks = '127.0.0.0/8'; } /* Allow anything from localhost and * fellow Kolab-hosts */ if ($client_addr == $local_addr) { return true; } $kolabhosts = explode(',', $kolabhosts); $kolabhosts = array_map('gethostbyname', $kolabhosts); $privnetworks = explode(',', $privnetworks); if (array_search($client_addr, $kolabhosts) !== false) { return true; } foreach ($privnetworks as $network) { $iplong = ip2long($client_addr); $cidr = explode("/", $network); $netiplong = ip2long($cidr[0]); if (count($cidr) == 2) { $iplong = $iplong & 0xffffffff << 32 - $cidr[1]; $netiplong = $netiplong & 0xffffffff << 32 - $cidr[1]; } if ($iplong == $netiplong) { return true; } } if ($sasluser) { /* Load the Server library */ require_once 'Horde/Kolab/Server.php'; $server =& Horde_Kolab_Server::singleton(); if (is_a($server, 'PEAR_Error')) { $server->code = OUT_LOG | EX_TEMPFAIL; return $server; } $allowed_addrs = $server->addrsForIdOrMail($sasluser); if (is_a($allowed_addrs, 'PEAR_Error')) { $allowed_addrs->code = OUT_LOG | EX_NOUSER; return $allowed_addrs; } } else { $allowed_addrs = false; } if (isset($conf['kolab']['filter']['unauthenticated_from_insert'])) { $fmt = $conf['kolab']['filter']['unauthenticated_from_insert']; } else { $fmt = '(UNTRUSTED, sender <%s> is not authenticated)'; } $adrs = imap_rfc822_parse_adrlist($fromhdr, $domains[0]); foreach ($adrs as $adr) { $from = $adr->mailbox . '@' . $adr->host; $fromdom = $adr->host; if ($sasluser) { if (!in_array(strtolower($from), $allowed_addrs)) { Horde::log(sprintf("%s is not an allowed From address for %s", $from, $sasluser), 'DEBUG'); return false; } } else { foreach ($domains as $domain) { if (strtolower($fromdom) == $domain || $verify_subdomains && substr($fromdom, -strlen($domain) - 1) == ".{$domain}") { if ($reject_forged_from_header) { Horde::log(sprintf("%s is not an allowed From address for unauthenticated users.", $from), 'DEBUG'); return false; } else { require_once 'Horde/String.php'; require_once 'Horde/MIME.php'; /* Rewrite */ Horde::log(sprintf("%s is not an allowed From address for unauthenticated users, rewriting.", $from), 'DEBUG'); if (property_exists($adr, 'personal')) { $name = str_replace(array("\\", '"'), array("\\\\", '\\"'), MIME::decode($adr->personal, 'utf-8')); } else { $name = ''; } $untrusted = sprintf($fmt, $sender, $from, $name); // Is this test really correct? Is $fromhdr a _decoded_ string? // If not comparing with the unencoded $untrusted is wrong. // sw - 20091125 if (strpos($fromhdr, $untrusted) === false) { $new_from = '"' . MIME::encode($untrusted) . '"'; return $new_from . ' <' . $from . '>'; } else { return true; } } } } } } /* All seems OK */ return true; }
/** * Возвращает следующий элемент итератора * */ public function next() { $this->current = ($line = $this->read_line()) === null ? null : MIME::decode_qp($line); $this->count++; }