class.phpmailer.php 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454
  1. <?php
  2. /**
  3. * PHPMailer - PHP email creation and transport class.
  4. * PHP Version 5
  5. * @package PHPMailer
  6. * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  7. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  8. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  9. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10. * @author Brent R. Matzelle (original founder)
  11. * @copyright 2012 - 2014 Marcus Bointon
  12. * @copyright 2010 - 2012 Jim Jagielski
  13. * @copyright 2004 - 2009 Andy Prevost
  14. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15. * @note This program is distributed in the hope that it will be useful - WITHOUT
  16. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17. * FITNESS FOR A PARTICULAR PURPOSE.
  18. */
  19. /**
  20. * PHPMailer - PHP email creation and transport class.
  21. * @package PHPMailer
  22. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  23. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  24. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  25. * @author Brent R. Matzelle (original founder)
  26. */
  27. class PHPMailer
  28. {
  29. /**
  30. * The PHPMailer Version number.
  31. * @type string
  32. */
  33. public $Version = '5.2.8';
  34. /**
  35. * Email priority.
  36. * Options: 1 = High, 3 = Normal, 5 = low.
  37. * @type integer
  38. */
  39. public $Priority = 3;
  40. /**
  41. * The character set of the message.
  42. * @type string
  43. */
  44. public $CharSet = 'iso-8859-1';
  45. /**
  46. * The MIME Content-type of the message.
  47. * @type string
  48. */
  49. public $ContentType = 'text/plain';
  50. /**
  51. * The message encoding.
  52. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  53. * @type string
  54. */
  55. public $Encoding = '8bit';
  56. /**
  57. * Holds the most recent mailer error message.
  58. * @type string
  59. */
  60. public $ErrorInfo = '';
  61. /**
  62. * The From email address for the message.
  63. * @type string
  64. */
  65. public $From = 'root@localhost';
  66. /**
  67. * The From name of the message.
  68. * @type string
  69. */
  70. public $FromName = 'Root User';
  71. /**
  72. * The Sender email (Return-Path) of the message.
  73. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  74. * @type string
  75. */
  76. public $Sender = '';
  77. /**
  78. * The Return-Path of the message.
  79. * If empty, it will be set to either From or Sender.
  80. * @type string
  81. * @deprecated Email senders should never set a return-path header;
  82. * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
  83. * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
  84. */
  85. public $ReturnPath = '';
  86. /**
  87. * The Subject of the message.
  88. * @type string
  89. */
  90. public $Subject = '';
  91. /**
  92. * An HTML or plain text message body.
  93. * If HTML then call isHTML(true).
  94. * @type string
  95. */
  96. public $Body = '';
  97. /**
  98. * The plain-text message body.
  99. * This body can be read by mail clients that do not have HTML email
  100. * capability such as mutt & Eudora.
  101. * Clients that can read HTML will view the normal Body.
  102. * @type string
  103. */
  104. public $AltBody = '';
  105. /**
  106. * An iCal message part body.
  107. * Only supported in simple alt or alt_inline message types
  108. * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  109. * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  110. * @link http://kigkonsult.se/iCalcreator/
  111. * @type string
  112. */
  113. public $Ical = '';
  114. /**
  115. * The complete compiled MIME message body.
  116. * @access protected
  117. * @type string
  118. */
  119. protected $MIMEBody = '';
  120. /**
  121. * The complete compiled MIME message headers.
  122. * @type string
  123. * @access protected
  124. */
  125. protected $MIMEHeader = '';
  126. /**
  127. * Extra headers that createHeader() doesn't fold in.
  128. * @type string
  129. * @access protected
  130. */
  131. protected $mailHeader = '';
  132. /**
  133. * Word-wrap the message body to this number of chars.
  134. * @type integer
  135. */
  136. public $WordWrap = 0;
  137. /**
  138. * Which method to use to send mail.
  139. * Options: "mail", "sendmail", or "smtp".
  140. * @type string
  141. */
  142. public $Mailer = 'mail';
  143. /**
  144. * The path to the sendmail program.
  145. * @type string
  146. */
  147. public $Sendmail = '/usr/sbin/sendmail';
  148. /**
  149. * Whether mail() uses a fully sendmail-compatible MTA.
  150. * One which supports sendmail's "-oi -f" options.
  151. * @type boolean
  152. */
  153. public $UseSendmailOptions = true;
  154. /**
  155. * Path to PHPMailer plugins.
  156. * Useful if the SMTP class is not in the PHP include path.
  157. * @type string
  158. * @deprecated Should not be needed now there is an autoloader.
  159. */
  160. public $PluginDir = '';
  161. /**
  162. * The email address that a reading confirmation should be sent to.
  163. * @type string
  164. */
  165. public $ConfirmReadingTo = '';
  166. /**
  167. * The hostname to use in Message-Id and Received headers
  168. * and as default HELO string.
  169. * If empty, the value returned
  170. * by SERVER_NAME is used or 'localhost.localdomain'.
  171. * @type string
  172. */
  173. public $Hostname = '';
  174. /**
  175. * An ID to be used in the Message-Id header.
  176. * If empty, a unique id will be generated.
  177. * @type string
  178. */
  179. public $MessageID = '';
  180. /**
  181. * The message Date to be used in the Date header.
  182. * If empty, the current date will be added.
  183. * @type string
  184. */
  185. public $MessageDate = '';
  186. /**
  187. * SMTP hosts.
  188. * Either a single hostname or multiple semicolon-delimited hostnames.
  189. * You can also specify a different port
  190. * for each host by using this format: [hostname:port]
  191. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  192. * You can also specify encryption type, for example:
  193. * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
  194. * Hosts will be tried in order.
  195. * @type string
  196. */
  197. public $Host = 'localhost';
  198. /**
  199. * The default SMTP server port.
  200. * @type integer
  201. * @TODO Why is this needed when the SMTP class takes care of it?
  202. */
  203. public $Port = 25;
  204. /**
  205. * The SMTP HELO of the message.
  206. * Default is $Hostname.
  207. * @type string
  208. * @see PHPMailer::$Hostname
  209. */
  210. public $Helo = '';
  211. /**
  212. * The secure connection prefix.
  213. * Options: "", "ssl" or "tls"
  214. * @type string
  215. */
  216. public $SMTPSecure = '';
  217. /**
  218. * Whether to use SMTP authentication.
  219. * Uses the Username and Password properties.
  220. * @type boolean
  221. * @see PHPMailer::$Username
  222. * @see PHPMailer::$Password
  223. */
  224. public $SMTPAuth = false;
  225. /**
  226. * SMTP username.
  227. * @type string
  228. */
  229. public $Username = '';
  230. /**
  231. * SMTP password.
  232. * @type string
  233. */
  234. public $Password = '';
  235. /**
  236. * SMTP auth type.
  237. * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
  238. * @type string
  239. */
  240. public $AuthType = '';
  241. /**
  242. * SMTP realm.
  243. * Used for NTLM auth
  244. * @type string
  245. */
  246. public $Realm = '';
  247. /**
  248. * SMTP workstation.
  249. * Used for NTLM auth
  250. * @type string
  251. */
  252. public $Workstation = '';
  253. /**
  254. * The SMTP server timeout in seconds.
  255. * @type integer
  256. */
  257. public $Timeout = 10;
  258. /**
  259. * SMTP class debug output mode.
  260. * Debug output level.
  261. * Options:
  262. * * `0` No output
  263. * * `1` Commands
  264. * * `2` Data and commands
  265. * * `3` As 2 plus connection status
  266. * * `4` Low-level data output
  267. * @type integer
  268. * @see SMTP::$do_debug
  269. */
  270. public $SMTPDebug = 0;
  271. /**
  272. * How to handle debug output.
  273. * Options:
  274. * * `echo` Output plain-text as-is, appropriate for CLI
  275. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  276. * * `error_log` Output to error log as configured in php.ini
  277. *
  278. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  279. * <code>
  280. * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  281. * </code>
  282. * @type string|callable
  283. * @see SMTP::$Debugoutput
  284. */
  285. public $Debugoutput = 'echo';
  286. /**
  287. * Whether to keep SMTP connection open after each message.
  288. * If this is set to true then to close the connection
  289. * requires an explicit call to smtpClose().
  290. * @type boolean
  291. */
  292. public $SMTPKeepAlive = false;
  293. /**
  294. * Whether to split multiple to addresses into multiple messages
  295. * or send them all in one message.
  296. * @type boolean
  297. */
  298. public $SingleTo = false;
  299. /**
  300. * Storage for addresses when SingleTo is enabled.
  301. * @type array
  302. * @TODO This should really not be public
  303. */
  304. public $SingleToArray = array();
  305. /**
  306. * Whether to generate VERP addresses on send.
  307. * Only applicable when sending via SMTP.
  308. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  309. * @link http://www.postfix.org/VERP_README.html Postfix VERP info
  310. * @type boolean
  311. */
  312. public $do_verp = false;
  313. /**
  314. * Whether to allow sending messages with an empty body.
  315. * @type boolean
  316. */
  317. public $AllowEmpty = false;
  318. /**
  319. * The default line ending.
  320. * @note The default remains "\n". We force CRLF where we know
  321. * it must be used via self::CRLF.
  322. * @type string
  323. */
  324. public $LE = "\n";
  325. /**
  326. * DKIM selector.
  327. * @type string
  328. */
  329. public $DKIM_selector = '';
  330. /**
  331. * DKIM Identity.
  332. * Usually the email address used as the source of the email
  333. * @type string
  334. */
  335. public $DKIM_identity = '';
  336. /**
  337. * DKIM passphrase.
  338. * Used if your key is encrypted.
  339. * @type string
  340. */
  341. public $DKIM_passphrase = '';
  342. /**
  343. * DKIM signing domain name.
  344. * @example 'example.com'
  345. * @type string
  346. */
  347. public $DKIM_domain = '';
  348. /**
  349. * DKIM private key file path.
  350. * @type string
  351. */
  352. public $DKIM_private = '';
  353. /**
  354. * Callback Action function name.
  355. *
  356. * The function that handles the result of the send email action.
  357. * It is called out by send() for each email sent.
  358. *
  359. * Value can be any php callable: http://www.php.net/is_callable
  360. *
  361. * Parameters:
  362. * boolean $result result of the send action
  363. * string $to email address of the recipient
  364. * string $cc cc email addresses
  365. * string $bcc bcc email addresses
  366. * string $subject the subject
  367. * string $body the email body
  368. * string $from email address of sender
  369. * @type string
  370. */
  371. public $action_function = '';
  372. /**
  373. * What to use in the X-Mailer header.
  374. * Options: null for default, whitespace for none, or a string to use
  375. * @type string
  376. */
  377. public $XMailer = '';
  378. /**
  379. * An instance of the SMTP sender class.
  380. * @type SMTP
  381. * @access protected
  382. */
  383. protected $smtp = null;
  384. /**
  385. * The array of 'to' addresses.
  386. * @type array
  387. * @access protected
  388. */
  389. protected $to = array();
  390. /**
  391. * The array of 'cc' addresses.
  392. * @type array
  393. * @access protected
  394. */
  395. protected $cc = array();
  396. /**
  397. * The array of 'bcc' addresses.
  398. * @type array
  399. * @access protected
  400. */
  401. protected $bcc = array();
  402. /**
  403. * The array of reply-to names and addresses.
  404. * @type array
  405. * @access protected
  406. */
  407. protected $ReplyTo = array();
  408. /**
  409. * An array of all kinds of addresses.
  410. * Includes all of $to, $cc, $bcc, $replyto
  411. * @type array
  412. * @access protected
  413. */
  414. protected $all_recipients = array();
  415. /**
  416. * The array of attachments.
  417. * @type array
  418. * @access protected
  419. */
  420. protected $attachment = array();
  421. /**
  422. * The array of custom headers.
  423. * @type array
  424. * @access protected
  425. */
  426. protected $CustomHeader = array();
  427. /**
  428. * The most recent Message-ID (including angular brackets).
  429. * @type string
  430. * @access protected
  431. */
  432. protected $lastMessageID = '';
  433. /**
  434. * The message's MIME type.
  435. * @type string
  436. * @access protected
  437. */
  438. protected $message_type = '';
  439. /**
  440. * The array of MIME boundary strings.
  441. * @type array
  442. * @access protected
  443. */
  444. protected $boundary = array();
  445. /**
  446. * The array of available languages.
  447. * @type array
  448. * @access protected
  449. */
  450. protected $language = array();
  451. /**
  452. * The number of errors encountered.
  453. * @type integer
  454. * @access protected
  455. */
  456. protected $error_count = 0;
  457. /**
  458. * The S/MIME certificate file path.
  459. * @type string
  460. * @access protected
  461. */
  462. protected $sign_cert_file = '';
  463. /**
  464. * The S/MIME key file path.
  465. * @type string
  466. * @access protected
  467. */
  468. protected $sign_key_file = '';
  469. /**
  470. * The S/MIME password for the key.
  471. * Used only if the key is encrypted.
  472. * @type string
  473. * @access protected
  474. */
  475. protected $sign_key_pass = '';
  476. /**
  477. * Whether to throw exceptions for errors.
  478. * @type boolean
  479. * @access protected
  480. */
  481. protected $exceptions = false;
  482. /**
  483. * Error severity: message only, continue processing.
  484. */
  485. const STOP_MESSAGE = 0;
  486. /**
  487. * Error severity: message, likely ok to continue processing.
  488. */
  489. const STOP_CONTINUE = 1;
  490. /**
  491. * Error severity: message, plus full stop, critical error reached.
  492. */
  493. const STOP_CRITICAL = 2;
  494. /**
  495. * SMTP RFC standard line ending.
  496. */
  497. const CRLF = "\r\n";
  498. /**
  499. * Constructor.
  500. * @param boolean $exceptions Should we throw external exceptions?
  501. */
  502. public function __construct($exceptions = false)
  503. {
  504. $this->exceptions = ($exceptions == true);
  505. }
  506. /**
  507. * Destructor.
  508. */
  509. public function __destruct()
  510. {
  511. if ($this->Mailer == 'smtp') { //close any open SMTP connection nicely
  512. $this->smtpClose();
  513. }
  514. }
  515. /**
  516. * Call mail() in a safe_mode-aware fashion.
  517. * Also, unless sendmail_path points to sendmail (or something that
  518. * claims to be sendmail), don't pass params (not a perfect fix,
  519. * but it will do)
  520. * @param string $to To
  521. * @param string $subject Subject
  522. * @param string $body Message Body
  523. * @param string $header Additional Header(s)
  524. * @param string $params Params
  525. * @access private
  526. * @return boolean
  527. */
  528. private function mailPassthru($to, $subject, $body, $header, $params)
  529. {
  530. //Check overloading of mail function to avoid double-encoding
  531. if (ini_get('mbstring.func_overload') & 1) {
  532. $subject = $this->secureHeader($subject);
  533. } else {
  534. $subject = $this->encodeHeader($this->secureHeader($subject));
  535. }
  536. if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
  537. $result = @mail($to, $subject, $body, $header);
  538. } else {
  539. $result = @mail($to, $subject, $body, $header, $params);
  540. }
  541. return $result;
  542. }
  543. /**
  544. * Output debugging info via user-defined method.
  545. * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
  546. * @see PHPMailer::$Debugoutput
  547. * @see PHPMailer::$SMTPDebug
  548. * @param string $str
  549. */
  550. protected function edebug($str)
  551. {
  552. if ($this->SMTPDebug <= 0) {
  553. return;
  554. }
  555. if (is_callable($this->Debugoutput)) {
  556. call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  557. return;
  558. }
  559. switch ($this->Debugoutput) {
  560. case 'error_log':
  561. //Don't output, just log
  562. error_log($str);
  563. break;
  564. case 'html':
  565. //Cleans up output a bit for a better looking, HTML-safe output
  566. echo htmlentities(
  567. preg_replace('/[\r\n]+/', '', $str),
  568. ENT_QUOTES,
  569. 'UTF-8'
  570. )
  571. . "<br>\n";
  572. break;
  573. case 'echo':
  574. default:
  575. //Normalize line breaks
  576. $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  577. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  578. "\n",
  579. "\n \t ",
  580. trim($str)
  581. ) . "\n";
  582. }
  583. }
  584. /**
  585. * Sets message type to HTML or plain.
  586. * @param boolean $isHtml True for HTML mode.
  587. * @return void
  588. */
  589. public function isHTML($isHtml = true)
  590. {
  591. if ($isHtml) {
  592. $this->ContentType = 'text/html';
  593. } else {
  594. $this->ContentType = 'text/plain';
  595. }
  596. }
  597. /**
  598. * Send messages using SMTP.
  599. * @return void
  600. */
  601. public function isSMTP()
  602. {
  603. $this->Mailer = 'smtp';
  604. }
  605. /**
  606. * Send messages using PHP's mail() function.
  607. * @return void
  608. */
  609. public function isMail()
  610. {
  611. $this->Mailer = 'mail';
  612. }
  613. /**
  614. * Send messages using $Sendmail.
  615. * @return void
  616. */
  617. public function isSendmail()
  618. {
  619. $ini_sendmail_path = ini_get('sendmail_path');
  620. if (!stristr($ini_sendmail_path, 'sendmail')) {
  621. $this->Sendmail = '/usr/sbin/sendmail';
  622. } else {
  623. $this->Sendmail = $ini_sendmail_path;
  624. }
  625. $this->Mailer = 'sendmail';
  626. }
  627. /**
  628. * Send messages using qmail.
  629. * @return void
  630. */
  631. public function isQmail()
  632. {
  633. $ini_sendmail_path = ini_get('sendmail_path');
  634. if (!stristr($ini_sendmail_path, 'qmail')) {
  635. $this->Sendmail = '/var/qmail/bin/qmail-inject';
  636. } else {
  637. $this->Sendmail = $ini_sendmail_path;
  638. }
  639. $this->Mailer = 'qmail';
  640. }
  641. /**
  642. * Add a "To" address.
  643. * @param string $address
  644. * @param string $name
  645. * @return boolean true on success, false if address already used
  646. */
  647. public function addAddress($address, $name = '')
  648. {
  649. return $this->addAnAddress('to', $address, $name);
  650. }
  651. /**
  652. * Add a "CC" address.
  653. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  654. * @param string $address
  655. * @param string $name
  656. * @return boolean true on success, false if address already used
  657. */
  658. public function addCC($address, $name = '')
  659. {
  660. return $this->addAnAddress('cc', $address, $name);
  661. }
  662. /**
  663. * Add a "BCC" address.
  664. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  665. * @param string $address
  666. * @param string $name
  667. * @return boolean true on success, false if address already used
  668. */
  669. public function addBCC($address, $name = '')
  670. {
  671. return $this->addAnAddress('bcc', $address, $name);
  672. }
  673. /**
  674. * Add a "Reply-to" address.
  675. * @param string $address
  676. * @param string $name
  677. * @return boolean
  678. */
  679. public function addReplyTo($address, $name = '')
  680. {
  681. return $this->addAnAddress('Reply-To', $address, $name);
  682. }
  683. /**
  684. * Add an address to one of the recipient arrays.
  685. * Addresses that have been added already return false, but do not throw exceptions
  686. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  687. * @param string $address The email address to send to
  688. * @param string $name
  689. * @throws phpmailerException
  690. * @return boolean true on success, false if address already used or invalid in some way
  691. * @access protected
  692. */
  693. protected function addAnAddress($kind, $address, $name = '')
  694. {
  695. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  696. $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
  697. $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
  698. if ($this->exceptions) {
  699. throw new phpmailerException('Invalid recipient array: ' . $kind);
  700. }
  701. return false;
  702. }
  703. $address = trim($address);
  704. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  705. if (!$this->validateAddress($address)) {
  706. $this->setError($this->lang('invalid_address') . ': ' . $address);
  707. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  708. if ($this->exceptions) {
  709. throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  710. }
  711. return false;
  712. }
  713. if ($kind != 'Reply-To') {
  714. if (!isset($this->all_recipients[strtolower($address)])) {
  715. array_push($this->$kind, array($address, $name));
  716. $this->all_recipients[strtolower($address)] = true;
  717. return true;
  718. }
  719. } else {
  720. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  721. $this->ReplyTo[strtolower($address)] = array($address, $name);
  722. return true;
  723. }
  724. }
  725. return false;
  726. }
  727. /**
  728. * Set the From and FromName properties.
  729. * @param string $address
  730. * @param string $name
  731. * @param boolean $auto Whether to also set the Sender address, defaults to true
  732. * @throws phpmailerException
  733. * @return boolean
  734. */
  735. public function setFrom($address, $name = '', $auto = true)
  736. {
  737. $address = trim($address);
  738. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  739. if (!$this->validateAddress($address)) {
  740. $this->setError($this->lang('invalid_address') . ': ' . $address);
  741. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  742. if ($this->exceptions) {
  743. throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  744. }
  745. return false;
  746. }
  747. $this->From = $address;
  748. $this->FromName = $name;
  749. if ($auto) {
  750. if (empty($this->Sender)) {
  751. $this->Sender = $address;
  752. }
  753. }
  754. return true;
  755. }
  756. /**
  757. * Return the Message-ID header of the last email.
  758. * Technically this is the value from the last time the headers were created,
  759. * but it's also the message ID of the last sent message except in
  760. * pathological cases.
  761. * @return string
  762. */
  763. public function getLastMessageID()
  764. {
  765. return $this->lastMessageID;
  766. }
  767. /**
  768. * Check that a string looks like an email address.
  769. * @param string $address The email address to check
  770. * @param string $patternselect A selector for the validation pattern to use :
  771. * * `auto` Pick strictest one automatically;
  772. * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
  773. * * `pcre` Use old PCRE implementation;
  774. * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
  775. * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
  776. * * `noregex` Don't use a regex: super fast, really dumb.
  777. * @return boolean
  778. * @static
  779. * @access public
  780. */
  781. public static function validateAddress($address, $patternselect = 'auto')
  782. {
  783. if (!$patternselect or $patternselect == 'auto') {
  784. //Check this constant first so it works when extension_loaded() is disabled by safe mode
  785. //Constant was added in PHP 5.2.4
  786. if (defined('PCRE_VERSION')) {
  787. //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  788. if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  789. $patternselect = 'pcre8';
  790. } else {
  791. $patternselect = 'pcre';
  792. }
  793. } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  794. //Fall back to older PCRE
  795. $patternselect = 'pcre';
  796. } else {
  797. //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  798. if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  799. $patternselect = 'php';
  800. } else {
  801. $patternselect = 'noregex';
  802. }
  803. }
  804. }
  805. switch ($patternselect) {
  806. case 'pcre8':
  807. /**
  808. * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
  809. * @link http://squiloople.com/2009/12/20/email-address-validation/
  810. * @copyright 2009-2010 Michael Rushton
  811. * Feel free to use and redistribute this code. But please keep this copyright notice.
  812. */
  813. return (boolean)preg_match(
  814. '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  815. '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  816. '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  817. '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  818. '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  819. '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  820. '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  821. '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  822. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  823. $address
  824. );
  825. case 'pcre':
  826. //An older regex that doesn't need a recent PCRE
  827. return (boolean)preg_match(
  828. '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  829. '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  830. '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  831. '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  832. '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  833. '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  834. '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  835. '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  836. '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  837. '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  838. $address
  839. );
  840. case 'html5':
  841. /**
  842. * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
  843. * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
  844. */
  845. return (boolean)preg_match(
  846. '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  847. '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  848. $address
  849. );
  850. case 'noregex':
  851. //No PCRE! Do something _very_ approximate!
  852. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  853. return (strlen($address) >= 3
  854. and strpos($address, '@') >= 1
  855. and strpos($address, '@') != strlen($address) - 1);
  856. case 'php':
  857. default:
  858. return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  859. }
  860. }
  861. /**
  862. * Create a message and send it.
  863. * Uses the sending method specified by $Mailer.
  864. * @throws phpmailerException
  865. * @return boolean false on error - See the ErrorInfo property for details of the error.
  866. */
  867. public function send()
  868. {
  869. try {
  870. if (!$this->preSend()) {
  871. return false;
  872. }
  873. return $this->postSend();
  874. } catch (phpmailerException $exc) {
  875. $this->mailHeader = '';
  876. $this->setError($exc->getMessage());
  877. if ($this->exceptions) {
  878. throw $exc;
  879. }
  880. return false;
  881. }
  882. }
  883. /**
  884. * Prepare a message for sending.
  885. * @throws phpmailerException
  886. * @return boolean
  887. */
  888. public function preSend()
  889. {
  890. try {
  891. $this->mailHeader = '';
  892. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  893. throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  894. }
  895. // Set whether the message is multipart/alternative
  896. if (!empty($this->AltBody)) {
  897. $this->ContentType = 'multipart/alternative';
  898. }
  899. $this->error_count = 0; // reset errors
  900. $this->setMessageType();
  901. // Refuse to send an empty message unless we are specifically allowing it
  902. if (!$this->AllowEmpty and empty($this->Body)) {
  903. throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  904. }
  905. $this->MIMEHeader = $this->createHeader();
  906. $this->MIMEBody = $this->createBody();
  907. // To capture the complete message when using mail(), create
  908. // an extra header list which createHeader() doesn't fold in
  909. if ($this->Mailer == 'mail') {
  910. if (count($this->to) > 0) {
  911. $this->mailHeader .= $this->addrAppend('To', $this->to);
  912. } else {
  913. $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  914. }
  915. $this->mailHeader .= $this->headerLine(
  916. 'Subject',
  917. $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  918. );
  919. }
  920. // Sign with DKIM if enabled
  921. if (!empty($this->DKIM_domain)
  922. && !empty($this->DKIM_private)
  923. && !empty($this->DKIM_selector)
  924. && !empty($this->DKIM_domain)
  925. && file_exists($this->DKIM_private)) {
  926. $header_dkim = $this->DKIM_Add(
  927. $this->MIMEHeader . $this->mailHeader,
  928. $this->encodeHeader($this->secureHeader($this->Subject)),
  929. $this->MIMEBody
  930. );
  931. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  932. str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  933. }
  934. return true;
  935. } catch (phpmailerException $exc) {
  936. $this->setError($exc->getMessage());
  937. if ($this->exceptions) {
  938. throw $exc;
  939. }
  940. return false;
  941. }
  942. }
  943. /**
  944. * Actually send a message.
  945. * Send the email via the selected mechanism
  946. * @throws phpmailerException
  947. * @return boolean
  948. */
  949. public function postSend()
  950. {
  951. try {
  952. // Choose the mailer and send through it
  953. switch ($this->Mailer) {
  954. case 'sendmail':
  955. case 'qmail':
  956. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  957. case 'smtp':
  958. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  959. case 'mail':
  960. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  961. default:
  962. $sendMethod = $this->Mailer.'Send';
  963. if (method_exists($this, $sendMethod)) {
  964. return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  965. }
  966. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  967. }
  968. } catch (phpmailerException $exc) {
  969. $this->setError($exc->getMessage());
  970. $this->edebug($exc->getMessage());
  971. if ($this->exceptions) {
  972. throw $exc;
  973. }
  974. }
  975. return false;
  976. }
  977. /**
  978. * Send mail using the $Sendmail program.
  979. * @param string $header The message headers
  980. * @param string $body The message body
  981. * @see PHPMailer::$Sendmail
  982. * @throws phpmailerException
  983. * @access protected
  984. * @return boolean
  985. */
  986. protected function sendmailSend($header, $body)
  987. {
  988. if ($this->Sender != '') {
  989. if ($this->Mailer == 'qmail') {
  990. $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  991. } else {
  992. $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  993. }
  994. } else {
  995. if ($this->Mailer == 'qmail') {
  996. $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  997. } else {
  998. $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  999. }
  1000. }
  1001. if ($this->SingleTo === true) {
  1002. foreach ($this->SingleToArray as $toAddr) {
  1003. if (!@$mail = popen($sendmail, 'w')) {
  1004. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1005. }
  1006. fputs($mail, 'To: ' . $toAddr . "\n");
  1007. fputs($mail, $header);
  1008. fputs($mail, $body);
  1009. $result = pclose($mail);
  1010. $this->doCallback(
  1011. ($result == 0),
  1012. array($toAddr),
  1013. $this->cc,
  1014. $this->bcc,
  1015. $this->Subject,
  1016. $body,
  1017. $this->From
  1018. );
  1019. if ($result != 0) {
  1020. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1021. }
  1022. }
  1023. } else {
  1024. if (!@$mail = popen($sendmail, 'w')) {
  1025. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1026. }
  1027. fputs($mail, $header);
  1028. fputs($mail, $body);
  1029. $result = pclose($mail);
  1030. $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1031. if ($result != 0) {
  1032. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1033. }
  1034. }
  1035. return true;
  1036. }
  1037. /**
  1038. * Send mail using the PHP mail() function.
  1039. * @param string $header The message headers
  1040. * @param string $body The message body
  1041. * @link http://www.php.net/manual/en/book.mail.php
  1042. * @throws phpmailerException
  1043. * @access protected
  1044. * @return boolean
  1045. */
  1046. protected function mailSend($header, $body)
  1047. {
  1048. $toArr = array();
  1049. foreach ($this->to as $toaddr) {
  1050. $toArr[] = $this->addrFormat($toaddr);
  1051. }
  1052. $to = implode(', ', $toArr);
  1053. if (empty($this->Sender)) {
  1054. $params = ' ';
  1055. } else {
  1056. $params = sprintf('-f%s', $this->Sender);
  1057. }
  1058. if ($this->Sender != '' and !ini_get('safe_mode')) {
  1059. $old_from = ini_get('sendmail_from');
  1060. ini_set('sendmail_from', $this->Sender);
  1061. }
  1062. $result = false;
  1063. if ($this->SingleTo === true && count($toArr) > 1) {
  1064. foreach ($toArr as $toAddr) {
  1065. $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  1066. $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1067. }
  1068. } else {
  1069. $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1070. $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1071. }
  1072. if (isset($old_from)) {
  1073. ini_set('sendmail_from', $old_from);
  1074. }
  1075. if (!$result) {
  1076. throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  1077. }
  1078. return true;
  1079. }
  1080. /**
  1081. * Get an instance to use for SMTP operations.
  1082. * Override this function to load your own SMTP implementation
  1083. * @return SMTP
  1084. */
  1085. public function getSMTPInstance()
  1086. {
  1087. if (!is_object($this->smtp)) {
  1088. $this->smtp = new SMTP;
  1089. }
  1090. return $this->smtp;
  1091. }
  1092. /**
  1093. * Send mail via SMTP.
  1094. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1095. * Uses the PHPMailerSMTP class by default.
  1096. * @see PHPMailer::getSMTPInstance() to use a different class.
  1097. * @param string $header The message headers
  1098. * @param string $body The message body
  1099. * @throws phpmailerException
  1100. * @uses SMTP
  1101. * @access protected
  1102. * @return boolean
  1103. */
  1104. protected function smtpSend($header, $body)
  1105. {
  1106. $bad_rcpt = array();
  1107. if (!$this->smtpConnect()) {
  1108. throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1109. }
  1110. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  1111. if (!$this->smtp->mail($smtp_from)) {
  1112. $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1113. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  1114. }
  1115. // Attempt to send to all recipients
  1116. foreach ($this->to as $to) {
  1117. if (!$this->smtp->recipient($to[0])) {
  1118. $bad_rcpt[] = $to[0];
  1119. $isSent = false;
  1120. } else {
  1121. $isSent = true;
  1122. }
  1123. $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  1124. }
  1125. foreach ($this->cc as $cc) {
  1126. if (!$this->smtp->recipient($cc[0])) {
  1127. $bad_rcpt[] = $cc[0];
  1128. $isSent = false;
  1129. } else {
  1130. $isSent = true;
  1131. }
  1132. $this->doCallback($isSent, array(), array($cc[0]), array(), $this->Subject, $body, $this->From);
  1133. }
  1134. foreach ($this->bcc as $bcc) {
  1135. if (!$this->smtp->recipient($bcc[0])) {
  1136. $bad_rcpt[] = $bcc[0];
  1137. $isSent = false;
  1138. } else {
  1139. $isSent = true;
  1140. }
  1141. $this->doCallback($isSent, array(), array(), array($bcc[0]), $this->Subject, $body, $this->From);
  1142. }
  1143. // Only send the DATA command if we have viable recipients
  1144. if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  1145. throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1146. }
  1147. if ($this->SMTPKeepAlive == true) {
  1148. $this->smtp->reset();
  1149. } else {
  1150. $this->smtp->quit();
  1151. $this->smtp->close();
  1152. }
  1153. if (count($bad_rcpt) > 0) { // Create error message for any bad addresses
  1154. throw new phpmailerException(
  1155. $this->lang('recipients_failed') . implode(', ', $bad_rcpt),
  1156. self::STOP_CONTINUE
  1157. );
  1158. }
  1159. return true;
  1160. }
  1161. /**
  1162. * Initiate a connection to an SMTP server.
  1163. * Returns false if the operation failed.
  1164. * @param array $options An array of options compatible with stream_context_create()
  1165. * @uses SMTP
  1166. * @access public
  1167. * @throws phpmailerException
  1168. * @return boolean
  1169. */
  1170. public function smtpConnect($options = array())
  1171. {
  1172. if (is_null($this->smtp)) {
  1173. $this->smtp = $this->getSMTPInstance();
  1174. }
  1175. // Already connected?
  1176. if ($this->smtp->connected()) {
  1177. return true;
  1178. }
  1179. $this->smtp->setTimeout($this->Timeout);
  1180. $this->smtp->setDebugLevel($this->SMTPDebug);
  1181. $this->smtp->setDebugOutput($this->Debugoutput);
  1182. $this->smtp->setVerp($this->do_verp);
  1183. $hosts = explode(';', $this->Host);
  1184. $lastexception = null;
  1185. foreach ($hosts as $hostentry) {
  1186. $hostinfo = array();
  1187. if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  1188. // Not a valid host entry
  1189. continue;
  1190. }
  1191. // $hostinfo[2]: optional ssl or tls prefix
  1192. // $hostinfo[3]: the hostname
  1193. // $hostinfo[4]: optional port number
  1194. // The host string prefix can temporarily override the current setting for SMTPSecure
  1195. // If it's not specified, the default value is used
  1196. $prefix = '';
  1197. $tls = ($this->SMTPSecure == 'tls');
  1198. if ($hostinfo[2] == 'ssl' or ($hostinfo[2] == '' and $this->SMTPSecure == 'ssl')) {
  1199. $prefix = 'ssl://';
  1200. $tls = false; // Can't have SSL and TLS at once
  1201. } elseif ($hostinfo[2] == 'tls') {
  1202. $tls = true;
  1203. // tls doesn't use a prefix
  1204. }
  1205. $host = $hostinfo[3];
  1206. $port = $this->Port;
  1207. $tport = (integer)$hostinfo[4];
  1208. if ($tport > 0 and $tport < 65536) {
  1209. $port = $tport;
  1210. }
  1211. if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1212. try {
  1213. if ($this->Helo) {
  1214. $hello = $this->Helo;
  1215. } else {
  1216. $hello = $this->serverHostname();
  1217. }
  1218. $this->smtp->hello($hello);
  1219. if ($tls) {
  1220. if (!$this->smtp->startTLS()) {
  1221. throw new phpmailerException($this->lang('connect_host'));
  1222. }
  1223. // We must resend HELO after tls negotiation
  1224. $this->smtp->hello($hello);
  1225. }
  1226. if ($this->SMTPAuth) {
  1227. if (!$this->smtp->authenticate(
  1228. $this->Username,
  1229. $this->Password,
  1230. $this->AuthType,
  1231. $this->Realm,
  1232. $this->Workstation
  1233. )
  1234. ) {
  1235. throw new phpmailerException($this->lang('authenticate'));
  1236. }
  1237. }
  1238. return true;
  1239. } catch (phpmailerException $exc) {
  1240. $lastexception = $exc;
  1241. // We must have connected, but then failed TLS or Auth, so close connection nicely
  1242. $this->smtp->quit();
  1243. }
  1244. }
  1245. }
  1246. // If we get here, all connection attempts have failed, so close connection hard
  1247. $this->smtp->close();
  1248. // As we've caught all exceptions, just report whatever the last one was
  1249. if ($this->exceptions and !is_null($lastexception)) {
  1250. throw $lastexception;
  1251. }
  1252. return false;
  1253. }
  1254. /**
  1255. * Close the active SMTP session if one exists.
  1256. * @return void
  1257. */
  1258. public function smtpClose()
  1259. {
  1260. if ($this->smtp !== null) {
  1261. if ($this->smtp->connected()) {
  1262. $this->smtp->quit();
  1263. $this->smtp->close();
  1264. }
  1265. }
  1266. }
  1267. /**
  1268. * Set the language for error messages.
  1269. * Returns false if it cannot load the language file.
  1270. * The default language is English.
  1271. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  1272. * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  1273. * @return boolean
  1274. * @access public
  1275. */
  1276. public function setLanguage($langcode = 'en', $lang_path = '')
  1277. {
  1278. // Define full set of translatable strings in English
  1279. $PHPMAILER_LANG = array(
  1280. 'authenticate' => 'SMTP Error: Could not authenticate.',
  1281. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1282. 'data_not_accepted' => 'SMTP Error: data not accepted.',
  1283. 'empty_message' => 'Message body empty',
  1284. 'encoding' => 'Unknown encoding: ',
  1285. 'execute' => 'Could not execute: ',
  1286. 'file_access' => 'Could not access file: ',
  1287. 'file_open' => 'File Error: Could not open file: ',
  1288. 'from_failed' => 'The following From address failed: ',
  1289. 'instantiate' => 'Could not instantiate mail function.',
  1290. 'invalid_address' => 'Invalid address',
  1291. 'mailer_not_supported' => ' mailer is not supported.',
  1292. 'provide_address' => 'You must provide at least one recipient email address.',
  1293. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1294. 'signing' => 'Signing Error: ',
  1295. 'smtp_connect_failed' => 'SMTP connect() failed.',
  1296. 'smtp_error' => 'SMTP server error: ',
  1297. 'variable_set' => 'Cannot set or reset variable: '
  1298. );
  1299. if (empty($lang_path)) {
  1300. // Calculate an absolute path so it can work if CWD is not here
  1301. $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
  1302. }
  1303. $foundlang = true;
  1304. $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  1305. if ($langcode != 'en') { // There is no English translation file
  1306. // Make sure language file path is readable
  1307. if (!is_readable($lang_file)) {
  1308. $foundlang = false;
  1309. } else {
  1310. // Overwrite language-specific strings.
  1311. // This way we'll never have missing translations.
  1312. $foundlang = include $lang_file;
  1313. }
  1314. }
  1315. $this->language = $PHPMAILER_LANG;
  1316. return ($foundlang == true); // Returns false if language not found
  1317. }
  1318. /**
  1319. * Get the array of strings for the current language.
  1320. * @return array
  1321. */
  1322. public function getTranslations()
  1323. {
  1324. return $this->language;
  1325. }
  1326. /**
  1327. * Create recipient headers.
  1328. * @access public
  1329. * @param string $type
  1330. * @param array $addr An array of recipient,
  1331. * where each recipient is a 2-element indexed array with element 0 containing an address
  1332. * and element 1 containing a name, like:
  1333. * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
  1334. * @return string
  1335. */
  1336. public function addrAppend($type, $addr)
  1337. {
  1338. $addresses = array();
  1339. foreach ($addr as $address) {
  1340. $addresses[] = $this->addrFormat($address);
  1341. }
  1342. return $type . ': ' . implode(', ', $addresses) . $this->LE;
  1343. }
  1344. /**
  1345. * Format an address for use in a message header.
  1346. * @access public
  1347. * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
  1348. * like array('joe@example.com', 'Joe User')
  1349. * @return string
  1350. */
  1351. public function addrFormat($addr)
  1352. {
  1353. if (empty($addr[1])) { // No name provided
  1354. return $this->secureHeader($addr[0]);
  1355. } else {
  1356. return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
  1357. $addr[0]
  1358. ) . '>';
  1359. }
  1360. }
  1361. /**
  1362. * Word-wrap message.
  1363. * For use with mailers that do not automatically perform wrapping
  1364. * and for quoted-printable encoded messages.
  1365. * Original written by philippe.
  1366. * @param string $message The message to wrap
  1367. * @param integer $length The line length to wrap to
  1368. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  1369. * @access public
  1370. * @return string
  1371. */
  1372. public function wrapText($message, $length, $qp_mode = false)
  1373. {
  1374. $soft_break = ($qp_mode) ? sprintf(' =%s', $this->LE) : $this->LE;
  1375. // If utf-8 encoding is used, we will need to make sure we don't
  1376. // split multibyte characters when we wrap
  1377. $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
  1378. $lelen = strlen($this->LE);
  1379. $crlflen = strlen(self::CRLF);
  1380. $message = $this->fixEOL($message);
  1381. if (substr($message, -$lelen) == $this->LE) {
  1382. $message = substr($message, 0, -$lelen);
  1383. }
  1384. $line = explode($this->LE, $message); // Magic. We know fixEOL uses $LE
  1385. $message = '';
  1386. for ($i = 0; $i < count($line); $i++) {
  1387. $line_part = explode(' ', $line[$i]);
  1388. $buf = '';
  1389. for ($e = 0; $e < count($line_part); $e++) {
  1390. $word = $line_part[$e];
  1391. if ($qp_mode and (strlen($word) > $length)) {
  1392. $space_left = $length - strlen($buf) - $crlflen;
  1393. if ($e != 0) {
  1394. if ($space_left > 20) {
  1395. $len = $space_left;
  1396. if ($is_utf8) {
  1397. $len = $this->utf8CharBoundary($word, $len);
  1398. } elseif (substr($word, $len - 1, 1) == '=') {
  1399. $len--;
  1400. } elseif (substr($word, $len - 2, 1) == '=') {
  1401. $len -= 2;
  1402. }
  1403. $part = substr($word, 0, $len);
  1404. $word = substr($word, $len);
  1405. $buf .= ' ' . $part;
  1406. $message .= $buf . sprintf('=%s', self::CRLF);
  1407. } else {
  1408. $message .= $buf . $soft_break;
  1409. }
  1410. $buf = '';
  1411. }
  1412. while (strlen($word) > 0) {
  1413. if ($length <= 0) {
  1414. break;
  1415. }
  1416. $len = $length;
  1417. if ($is_utf8) {
  1418. $len = $this->utf8CharBoundary($word, $len);
  1419. } elseif (substr($word, $len - 1, 1) == '=') {
  1420. $len--;
  1421. } elseif (substr($word, $len - 2, 1) == '=') {
  1422. $len -= 2;
  1423. }
  1424. $part = substr($word, 0, $len);
  1425. $word = substr($word, $len);
  1426. if (strlen($word) > 0) {
  1427. $message .= $part . sprintf('=%s', self::CRLF);
  1428. } else {
  1429. $buf = $part;
  1430. }
  1431. }
  1432. } else {
  1433. $buf_o = $buf;
  1434. $buf .= ($e == 0) ? $word : (' ' . $word);
  1435. if (strlen($buf) > $length and $buf_o != '') {
  1436. $message .= $buf_o . $soft_break;
  1437. $buf = $word;
  1438. }
  1439. }
  1440. }
  1441. $message .= $buf . self::CRLF;
  1442. }
  1443. return $message;
  1444. }
  1445. /**
  1446. * Find the last character boundary prior to $maxLength in a utf-8
  1447. * quoted (printable) encoded string.
  1448. * Original written by Colin Brown.
  1449. * @access public
  1450. * @param string $encodedText utf-8 QP text
  1451. * @param integer $maxLength find last character boundary prior to this length
  1452. * @return integer
  1453. */
  1454. public function utf8CharBoundary($encodedText, $maxLength)
  1455. {
  1456. $foundSplitPos = false;
  1457. $lookBack = 3;
  1458. while (!$foundSplitPos) {
  1459. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1460. $encodedCharPos = strpos($lastChunk, '=');
  1461. if ($encodedCharPos !== false) {
  1462. // Found start of encoded character byte within $lookBack block.
  1463. // Check the encoded byte value (the 2 chars after the '=')
  1464. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1465. $dec = hexdec($hex);
  1466. if ($dec < 128) { // Single byte character.
  1467. // If the encoded char was found at pos 0, it will fit
  1468. // otherwise reduce maxLength to start of the encoded char
  1469. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  1470. $maxLength - ($lookBack - $encodedCharPos);
  1471. $foundSplitPos = true;
  1472. } elseif ($dec >= 192) { // First byte of a multi byte character
  1473. // Reduce maxLength to split at start of character
  1474. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1475. $foundSplitPos = true;
  1476. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  1477. $lookBack += 3;
  1478. }
  1479. } else {
  1480. // No encoded character found
  1481. $foundSplitPos = true;
  1482. }
  1483. }
  1484. return $maxLength;
  1485. }
  1486. /**
  1487. * Set the body wrapping.
  1488. * @access public
  1489. * @return void
  1490. */
  1491. public function setWordWrap()
  1492. {
  1493. if ($this->WordWrap < 1) {
  1494. return;
  1495. }
  1496. switch ($this->message_type) {
  1497. case 'alt':
  1498. case 'alt_inline':
  1499. case 'alt_attach':
  1500. case 'alt_inline_attach':
  1501. $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  1502. break;
  1503. default:
  1504. $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  1505. break;
  1506. }
  1507. }
  1508. /**
  1509. * Assemble message headers.
  1510. * @access public
  1511. * @return string The assembled headers
  1512. */
  1513. public function createHeader()
  1514. {
  1515. $result = '';
  1516. // Set the boundaries
  1517. $uniq_id = md5(uniqid(time()));
  1518. $this->boundary[1] = 'b1_' . $uniq_id;
  1519. $this->boundary[2] = 'b2_' . $uniq_id;
  1520. $this->boundary[3] = 'b3_' . $uniq_id;
  1521. if ($this->MessageDate == '') {
  1522. $this->MessageDate = self::rfcDate();
  1523. }
  1524. $result .= $this->headerLine('Date', $this->MessageDate);
  1525. // To be created automatically by mail()
  1526. if ($this->SingleTo === true) {
  1527. if ($this->Mailer != 'mail') {
  1528. foreach ($this->to as $toaddr) {
  1529. $this->SingleToArray[] = $this->addrFormat($toaddr);
  1530. }
  1531. }
  1532. } else {
  1533. if (count($this->to) > 0) {
  1534. if ($this->Mailer != 'mail') {
  1535. $result .= $this->addrAppend('To', $this->to);
  1536. }
  1537. } elseif (count($this->cc) == 0) {
  1538. $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  1539. }
  1540. }
  1541. $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  1542. // sendmail and mail() extract Cc from the header before sending
  1543. if (count($this->cc) > 0) {
  1544. $result .= $this->addrAppend('Cc', $this->cc);
  1545. }
  1546. // sendmail and mail() extract Bcc from the header before sending
  1547. if ((
  1548. $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
  1549. )
  1550. and count($this->bcc) > 0
  1551. ) {
  1552. $result .= $this->addrAppend('Bcc', $this->bcc);
  1553. }
  1554. if (count($this->ReplyTo) > 0) {
  1555. $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  1556. }
  1557. // mail() sets the subject itself
  1558. if ($this->Mailer != 'mail') {
  1559. $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  1560. }
  1561. if ($this->MessageID != '') {
  1562. $this->lastMessageID = $this->MessageID;
  1563. } else {
  1564. $this->lastMessageID = sprintf('<%s@%s>', $uniq_id, $this->ServerHostname());
  1565. }
  1566. $result .= $this->HeaderLine('Message-ID', $this->lastMessageID);
  1567. $result .= $this->headerLine('X-Priority', $this->Priority);
  1568. if ($this->XMailer == '') {
  1569. $result .= $this->headerLine(
  1570. 'X-Mailer',
  1571. 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer/)'
  1572. );
  1573. } else {
  1574. $myXmailer = trim($this->XMailer);
  1575. if ($myXmailer) {
  1576. $result .= $this->headerLine('X-Mailer', $myXmailer);
  1577. }
  1578. }
  1579. if ($this->ConfirmReadingTo != '') {
  1580. $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1581. }
  1582. // Add custom headers
  1583. for ($index = 0; $index < count($this->CustomHeader); $index++) {
  1584. $result .= $this->headerLine(
  1585. trim($this->CustomHeader[$index][0]),
  1586. $this->encodeHeader(trim($this->CustomHeader[$index][1]))
  1587. );
  1588. }
  1589. if (!$this->sign_key_file) {
  1590. $result .= $this->headerLine('MIME-Version', '1.0');
  1591. $result .= $this->getMailMIME();
  1592. }
  1593. return $result;
  1594. }
  1595. /**
  1596. * Get the message MIME type headers.
  1597. * @access public
  1598. * @return string
  1599. */
  1600. public function getMailMIME()
  1601. {
  1602. $result = '';
  1603. $ismultipart = true;
  1604. switch ($this->message_type) {
  1605. case 'inline':
  1606. $result .= $this->headerLine('Content-Type', 'multipart/related;');
  1607. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1608. break;
  1609. case 'attach':
  1610. case 'inline_attach':
  1611. case 'alt_attach':
  1612. case 'alt_inline_attach':
  1613. $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  1614. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1615. break;
  1616. case 'alt':
  1617. case 'alt_inline':
  1618. $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1619. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1620. break;
  1621. default:
  1622. // Catches case 'plain': and case '':
  1623. $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  1624. $ismultipart = false;
  1625. break;
  1626. }
  1627. // RFC1341 part 5 says 7bit is assumed if not specified
  1628. if ($this->Encoding != '7bit') {
  1629. // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  1630. if ($ismultipart) {
  1631. if ($this->Encoding == '8bit') {
  1632. $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
  1633. }
  1634. // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  1635. } else {
  1636. $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  1637. }
  1638. }
  1639. if ($this->Mailer != 'mail') {
  1640. $result .= $this->LE;
  1641. }
  1642. return $result;
  1643. }
  1644. /**
  1645. * Returns the whole MIME message.
  1646. * Includes complete headers and body.
  1647. * Only valid post preSend().
  1648. * @see PHPMailer::preSend()
  1649. * @access public
  1650. * @return string
  1651. */
  1652. public function getSentMIMEMessage()
  1653. {
  1654. return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  1655. }
  1656. /**
  1657. * Assemble the message body.
  1658. * Returns an empty string on failure.
  1659. * @access public
  1660. * @throws phpmailerException
  1661. * @return string The assembled message body
  1662. */
  1663. public function createBody()
  1664. {
  1665. $body = '';
  1666. if ($this->sign_key_file) {
  1667. $body .= $this->getMailMIME() . $this->LE;
  1668. }
  1669. $this->setWordWrap();
  1670. $bodyEncoding = $this->Encoding;
  1671. $bodyCharSet = $this->CharSet;
  1672. if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
  1673. $bodyEncoding = '7bit';
  1674. $bodyCharSet = 'us-ascii';
  1675. }
  1676. $altBodyEncoding = $this->Encoding;
  1677. $altBodyCharSet = $this->CharSet;
  1678. if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
  1679. $altBodyEncoding = '7bit';
  1680. $altBodyCharSet = 'us-ascii';
  1681. }
  1682. switch ($this->message_type) {
  1683. case 'inline':
  1684. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1685. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1686. $body .= $this->LE . $this->LE;
  1687. $body .= $this->attachAll('inline', $this->boundary[1]);
  1688. break;
  1689. case 'attach':
  1690. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1691. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1692. $body .= $this->LE . $this->LE;
  1693. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1694. break;
  1695. case 'inline_attach':
  1696. $body .= $this->textLine('--' . $this->boundary[1]);
  1697. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1698. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1699. $body .= $this->LE;
  1700. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  1701. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1702. $body .= $this->LE . $this->LE;
  1703. $body .= $this->attachAll('inline', $this->boundary[2]);
  1704. $body .= $this->LE;
  1705. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1706. break;
  1707. case 'alt':
  1708. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1709. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1710. $body .= $this->LE . $this->LE;
  1711. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  1712. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1713. $body .= $this->LE . $this->LE;
  1714. if (!empty($this->Ical)) {
  1715. $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  1716. $body .= $this->encodeString($this->Ical, $this->Encoding);
  1717. $body .= $this->LE . $this->LE;
  1718. }
  1719. $body .= $this->endBoundary($this->boundary[1]);
  1720. break;
  1721. case 'alt_inline':
  1722. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1723. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1724. $body .= $this->LE . $this->LE;
  1725. $body .= $this->textLine('--' . $this->boundary[1]);
  1726. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1727. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1728. $body .= $this->LE;
  1729. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1730. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1731. $body .= $this->LE . $this->LE;
  1732. $body .= $this->attachAll('inline', $this->boundary[2]);
  1733. $body .= $this->LE;
  1734. $body .= $this->endBoundary($this->boundary[1]);
  1735. break;
  1736. case 'alt_attach':
  1737. $body .= $this->textLine('--' . $this->boundary[1]);
  1738. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1739. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1740. $body .= $this->LE;
  1741. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1742. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1743. $body .= $this->LE . $this->LE;
  1744. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1745. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1746. $body .= $this->LE . $this->LE;
  1747. $body .= $this->endBoundary($this->boundary[2]);
  1748. $body .= $this->LE;
  1749. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1750. break;
  1751. case 'alt_inline_attach':
  1752. $body .= $this->textLine('--' . $this->boundary[1]);
  1753. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1754. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1755. $body .= $this->LE;
  1756. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1757. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1758. $body .= $this->LE . $this->LE;
  1759. $body .= $this->textLine('--' . $this->boundary[2]);
  1760. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1761. $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  1762. $body .= $this->LE;
  1763. $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  1764. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1765. $body .= $this->LE . $this->LE;
  1766. $body .= $this->attachAll('inline', $this->boundary[3]);
  1767. $body .= $this->LE;
  1768. $body .= $this->endBoundary($this->boundary[2]);
  1769. $body .= $this->LE;
  1770. $body .= $this->attachAll('attachment', $this->boundary[1]);
  1771. break;
  1772. default:
  1773. // catch case 'plain' and case ''
  1774. $body .= $this->encodeString($this->Body, $bodyEncoding);
  1775. break;
  1776. }
  1777. if ($this->isError()) {
  1778. $body = '';
  1779. } elseif ($this->sign_key_file) {
  1780. try {
  1781. if (!defined('PKCS7_TEXT')) {
  1782. throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  1783. }
  1784. // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  1785. $file = tempnam(sys_get_temp_dir(), 'mail');
  1786. file_put_contents($file, $body); // @TODO check this worked
  1787. $signed = tempnam(sys_get_temp_dir(), 'signed');
  1788. if (@openssl_pkcs7_sign(
  1789. $file,
  1790. $signed,
  1791. 'file://' . realpath($this->sign_cert_file),
  1792. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  1793. null
  1794. )
  1795. ) {
  1796. @unlink($file);
  1797. $body = file_get_contents($signed);
  1798. @unlink($signed);
  1799. } else {
  1800. @unlink($file);
  1801. @unlink($signed);
  1802. throw new phpmailerException($this->lang('signing') . openssl_error_string());
  1803. }
  1804. } catch (phpmailerException $exc) {
  1805. $body = '';
  1806. if ($this->exceptions) {
  1807. throw $exc;
  1808. }
  1809. }
  1810. }
  1811. return $body;
  1812. }
  1813. /**
  1814. * Return the start of a message boundary.
  1815. * @access protected
  1816. * @param string $boundary
  1817. * @param string $charSet
  1818. * @param string $contentType
  1819. * @param string $encoding
  1820. * @return string
  1821. */
  1822. protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  1823. {
  1824. $result = '';
  1825. if ($charSet == '') {
  1826. $charSet = $this->CharSet;
  1827. }
  1828. if ($contentType == '') {
  1829. $contentType = $this->ContentType;
  1830. }
  1831. if ($encoding == '') {
  1832. $encoding = $this->Encoding;
  1833. }
  1834. $result .= $this->textLine('--' . $boundary);
  1835. $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  1836. $result .= $this->LE;
  1837. // RFC1341 part 5 says 7bit is assumed if not specified
  1838. if ($encoding != '7bit') {
  1839. $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  1840. }
  1841. $result .= $this->LE;
  1842. return $result;
  1843. }
  1844. /**
  1845. * Return the end of a message boundary.
  1846. * @access protected
  1847. * @param string $boundary
  1848. * @return string
  1849. */
  1850. protected function endBoundary($boundary)
  1851. {
  1852. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1853. }
  1854. /**
  1855. * Set the message type.
  1856. * PHPMailer only supports some preset message types,
  1857. * not arbitrary MIME structures.
  1858. * @access protected
  1859. * @return void
  1860. */
  1861. protected function setMessageType()
  1862. {
  1863. $type = array();
  1864. if ($this->alternativeExists()) {
  1865. $type[] = 'alt';
  1866. }
  1867. if ($this->inlineImageExists()) {
  1868. $type[] = 'inline';
  1869. }
  1870. if ($this->attachmentExists()) {
  1871. $type[] = 'attach';
  1872. }
  1873. $this->message_type = implode('_', $type);
  1874. if ($this->message_type == '') {
  1875. $this->message_type = 'plain';
  1876. }
  1877. }
  1878. /**
  1879. * Format a header line.
  1880. * @access public
  1881. * @param string $name
  1882. * @param string $value
  1883. * @return string
  1884. */
  1885. public function headerLine($name, $value)
  1886. {
  1887. return $name . ': ' . $value . $this->LE;
  1888. }
  1889. /**
  1890. * Return a formatted mail line.
  1891. * @access public
  1892. * @param string $value
  1893. * @return string
  1894. */
  1895. public function textLine($value)
  1896. {
  1897. return $value . $this->LE;
  1898. }
  1899. /**
  1900. * Add an attachment from a path on the filesystem.
  1901. * Returns false if the file could not be found or read.
  1902. * @param string $path Path to the attachment.
  1903. * @param string $name Overrides the attachment name.
  1904. * @param string $encoding File encoding (see $Encoding).
  1905. * @param string $type File extension (MIME) type.
  1906. * @param string $disposition Disposition to use
  1907. * @throws phpmailerException
  1908. * @return boolean
  1909. */
  1910. public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  1911. {
  1912. try {
  1913. if (!@is_file($path)) {
  1914. throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  1915. }
  1916. // If a MIME type is not specified, try to work it out from the file name
  1917. if ($type == '') {
  1918. $type = self::filenameToType($path);
  1919. }
  1920. $filename = basename($path);
  1921. if ($name == '') {
  1922. $name = $filename;
  1923. }
  1924. $this->attachment[] = array(
  1925. 0 => $path,
  1926. 1 => $filename,
  1927. 2 => $name,
  1928. 3 => $encoding,
  1929. 4 => $type,
  1930. 5 => false, // isStringAttachment
  1931. 6 => $disposition,
  1932. 7 => 0
  1933. );
  1934. } catch (phpmailerException $exc) {
  1935. $this->setError($exc->getMessage());
  1936. $this->edebug($exc->getMessage());
  1937. if ($this->exceptions) {
  1938. throw $exc;
  1939. }
  1940. return false;
  1941. }
  1942. return true;
  1943. }
  1944. /**
  1945. * Return the array of attachments.
  1946. * @return array
  1947. */
  1948. public function getAttachments()
  1949. {
  1950. return $this->attachment;
  1951. }
  1952. /**
  1953. * Attach all file, string, and binary attachments to the message.
  1954. * Returns an empty string on failure.
  1955. * @access protected
  1956. * @param string $disposition_type
  1957. * @param string $boundary
  1958. * @return string
  1959. */
  1960. protected function attachAll($disposition_type, $boundary)
  1961. {
  1962. // Return text of body
  1963. $mime = array();
  1964. $cidUniq = array();
  1965. $incl = array();
  1966. // Add all attachments
  1967. foreach ($this->attachment as $attachment) {
  1968. // Check if it is a valid disposition_filter
  1969. if ($attachment[6] == $disposition_type) {
  1970. // Check for string attachment
  1971. $string = '';
  1972. $path = '';
  1973. $bString = $attachment[5];
  1974. if ($bString) {
  1975. $string = $attachment[0];
  1976. } else {
  1977. $path = $attachment[0];
  1978. }
  1979. $inclhash = md5(serialize($attachment));
  1980. if (in_array($inclhash, $incl)) {
  1981. continue;
  1982. }
  1983. $incl[] = $inclhash;
  1984. $name = $attachment[2];
  1985. $encoding = $attachment[3];
  1986. $type = $attachment[4];
  1987. $disposition = $attachment[6];
  1988. $cid = $attachment[7];
  1989. if ($disposition == 'inline' && isset($cidUniq[$cid])) {
  1990. continue;
  1991. }
  1992. $cidUniq[$cid] = true;
  1993. $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  1994. $mime[] = sprintf(
  1995. 'Content-Type: %s; name="%s"%s',
  1996. $type,
  1997. $this->encodeHeader($this->secureHeader($name)),
  1998. $this->LE
  1999. );
  2000. // RFC1341 part 5 says 7bit is assumed if not specified
  2001. if ($encoding != '7bit') {
  2002. $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  2003. }
  2004. if ($disposition == 'inline') {
  2005. $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
  2006. }
  2007. // If a filename contains any of these chars, it should be quoted,
  2008. // but not otherwise: RFC2183 & RFC2045 5.1
  2009. // Fixes a warning in IETF's msglint MIME checker
  2010. // Allow for bypassing the Content-Disposition header totally
  2011. if (!(empty($disposition))) {
  2012. $encoded_name = $this->encodeHeader($this->secureHeader($name));
  2013. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  2014. $mime[] = sprintf(
  2015. 'Content-Disposition: %s; filename="%s"%s',
  2016. $disposition,
  2017. $encoded_name,
  2018. $this->LE . $this->LE
  2019. );
  2020. } else {
  2021. $mime[] = sprintf(
  2022. 'Content-Disposition: %s; filename=%s%s',
  2023. $disposition,
  2024. $encoded_name,
  2025. $this->LE . $this->LE
  2026. );
  2027. }
  2028. } else {
  2029. $mime[] = $this->LE;
  2030. }
  2031. // Encode as string attachment
  2032. if ($bString) {
  2033. $mime[] = $this->encodeString($string, $encoding);
  2034. if ($this->isError()) {
  2035. return '';
  2036. }
  2037. $mime[] = $this->LE . $this->LE;
  2038. } else {
  2039. $mime[] = $this->encodeFile($path, $encoding);
  2040. if ($this->isError()) {
  2041. return '';
  2042. }
  2043. $mime[] = $this->LE . $this->LE;
  2044. }
  2045. }
  2046. }
  2047. $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  2048. return implode('', $mime);
  2049. }
  2050. /**
  2051. * Encode a file attachment in requested format.
  2052. * Returns an empty string on failure.
  2053. * @param string $path The full path to the file
  2054. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2055. * @throws phpmailerException
  2056. * @see EncodeFile(encodeFile
  2057. * @access protected
  2058. * @return string
  2059. */
  2060. protected function encodeFile($path, $encoding = 'base64')
  2061. {
  2062. try {
  2063. if (!is_readable($path)) {
  2064. throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2065. }
  2066. $magic_quotes = get_magic_quotes_runtime();
  2067. if ($magic_quotes) {
  2068. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2069. set_magic_quotes_runtime(false);
  2070. } else {
  2071. //Doesn't exist in PHP 5.4, but we don't need to check because
  2072. //get_magic_quotes_runtime always returns false in 5.4+
  2073. //so it will never get here
  2074. ini_set('magic_quotes_runtime', 0);
  2075. }
  2076. }
  2077. $file_buffer = file_get_contents($path);
  2078. $file_buffer = $this->encodeString($file_buffer, $encoding);
  2079. if ($magic_quotes) {
  2080. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2081. set_magic_quotes_runtime($magic_quotes);
  2082. } else {
  2083. ini_set('magic_quotes_runtime', ($magic_quotes?'1':'0'));
  2084. }
  2085. }
  2086. return $file_buffer;
  2087. } catch (Exception $exc) {
  2088. $this->setError($exc->getMessage());
  2089. return '';
  2090. }
  2091. }
  2092. /**
  2093. * Encode a string in requested format.
  2094. * Returns an empty string on failure.
  2095. * @param string $str The text to encode
  2096. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2097. * @access public
  2098. * @return string
  2099. */
  2100. public function encodeString($str, $encoding = 'base64')
  2101. {
  2102. $encoded = '';
  2103. switch (strtolower($encoding)) {
  2104. case 'base64':
  2105. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  2106. break;
  2107. case '7bit':
  2108. case '8bit':
  2109. $encoded = $this->fixEOL($str);
  2110. // Make sure it ends with a line break
  2111. if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  2112. $encoded .= $this->LE;
  2113. }
  2114. break;
  2115. case 'binary':
  2116. $encoded = $str;
  2117. break;
  2118. case 'quoted-printable':
  2119. $encoded = $this->encodeQP($str);
  2120. break;
  2121. default:
  2122. $this->setError($this->lang('encoding') . $encoding);
  2123. break;
  2124. }
  2125. return $encoded;
  2126. }
  2127. /**
  2128. * Encode a header string optimally.
  2129. * Picks shortest of Q, B, quoted-printable or none.
  2130. * @access public
  2131. * @param string $str
  2132. * @param string $position
  2133. * @return string
  2134. */
  2135. public function encodeHeader($str, $position = 'text')
  2136. {
  2137. $matchcount = 0;
  2138. switch (strtolower($position)) {
  2139. case 'phrase':
  2140. if (!preg_match('/[\200-\377]/', $str)) {
  2141. // Can't use addslashes as we don't know the value of magic_quotes_sybase
  2142. $encoded = addcslashes($str, "\0..\37\177\\\"");
  2143. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  2144. return ($encoded);
  2145. } else {
  2146. return ("\"$encoded\"");
  2147. }
  2148. }
  2149. $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  2150. break;
  2151. /** @noinspection PhpMissingBreakStatementInspection */
  2152. case 'comment':
  2153. $matchcount = preg_match_all('/[()"]/', $str, $matches);
  2154. // Intentional fall-through
  2155. case 'text':
  2156. default:
  2157. $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  2158. break;
  2159. }
  2160. if ($matchcount == 0) { // There are no chars that need encoding
  2161. return ($str);
  2162. }
  2163. $maxlen = 75 - 7 - strlen($this->CharSet);
  2164. // Try to select the encoding which should produce the shortest output
  2165. if ($matchcount > strlen($str) / 3) {
  2166. // More than a third of the content will need encoding, so B encoding will be most efficient
  2167. $encoding = 'B';
  2168. if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  2169. // Use a custom function which correctly encodes and wraps long
  2170. // multibyte strings without breaking lines within a character
  2171. $encoded = $this->base64EncodeWrapMB($str, "\n");
  2172. } else {
  2173. $encoded = base64_encode($str);
  2174. $maxlen -= $maxlen % 4;
  2175. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  2176. }
  2177. } else {
  2178. $encoding = 'Q';
  2179. $encoded = $this->encodeQ($str, $position);
  2180. $encoded = $this->wrapText($encoded, $maxlen, true);
  2181. $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  2182. }
  2183. $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2184. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  2185. return $encoded;
  2186. }
  2187. /**
  2188. * Check if a string contains multi-byte characters.
  2189. * @access public
  2190. * @param string $str multi-byte text to wrap encode
  2191. * @return boolean
  2192. */
  2193. public function hasMultiBytes($str)
  2194. {
  2195. if (function_exists('mb_strlen')) {
  2196. return (strlen($str) > mb_strlen($str, $this->CharSet));
  2197. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  2198. return false;
  2199. }
  2200. }
  2201. /**
  2202. * Does a string contain any 8-bit chars (in any charset)?
  2203. * @param string $text
  2204. * @return boolean
  2205. */
  2206. public function has8bitChars($text)
  2207. {
  2208. return (boolean)preg_match('/[\x80-\xFF]/', $text);
  2209. }
  2210. /**
  2211. * Encode and wrap long multibyte strings for mail headers
  2212. * without breaking lines within a character.
  2213. * Adapted from a function by paravoid
  2214. * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  2215. * @access public
  2216. * @param string $str multi-byte text to wrap encode
  2217. * @param string $linebreak string to use as linefeed/end-of-line
  2218. * @return string
  2219. */
  2220. public function base64EncodeWrapMB($str, $linebreak = null)
  2221. {
  2222. $start = '=?' . $this->CharSet . '?B?';
  2223. $end = '?=';
  2224. $encoded = '';
  2225. if ($linebreak === null) {
  2226. $linebreak = $this->LE;
  2227. }
  2228. $mb_length = mb_strlen($str, $this->CharSet);
  2229. // Each line must have length <= 75, including $start and $end
  2230. $length = 75 - strlen($start) - strlen($end);
  2231. // Average multi-byte ratio
  2232. $ratio = $mb_length / strlen($str);
  2233. // Base64 has a 4:3 ratio
  2234. $avgLength = floor($length * $ratio * .75);
  2235. for ($i = 0; $i < $mb_length; $i += $offset) {
  2236. $lookBack = 0;
  2237. do {
  2238. $offset = $avgLength - $lookBack;
  2239. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  2240. $chunk = base64_encode($chunk);
  2241. $lookBack++;
  2242. } while (strlen($chunk) > $length);
  2243. $encoded .= $chunk . $linebreak;
  2244. }
  2245. // Chomp the last linefeed
  2246. $encoded = substr($encoded, 0, -strlen($linebreak));
  2247. return $encoded;
  2248. }
  2249. /**
  2250. * Encode a string in quoted-printable format.
  2251. * According to RFC2045 section 6.7.
  2252. * @access public
  2253. * @param string $string The text to encode
  2254. * @param integer $line_max Number of chars allowed on a line before wrapping
  2255. * @return string
  2256. * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
  2257. */
  2258. public function encodeQP($string, $line_max = 76)
  2259. {
  2260. if (function_exists('quoted_printable_encode')) { // Use native function if it's available (>= PHP5.3)
  2261. return $this->fixEOL(quoted_printable_encode($string));
  2262. }
  2263. // Fall back to a pure PHP implementation
  2264. $string = str_replace(
  2265. array('%20', '%0D%0A.', '%0D%0A', '%'),
  2266. array(' ', "\r\n=2E", "\r\n", '='),
  2267. rawurlencode($string)
  2268. );
  2269. $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  2270. return $this->fixEOL($string);
  2271. }
  2272. /**
  2273. * Backward compatibility wrapper for an old QP encoding function that was removed.
  2274. * @see PHPMailer::encodeQP()
  2275. * @access public
  2276. * @param string $string
  2277. * @param integer $line_max
  2278. * @param boolean $space_conv
  2279. * @return string
  2280. * @deprecated Use encodeQP instead.
  2281. */
  2282. public function encodeQPphp(
  2283. $string,
  2284. $line_max = 76,
  2285. /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
  2286. ) {
  2287. return $this->encodeQP($string, $line_max);
  2288. }
  2289. /**
  2290. * Encode a string using Q encoding.
  2291. * @link http://tools.ietf.org/html/rfc2047
  2292. * @param string $str the text to encode
  2293. * @param string $position Where the text is going to be used, see the RFC for what that means
  2294. * @access public
  2295. * @return string
  2296. */
  2297. public function encodeQ($str, $position = 'text')
  2298. {
  2299. // There should not be any EOL in the string
  2300. $pattern = '';
  2301. $encoded = str_replace(array("\r", "\n"), '', $str);
  2302. switch (strtolower($position)) {
  2303. case 'phrase':
  2304. // RFC 2047 section 5.3
  2305. $pattern = '^A-Za-z0-9!*+\/ -';
  2306. break;
  2307. /** @noinspection PhpMissingBreakStatementInspection */
  2308. case 'comment':
  2309. // RFC 2047 section 5.2
  2310. $pattern = '\(\)"';
  2311. // intentional fall-through
  2312. // for this reason we build the $pattern without including delimiters and []
  2313. case 'text':
  2314. default:
  2315. // RFC 2047 section 5.1
  2316. // Replace every high ascii, control, =, ? and _ characters
  2317. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  2318. break;
  2319. }
  2320. $matches = array();
  2321. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  2322. // If the string contains an '=', make sure it's the first thing we replace
  2323. // so as to avoid double-encoding
  2324. $eqkey = array_search('=', $matches[0]);
  2325. if ($eqkey !== false) {
  2326. unset($matches[0][$eqkey]);
  2327. array_unshift($matches[0], '=');
  2328. }
  2329. foreach (array_unique($matches[0]) as $char) {
  2330. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  2331. }
  2332. }
  2333. // Replace every spaces to _ (more readable than =20)
  2334. return str_replace(' ', '_', $encoded);
  2335. }
  2336. /**
  2337. * Add a string or binary attachment (non-filesystem).
  2338. * This method can be used to attach ascii or binary data,
  2339. * such as a BLOB record from a database.
  2340. * @param string $string String attachment data.
  2341. * @param string $filename Name of the attachment.
  2342. * @param string $encoding File encoding (see $Encoding).
  2343. * @param string $type File extension (MIME) type.
  2344. * @param string $disposition Disposition to use
  2345. * @return void
  2346. */
  2347. public function addStringAttachment(
  2348. $string,
  2349. $filename,
  2350. $encoding = 'base64',
  2351. $type = '',
  2352. $disposition = 'attachment'
  2353. ) {
  2354. // If a MIME type is not specified, try to work it out from the file name
  2355. if ($type == '') {
  2356. $type = self::filenameToType($filename);
  2357. }
  2358. // Append to $attachment array
  2359. $this->attachment[] = array(
  2360. 0 => $string,
  2361. 1 => $filename,
  2362. 2 => basename($filename),
  2363. 3 => $encoding,
  2364. 4 => $type,
  2365. 5 => true, // isStringAttachment
  2366. 6 => $disposition,
  2367. 7 => 0
  2368. );
  2369. }
  2370. /**
  2371. * Add an embedded (inline) attachment from a file.
  2372. * This can include images, sounds, and just about any other document type.
  2373. * These differ from 'regular' attachmants in that they are intended to be
  2374. * displayed inline with the message, not just attached for download.
  2375. * This is used in HTML messages that embed the images
  2376. * the HTML refers to using the $cid value.
  2377. * @param string $path Path to the attachment.
  2378. * @param string $cid Content ID of the attachment; Use this to reference
  2379. * the content when using an embedded image in HTML.
  2380. * @param string $name Overrides the attachment name.
  2381. * @param string $encoding File encoding (see $Encoding).
  2382. * @param string $type File MIME type.
  2383. * @param string $disposition Disposition to use
  2384. * @return boolean True on successfully adding an attachment
  2385. */
  2386. public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  2387. {
  2388. if (!@is_file($path)) {
  2389. $this->setError($this->lang('file_access') . $path);
  2390. return false;
  2391. }
  2392. // If a MIME type is not specified, try to work it out from the file name
  2393. if ($type == '') {
  2394. $type = self::filenameToType($path);
  2395. }
  2396. $filename = basename($path);
  2397. if ($name == '') {
  2398. $name = $filename;
  2399. }
  2400. // Append to $attachment array
  2401. $this->attachment[] = array(
  2402. 0 => $path,
  2403. 1 => $filename,
  2404. 2 => $name,
  2405. 3 => $encoding,
  2406. 4 => $type,
  2407. 5 => false, // isStringAttachment
  2408. 6 => $disposition,
  2409. 7 => $cid
  2410. );
  2411. return true;
  2412. }
  2413. /**
  2414. * Add an embedded stringified attachment.
  2415. * This can include images, sounds, and just about any other document type.
  2416. * Be sure to set the $type to an image type for images:
  2417. * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  2418. * @param string $string The attachment binary data.
  2419. * @param string $cid Content ID of the attachment; Use this to reference
  2420. * the content when using an embedded image in HTML.
  2421. * @param string $name
  2422. * @param string $encoding File encoding (see $Encoding).
  2423. * @param string $type MIME type.
  2424. * @param string $disposition Disposition to use
  2425. * @return boolean True on successfully adding an attachment
  2426. */
  2427. public function addStringEmbeddedImage(
  2428. $string,
  2429. $cid,
  2430. $name = '',
  2431. $encoding = 'base64',
  2432. $type = '',
  2433. $disposition = 'inline'
  2434. ) {
  2435. // If a MIME type is not specified, try to work it out from the name
  2436. if ($type == '') {
  2437. $type = self::filenameToType($name);
  2438. }
  2439. // Append to $attachment array
  2440. $this->attachment[] = array(
  2441. 0 => $string,
  2442. 1 => $name,
  2443. 2 => $name,
  2444. 3 => $encoding,
  2445. 4 => $type,
  2446. 5 => true, // isStringAttachment
  2447. 6 => $disposition,
  2448. 7 => $cid
  2449. );
  2450. return true;
  2451. }
  2452. /**
  2453. * Check if an inline attachment is present.
  2454. * @access public
  2455. * @return boolean
  2456. */
  2457. public function inlineImageExists()
  2458. {
  2459. foreach ($this->attachment as $attachment) {
  2460. if ($attachment[6] == 'inline') {
  2461. return true;
  2462. }
  2463. }
  2464. return false;
  2465. }
  2466. /**
  2467. * Check if an attachment (non-inline) is present.
  2468. * @return boolean
  2469. */
  2470. public function attachmentExists()
  2471. {
  2472. foreach ($this->attachment as $attachment) {
  2473. if ($attachment[6] == 'attachment') {
  2474. return true;
  2475. }
  2476. }
  2477. return false;
  2478. }
  2479. /**
  2480. * Check if this message has an alternative body set.
  2481. * @return boolean
  2482. */
  2483. public function alternativeExists()
  2484. {
  2485. return !empty($this->AltBody);
  2486. }
  2487. /**
  2488. * Clear all To recipients.
  2489. * @return void
  2490. */
  2491. public function clearAddresses()
  2492. {
  2493. foreach ($this->to as $to) {
  2494. unset($this->all_recipients[strtolower($to[0])]);
  2495. }
  2496. $this->to = array();
  2497. }
  2498. /**
  2499. * Clear all CC recipients.
  2500. * @return void
  2501. */
  2502. public function clearCCs()
  2503. {
  2504. foreach ($this->cc as $cc) {
  2505. unset($this->all_recipients[strtolower($cc[0])]);
  2506. }
  2507. $this->cc = array();
  2508. }
  2509. /**
  2510. * Clear all BCC recipients.
  2511. * @return void
  2512. */
  2513. public function clearBCCs()
  2514. {
  2515. foreach ($this->bcc as $bcc) {
  2516. unset($this->all_recipients[strtolower($bcc[0])]);
  2517. }
  2518. $this->bcc = array();
  2519. }
  2520. /**
  2521. * Clear all ReplyTo recipients.
  2522. * @return void
  2523. */
  2524. public function clearReplyTos()
  2525. {
  2526. $this->ReplyTo = array();
  2527. }
  2528. /**
  2529. * Clear all recipient types.
  2530. * @return void
  2531. */
  2532. public function clearAllRecipients()
  2533. {
  2534. $this->to = array();
  2535. $this->cc = array();
  2536. $this->bcc = array();
  2537. $this->all_recipients = array();
  2538. }
  2539. /**
  2540. * Clear all filesystem, string, and binary attachments.
  2541. * @return void
  2542. */
  2543. public function clearAttachments()
  2544. {
  2545. $this->attachment = array();
  2546. }
  2547. /**
  2548. * Clear all custom headers.
  2549. * @return void
  2550. */
  2551. public function clearCustomHeaders()
  2552. {
  2553. $this->CustomHeader = array();
  2554. }
  2555. /**
  2556. * Add an error message to the error container.
  2557. * @access protected
  2558. * @param string $msg
  2559. * @return void
  2560. */
  2561. protected function setError($msg)
  2562. {
  2563. $this->error_count++;
  2564. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2565. $lasterror = $this->smtp->getError();
  2566. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2567. $msg .= '<p>' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  2568. }
  2569. }
  2570. $this->ErrorInfo = $msg;
  2571. }
  2572. /**
  2573. * Return an RFC 822 formatted date.
  2574. * @access public
  2575. * @return string
  2576. * @static
  2577. */
  2578. public static function rfcDate()
  2579. {
  2580. // Set the time zone to whatever the default is to avoid 500 errors
  2581. // Will default to UTC if it's not set properly in php.ini
  2582. date_default_timezone_set(@date_default_timezone_get());
  2583. return date('D, j M Y H:i:s O');
  2584. }
  2585. /**
  2586. * Get the server hostname.
  2587. * Returns 'localhost.localdomain' if unknown.
  2588. * @access protected
  2589. * @return string
  2590. */
  2591. protected function serverHostname()
  2592. {
  2593. $result = 'localhost.localdomain';
  2594. if (!empty($this->Hostname)) {
  2595. $result = $this->Hostname;
  2596. } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  2597. $result = $_SERVER['SERVER_NAME'];
  2598. } elseif (function_exists('gethostname') && gethostname() !== false) {
  2599. $result = gethostname();
  2600. } elseif (php_uname('n') !== false) {
  2601. $result = php_uname('n');
  2602. }
  2603. return $result;
  2604. }
  2605. /**
  2606. * Get an error message in the current language.
  2607. * @access protected
  2608. * @param string $key
  2609. * @return string
  2610. */
  2611. protected function lang($key)
  2612. {
  2613. if (count($this->language) < 1) {
  2614. $this->setLanguage('en'); // set the default language
  2615. }
  2616. if (isset($this->language[$key])) {
  2617. return $this->language[$key];
  2618. } else {
  2619. return 'Language string failed to load: ' . $key;
  2620. }
  2621. }
  2622. /**
  2623. * Check if an error occurred.
  2624. * @access public
  2625. * @return boolean True if an error did occur.
  2626. */
  2627. public function isError()
  2628. {
  2629. return ($this->error_count > 0);
  2630. }
  2631. /**
  2632. * Ensure consistent line endings in a string.
  2633. * Changes every end of line from CRLF, CR or LF to $this->LE.
  2634. * @access public
  2635. * @param string $str String to fixEOL
  2636. * @return string
  2637. */
  2638. public function fixEOL($str)
  2639. {
  2640. // Normalise to \n
  2641. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  2642. // Now convert LE as needed
  2643. if ($this->LE !== "\n") {
  2644. $nstr = str_replace("\n", $this->LE, $nstr);
  2645. }
  2646. return $nstr;
  2647. }
  2648. /**
  2649. * Add a custom header.
  2650. * $name value can be overloaded to contain
  2651. * both header name and value (name:value)
  2652. * @access public
  2653. * @param string $name Custom header name
  2654. * @param string $value Header value
  2655. * @return void
  2656. */
  2657. public function addCustomHeader($name, $value = null)
  2658. {
  2659. if ($value === null) {
  2660. // Value passed in as name:value
  2661. $this->CustomHeader[] = explode(':', $name, 2);
  2662. } else {
  2663. $this->CustomHeader[] = array($name, $value);
  2664. }
  2665. }
  2666. /**
  2667. * Create a message from an HTML string.
  2668. * Automatically makes modifications for inline images and backgrounds
  2669. * and creates a plain-text version by converting the HTML.
  2670. * Overwrites any existing values in $this->Body and $this->AltBody
  2671. * @access public
  2672. * @param string $message HTML message string
  2673. * @param string $basedir baseline directory for path
  2674. * @param boolean $advanced Whether to use the advanced HTML to text converter
  2675. * @return string $message
  2676. */
  2677. public function msgHTML($message, $basedir = '', $advanced = false)
  2678. {
  2679. preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  2680. if (isset($images[2])) {
  2681. foreach ($images[2] as $imgindex => $url) {
  2682. // Convert data URIs into embedded images
  2683. if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
  2684. $data = substr($url, strpos($url, ','));
  2685. if ($match[2]) {
  2686. $data = base64_decode($data);
  2687. } else {
  2688. $data = rawurldecode($data);
  2689. }
  2690. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  2691. if ($this->addStringEmbeddedImage($data, $cid, '', 'base64', $match[1])) {
  2692. $message = preg_replace(
  2693. '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  2694. $images[1][$imgindex] . '="cid:' . $cid . '"',
  2695. $message
  2696. );
  2697. }
  2698. } elseif (!preg_match('#^[A-z]+://#', $url)) {
  2699. // Do not change urls for absolute images (thanks to corvuscorax)
  2700. $filename = basename($url);
  2701. $directory = dirname($url);
  2702. if ($directory == '.') {
  2703. $directory = '';
  2704. }
  2705. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  2706. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  2707. $basedir .= '/';
  2708. }
  2709. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  2710. $directory .= '/';
  2711. }
  2712. if ($this->addEmbeddedImage(
  2713. $basedir . $directory . $filename,
  2714. $cid,
  2715. $filename,
  2716. 'base64',
  2717. self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  2718. )
  2719. ) {
  2720. $message = preg_replace(
  2721. '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  2722. $images[1][$imgindex] . '="cid:' . $cid . '"',
  2723. $message
  2724. );
  2725. }
  2726. }
  2727. }
  2728. }
  2729. $this->isHTML(true);
  2730. // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  2731. $this->Body = $this->normalizeBreaks($message);
  2732. $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  2733. if (empty($this->AltBody)) {
  2734. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  2735. self::CRLF . self::CRLF;
  2736. }
  2737. return $this->Body;
  2738. }
  2739. /**
  2740. * Convert an HTML string into plain text.
  2741. * @param string $html The HTML text to convert
  2742. * @param boolean $advanced Should this use the more complex html2text converter or just a simple one?
  2743. * @return string
  2744. */
  2745. public function html2text($html, $advanced = false)
  2746. {
  2747. if ($advanced) {
  2748. require_once 'extras/class.html2text.php';
  2749. $htmlconverter = new html2text($html);
  2750. return $htmlconverter->get_text();
  2751. }
  2752. return html_entity_decode(
  2753. trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  2754. ENT_QUOTES,
  2755. $this->CharSet
  2756. );
  2757. }
  2758. /**
  2759. * Get the MIME type for a file extension.
  2760. * @param string $ext File extension
  2761. * @access public
  2762. * @return string MIME type of file.
  2763. * @static
  2764. */
  2765. public static function _mime_types($ext = '')
  2766. {
  2767. $mimes = array(
  2768. 'xl' => 'application/excel',
  2769. 'hqx' => 'application/mac-binhex40',
  2770. 'cpt' => 'application/mac-compactpro',
  2771. 'bin' => 'application/macbinary',
  2772. 'doc' => 'application/msword',
  2773. 'word' => 'application/msword',
  2774. 'class' => 'application/octet-stream',
  2775. 'dll' => 'application/octet-stream',
  2776. 'dms' => 'application/octet-stream',
  2777. 'exe' => 'application/octet-stream',
  2778. 'lha' => 'application/octet-stream',
  2779. 'lzh' => 'application/octet-stream',
  2780. 'psd' => 'application/octet-stream',
  2781. 'sea' => 'application/octet-stream',
  2782. 'so' => 'application/octet-stream',
  2783. 'oda' => 'application/oda',
  2784. 'pdf' => 'application/pdf',
  2785. 'ai' => 'application/postscript',
  2786. 'eps' => 'application/postscript',
  2787. 'ps' => 'application/postscript',
  2788. 'smi' => 'application/smil',
  2789. 'smil' => 'application/smil',
  2790. 'mif' => 'application/vnd.mif',
  2791. 'xls' => 'application/vnd.ms-excel',
  2792. 'ppt' => 'application/vnd.ms-powerpoint',
  2793. 'wbxml' => 'application/vnd.wap.wbxml',
  2794. 'wmlc' => 'application/vnd.wap.wmlc',
  2795. 'dcr' => 'application/x-director',
  2796. 'dir' => 'application/x-director',
  2797. 'dxr' => 'application/x-director',
  2798. 'dvi' => 'application/x-dvi',
  2799. 'gtar' => 'application/x-gtar',
  2800. 'php3' => 'application/x-httpd-php',
  2801. 'php4' => 'application/x-httpd-php',
  2802. 'php' => 'application/x-httpd-php',
  2803. 'phtml' => 'application/x-httpd-php',
  2804. 'phps' => 'application/x-httpd-php-source',
  2805. 'js' => 'application/x-javascript',
  2806. 'swf' => 'application/x-shockwave-flash',
  2807. 'sit' => 'application/x-stuffit',
  2808. 'tar' => 'application/x-tar',
  2809. 'tgz' => 'application/x-tar',
  2810. 'xht' => 'application/xhtml+xml',
  2811. 'xhtml' => 'application/xhtml+xml',
  2812. 'zip' => 'application/zip',
  2813. 'mid' => 'audio/midi',
  2814. 'midi' => 'audio/midi',
  2815. 'mp2' => 'audio/mpeg',
  2816. 'mp3' => 'audio/mpeg',
  2817. 'mpga' => 'audio/mpeg',
  2818. 'aif' => 'audio/x-aiff',
  2819. 'aifc' => 'audio/x-aiff',
  2820. 'aiff' => 'audio/x-aiff',
  2821. 'ram' => 'audio/x-pn-realaudio',
  2822. 'rm' => 'audio/x-pn-realaudio',
  2823. 'rpm' => 'audio/x-pn-realaudio-plugin',
  2824. 'ra' => 'audio/x-realaudio',
  2825. 'wav' => 'audio/x-wav',
  2826. 'bmp' => 'image/bmp',
  2827. 'gif' => 'image/gif',
  2828. 'jpeg' => 'image/jpeg',
  2829. 'jpe' => 'image/jpeg',
  2830. 'jpg' => 'image/jpeg',
  2831. 'png' => 'image/png',
  2832. 'tiff' => 'image/tiff',
  2833. 'tif' => 'image/tiff',
  2834. 'eml' => 'message/rfc822',
  2835. 'css' => 'text/css',
  2836. 'html' => 'text/html',
  2837. 'htm' => 'text/html',
  2838. 'shtml' => 'text/html',
  2839. 'log' => 'text/plain',
  2840. 'text' => 'text/plain',
  2841. 'txt' => 'text/plain',
  2842. 'rtx' => 'text/richtext',
  2843. 'rtf' => 'text/rtf',
  2844. 'vcf' => 'text/vcard',
  2845. 'vcard' => 'text/vcard',
  2846. 'xml' => 'text/xml',
  2847. 'xsl' => 'text/xml',
  2848. 'mpeg' => 'video/mpeg',
  2849. 'mpe' => 'video/mpeg',
  2850. 'mpg' => 'video/mpeg',
  2851. 'mov' => 'video/quicktime',
  2852. 'qt' => 'video/quicktime',
  2853. 'rv' => 'video/vnd.rn-realvideo',
  2854. 'avi' => 'video/x-msvideo',
  2855. 'movie' => 'video/x-sgi-movie'
  2856. );
  2857. return (array_key_exists(strtolower($ext), $mimes) ? $mimes[strtolower($ext)]: 'application/octet-stream');
  2858. }
  2859. /**
  2860. * Map a file name to a MIME type.
  2861. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  2862. * @param string $filename A file name or full path, does not need to exist as a file
  2863. * @return string
  2864. * @static
  2865. */
  2866. public static function filenameToType($filename)
  2867. {
  2868. // In case the path is a URL, strip any query string before getting extension
  2869. $qpos = strpos($filename, '?');
  2870. if ($qpos !== false) {
  2871. $filename = substr($filename, 0, $qpos);
  2872. }
  2873. $pathinfo = self::mb_pathinfo($filename);
  2874. return self::_mime_types($pathinfo['extension']);
  2875. }
  2876. /**
  2877. * Multi-byte-safe pathinfo replacement.
  2878. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  2879. * Works similarly to the one in PHP >= 5.2.0
  2880. * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  2881. * @param string $path A filename or path, does not need to exist as a file
  2882. * @param integer|string $options Either a PATHINFO_* constant,
  2883. * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  2884. * @return string|array
  2885. * @static
  2886. */
  2887. public static function mb_pathinfo($path, $options = null)
  2888. {
  2889. $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  2890. $pathinfo = array();
  2891. if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
  2892. if (array_key_exists(1, $pathinfo)) {
  2893. $ret['dirname'] = $pathinfo[1];
  2894. }
  2895. if (array_key_exists(2, $pathinfo)) {
  2896. $ret['basename'] = $pathinfo[2];
  2897. }
  2898. if (array_key_exists(5, $pathinfo)) {
  2899. $ret['extension'] = $pathinfo[5];
  2900. }
  2901. if (array_key_exists(3, $pathinfo)) {
  2902. $ret['filename'] = $pathinfo[3];
  2903. }
  2904. }
  2905. switch ($options) {
  2906. case PATHINFO_DIRNAME:
  2907. case 'dirname':
  2908. return $ret['dirname'];
  2909. case PATHINFO_BASENAME:
  2910. case 'basename':
  2911. return $ret['basename'];
  2912. case PATHINFO_EXTENSION:
  2913. case 'extension':
  2914. return $ret['extension'];
  2915. case PATHINFO_FILENAME:
  2916. case 'filename':
  2917. return $ret['filename'];
  2918. default:
  2919. return $ret;
  2920. }
  2921. }
  2922. /**
  2923. * Set or reset instance properties.
  2924. *
  2925. * Usage Example:
  2926. * $page->set('X-Priority', '3');
  2927. *
  2928. * @access public
  2929. * @param string $name
  2930. * @param mixed $value
  2931. * NOTE: will not work with arrays, there are no arrays to set/reset
  2932. * @throws phpmailerException
  2933. * @return boolean
  2934. * @TODO Should this not be using __set() magic function?
  2935. */
  2936. public function set($name, $value = '')
  2937. {
  2938. try {
  2939. if (isset($this->$name)) {
  2940. $this->$name = $value;
  2941. } else {
  2942. throw new phpmailerException($this->lang('variable_set') . $name, self::STOP_CRITICAL);
  2943. }
  2944. } catch (Exception $exc) {
  2945. $this->setError($exc->getMessage());
  2946. if ($exc->getCode() == self::STOP_CRITICAL) {
  2947. return false;
  2948. }
  2949. }
  2950. return true;
  2951. }
  2952. /**
  2953. * Strip newlines to prevent header injection.
  2954. * @access public
  2955. * @param string $str
  2956. * @return string
  2957. */
  2958. public function secureHeader($str)
  2959. {
  2960. return trim(str_replace(array("\r", "\n"), '', $str));
  2961. }
  2962. /**
  2963. * Normalize line breaks in a string.
  2964. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  2965. * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  2966. * @param string $text
  2967. * @param string $breaktype What kind of line break to use, defaults to CRLF
  2968. * @return string
  2969. * @access public
  2970. * @static
  2971. */
  2972. public static function normalizeBreaks($text, $breaktype = "\r\n")
  2973. {
  2974. return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  2975. }
  2976. /**
  2977. * Set the public and private key files and password for S/MIME signing.
  2978. * @access public
  2979. * @param string $cert_filename
  2980. * @param string $key_filename
  2981. * @param string $key_pass Password for private key
  2982. */
  2983. public function sign($cert_filename, $key_filename, $key_pass)
  2984. {
  2985. $this->sign_cert_file = $cert_filename;
  2986. $this->sign_key_file = $key_filename;
  2987. $this->sign_key_pass = $key_pass;
  2988. }
  2989. /**
  2990. * Quoted-Printable-encode a DKIM header.
  2991. * @access public
  2992. * @param string $txt
  2993. * @return string
  2994. */
  2995. public function DKIM_QP($txt)
  2996. {
  2997. $line = '';
  2998. for ($i = 0; $i < strlen($txt); $i++) {
  2999. $ord = ord($txt[$i]);
  3000. if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  3001. $line .= $txt[$i];
  3002. } else {
  3003. $line .= '=' . sprintf('%02X', $ord);
  3004. }
  3005. }
  3006. return $line;
  3007. }
  3008. /**
  3009. * Generate a DKIM signature.
  3010. * @access public
  3011. * @param string $signHeader
  3012. * @throws phpmailerException
  3013. * @return string
  3014. */
  3015. public function DKIM_Sign($signHeader)
  3016. {
  3017. if (!defined('PKCS7_TEXT')) {
  3018. if ($this->exceptions) {
  3019. throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  3020. }
  3021. return '';
  3022. }
  3023. $privKeyStr = file_get_contents($this->DKIM_private);
  3024. if ($this->DKIM_passphrase != '') {
  3025. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  3026. } else {
  3027. $privKey = $privKeyStr;
  3028. }
  3029. if (openssl_sign($signHeader, $signature, $privKey)) {
  3030. return base64_encode($signature);
  3031. }
  3032. return '';
  3033. }
  3034. /**
  3035. * Generate a DKIM canonicalization header.
  3036. * @access public
  3037. * @param string $signHeader Header
  3038. * @return string
  3039. */
  3040. public function DKIM_HeaderC($signHeader)
  3041. {
  3042. $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  3043. $lines = explode("\r\n", $signHeader);
  3044. foreach ($lines as $key => $line) {
  3045. list($heading, $value) = explode(':', $line, 2);
  3046. $heading = strtolower($heading);
  3047. $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
  3048. $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
  3049. }
  3050. $signHeader = implode("\r\n", $lines);
  3051. return $signHeader;
  3052. }
  3053. /**
  3054. * Generate a DKIM canonicalization body.
  3055. * @access public
  3056. * @param string $body Message Body
  3057. * @return string
  3058. */
  3059. public function DKIM_BodyC($body)
  3060. {
  3061. if ($body == '') {
  3062. return "\r\n";
  3063. }
  3064. // stabilize line endings
  3065. $body = str_replace("\r\n", "\n", $body);
  3066. $body = str_replace("\n", "\r\n", $body);
  3067. // END stabilize line endings
  3068. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  3069. $body = substr($body, 0, strlen($body) - 2);
  3070. }
  3071. return $body;
  3072. }
  3073. /**
  3074. * Create the DKIM header and body in a new message header.
  3075. * @access public
  3076. * @param string $headers_line Header lines
  3077. * @param string $subject Subject
  3078. * @param string $body Body
  3079. * @return string
  3080. */
  3081. public function DKIM_Add($headers_line, $subject, $body)
  3082. {
  3083. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  3084. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  3085. $DKIMquery = 'dns/txt'; // Query method
  3086. $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  3087. $subject_header = "Subject: $subject";
  3088. $headers = explode($this->LE, $headers_line);
  3089. $from_header = '';
  3090. $to_header = '';
  3091. $current = '';
  3092. foreach ($headers as $header) {
  3093. if (strpos($header, 'From:') === 0) {
  3094. $from_header = $header;
  3095. $current = 'from_header';
  3096. } elseif (strpos($header, 'To:') === 0) {
  3097. $to_header = $header;
  3098. $current = 'to_header';
  3099. } else {
  3100. if ($current && strpos($header, ' =?') === 0) {
  3101. $current .= $header;
  3102. } else {
  3103. $current = '';
  3104. }
  3105. }
  3106. }
  3107. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  3108. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  3109. $subject = str_replace(
  3110. '|',
  3111. '=7C',
  3112. $this->DKIM_QP($subject_header)
  3113. ); // Copied header fields (dkim-quoted-printable)
  3114. $body = $this->DKIM_BodyC($body);
  3115. $DKIMlen = strlen($body); // Length of body
  3116. $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
  3117. $ident = ($this->DKIM_identity == '') ? '' : ' i=' . $this->DKIM_identity . ';';
  3118. $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  3119. $DKIMsignatureType . '; q=' .
  3120. $DKIMquery . '; l=' .
  3121. $DKIMlen . '; s=' .
  3122. $this->DKIM_selector .
  3123. ";\r\n" .
  3124. "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  3125. "\th=From:To:Subject;\r\n" .
  3126. "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  3127. "\tz=$from\r\n" .
  3128. "\t|$to\r\n" .
  3129. "\t|$subject;\r\n" .
  3130. "\tbh=" . $DKIMb64 . ";\r\n" .
  3131. "\tb=";
  3132. $toSign = $this->DKIM_HeaderC(
  3133. $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs
  3134. );
  3135. $signed = $this->DKIM_Sign($toSign);
  3136. return $dkimhdrs . $signed . "\r\n";
  3137. }
  3138. /**
  3139. * Allows for public read access to 'to' property.
  3140. * @access public
  3141. * @return array
  3142. */
  3143. public function getToAddresses()
  3144. {
  3145. return $this->to;
  3146. }
  3147. /**
  3148. * Allows for public read access to 'cc' property.
  3149. * @access public
  3150. * @return array
  3151. */
  3152. public function getCcAddresses()
  3153. {
  3154. return $this->cc;
  3155. }
  3156. /**
  3157. * Allows for public read access to 'bcc' property.
  3158. * @access public
  3159. * @return array
  3160. */
  3161. public function getBccAddresses()
  3162. {
  3163. return $this->bcc;
  3164. }
  3165. /**
  3166. * Allows for public read access to 'ReplyTo' property.
  3167. * @access public
  3168. * @return array
  3169. */
  3170. public function getReplyToAddresses()
  3171. {
  3172. return $this->ReplyTo;
  3173. }
  3174. /**
  3175. * Allows for public read access to 'all_recipients' property.
  3176. * @access public
  3177. * @return array
  3178. */
  3179. public function getAllRecipientAddresses()
  3180. {
  3181. return $this->all_recipients;
  3182. }
  3183. /**
  3184. * Perform a callback.
  3185. * @param boolean $isSent
  3186. * @param array $to
  3187. * @param array $cc
  3188. * @param array $bcc
  3189. * @param string $subject
  3190. * @param string $body
  3191. * @param string $from
  3192. */
  3193. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
  3194. {
  3195. if (!empty($this->action_function) && is_callable($this->action_function)) {
  3196. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  3197. call_user_func_array($this->action_function, $params);
  3198. }
  3199. }
  3200. }
  3201. /**
  3202. * PHPMailer exception handler
  3203. * @package PHPMailer
  3204. */
  3205. class phpmailerException extends Exception
  3206. {
  3207. /**
  3208. * Prettify error message output
  3209. * @return string
  3210. */
  3211. public function errorMessage()
  3212. {
  3213. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  3214. return $errorMsg;
  3215. }
  3216. }