Webylon 3.1 API Docs
  • Package
  • Function
  • Tree
  • Deprecated
  • Download
Version: current
  • 3.2
  • 3.1

Packages

  • auth
  • Booking
  • cart
    • shipping
    • steppedcheckout
  • Catalog
  • cms
    • assets
    • batchaction
    • batchactions
    • bulkloading
    • comments
    • content
    • core
    • export
    • newsletter
    • publishers
    • reports
    • security
    • tasks
  • Dashboard
  • DataObjectManager
  • event
  • faq
  • forms
    • actions
    • core
    • fields-basic
    • fields-dataless
    • fields-datetime
    • fields-files
    • fields-formatted
    • fields-formattedinput
    • fields-relational
    • fields-structural
    • transformations
    • validators
  • googlesitemaps
  • guestbook
  • installer
  • newsletter
  • None
  • photo
    • gallery
  • PHP
  • polls
  • recaptcha
  • sapphire
    • api
    • bulkloading
    • control
    • core
    • cron
    • dev
    • email
    • fields-formattedinput
    • filesystem
    • formatters
    • forms
    • i18n
    • integration
    • misc
    • model
    • parsers
    • search
    • security
    • tasks
    • testing
    • tools
    • validation
    • view
    • widgets
  • seo
    • open
      • graph
  • sfDateTimePlugin
  • spamprotection
  • stealth
    • captha
  • subsites
  • userform
    • pagetypes
  • userforms
  • webylon
  • widgets

Classes

  • Address
  • AddSubsiteTask
  • Announcement
  • AnnouncementDecorator
  • AnnouncementHolder
  • AssociatedFolderDecorator
  • AttachedFiles
  • AudioPhpCaptcha
  • AutoCompleteField
  • BaseMediawebImportParser
  • BookingOrder_StatusLog
  • CalendarUtil
  • CalendarWidgetExtention
  • CatalogCatalogLinkedDecorator
  • CatalogImportTask
  • CatalogOldFieldsDecorator
  • CatalogProductLinkedDecorator
  • CheckoutStep_ShippingMethod
  • ChequePayment
  • ClearHistoryTask
  • ClientEmailOrderNotification_SiteConfig
  • ClientVKOrderNotification_SiteConfig
  • CommentsSiteConfig
  • ContactsPage
  • CookieExtention
  • CostTableShippingRate
  • CustomMenu
  • CustomMenuAdmin
  • CustomMenuDecorator
  • CustomMenuHolder
  • CustomMenuItem
  • CustomPayment
  • DataObjectLoggerExtension
  • DataObjectSubsites
  • DefaultCMSActionDecorator
  • DeleteOldAssociatedFoldersTask
  • DocPage
  • DocumentDirection
  • DocumentHaving
  • DocumentSearchForm
  • DocumentSiteConfig
  • DocumentsPage
  • DocumentType
  • DOMUtil
  • ExtendPageAnnouncement
  • ExtendPageNews
  • ExtendPagePoll
  • FileOversizeDecorator
  • FindCyrillicSiteConfig
  • FolderRenameTask
  • GDMergeAlpha
  • HomePage
  • ImageAutoResize
  • ImageResizeTask
  • ImportAdmin
  • ImportAutoStartTask
  • ImportCatalogMessage
  • ImportConfig
  • ImportLog
  • ImportSiteConfig
  • ImportTask
  • LoggerAdmin
  • LogItem
  • ManagerEmailOrderNotification_SiteConfig
  • MapObject
  • MapObjectGroup
  • MapPage
  • MediawebForm
  • MediawebImportParser
  • MemberLoggerExtension
  • MultiUploadConfig
  • NearestEventExtention
  • NewDocumentsAdmin
  • News_Controller
  • NewsEntry
  • NewsEntry_Controller
  • NewsHolder
  • NewsHolder_Controller
  • NewsLiveCalendarWidget
  • NewsSiteConfig
  • Order_StatusLog
  • Orders1CExchange
  • PageHideFieldsExtension
  • PageInformerRates
  • PageInformerWeather
  • Payment_Failure
  • Payment_Processing
  • Payment_Result
  • Payment_Success
  • PaymentMethod
  • PaymentSiteConfig
  • PayPalPayment
  • PayPalPayment_Handler
  • PhoneField
  • PhotoAlbumExtentions
  • PhpCaptcha
  • PhpCaptchaColour
  • PhpCaptchaField
  • phpMorphy
  • phpMorphy_AncodesResolver_AsIs
  • phpMorphy_AncodesResolver_Proxy
  • phpMorphy_AncodesResolver_ToDialingAncodes
  • phpMorphy_AncodesResolver_ToText
  • phpMorphy_AnnotDecoder_Base
  • phpMorphy_AnnotDecoder_Common
  • phpMorphy_AnnotDecoder_Factory
  • phpMorphy_AnnotDecoder_Predict
  • phpMorphy_FilesBundle
  • phpMorphy_Fsa
  • phpMorphy_Fsa_Decorator
  • phpMorphy_Fsa_Proxy
  • phpMorphy_Fsa_Sparse_File
  • phpMorphy_Fsa_Sparse_Mem
  • phpMorphy_Fsa_Sparse_Shm
  • phpMorphy_Fsa_Tree_File
  • phpMorphy_Fsa_Tree_Mem
  • phpMorphy_Fsa_Tree_Shm
  • phpMorphy_Fsa_WordsCollector
  • phpMorphy_GramInfo
  • phpMorphy_GramInfo_AncodeCache
  • phpMorphy_GramInfo_Decorator
  • phpMorphy_Graminfo_File
  • phpMorphy_Graminfo_Mem
  • phpMorphy_GramInfo_Proxy
  • phpMorphy_GramInfo_Proxy_WithHeader
  • phpMorphy_GramInfo_RuntimeCaching
  • phpMorphy_Graminfo_Shm
  • phpMorphy_GrammemsProvider_Base
  • phpMorphy_GrammemsProvider_Decorator
  • phpMorphy_GrammemsProvider_Empty
  • phpMorphy_GrammemsProvider_Factory
  • phpMorphy_GrammemsProvider_ForFactory
  • phpMorphy_GrammemsProvider_ru_RU
  • phpMorphy_GramTab
  • phpMorphy_GramTab_Empty
  • phpMorphy_GramTab_Proxy
  • phpMorphy_Link
  • phpMorphy_Link_Annot
  • phpMorphy_Link_Base
  • phpMorphy_Morphier_Base
  • phpMorphy_Morphier_Bulk
  • phpMorphy_Morphier_Common
  • phpMorphy_Morphier_Empty
  • phpMorphy_Morphier_Finder_Base
  • phpMorphy_Morphier_Finder_Common
  • phpMorphy_Morphier_Finder_Predict_Databse
  • phpMorphy_Morphier_Finder_Predict_Suffix
  • phpMorphy_Morphier_Helper
  • phpMorphy_Morphier_Predict_Database
  • phpMorphy_Morphier_Predict_Suffix
  • phpMorphy_Morphier_PredictCollector
  • phpMorphy_Semaphore
  • phpMorphy_Semaphore_Empty
  • phpMorphy_Semaphore_Nix
  • phpMorphy_Semaphore_Win
  • phpMorphy_Shm_Cache
  • phpMorphy_Shm_Cache_FileDescriptor
  • phpMorphy_Shm_Header
  • phpMorphy_Source_Dba
  • phpMorphy_Source_Fsa
  • phpMorphy_State
  • phpMorphy_Storage
  • phpMorphy_Storage_Factory
  • phpMorphy_Storage_File
  • phpMorphy_Storage_Mem
  • phpMorphy_Storage_Proxy
  • phpMorphy_Storage_Shm
  • phpMorphy_UnicodeHelper
  • phpMorphy_UnicodeHelper_Base
  • phpMorphy_UnicodeHelper_MultiByteFixed
  • phpMorphy_UnicodeHelper_singlebyte
  • phpMorphy_UnicodeHelper_ucs_2be
  • phpMorphy_UnicodeHelper_ucs_2le
  • phpMorphy_UnicodeHelper_ucs_4be
  • phpMorphy_UnicodeHelper_ucs_4le
  • phpMorphy_UnicodeHelper_utf_16_Base
  • phpMorphy_UnicodeHelper_utf_16be
  • phpMorphy_UnicodeHelper_utf_16le
  • phpMorphy_UnicodeHelper_utf_32_Base
  • phpMorphy_UnicodeHelper_utf_32be
  • phpMorphy_UnicodeHelper_utf_32le
  • phpMorphy_UnicodeHelper_utf_8
  • phpMorphy_WordDescriptor
  • phpMorphy_WordDescriptor_Collection
  • phpMorphy_WordDescriptor_Collection_Serializer
  • phpMorphy_WordForm
  • ProductImportV1Decorator
  • ProductOldFieldsDecorator
  • ProductProductLinkedDecorator
  • PublHolder
  • Publication
  • PublicationSiteTree
  • RatingDataObject
  • RatingExtension
  • RealtySiteConfigDecorator
  • RecentComments
  • RecentFiles
  • RecentPages
  • RelatedPageLink
  • RepairImportTask
  • RoomRate_PriceField
  • RussianUpLower
  • SberbankPayment
  • SberbankPayment_Handler
  • SetMainSiteHomePageTypeTask
  • ShippingEstimator
  • ShippingPackage
  • ShowUserFromExtension
  • SiteConfigDecorator
  • SiteConfigSubsites
  • SiteTreeSubsites
  • SMSCOrderNotification_SiteConfig
  • SMSOrderNotification_SiteConfig
  • SortCMSActionDecorator
  • SS_Report_FakeQuery
  • SSMorphy
  • SSNController
  • SteppedCheckout_PageMessages
  • SubpageListField
  • SubscribeFormAllPagesExtension
  • SubsiteDropdownField
  • SubsiteReportWrapper
  • TableShippingRate
  • UnitellerPayment
  • UnitellerPayment_Handler
  • UnmoderatedComments
  • VideoManager
  • VideoSiteConfig
  • WatermarkImage
  • WatermarkSiteConfig
  • WebylonImportAdmin
  • WebylonImportCatalog
  • WeightTableShippingRate
  • XMLValidate
  • YaMoneyPayment
  • YaMoneyPayment_Handler
  • YMLExporter
  • YMLSiteConfig

Interfaces

  • ImportInterface
  • PaymentObjectInterface
  • phpMorphy_AncodesResolver_Interface
  • phpMorphy_AnnotDecoder_Interface
  • phpMorphy_Fsa_Interface
  • phpMorphy_GramInfo_Interace
  • phpMorphy_GrammemsProvider_Interface
  • phpMorphy_GramTab_Interface
  • phpMorphy_Morphier_Finder_Interface
  • phpMorphy_Morphier_Interface
  • phpMorphy_Shm_Cache_Interface
  • phpMorphy_Source_Interface

Exceptions

  • phpMorphy_Exception

Functions

  • column_sort
  • column_sort_callback_basic
  • encodeFileForEmail
  • encodeMultipart
  • getMimeType
  • htmlEmail
  • loadMimeTypes
  • phpmorphy_overload_mb_funcs
  • plaintextEmail
  • processHeaders
  • QuotedPrintable_encode
  • supressOutput
  • validateError
  • validEmailAddr
  • wrapImagesInline
  • wrapImagesInline_rewriter
  1 <?php
  2 /**
  3  * Mailer objects are responsible for actually sending emails.
  4  * The default Mailer class will use PHP's mail() function.
  5  * 
  6  * @package sapphire
  7  * @subpackage email
  8  */
  9 class Mailer extends Object {
 10         
 11     /**
 12      * Отправитель для тех случаев когда пиьсмо не принимается
 13      */
 14     protected static $fallback_sender = 'trash@mediaweb.ru';
 15     
 16     static function set_fallback_sender($value) {
 17         self::$fallback_sender = validEmailAddr($value);
 18     }
 19     
 20     static function get_fallback_sender() {
 21         return self::$fallback_sender;
 22     }
 23     
 24     /**
 25      * Send a plain-text email.
 26      *  
 27      * @param string $to
 28      * @param string $from
 29      * @param string §subject
 30      * @param string $plainContent
 31      * @param bool $attachedFiles
 32      * @param array $customheaders
 33      * @return bool
 34      */
 35     function sendPlain($to, $from, $subject, $plainContent, $attachedFiles = false, $customheaders = false) {
 36         return plaintextEmail($to, $from, $subject, $plainContent, $attachedFiles, $customheaders);
 37     }
 38     
 39     /**
 40      * Send a multi-part HTML email.
 41      * 
 42      * @return bool
 43      */
 44     function sendHTML($to, $from, $subject, $htmlContent, $attachedFiles = false, $customheaders = false, $plainContent = false, $inlineImages = false) {
 45         return htmlEmail($to, $from, $subject, $htmlContent, $attachedFiles, $customheaders, $plainContent, $inlineImages);
 46     }
 47 
 48     /**
 49      * Заменяет отправителя в заголовках письма
 50      * 
 51      * @param mixed $headers    строка или массив с заголовками письма
 52      * @param string $sender    новый отправитель (по-умолчанию @link Mailer::get_fallback_sender())
 53      * 
 54      * @return mixed    обновленные заголовки
 55      */
 56     static function replace_sender($headers, $sender = false) {
 57         if (!$sender) 
 58             $sender = self::get_fallback_sender();
 59         
 60         // $sender may be a just email like 'user@domain.com' or have human name like '"User Name" <user@domain.com>'
 61         // Add hostname if not human name in $sender
 62         if (isset($_SERVER['HTTP_HOST']) && strpos($sender, '<') === false)
 63             $sender = sprintf('"%s" <%s>', $_SERVER['HTTP_HOST'], $sender);
 64         
 65         return preg_replace('/(From|Sender): .*/i', '$1: ' . validEmailAddr($sender), $headers);
 66     }
 67 }
 68 
 69 // TO DO: Clean this code up, make it more OO.
 70 // For now, we've just put a clean interface around this dirty code :)
 71 
 72 /*
 73  * Sends an email as a both HTML and plaintext
 74  *   $attachedFiles should be an array of file names
 75  *    - if you pass the entire $_FILES entry, the user-uploaded filename will be preserved
 76  *   use $plainContent to override default plain-content generation
 77  * 
 78  * @return bool
 79  */
 80 function htmlEmail($to, $from, $subject, $htmlContent, $attachedFiles = false, $customheaders = false, $plainContent = false, $inlineImages = false) {
 81     if ($customheaders && is_array($customheaders) == false) {
 82         echo "htmlEmail($to, $from, $subject, ...) could not send mail: improper \$customheaders passed:<BR>";
 83         dieprintr($headers);
 84     }
 85 
 86     $from = validEmailAddr($from);
 87     $to = validEmailAddr($to);
 88     
 89     $subjectIsUnicode = true;
 90     $bodyIsUnicode = true;
 91     $plainEncoding = "";
 92     
 93     // We generate plaintext content by default, but you can pass custom stuff
 94     $plainEncoding = 'base64';
 95     if(!$plainContent) {
 96         $plainContent = Convert::xml2raw($htmlContent);
 97     }
 98 
 99 
100     // If the subject line contains extended characters, we must encode the 
101     $subject = Convert::xml2raw($subject);
102     if(isset($subjectIsUnicode) && $subjectIsUnicode)
103         $subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";
104 
105 
106     // Make the plain text part
107     $headers["Content-Type"] = "text/plain; charset=\"utf-8\"";
108     $headers["Content-Transfer-Encoding"] = $plainEncoding ? $plainEncoding : "8bit";
109 
110     $plainPart = processHeaders($headers, ($plainEncoding == "base64") ? chunk_split(base64_encode($plainContent),60) : wordwrap($plainContent,120));
111 
112     // Make the HTML part
113     $headers["Content-Type"] = "text/html; charset=\"utf-8\"";
114         
115     
116     // Add basic wrapper tags if the body tag hasn't been given
117     if(stripos($htmlContent, '<body') === false) {
118         $htmlContent =
119             "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" .
120             "<HTML><HEAD>\n" .
121             "<META http-equiv=Content-Type content=\"text/html; charset=utf-8\">\n" .
122             "<STYLE type=3Dtext/css></STYLE>\n\n".
123             "</HEAD>\n" .
124             "<BODY bgColor=#ffffff>\n" .
125                 $htmlContent .
126             "\n</BODY>\n" .
127             "</HTML>";
128     }
129 
130     if($inlineImages) {
131         $htmlPart = wrapImagesInline($htmlContent);
132     } else {
133         $headers["Content-Transfer-Encoding"] = "base64";
134         $htmlPart = processHeaders($headers, chunk_split(base64_encode($htmlContent),120));
135     }
136     
137     list($messageBody, $messageHeaders) = encodeMultipart(array($plainPart,$htmlPart), "multipart/alternative");
138 
139     // Messages with attachments are handled differently
140     if($attachedFiles && is_array($attachedFiles)) {
141         
142         // The first part is the message itself
143         $fullMessage = processHeaders($messageHeaders, $messageBody);
144         $messageParts = array($fullMessage);
145 
146         // Include any specified attachments as additional parts
147         foreach($attachedFiles as $file) {
148             if(isset($file['tmp_name']) && isset($file['name'])) {
149                 $messageParts[] = encodeFileForEmail($file['tmp_name'], $file['name']);
150             } else {
151                 $messageParts[] = encodeFileForEmail($file);
152             }
153         }
154             
155         // We further wrap all of this into another multipart block
156         list($fullBody, $headers) = encodeMultipart($messageParts, "multipart/mixed");
157 
158     // Messages without attachments do not require such treatment
159     } else {
160         $headers = $messageHeaders;
161         $fullBody = $messageBody;
162     }
163 
164     // Email headers
165     $headers["From"] = $from;
166     $headers["Reply-To"] = $from;
167 
168     // Messages with the X-SilverStripeMessageID header can be tracked
169     if(isset($customheaders["X-SilverStripeMessageID"]) && defined('BOUNCE_EMAIL')) {
170             $bounceAddress = BOUNCE_EMAIL;
171     } else {
172             $bounceAddress = $from;
173     }
174 
175     // Strip the human name from the bounce address
176     if(ereg('^([^<>]*)<([^<>]+)> *$', $bounceAddress, $parts)) $bounceAddress = $parts[2];  
177     
178     // $headers["Sender"]       = $from;
179     $headers["X-Mailer"]    = X_MAILER;
180     if (!isset($customheaders["X-Priority"])) $headers["X-Priority"]    = 3;
181     
182     $headers = array_merge((array)$headers, (array)$customheaders);
183 
184     // the carbon copy header has to be 'Cc', not 'CC' or 'cc' -- ensure this.
185     if (isset($headers['CC'])) { $headers['Cc'] = $headers['CC']; unset($headers['CC']); }
186     if (isset($headers['cc'])) { $headers['Cc'] = $headers['cc']; unset($headers['cc']); }
187     
188     // the carbon copy header has to be 'Bcc', not 'BCC' or 'bcc' -- ensure this.
189     if (isset($headers['BCC'])) {$headers['Bcc']=$headers['BCC']; unset($headers['BCC']); }
190     if (isset($headers['bcc'])) {$headers['Bcc']=$headers['bcc']; unset($headers['bcc']); }
191         
192     // Send the email
193     $headers = processHeaders($headers);
194     
195     // Try it without the -f option if it fails
196     if (!($result = @mail($to, $subject, $fullBody, $headers, "-f$bounceAddress"))) {
197         $result = mail($to, $subject, $fullBody, Mailer::replace_sender($headers));
198     }
199     
200     return $result;
201 }
202 
203 /*
204  * Send a plain text e-mail
205  */
206 function plaintextEmail($to, $from, $subject, $plainContent, $attachedFiles, $customheaders = false) {
207     $subjectIsUnicode = false;  
208     $plainEncoding = false; // Not ensurely where this is supposed to be set, but defined it false for now to remove php notices
209 
210     if ($customheaders && is_array($customheaders) == false) {
211         echo "htmlEmail($to, $from, $subject, ...) could not send mail: improper \$customheaders passed:<BR>";
212         dieprintr($headers);
213     }
214 
215     $from = validEmailAddr($from);
216     $to = validEmailAddr($to);
217     
218     if(strpos($subject,"&#") !== false) $subjectIsUnicode = true;
219 
220     // If the subject line contains extended characters, we must encode it
221     $subject = Convert::xml2raw($subject);
222     if($subjectIsUnicode)
223         $subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";
224 
225 
226     // Make the plain text part
227     $headers["Content-Type"] = "text/plain; charset=\"utf-8\"";
228     $headers["Content-Transfer-Encoding"] = $plainEncoding ? $plainEncoding : "quoted-printable";
229 
230     $plainContent = ($plainEncoding == "base64") ? chunk_split(base64_encode($plainContent),60) : QuotedPrintable_encode($plainContent);
231 
232     // Messages with attachments are handled differently
233     if(is_array($attachedFiles)) {
234         // The first part is the message itself
235         $fullMessage = processHeaders($headers, $plainContent);
236         $messageParts = array($fullMessage);
237 
238         // Include any specified attachments as additional parts
239         foreach($attachedFiles as $file) {
240             if(isset($file['tmp_name']) && isset($file['name'])) {
241                 $messageParts[] = encodeFileForEmail($file['tmp_name'], $file['name']);
242             } else {
243                 $messageParts[] = encodeFileForEmail($file);
244             }
245         }
246         
247 
248         // We further wrap all of this into another multipart block
249         list($fullBody, $headers) = encodeMultipart($messageParts, "multipart/mixed");
250 
251     // Messages without attachments do not require such treatment
252     } else {
253         $fullBody = $plainContent;
254     }
255 
256     // Email headers
257     $headers["From"] = $from;
258     $headers["Reply-To"] = $from;
259 
260     // Messages with the X-SilverStripeMessageID header can be tracked
261     if(isset($customheaders["X-SilverStripeMessageID"]) && defined('BOUNCE_EMAIL')) {       
262         $bounceAddress = BOUNCE_EMAIL;
263         // Get the human name from the from address, if there is one
264         if(ereg('^([^<>]+)<([^<>])> *$', $from, $parts))
265             $bounceAddress = "$parts[1]<$bounceAddress>";
266     } else {
267         $bounceAddress = $from;
268     }
269     
270     // $headers["Sender"]       = $from;
271     $headers["X-Mailer"]    = X_MAILER;
272     if(!isset($customheaders["X-Priority"])) {
273         $headers["X-Priority"]  = 3;
274     }
275     
276     $headers = array_merge((array)$headers, (array)$customheaders);
277 
278     // the carbon copy header has to be 'Cc', not 'CC' or 'cc' -- ensure this.
279     if (isset($headers['CC'])) { $headers['Cc'] = $headers['CC']; unset($headers['CC']); }
280     if (isset($headers['cc'])) { $headers['Cc'] = $headers['cc']; unset($headers['cc']); }
281         
282     // Send the email
283     $headers = processHeaders($headers);
284 
285     // Try it without the -f option if it fails
286     if(!$result = @mail($to, $subject, $fullBody, $headers, "-f$bounceAddress")) {
287         $result = mail($to, $subject, $fullBody, Mailer::replace_sender($headers));
288     }
289     
290     return $result;
291 }
292 
293 
294 function encodeMultipart($parts, $contentType, $headers = false) {
295     $separator = "----=_NextPart_" . ereg_replace('[^0-9]','',rand() * 10000000000);
296 
297 
298     $headers["MIME-Version"] = "1.0";
299     $headers["Content-Type"] = "$contentType; boundary=\"$separator\"";
300     $headers["Content-Transfer-Encoding"] = "7bit";
301 
302     if($contentType == "multipart/alternative") {
303         //$baseMessage = "This is an encoded HTML message.  There are two parts: a plain text and an HTML message, open whatever suits you better.";
304         $baseMessage = "\nThis is a multi-part message in MIME format.";
305     } else {
306         //$baseMessage = "This is a message containing attachments.  The e-mail body is contained in the first attachment";
307         $baseMessage = "\nThis is a multi-part message in MIME format.";
308     }
309 
310 
311     $separator = "\n--$separator\n";
312     $body = "$baseMessage\n" .
313         $separator . implode("\n".$separator, $parts) . "\n" . trim($separator) . "--";
314 
315     return array($body, $headers);
316 }
317 
318 /*
319  * Return a multipart/related e-mail chunk for the given HTML message and its linked images
320  * Decodes absolute URLs, accessing the appropriate local images
321  */
322 function wrapImagesInline($htmlContent) {
323     global $_INLINED_IMAGES;
324     $_INLINED_IMAGES = null;
325     
326     $replacedContent = imageRewriter($htmlContent, 'wrapImagesInline_rewriter($URL)');
327     
328     
329     // Make the HTML part
330     $headers["Content-Type"] = "text/html; charset=\"utf-8\"";
331     $headers["Content-Transfer-Encoding"] = "quoted-printable";
332     $multiparts[] = processHeaders($headers, QuotedPrintable_encode($replacedContent));
333     
334     // Make all the image parts     
335     global $_INLINED_IMAGES;
336     foreach($_INLINED_IMAGES as $url => $cid) {
337         $multiparts[] = encodeFileForEmail($url, false, "inline", "Content-ID: <$cid>\n");      
338     }
339 
340     // Merge together in a multipart
341     list($body, $headers) = encodeMultipart($multiparts, "multipart/related");
342     return processHeaders($headers, $body);
343 }
344 function wrapImagesInline_rewriter($url) {
345     $url = relativiseURL($url);
346     
347     global $_INLINED_IMAGES;
348     if(!$_INLINED_IMAGES[$url]) {
349         $identifier = "automatedmessage." . rand(1000,1000000000) . "@silverstripe.com";
350         $_INLINED_IMAGES[$url] = $identifier;
351     }
352     return "cid:" . $_INLINED_IMAGES[$url];
353     
354 }
355 
356 /*
357  * Combine headers w/ the body into a single string.
358  */
359 function processHeaders($headers, $body = false) {
360     $res = '';
361     if(is_array($headers)) while(list($k, $v) = each($headers))
362         $res .= "$k: $v\n";
363     if($body) $res .= "\n$body";
364     return $res;
365 }
366 
367 /**
368  * Encode the contents of a file for emailing, including headers
369  * 
370  * $file can be an array, in which case it expects these members:
371  *   'filename'        - the filename of the file
372  *   'contents'        - the raw binary contents of the file as a string
373  *  and can optionally include these members:
374  *   'mimetype'        - the mimetype of the file (calculated from filename if missing)
375  *   'contentLocation' - the 'Content-Location' header value for the file
376  *   
377  * $file can also be a string, in which case it is assumed to be the filename
378  * 
379  * h5. contentLocation
380  * 
381  * Content Location is one of the two methods allowed for embedding images into an html email. It's also the simplest, and best supported
382  * 
383  * Assume we have an email with this in the body:
384  * 
385  *   <img src="http://example.com/image.gif" />
386  * 
387  * To display the image, an email viewer would have to download the image from the web every time it is displayed. Due to privacy issues, most
388  * viewers will not display any images unless the user clicks 'Show images in this email'. Not optimal.
389  * 
390  * However, we can also include a copy of this image as an attached file in the email. By giving it a contentLocation of "http://example.com/image.gif"
391  * most email viewers will use this attached copy instead of downloading it. Better, most viewers will show it without a 'Show images in this email'
392  * conformation.
393  * 
394  * Here is an example of passing this information through Email.php:
395  * 
396  *   $email = new Email();
397  *   $email->attachments[] = array(
398  *     'filename' => BASE_PATH . "/themes/mytheme/images/header.gif",
399  *     'contents' => file_get_contents(BASE_PATH . "/themes/mytheme/images/header.gif"),
400  *     'mimetype' => 'image/gif',
401  *     'contentLocation' => Director::absoluteBaseURL() . "/themes/mytheme/images/header.gif"
402  *   );
403  * 
404  */
405 function encodeFileForEmail($file, $destFileName = false, $disposition = NULL, $extraHeaders = "") {    
406     if(!$file) {
407         user_error("encodeFileForEmail: not passed a filename and/or data", E_USER_WARNING);
408         return;
409     }
410     
411     if (is_string($file)) {
412         $file = array('filename' => $file);
413         $fh = fopen($file['filename'], "rb");
414         if ($fh) {
415             while(!feof($fh)) $file['contents'] .= fread($fh, 10000);   
416             fclose($fh);
417         }
418     }
419 
420     // Build headers, including content type
421     if(!$destFileName) $base = basename($file['filename']);
422     else $base = $destFileName;
423 
424     $mimeType = $file['mimetype'] ? $file['mimetype'] : getMimeType($file['filename']);
425     if(!$mimeType) $mimeType = "application/unknown";
426         
427     if (empty($disposition)) $disposition = isset($file['contentLocation']) ? 'inline' : 'attachment';
428     
429     // Encode for emailing
430     if (substr($file['mimetype'], 0, 4) != 'text') {
431         $encoding = "base64";
432         $file['contents'] = chunk_split(base64_encode($file['contents']));
433     } else {
434         // This mime type is needed, otherwise some clients will show it as an inline attachment
435         $mimeType = 'application/octet-stream';
436         $encoding = "quoted-printable";     
437         $file['contents'] = QuotedPrintable_encode($file['contents']);      
438     }
439 
440     $headers = "Content-type: $mimeType;\n\tname=\"$base\"\n".
441                "Content-Transfer-Encoding: $encoding\n".
442                "Content-Disposition: $disposition;\n\tfilename=\"$base\"\n" ;
443     
444     if ( isset($file['contentLocation']) ) $headers .= 'Content-Location: ' . $file['contentLocation'] . "\n" ;
445     
446     $headers .= $extraHeaders . "\n";
447 
448     // Return completed packet
449     return $headers . $file['contents'];
450 }
451 
452 function QuotedPrintable_encode($quotprint) {       
453         $quotprint = (string) str_replace('\r\n',chr(13).chr(10),$quotprint);
454         $quotprint = (string) str_replace('\n',  chr(13).chr(10),$quotprint);
455         $quotprint = (string) preg_replace("~([\x01-\x1F\x3D\x7F-\xFF])~e", "sprintf('=%02X', ord('\\1'))", $quotprint);
456         //$quotprint = (string) str_replace('\=0D=0A',"=0D=0A",$quotprint);
457         $quotprint = (string) str_replace('=0D=0A',"\n",$quotprint);    
458         $quotprint = (string) str_replace('=0A=0D',"\n",$quotprint);    
459         $quotprint = (string) str_replace('=0D',"\n",$quotprint);   
460         $quotprint = (string) str_replace('=0A',"\n",$quotprint);   
461         return (string) $quotprint;
462 }
463 
464 function validEmailAddr($emailAddress) {
465     $emailAddress = trim($emailAddress);
466     $angBrack = strpos($emailAddress, '<');
467     
468     if($angBrack === 0) {
469         $emailAddress = substr($emailAddress, 1, strpos($emailAddress,'>')-1);
470         
471     } else if($angBrack) {      
472         $emailAddress = str_replace('@', '', substr($emailAddress, 0, $angBrack))
473                             .substr($emailAddress, $angBrack);
474     }
475     
476     return $emailAddress;
477 }
478 
479 /*
480  * Get mime type based on extension
481  */
482 function getMimeType($filename) {
483     global $global_mimetypes;
484     if(!$global_mimetypes) loadMimeTypes();
485     $ext = strtolower(substr($filename,strrpos($filename,'.')+1));
486     return isset($global_mimetypes[$ext]) ? $global_mimetypes[$ext] : 'application/octet-stream';
487 }
488 
489 /*
490  * Load the mime-type data from the system file
491  */
492 function loadMimeTypes() {
493     $mimetypePathCustom = '/etc/mime.types';
494     $mimetypePathGeneric = Director::baseFolder() . '/sapphire/email/mime.types';
495     $mimeTypes = file_exists($mimetypePathGeneric) ?  file($mimetypePathGeneric) : file($mimetypePathCustom);
496     foreach($mimeTypes as $typeSpec) {
497         if(($typeSpec = trim($typeSpec)) && substr($typeSpec,0,1) != "#") {
498             $parts = preg_split("/[ \t\r\n]+/", $typeSpec);
499             if(sizeof($parts) > 1) {
500                 $mimeType = array_shift($parts);
501                 foreach($parts as $ext) {
502                     $ext = strtolower($ext);
503                     $mimeData[$ext] = $mimeType;
504                 }
505             }
506         }
507     }
508 
509     global $global_mimetypes;
510     $global_mimetypes = $mimeData;
511     return $mimeData;
512 }
513 
514 
[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -
Webylon 3.1 API Docs API documentation generated by ApiGen 2.8.0