PHPMailer.class.php 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674
  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.2.2 |
  6. | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ |
  7. | ------------------------------------------------------------------------- |
  8. | Admin: Jim Jagielski (project admininistrator) |
  9. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  10. | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
  11. | : Jim Jagielski (jimjag) jimjag@gmail.com |
  12. | Founder: Brent R. Matzelle (original founder) |
  13. | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. |
  14. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  15. | Copyright (c) 2001-2003, Brent R. Matzelle |
  16. | ------------------------------------------------------------------------- |
  17. | License: Distributed under the Lesser General Public License (LGPL) |
  18. | http://www.gnu.org/copyleft/lesser.html |
  19. | This program is distributed in the hope that it will be useful - WITHOUT |
  20. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  21. | FITNESS FOR A PARTICULAR PURPOSE. |
  22. '---------------------------------------------------------------------------'
  23. */
  24. /**
  25. * PHPMailer - PHP email transport class
  26. * NOTE: Requires PHP version 5 or later
  27. * @package PHPMailer
  28. * @author Andy Prevost
  29. * @author Marcus Bointon
  30. * @author Jim Jagielski
  31. * @copyright 2010 - 2012 Jim Jagielski
  32. * @copyright 2004 - 2009 Andy Prevost
  33. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  34. */
  35. if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
  36. /**
  37. * Main PHPMailer class definition
  38. */
  39. class PHPMailer {
  40. /////////////////////////////////////////////////
  41. // PROPERTIES, PUBLIC
  42. /////////////////////////////////////////////////
  43. /**
  44. * Email priority (1 = High, 3 = Normal, 5 = low).
  45. * @var int
  46. */
  47. public $Priority = 3;
  48. /**
  49. * Sets the CharSet of the message.
  50. * @var string
  51. */
  52. public $CharSet = 'iso-8859-1';
  53. /**
  54. * Sets the Content-type of the message.
  55. * @var string
  56. */
  57. public $ContentType = 'text/plain';
  58. /**
  59. * Sets the Encoding of the message. Options for this are
  60. * "8bit", "7bit", "binary", "base64", and "quoted-printable".
  61. * @var string
  62. */
  63. public $Encoding = '8bit';
  64. /**
  65. * Holds the most recent mailer error message.
  66. * @var string
  67. */
  68. public $ErrorInfo = '';
  69. /**
  70. * Sets the From email address for the message.
  71. * @var string
  72. */
  73. public $From = 'root@localhost';
  74. /**
  75. * Sets the From name of the message.
  76. * @var string
  77. */
  78. public $FromName = 'Root User';
  79. /**
  80. * Sets the Sender email of the message. If not empty,
  81. * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  82. * If not empty, and ReturnPath is empty, will also be the
  83. * Return-Path header.
  84. * @var string
  85. */
  86. public $Sender = '';
  87. /**
  88. * Sets the Return-Path of the message. If empty, it will
  89. * be set to either From or Sender.
  90. * @var string
  91. */
  92. public $ReturnPath = '';
  93. /**
  94. * Sets the Subject of the message.
  95. * @var string
  96. */
  97. public $Subject = '';
  98. /**
  99. * Sets the Body of the message. This can be either an HTML or text body.
  100. * If HTML then run IsHTML(true).
  101. * @var string
  102. */
  103. public $Body = '';
  104. /**
  105. * Sets the text-only body of the message. This automatically sets the
  106. * email to multipart/alternative. This body can be read by mail
  107. * clients that do not have HTML email capability such as mutt. Clients
  108. * that can read HTML will view the normal Body.
  109. * @var string
  110. */
  111. public $AltBody = '';
  112. /**
  113. * Stores the complete compiled MIME message body.
  114. * @var string
  115. * @access protected
  116. */
  117. protected $MIMEBody = '';
  118. /**
  119. * Stores the complete compiled MIME message headers.
  120. * @var string
  121. * @access protected
  122. */
  123. protected $MIMEHeader = '';
  124. /**
  125. * Stores the extra header list which CreateHeader() doesn't fold in
  126. * @var string
  127. * @access protected
  128. */
  129. protected $mailHeader = '';
  130. /**
  131. * Sets word wrapping on the body of the message to a given number of
  132. * characters.
  133. * @var int
  134. */
  135. public $WordWrap = 0;
  136. /**
  137. * Method to send mail: ("mail", "sendmail", or "smtp").
  138. * @var string
  139. */
  140. public $Mailer = 'mail';
  141. /**
  142. * Sets the path of the sendmail program.
  143. * @var string
  144. */
  145. public $Sendmail = '/usr/sbin/sendmail';
  146. /**
  147. * Determine if mail() uses a fully sendmail compatible MTA that
  148. * supports sendmail's "-oi -f" options
  149. * @var boolean
  150. */
  151. public $UseSendmailOptions = true;
  152. /**
  153. * Path to PHPMailer plugins. Useful if the SMTP class
  154. * is in a different directory than the PHP include path.
  155. * @var string
  156. */
  157. public $PluginDir = '';
  158. /**
  159. * Sets the email address that a reading confirmation will be sent.
  160. * @var string
  161. */
  162. public $ConfirmReadingTo = '';
  163. /**
  164. * Sets the hostname to use in Message-Id and Received headers
  165. * and as default HELO string. If empty, the value returned
  166. * by SERVER_NAME is used or 'localhost.localdomain'.
  167. * @var string
  168. */
  169. public $Hostname = '';
  170. /**
  171. * Sets the message ID to be used in the Message-Id header.
  172. * If empty, a unique id will be generated.
  173. * @var string
  174. */
  175. public $MessageID = '';
  176. /////////////////////////////////////////////////
  177. // PROPERTIES FOR SMTP
  178. /////////////////////////////////////////////////
  179. /**
  180. * Sets the SMTP hosts.
  181. *
  182. * All hosts must be separated by a
  183. * semicolon. You can also specify a different port
  184. * for each host by using this format: [hostname:port]
  185. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  186. * Hosts will be tried in order.
  187. * @var string
  188. */
  189. public $Host = 'localhost';
  190. /**
  191. * Sets the default SMTP server port.
  192. * @var int
  193. */
  194. public $Port = 25;
  195. /**
  196. * Sets the SMTP HELO of the message (Default is $Hostname).
  197. * @var string
  198. */
  199. public $Helo = '';
  200. /**
  201. * Sets connection prefix. Options are "", "ssl" or "tls"
  202. * @var string
  203. */
  204. public $SMTPSecure = '';
  205. /**
  206. * Sets SMTP authentication. Utilizes the Username and Password variables.
  207. * @var bool
  208. */
  209. public $SMTPAuth = false;
  210. /**
  211. * Sets SMTP username.
  212. * @var string
  213. */
  214. public $Username = '';
  215. /**
  216. * Sets SMTP password.
  217. * @var string
  218. */
  219. public $Password = '';
  220. /**
  221. * Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM (default LOGIN)
  222. * @var string
  223. */
  224. public $AuthType = '';
  225. /**
  226. * Sets SMTP realm.
  227. * @var string
  228. */
  229. public $Realm = '';
  230. /**
  231. * Sets SMTP workstation.
  232. * @var string
  233. */
  234. public $Workstation = '';
  235. /**
  236. * Sets the SMTP server in seconds.
  237. * This function will not work with the win32 version.
  238. * @var int
  239. */
  240. public $Timeout = 10;
  241. /**
  242. * Sets SMTP class debugging on or off.
  243. * @var bool
  244. */
  245. public $SMTPDebug = false;
  246. /**
  247. * Sets the function/method to use for debugging output.
  248. * Right now we only honor "echo" or "error_log"
  249. * @var string
  250. */
  251. public $Debugoutput = "echo";
  252. /**
  253. * Prevents the SMTP connection from being closed after each mail
  254. * sending. If this is set to true then to close the connection
  255. * requires an explicit call to SmtpClose().
  256. * @var bool
  257. */
  258. public $SMTPKeepAlive = false;
  259. /**
  260. * Provides the ability to have the TO field process individual
  261. * emails, instead of sending to entire TO addresses
  262. * @var bool
  263. */
  264. public $SingleTo = false;
  265. /**
  266. * If SingleTo is true, this provides the array to hold the email addresses
  267. * @var bool
  268. */
  269. public $SingleToArray = array();
  270. /**
  271. * Provides the ability to change the generic line ending
  272. * NOTE: The default remains '\n'. We force CRLF where we KNOW
  273. * it must be used via self::CRLF
  274. * @var string
  275. */
  276. public $LE = "\n";
  277. /**
  278. * Used with DKIM Signing
  279. * required parameter if DKIM is enabled
  280. *
  281. * domain selector example domainkey
  282. * @var string
  283. */
  284. public $DKIM_selector = '';
  285. /**
  286. * Used with DKIM Signing
  287. * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email
  288. * @var string
  289. */
  290. public $DKIM_identity = '';
  291. /**
  292. * Used with DKIM Signing
  293. * optional parameter if your private key requires a passphras
  294. * @var string
  295. */
  296. public $DKIM_passphrase = '';
  297. /**
  298. * Used with DKIM Singing
  299. * required if DKIM is enabled, in format of email address 'domain.com'
  300. * @var string
  301. */
  302. public $DKIM_domain = '';
  303. /**
  304. * Used with DKIM Signing
  305. * required if DKIM is enabled, path to private key file
  306. * @var string
  307. */
  308. public $DKIM_private = '';
  309. /**
  310. * Callback Action function name.
  311. * The function that handles the result of the send email action.
  312. * It is called out by Send() for each email sent.
  313. *
  314. * Value can be:
  315. * - 'function_name' for function names
  316. * - 'Class::Method' for static method calls
  317. * - array($object, 'Method') for calling methods on $object
  318. * See http://php.net/is_callable manual page for more details.
  319. *
  320. * Parameters:
  321. * bool $result result of the send action
  322. * string $to email address of the recipient
  323. * string $cc cc email addresses
  324. * string $bcc bcc email addresses
  325. * string $subject the subject
  326. * string $body the email body
  327. * string $from email address of sender
  328. * @var string
  329. */
  330. public $action_function = ''; //'callbackAction';
  331. /**
  332. * Sets the PHPMailer Version number
  333. * @var string
  334. */
  335. public $Version = '5.2.2-rc1';
  336. /**
  337. * What to use in the X-Mailer header
  338. * @var string NULL for default, whitespace for None, or actual string to use
  339. */
  340. public $XMailer = '';
  341. /////////////////////////////////////////////////
  342. // PROPERTIES, PRIVATE AND PROTECTED
  343. /////////////////////////////////////////////////
  344. protected $smtp = NULL;
  345. protected $to = array();
  346. protected $cc = array();
  347. protected $bcc = array();
  348. protected $ReplyTo = array();
  349. protected $all_recipients = array();
  350. protected $attachment = array();
  351. protected $CustomHeader = array();
  352. protected $message_type = '';
  353. protected $boundary = array();
  354. protected $language = array();
  355. protected $error_count = 0;
  356. protected $sign_cert_file = '';
  357. protected $sign_key_file = '';
  358. protected $sign_key_pass = '';
  359. protected $exceptions = false;
  360. /////////////////////////////////////////////////
  361. // CONSTANTS
  362. /////////////////////////////////////////////////
  363. const STOP_MESSAGE = 0; // message only, continue processing
  364. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  365. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  366. const CRLF = "\r\n"; // SMTP RFC specified EOL
  367. /////////////////////////////////////////////////
  368. // METHODS, VARIABLES
  369. /////////////////////////////////////////////////
  370. /**
  371. * Calls actual mail() function, but in a safe_mode aware fashion
  372. * Also, unless sendmail_path points to sendmail (or something that
  373. * claims to be sendmail), don't pass params (not a perfect fix,
  374. * but it will do)
  375. * @param string $to To
  376. * @param string $subject Subject
  377. * @param string $body Message Body
  378. * @param string $header Additional Header(s)
  379. * @param string $params Params
  380. * @access private
  381. * @return bool
  382. */
  383. private function mail_passthru($to, $subject, $body, $header, $params) {
  384. if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
  385. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
  386. } else {
  387. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
  388. }
  389. return $rt;
  390. }
  391. /**
  392. * Outputs debugging info via user-defined method
  393. * @param string $str
  394. */
  395. private function edebug($str) {
  396. if ($this->Debugoutput == "error_log") {
  397. error_log($str);
  398. } else {
  399. echo $str;
  400. }
  401. }
  402. /**
  403. * Constructor
  404. * @param boolean $exceptions Should we throw external exceptions?
  405. */
  406. public function __construct($exceptions = false) {
  407. $this->exceptions = ($exceptions == true);
  408. }
  409. /**
  410. * Sets message type to HTML.
  411. * @param bool $ishtml
  412. * @return void
  413. */
  414. public function IsHTML($ishtml = true) {
  415. if ($ishtml) {
  416. $this->ContentType = 'text/html';
  417. } else {
  418. $this->ContentType = 'text/plain';
  419. }
  420. }
  421. /**
  422. * Sets Mailer to send message using SMTP.
  423. * @return void
  424. * @deprecated
  425. */
  426. public function IsSMTP() {
  427. $this->Mailer = 'smtp';
  428. }
  429. /**
  430. * Sets Mailer to send message using PHP mail() function.
  431. * @return void
  432. * @deprecated
  433. */
  434. public function IsMail() {
  435. $this->Mailer = 'mail';
  436. }
  437. /**
  438. * Sets Mailer to send message using the $Sendmail program.
  439. * @return void
  440. * @deprecated
  441. */
  442. public function IsSendmail() {
  443. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  444. $this->Sendmail = '/var/qmail/bin/sendmail';
  445. }
  446. $this->Mailer = 'sendmail';
  447. }
  448. /**
  449. * Sets Mailer to send message using the qmail MTA.
  450. * @return void
  451. * @deprecated
  452. */
  453. public function IsQmail() {
  454. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  455. $this->Sendmail = '/var/qmail/bin/sendmail';
  456. }
  457. $this->Mailer = 'sendmail';
  458. }
  459. /////////////////////////////////////////////////
  460. // METHODS, RECIPIENTS
  461. /////////////////////////////////////////////////
  462. /**
  463. * Adds a "To" address.
  464. * @param string $address
  465. * @param string $name
  466. * @return boolean true on success, false if address already used
  467. */
  468. public function AddAddress($address, $name = '') {
  469. return $this->AddAnAddress('to', $address, $name);
  470. }
  471. /**
  472. * Adds a "Cc" address.
  473. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  474. * @param string $address
  475. * @param string $name
  476. * @return boolean true on success, false if address already used
  477. */
  478. public function AddCC($address, $name = '') {
  479. return $this->AddAnAddress('cc', $address, $name);
  480. }
  481. /**
  482. * Adds a "Bcc" address.
  483. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  484. * @param string $address
  485. * @param string $name
  486. * @return boolean true on success, false if address already used
  487. */
  488. public function AddBCC($address, $name = '') {
  489. return $this->AddAnAddress('bcc', $address, $name);
  490. }
  491. /**
  492. * Adds a "Reply-to" address.
  493. * @param string $address
  494. * @param string $name
  495. * @return boolean
  496. */
  497. public function AddReplyTo($address, $name = '') {
  498. return $this->AddAnAddress('Reply-To', $address, $name);
  499. }
  500. /**
  501. * Adds an address to one of the recipient arrays
  502. * Addresses that have been added already return false, but do not throw exceptions
  503. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  504. * @param string $address The email address to send to
  505. * @param string $name
  506. * @return boolean true on success, false if address already used or invalid in some way
  507. * @access protected
  508. */
  509. protected function AddAnAddress($kind, $address, $name = '') {
  510. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  511. $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
  512. if ($this->exceptions) {
  513. throw new phpmailerException('Invalid recipient array: ' . $kind);
  514. }
  515. if ($this->SMTPDebug) {
  516. $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
  517. }
  518. return false;
  519. }
  520. $address = trim($address);
  521. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  522. if (!$this->ValidateAddress($address)) {
  523. $this->SetError($this->Lang('invalid_address').': '. $address);
  524. if ($this->exceptions) {
  525. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  526. }
  527. if ($this->SMTPDebug) {
  528. $this->edebug($this->Lang('invalid_address').': '.$address);
  529. }
  530. return false;
  531. }
  532. if ($kind != 'Reply-To') {
  533. if (!isset($this->all_recipients[strtolower($address)])) {
  534. array_push($this->$kind, array($address, $name));
  535. $this->all_recipients[strtolower($address)] = true;
  536. return true;
  537. }
  538. } else {
  539. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  540. $this->ReplyTo[strtolower($address)] = array($address, $name);
  541. return true;
  542. }
  543. }
  544. return false;
  545. }
  546. /**
  547. * Set the From and FromName properties
  548. * @param string $address
  549. * @param string $name
  550. * @param int $auto Also set Reply-To and Sender
  551. * @return boolean
  552. */
  553. public function SetFrom($address, $name = '', $auto = 1) {
  554. $address = trim($address);
  555. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  556. if (!$this->ValidateAddress($address)) {
  557. $this->SetError($this->Lang('invalid_address').': '. $address);
  558. if ($this->exceptions) {
  559. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  560. }
  561. if ($this->SMTPDebug) {
  562. $this->edebug($this->Lang('invalid_address').': '.$address);
  563. }
  564. return false;
  565. }
  566. $this->From = $address;
  567. $this->FromName = $name;
  568. if ($auto) {
  569. if (empty($this->ReplyTo)) {
  570. $this->AddAnAddress('Reply-To', $address, $name);
  571. }
  572. if (empty($this->Sender)) {
  573. $this->Sender = $address;
  574. }
  575. }
  576. return true;
  577. }
  578. /**
  579. * Check that a string looks roughly like an email address should
  580. * Static so it can be used without instantiation, public so people can overload
  581. * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
  582. * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
  583. * not allow a@b type valid addresses :(
  584. * @link http://squiloople.com/2009/12/20/email-address-validation/
  585. * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
  586. * @param string $address The email address to check
  587. * @return boolean
  588. * @static
  589. * @access public
  590. */
  591. public static function ValidateAddress($address) {
  592. return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[ ])+|(?>[ ]*\x0D\x0A)?[ ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){7,})((?6)(?>:(?6)){0,5})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){5,})(?8)?::(?>((?6)(?>:(?6)){0,3}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
  593. }
  594. /////////////////////////////////////////////////
  595. // METHODS, MAIL SENDING
  596. /////////////////////////////////////////////////
  597. /**
  598. * Creates message and assigns Mailer. If the message is
  599. * not sent successfully then it returns false. Use the ErrorInfo
  600. * variable to view description of the error.
  601. * @return bool
  602. */
  603. public function Send() {
  604. try {
  605. if(!$this->PreSend()) return false;
  606. return $this->PostSend();
  607. } catch (phpmailerException $e) {
  608. $this->mailHeader = '';
  609. $this->SetError($e->getMessage());
  610. if ($this->exceptions) {
  611. throw $e;
  612. }
  613. return false;
  614. }
  615. }
  616. /**
  617. * Prep mail by constructing all message entities
  618. * @return bool
  619. */
  620. public function PreSend() {
  621. try {
  622. $this->mailHeader = "";
  623. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  624. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  625. }
  626. // Set whether the message is multipart/alternative
  627. if(!empty($this->AltBody)) {
  628. $this->ContentType = 'multipart/alternative';
  629. }
  630. $this->error_count = 0; // reset errors
  631. $this->SetMessageType();
  632. //Refuse to send an empty message
  633. if (empty($this->Body)) {
  634. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  635. }
  636. $this->MIMEHeader = $this->CreateHeader();
  637. $this->MIMEBody = $this->CreateBody();
  638. // To capture the complete message when using mail(), create
  639. // an extra header list which CreateHeader() doesn't fold in
  640. if ($this->Mailer == 'mail') {
  641. if (count($this->to) > 0) {
  642. $this->mailHeader .= $this->AddrAppend("To", $this->to);
  643. } else {
  644. $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
  645. }
  646. $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
  647. // if(count($this->cc) > 0) {
  648. // $this->mailHeader .= $this->AddrAppend("Cc", $this->cc);
  649. // }
  650. }
  651. // digitally sign with DKIM if enabled
  652. if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
  653. $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
  654. $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
  655. }
  656. return true;
  657. } catch (phpmailerException $e) {
  658. $this->SetError($e->getMessage());
  659. if ($this->exceptions) {
  660. throw $e;
  661. }
  662. return false;
  663. }
  664. }
  665. /**
  666. * Actual Email transport function
  667. * Send the email via the selected mechanism
  668. * @return bool
  669. */
  670. public function PostSend() {
  671. $rtn = false;
  672. try {
  673. // Choose the mailer and send through it
  674. switch($this->Mailer) {
  675. case 'sendmail':
  676. $rtn = $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
  677. break;
  678. case 'smtp':
  679. $rtn = $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
  680. break;
  681. case 'mail':
  682. $rtn = $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  683. break;
  684. default:
  685. $rtn = $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  686. break;
  687. }
  688. } catch (phpmailerException $e) {
  689. $this->SetError($e->getMessage());
  690. if ($this->exceptions) {
  691. throw $e;
  692. }
  693. if ($this->SMTPDebug) {
  694. $this->edebug($e->getMessage()."\n");
  695. }
  696. return false;
  697. }
  698. return $rtn;
  699. }
  700. /**
  701. * Sends mail using the $Sendmail program.
  702. * @param string $header The message headers
  703. * @param string $body The message body
  704. * @access protected
  705. * @return bool
  706. */
  707. protected function SendmailSend($header, $body) {
  708. if ($this->Sender != '') {
  709. $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  710. } else {
  711. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  712. }
  713. if ($this->SingleTo === true) {
  714. foreach ($this->SingleToArray as $key => $val) {
  715. if(!@$mail = popen($sendmail, 'w')) {
  716. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  717. }
  718. fputs($mail, "To: " . $val . "\n");
  719. fputs($mail, $header);
  720. fputs($mail, $body);
  721. $result = pclose($mail);
  722. // implement call back function if it exists
  723. $isSent = ($result == 0) ? 1 : 0;
  724. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  725. if($result != 0) {
  726. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  727. }
  728. }
  729. } else {
  730. if(!@$mail = popen($sendmail, 'w')) {
  731. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  732. }
  733. fputs($mail, $header);
  734. fputs($mail, $body);
  735. $result = pclose($mail);
  736. // implement call back function if it exists
  737. $isSent = ($result == 0) ? 1 : 0;
  738. $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
  739. if($result != 0) {
  740. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  741. }
  742. }
  743. return true;
  744. }
  745. /**
  746. * Sends mail using the PHP mail() function.
  747. * @param string $header The message headers
  748. * @param string $body The message body
  749. * @access protected
  750. * @return bool
  751. */
  752. protected function MailSend($header, $body) {
  753. $toArr = array();
  754. foreach($this->to as $t) {
  755. $toArr[] = $this->AddrFormat($t);
  756. }
  757. $to = implode(', ', $toArr);
  758. if (empty($this->Sender)) {
  759. $params = "-oi ";
  760. } else {
  761. $params = sprintf("-oi -f %s", $this->Sender);
  762. }
  763. if ($this->Sender != '' and !ini_get('safe_mode')) {
  764. $old_from = ini_get('sendmail_from');
  765. ini_set('sendmail_from', $this->Sender);
  766. }
  767. if ($this->SingleTo === true && count($toArr) > 1) {
  768. foreach ($toArr as $key => $val) {
  769. $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
  770. // implement call back function if it exists
  771. $isSent = ($rt == 1) ? 1 : 0;
  772. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  773. }
  774. } else {
  775. $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
  776. // implement call back function if it exists
  777. $isSent = ($rt == 1) ? 1 : 0;
  778. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  779. }
  780. if (isset($old_from)) {
  781. ini_set('sendmail_from', $old_from);
  782. }
  783. if(!$rt) {
  784. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  785. }
  786. return true;
  787. }
  788. /**
  789. * Sends mail via SMTP using PhpSMTP
  790. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  791. * @param string $header The message headers
  792. * @param string $body The message body
  793. * @uses SMTP
  794. * @access protected
  795. * @return bool
  796. */
  797. protected function SmtpSend($header, $body) {
  798. require_once $this->PluginDir . 'class.smtp.php';
  799. $bad_rcpt = array();
  800. if(!$this->SmtpConnect()) {
  801. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  802. }
  803. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  804. if(!$this->smtp->Mail($smtp_from)) {
  805. throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
  806. }
  807. // Attempt to send attach all recipients
  808. foreach($this->to as $to) {
  809. if (!$this->smtp->Recipient($to[0])) {
  810. $bad_rcpt[] = $to[0];
  811. // implement call back function if it exists
  812. $isSent = 0;
  813. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  814. } else {
  815. // implement call back function if it exists
  816. $isSent = 1;
  817. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  818. }
  819. }
  820. foreach($this->cc as $cc) {
  821. if (!$this->smtp->Recipient($cc[0])) {
  822. $bad_rcpt[] = $cc[0];
  823. // implement call back function if it exists
  824. $isSent = 0;
  825. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  826. } else {
  827. // implement call back function if it exists
  828. $isSent = 1;
  829. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  830. }
  831. }
  832. foreach($this->bcc as $bcc) {
  833. if (!$this->smtp->Recipient($bcc[0])) {
  834. $bad_rcpt[] = $bcc[0];
  835. // implement call back function if it exists
  836. $isSent = 0;
  837. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  838. } else {
  839. // implement call back function if it exists
  840. $isSent = 1;
  841. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  842. }
  843. }
  844. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  845. $badaddresses = implode(', ', $bad_rcpt);
  846. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  847. }
  848. if(!$this->smtp->Data($header . $body)) {
  849. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  850. }
  851. if($this->SMTPKeepAlive == true) {
  852. $this->smtp->Reset();
  853. }
  854. return true;
  855. }
  856. /**
  857. * Initiates a connection to an SMTP server.
  858. * Returns false if the operation failed.
  859. * @uses SMTP
  860. * @access public
  861. * @return bool
  862. */
  863. public function SmtpConnect() {
  864. if ($this->smtp === null) {
  865. $this->smtp = new SMTP();
  866. }
  867. $this->smtp->Timeout = $this->Timeout;
  868. $this->smtp->do_debug = $this->SMTPDebug;
  869. $hosts = explode(';', $this->Host);
  870. $index = 0;
  871. $connection = $this->smtp->Connected();
  872. $rtn = true;
  873. // Retry while there is no connection
  874. try {
  875. while($index < count($hosts) && !$connection) {
  876. $hostinfo = array();
  877. if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
  878. $host = $hostinfo[1];
  879. $port = $hostinfo[2];
  880. } else {
  881. $host = $hosts[$index];
  882. $port = $this->Port;
  883. }
  884. $tls = ($this->SMTPSecure == 'tls');
  885. $ssl = ($this->SMTPSecure == 'ssl');
  886. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
  887. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  888. $this->smtp->Hello($hello);
  889. if ($tls) {
  890. if (!$this->smtp->StartTLS()) {
  891. $rtn = false;
  892. throw new phpmailerException($this->Lang('tls'));
  893. }
  894. //We must resend HELO after tls negotiation
  895. $this->smtp->Hello($hello);
  896. }
  897. $connection = true;
  898. if ($this->SMTPAuth) {
  899. if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType,
  900. $this->Realm, $this->Workstation)) {
  901. $rtn = false;
  902. throw new phpmailerException($this->Lang('authenticate'));
  903. }
  904. }
  905. }
  906. $index++;
  907. if (!$connection) {
  908. $rtn = false;
  909. throw new phpmailerException($this->Lang('connect_host'));
  910. }
  911. }
  912. } catch (phpmailerException $e) {
  913. $this->smtp->Reset();
  914. if ($this->exceptions) {
  915. throw $e;
  916. }
  917. $rtn = false;
  918. }
  919. return $rtn;
  920. }
  921. /**
  922. * Closes the active SMTP session if one exists.
  923. * @return void
  924. */
  925. public function SmtpClose() {
  926. if ($this->smtp !== null) {
  927. if($this->smtp->Connected()) {
  928. $this->smtp->Quit();
  929. $this->smtp->Close();
  930. }
  931. }
  932. }
  933. /**
  934. * Sets the language for all class error messages.
  935. * Returns false if it cannot load the language file. The default language is English.
  936. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  937. * @param string $lang_path Path to the language file directory
  938. * @access public
  939. */
  940. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  941. //Define full set of translatable strings
  942. $PHPMAILER_LANG = array(
  943. 'authenticate' => 'SMTP Error: Could not authenticate.',
  944. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  945. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  946. 'empty_message' => 'Message body empty',
  947. 'encoding' => 'Unknown encoding: ',
  948. 'execute' => 'Could not execute: ',
  949. 'file_access' => 'Could not access file: ',
  950. 'file_open' => 'File Error: Could not open file: ',
  951. 'from_failed' => 'The following From address failed: ',
  952. 'instantiate' => 'Could not instantiate mail function.',
  953. 'invalid_address' => 'Invalid address',
  954. 'mailer_not_supported' => ' mailer is not supported.',
  955. 'provide_address' => 'You must provide at least one recipient email address.',
  956. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  957. 'signing' => 'Signing Error: ',
  958. 'smtp_connect_failed' => 'SMTP Connect() failed.',
  959. 'smtp_error' => 'SMTP server error: ',
  960. 'variable_set' => 'Cannot set or reset variable: '
  961. );
  962. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  963. $l = true;
  964. if ($langcode != 'en') { //There is no English translation file
  965. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  966. }
  967. $this->language = $PHPMAILER_LANG;
  968. return ($l == true); //Returns false if language not found
  969. }
  970. /**
  971. * Return the current array of language strings
  972. * @return array
  973. */
  974. public function GetTranslations() {
  975. return $this->language;
  976. }
  977. /////////////////////////////////////////////////
  978. // METHODS, MESSAGE CREATION
  979. /////////////////////////////////////////////////
  980. /**
  981. * Creates recipient headers.
  982. * @access public
  983. * @return string
  984. */
  985. public function AddrAppend($type, $addr) {
  986. $addr_str = $type . ': ';
  987. $addresses = array();
  988. foreach ($addr as $a) {
  989. $addresses[] = $this->AddrFormat($a);
  990. }
  991. $addr_str .= implode(', ', $addresses);
  992. $addr_str .= $this->LE;
  993. return $addr_str;
  994. }
  995. /**
  996. * Formats an address correctly.
  997. * @access public
  998. * @return string
  999. */
  1000. public function AddrFormat($addr) {
  1001. if (empty($addr[1])) {
  1002. return $this->SecureHeader($addr[0]);
  1003. } else {
  1004. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  1005. }
  1006. }
  1007. /**
  1008. * Wraps message for use with mailers that do not
  1009. * automatically perform wrapping and for quoted-printable.
  1010. * Original written by philippe.
  1011. * @param string $message The message to wrap
  1012. * @param integer $length The line length to wrap to
  1013. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  1014. * @access public
  1015. * @return string
  1016. */
  1017. public function WrapText($message, $length, $qp_mode = false) {
  1018. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  1019. // If utf-8 encoding is used, we will need to make sure we don't
  1020. // split multibyte characters when we wrap
  1021. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  1022. $lelen = strlen($this->LE);
  1023. $crlflen = strlen(self::CRLF);
  1024. $message = $this->FixEOL($message);
  1025. if (substr($message, -$lelen) == $this->LE) {
  1026. $message = substr($message, 0, -$lelen);
  1027. }
  1028. $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE
  1029. $message = '';
  1030. for ($i = 0 ;$i < count($line); $i++) {
  1031. $line_part = explode(' ', $line[$i]);
  1032. $buf = '';
  1033. for ($e = 0; $e<count($line_part); $e++) {
  1034. $word = $line_part[$e];
  1035. if ($qp_mode and (strlen($word) > $length)) {
  1036. $space_left = $length - strlen($buf) - $crlflen;
  1037. if ($e != 0) {
  1038. if ($space_left > 20) {
  1039. $len = $space_left;
  1040. if ($is_utf8) {
  1041. $len = $this->UTF8CharBoundary($word, $len);
  1042. } elseif (substr($word, $len - 1, 1) == "=") {
  1043. $len--;
  1044. } elseif (substr($word, $len - 2, 1) == "=") {
  1045. $len -= 2;
  1046. }
  1047. $part = substr($word, 0, $len);
  1048. $word = substr($word, $len);
  1049. $buf .= ' ' . $part;
  1050. $message .= $buf . sprintf("=%s", self::CRLF);
  1051. } else {
  1052. $message .= $buf . $soft_break;
  1053. }
  1054. $buf = '';
  1055. }
  1056. while (strlen($word) > 0) {
  1057. $len = $length;
  1058. if ($is_utf8) {
  1059. $len = $this->UTF8CharBoundary($word, $len);
  1060. } elseif (substr($word, $len - 1, 1) == "=") {
  1061. $len--;
  1062. } elseif (substr($word, $len - 2, 1) == "=") {
  1063. $len -= 2;
  1064. }
  1065. $part = substr($word, 0, $len);
  1066. $word = substr($word, $len);
  1067. if (strlen($word) > 0) {
  1068. $message .= $part . sprintf("=%s", self::CRLF);
  1069. } else {
  1070. $buf = $part;
  1071. }
  1072. }
  1073. } else {
  1074. $buf_o = $buf;
  1075. $buf .= ($e == 0) ? $word : (' ' . $word);
  1076. if (strlen($buf) > $length and $buf_o != '') {
  1077. $message .= $buf_o . $soft_break;
  1078. $buf = $word;
  1079. }
  1080. }
  1081. }
  1082. $message .= $buf . self::CRLF;
  1083. }
  1084. return $message;
  1085. }
  1086. /**
  1087. * Finds last character boundary prior to maxLength in a utf-8
  1088. * quoted (printable) encoded string.
  1089. * Original written by Colin Brown.
  1090. * @access public
  1091. * @param string $encodedText utf-8 QP text
  1092. * @param int $maxLength find last character boundary prior to this length
  1093. * @return int
  1094. */
  1095. public function UTF8CharBoundary($encodedText, $maxLength) {
  1096. $foundSplitPos = false;
  1097. $lookBack = 3;
  1098. while (!$foundSplitPos) {
  1099. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1100. $encodedCharPos = strpos($lastChunk, "=");
  1101. if ($encodedCharPos !== false) {
  1102. // Found start of encoded character byte within $lookBack block.
  1103. // Check the encoded byte value (the 2 chars after the '=')
  1104. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1105. $dec = hexdec($hex);
  1106. if ($dec < 128) { // Single byte character.
  1107. // If the encoded char was found at pos 0, it will fit
  1108. // otherwise reduce maxLength to start of the encoded char
  1109. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  1110. $maxLength - ($lookBack - $encodedCharPos);
  1111. $foundSplitPos = true;
  1112. } elseif ($dec >= 192) { // First byte of a multi byte character
  1113. // Reduce maxLength to split at start of character
  1114. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1115. $foundSplitPos = true;
  1116. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  1117. $lookBack += 3;
  1118. }
  1119. } else {
  1120. // No encoded character found
  1121. $foundSplitPos = true;
  1122. }
  1123. }
  1124. return $maxLength;
  1125. }
  1126. /**
  1127. * Set the body wrapping.
  1128. * @access public
  1129. * @return void
  1130. */
  1131. public function SetWordWrap() {
  1132. if($this->WordWrap < 1) {
  1133. return;
  1134. }
  1135. switch($this->message_type) {
  1136. case 'alt':
  1137. case 'alt_inline':
  1138. case 'alt_attach':
  1139. case 'alt_inline_attach':
  1140. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  1141. break;
  1142. default:
  1143. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  1144. break;
  1145. }
  1146. }
  1147. /**
  1148. * Assembles message header.
  1149. * @access public
  1150. * @return string The assembled header
  1151. */
  1152. public function CreateHeader() {
  1153. $result = '';
  1154. // Set the boundaries
  1155. $uniq_id = md5(uniqid(time()));
  1156. $this->boundary[1] = 'b1_' . $uniq_id;
  1157. $this->boundary[2] = 'b2_' . $uniq_id;
  1158. $this->boundary[3] = 'b3_' . $uniq_id;
  1159. $result .= $this->HeaderLine('Date', self::RFCDate());
  1160. if ($this->ReturnPath) {
  1161. $result .= $this->HeaderLine('Return-Path', trim($this->ReturnPath));
  1162. } elseif ($this->Sender == '') {
  1163. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  1164. } else {
  1165. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  1166. }
  1167. // To be created automatically by mail()
  1168. if($this->Mailer != 'mail') {
  1169. if ($this->SingleTo === true) {
  1170. foreach($this->to as $t) {
  1171. $this->SingleToArray[] = $this->AddrFormat($t);
  1172. }
  1173. } else {
  1174. if(count($this->to) > 0) {
  1175. $result .= $this->AddrAppend('To', $this->to);
  1176. } elseif (count($this->cc) == 0) {
  1177. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  1178. }
  1179. }
  1180. }
  1181. $from = array();
  1182. $from[0][0] = trim($this->From);
  1183. $from[0][1] = $this->FromName;
  1184. $result .= $this->AddrAppend('From', $from);
  1185. // sendmail and mail() extract Cc from the header before sending
  1186. if(count($this->cc) > 0) {
  1187. $result .= $this->AddrAppend('Cc', $this->cc);
  1188. }
  1189. // sendmail and mail() extract Bcc from the header before sending
  1190. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  1191. $result .= $this->AddrAppend('Bcc', $this->bcc);
  1192. }
  1193. if(count($this->ReplyTo) > 0) {
  1194. $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
  1195. }
  1196. // mail() sets the subject itself
  1197. if($this->Mailer != 'mail') {
  1198. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  1199. }
  1200. if($this->MessageID != '') {
  1201. $result .= $this->HeaderLine('Message-ID', $this->MessageID);
  1202. } else {
  1203. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  1204. }
  1205. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  1206. if ($this->XMailer == '') {
  1207. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
  1208. } else {
  1209. $myXmailer = trim($this->XMailer);
  1210. if ($myXmailer) {
  1211. $result .= $this->HeaderLine('X-Mailer', $myXmailer);
  1212. }
  1213. }
  1214. if($this->ConfirmReadingTo != '') {
  1215. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1216. }
  1217. // Add custom headers
  1218. for($index = 0; $index < count($this->CustomHeader); $index++) {
  1219. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  1220. }
  1221. if (!$this->sign_key_file) {
  1222. $result .= $this->HeaderLine('MIME-Version', '1.0');
  1223. $result .= $this->GetMailMIME();
  1224. }
  1225. return $result;
  1226. }
  1227. /**
  1228. * Returns the message MIME.
  1229. * @access public
  1230. * @return string
  1231. */
  1232. public function GetMailMIME() {
  1233. $result = '';
  1234. switch($this->message_type) {
  1235. case 'inline':
  1236. $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1237. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1238. break;
  1239. case 'attach':
  1240. case 'inline_attach':
  1241. case 'alt_attach':
  1242. case 'alt_inline_attach':
  1243. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  1244. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1245. break;
  1246. case 'alt':
  1247. case 'alt_inline':
  1248. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1249. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1250. break;
  1251. default:
  1252. // Catches case 'plain': and case '':
  1253. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  1254. $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
  1255. break;
  1256. }
  1257. if($this->Mailer != 'mail') {
  1258. $result .= $this->LE;
  1259. }
  1260. return $result;
  1261. }
  1262. /**
  1263. * Returns the MIME message (headers and body). Only really valid post PreSend().
  1264. * @access public
  1265. * @return string
  1266. */
  1267. public function GetSentMIMEMessage() {
  1268. return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  1269. }
  1270. /**
  1271. * Assembles the message body. Returns an empty string on failure.
  1272. * @access public
  1273. * @return string The assembled message body
  1274. */
  1275. public function CreateBody() {
  1276. $body = '';
  1277. if ($this->sign_key_file) {
  1278. $body .= $this->GetMailMIME().$this->LE;
  1279. }
  1280. $this->SetWordWrap();
  1281. switch($this->message_type) {
  1282. case 'inline':
  1283. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1284. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1285. $body .= $this->LE.$this->LE;
  1286. $body .= $this->AttachAll("inline", $this->boundary[1]);
  1287. break;
  1288. case 'attach':
  1289. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1290. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1291. $body .= $this->LE.$this->LE;
  1292. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1293. break;
  1294. case 'inline_attach':
  1295. $body .= $this->TextLine("--" . $this->boundary[1]);
  1296. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1297. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1298. $body .= $this->LE;
  1299. $body .= $this->GetBoundary($this->boundary[2], '', '', '');
  1300. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1301. $body .= $this->LE.$this->LE;
  1302. $body .= $this->AttachAll("inline", $this->boundary[2]);
  1303. $body .= $this->LE;
  1304. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1305. break;
  1306. case 'alt':
  1307. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1308. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1309. $body .= $this->LE.$this->LE;
  1310. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  1311. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1312. $body .= $this->LE.$this->LE;
  1313. $body .= $this->EndBoundary($this->boundary[1]);
  1314. break;
  1315. case 'alt_inline':
  1316. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1317. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1318. $body .= $this->LE.$this->LE;
  1319. $body .= $this->TextLine("--" . $this->boundary[1]);
  1320. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1321. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1322. $body .= $this->LE;
  1323. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1324. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1325. $body .= $this->LE.$this->LE;
  1326. $body .= $this->AttachAll("inline", $this->boundary[2]);
  1327. $body .= $this->LE;
  1328. $body .= $this->EndBoundary($this->boundary[1]);
  1329. break;
  1330. case 'alt_attach':
  1331. $body .= $this->TextLine("--" . $this->boundary[1]);
  1332. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1333. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1334. $body .= $this->LE;
  1335. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1336. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1337. $body .= $this->LE.$this->LE;
  1338. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1339. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1340. $body .= $this->LE.$this->LE;
  1341. $body .= $this->EndBoundary($this->boundary[2]);
  1342. $body .= $this->LE;
  1343. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1344. break;
  1345. case 'alt_inline_attach':
  1346. $body .= $this->TextLine("--" . $this->boundary[1]);
  1347. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1348. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1349. $body .= $this->LE;
  1350. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1351. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1352. $body .= $this->LE.$this->LE;
  1353. $body .= $this->TextLine("--" . $this->boundary[2]);
  1354. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1355. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
  1356. $body .= $this->LE;
  1357. $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
  1358. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1359. $body .= $this->LE.$this->LE;
  1360. $body .= $this->AttachAll("inline", $this->boundary[3]);
  1361. $body .= $this->LE;
  1362. $body .= $this->EndBoundary($this->boundary[2]);
  1363. $body .= $this->LE;
  1364. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1365. break;
  1366. default:
  1367. // catch case 'plain' and case ''
  1368. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1369. break;
  1370. }
  1371. if ($this->IsError()) {
  1372. $body = '';
  1373. } elseif ($this->sign_key_file) {
  1374. try {
  1375. $file = tempnam('', 'mail');
  1376. file_put_contents($file, $body); //TODO check this worked
  1377. $signed = tempnam("", "signed");
  1378. if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
  1379. @unlink($file);
  1380. $body = file_get_contents($signed);
  1381. @unlink($signed);
  1382. } else {
  1383. @unlink($file);
  1384. @unlink($signed);
  1385. throw new phpmailerException($this->Lang("signing").openssl_error_string());
  1386. }
  1387. } catch (phpmailerException $e) {
  1388. $body = '';
  1389. if ($this->exceptions) {
  1390. throw $e;
  1391. }
  1392. }
  1393. }
  1394. return $body;
  1395. }
  1396. /**
  1397. * Returns the start of a message boundary.
  1398. * @access protected
  1399. * @return string
  1400. */
  1401. protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1402. $result = '';
  1403. if($charSet == '') {
  1404. $charSet = $this->CharSet;
  1405. }
  1406. if($contentType == '') {
  1407. $contentType = $this->ContentType;
  1408. }
  1409. if($encoding == '') {
  1410. $encoding = $this->Encoding;
  1411. }
  1412. $result .= $this->TextLine('--' . $boundary);
  1413. $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
  1414. $result .= $this->LE;
  1415. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1416. $result .= $this->LE;
  1417. return $result;
  1418. }
  1419. /**
  1420. * Returns the end of a message boundary.
  1421. * @access protected
  1422. * @return string
  1423. */
  1424. protected function EndBoundary($boundary) {
  1425. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1426. }
  1427. /**
  1428. * Sets the message type.
  1429. * @access protected
  1430. * @return void
  1431. */
  1432. protected function SetMessageType() {
  1433. $this->message_type = array();
  1434. if($this->AlternativeExists()) $this->message_type[] = "alt";
  1435. if($this->InlineImageExists()) $this->message_type[] = "inline";
  1436. if($this->AttachmentExists()) $this->message_type[] = "attach";
  1437. $this->message_type = implode("_", $this->message_type);
  1438. if($this->message_type == "") $this->message_type = "plain";
  1439. }
  1440. /**
  1441. * Returns a formatted header line.
  1442. * @access public
  1443. * @return string
  1444. */
  1445. public function HeaderLine($name, $value) {
  1446. return $name . ': ' . $value . $this->LE;
  1447. }
  1448. /**
  1449. * Returns a formatted mail line.
  1450. * @access public
  1451. * @return string
  1452. */
  1453. public function TextLine($value) {
  1454. return $value . $this->LE;
  1455. }
  1456. /////////////////////////////////////////////////
  1457. // CLASS METHODS, ATTACHMENTS
  1458. /////////////////////////////////////////////////
  1459. /**
  1460. * Adds an attachment from a path on the filesystem.
  1461. * Returns false if the file could not be found
  1462. * or accessed.
  1463. * @param string $path Path to the attachment.
  1464. * @param string $name Overrides the attachment name.
  1465. * @param string $encoding File encoding (see $Encoding).
  1466. * @param string $type File extension (MIME) type.
  1467. * @return bool
  1468. */
  1469. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1470. try {
  1471. if ( !@is_file($path) ) {
  1472. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1473. }
  1474. $filename = basename($path);
  1475. if ( $name == '' ) {
  1476. $name = $filename;
  1477. }
  1478. $this->attachment[] = array(
  1479. 0 => $path,
  1480. 1 => $filename,
  1481. 2 => $name,
  1482. 3 => $encoding,
  1483. 4 => $type,
  1484. 5 => false, // isStringAttachment
  1485. 6 => 'attachment',
  1486. 7 => 0
  1487. );
  1488. } catch (phpmailerException $e) {
  1489. $this->SetError($e->getMessage());
  1490. if ($this->exceptions) {
  1491. throw $e;
  1492. }
  1493. if ($this->SMTPDebug) {
  1494. $this->edebug($e->getMessage()."\n");
  1495. }
  1496. if ( $e->getCode() == self::STOP_CRITICAL ) {
  1497. return false;
  1498. }
  1499. }
  1500. return true;
  1501. }
  1502. /**
  1503. * Return the current array of attachments
  1504. * @return array
  1505. */
  1506. public function GetAttachments() {
  1507. return $this->attachment;
  1508. }
  1509. /**
  1510. * Attaches all fs, string, and binary attachments to the message.
  1511. * Returns an empty string on failure.
  1512. * @access protected
  1513. * @return string
  1514. */
  1515. protected function AttachAll($disposition_type, $boundary) {
  1516. // Return text of body
  1517. $mime = array();
  1518. $cidUniq = array();
  1519. $incl = array();
  1520. // Add all attachments
  1521. foreach ($this->attachment as $attachment) {
  1522. // CHECK IF IT IS A VALID DISPOSITION_FILTER
  1523. if($attachment[6] == $disposition_type) {
  1524. // Check for string attachment
  1525. $bString = $attachment[5];
  1526. if ($bString) {
  1527. $string = $attachment[0];
  1528. } else {
  1529. $path = $attachment[0];
  1530. }
  1531. $inclhash = md5(serialize($attachment));
  1532. if (in_array($inclhash, $incl)) { continue; }
  1533. $incl[] = $inclhash;
  1534. $filename = $attachment[1];
  1535. $name = $attachment[2];
  1536. $encoding = $attachment[3];
  1537. $type = $attachment[4];
  1538. $disposition = $attachment[6];
  1539. $cid = $attachment[7];
  1540. if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
  1541. $cidUniq[$cid] = true;
  1542. $mime[] = sprintf("--%s%s", $boundary, $this->LE);
  1543. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1544. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1545. if($disposition == 'inline') {
  1546. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1547. }
  1548. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1549. // Encode as string attachment
  1550. if($bString) {
  1551. $mime[] = $this->EncodeString($string, $encoding);
  1552. if($this->IsError()) {
  1553. return '';
  1554. }
  1555. $mime[] = $this->LE.$this->LE;
  1556. } else {
  1557. $mime[] = $this->EncodeFile($path, $encoding);
  1558. if($this->IsError()) {
  1559. return '';
  1560. }
  1561. $mime[] = $this->LE.$this->LE;
  1562. }
  1563. }
  1564. }
  1565. $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
  1566. return implode("", $mime);
  1567. }
  1568. /**
  1569. * Encodes attachment in requested format.
  1570. * Returns an empty string on failure.
  1571. * @param string $path The full path to the file
  1572. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1573. * @see EncodeFile()
  1574. * @access protected
  1575. * @return string
  1576. */
  1577. protected function EncodeFile($path, $encoding = 'base64') {
  1578. try {
  1579. if (!is_readable($path)) {
  1580. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1581. }
  1582. // if (!function_exists('get_magic_quotes')) {
  1583. // function get_magic_quotes() {
  1584. // return false;
  1585. // }
  1586. // }
  1587. $magic_quotes = get_magic_quotes_runtime();
  1588. if ($magic_quotes) {
  1589. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1590. set_magic_quotes_runtime(0);
  1591. } else {
  1592. ini_set('magic_quotes_runtime', 0);
  1593. }
  1594. }
  1595. $file_buffer = file_get_contents($path);
  1596. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1597. if ($magic_quotes) {
  1598. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1599. set_magic_quotes_runtime($magic_quotes);
  1600. } else {
  1601. ini_set('magic_quotes_runtime', $magic_quotes);
  1602. }
  1603. }
  1604. return $file_buffer;
  1605. } catch (Exception $e) {
  1606. $this->SetError($e->getMessage());
  1607. return '';
  1608. }
  1609. }
  1610. /**
  1611. * Encodes string to requested format.
  1612. * Returns an empty string on failure.
  1613. * @param string $str The text to encode
  1614. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1615. * @access public
  1616. * @return string
  1617. */
  1618. public function EncodeString($str, $encoding = 'base64') {
  1619. $encoded = '';
  1620. switch(strtolower($encoding)) {
  1621. case 'base64':
  1622. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1623. break;
  1624. case '7bit':
  1625. case '8bit':
  1626. $encoded = $this->FixEOL($str);
  1627. //Make sure it ends with a line break
  1628. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1629. $encoded .= $this->LE;
  1630. break;
  1631. case 'binary':
  1632. $encoded = $str;
  1633. break;
  1634. case 'quoted-printable':
  1635. $encoded = $this->EncodeQP($str);
  1636. break;
  1637. default:
  1638. $this->SetError($this->Lang('encoding') . $encoding);
  1639. break;
  1640. }
  1641. return $encoded;
  1642. }
  1643. /**
  1644. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1645. * @access public
  1646. * @return string
  1647. */
  1648. public function EncodeHeader($str, $position = 'text') {
  1649. $x = 0;
  1650. switch (strtolower($position)) {
  1651. case 'phrase':
  1652. if (!preg_match('/[\200-\377]/', $str)) {
  1653. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1654. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1655. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1656. return ($encoded);
  1657. } else {
  1658. return ("\"$encoded\"");
  1659. }
  1660. }
  1661. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1662. break;
  1663. case 'comment':
  1664. $x = preg_match_all('/[()"]/', $str, $matches);
  1665. // Fall-through
  1666. case 'text':
  1667. default:
  1668. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1669. break;
  1670. }
  1671. if ($x == 0) {
  1672. return ($str);
  1673. }
  1674. $maxlen = 75 - 7 - strlen($this->CharSet);
  1675. // Try to select the encoding which should produce the shortest output
  1676. if (strlen($str)/3 < $x) {
  1677. $encoding = 'B';
  1678. if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1679. // Use a custom function which correctly encodes and wraps long
  1680. // multibyte strings without breaking lines within a character
  1681. $encoded = $this->Base64EncodeWrapMB($str, "\n");
  1682. } else {
  1683. $encoded = base64_encode($str);
  1684. $maxlen -= $maxlen % 4;
  1685. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1686. }
  1687. } else {
  1688. $encoding = 'Q';
  1689. $encoded = $this->EncodeQ($str, $position);
  1690. $encoded = $this->WrapText($encoded, $maxlen, true);
  1691. $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
  1692. }
  1693. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1694. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1695. return $encoded;
  1696. }
  1697. /**
  1698. * Checks if a string contains multibyte characters.
  1699. * @access public
  1700. * @param string $str multi-byte text to wrap encode
  1701. * @return bool
  1702. */
  1703. public function HasMultiBytes($str) {
  1704. if (function_exists('mb_strlen')) {
  1705. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1706. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1707. return false;
  1708. }
  1709. }
  1710. /**
  1711. * Correctly encodes and wraps long multibyte strings for mail headers
  1712. * without breaking lines within a character.
  1713. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1714. * @access public
  1715. * @param string $str multi-byte text to wrap encode
  1716. * @param string $lf string to use as linefeed/end-of-line
  1717. * @return string
  1718. */
  1719. public function Base64EncodeWrapMB($str, $lf=null) {
  1720. $start = "=?".$this->CharSet."?B?";
  1721. $end = "?=";
  1722. $encoded = "";
  1723. if ($lf === null) {
  1724. $lf = $this->LE;
  1725. }
  1726. $mb_length = mb_strlen($str, $this->CharSet);
  1727. // Each line must have length <= 75, including $start and $end
  1728. $length = 75 - strlen($start) - strlen($end);
  1729. // Average multi-byte ratio
  1730. $ratio = $mb_length / strlen($str);
  1731. // Base64 has a 4:3 ratio
  1732. $offset = $avgLength = floor($length * $ratio * .75);
  1733. for ($i = 0; $i < $mb_length; $i += $offset) {
  1734. $lookBack = 0;
  1735. do {
  1736. $offset = $avgLength - $lookBack;
  1737. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1738. $chunk = base64_encode($chunk);
  1739. $lookBack++;
  1740. }
  1741. while (strlen($chunk) > $length);
  1742. $encoded .= $chunk . $lf;
  1743. }
  1744. // Chomp the last linefeed
  1745. $encoded = substr($encoded, 0, -strlen($lf));
  1746. return $encoded;
  1747. }
  1748. /**
  1749. * Encode string to quoted-printable.
  1750. * Only uses standard PHP, slow, but will always work
  1751. * @access public
  1752. * @param string $string the text to encode
  1753. * @param integer $line_max Number of chars allowed on a line before wrapping
  1754. * @return string
  1755. */
  1756. public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
  1757. $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
  1758. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1759. $eol = "\r\n";
  1760. $escape = '=';
  1761. $output = '';
  1762. while( list(, $line) = each($lines) ) {
  1763. $linlen = strlen($line);
  1764. $newline = '';
  1765. for($i = 0; $i < $linlen; $i++) {
  1766. $c = substr( $line, $i, 1 );
  1767. $dec = ord( $c );
  1768. if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
  1769. $c = '=2E';
  1770. }
  1771. if ( $dec == 32 ) {
  1772. if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
  1773. $c = '=20';
  1774. } else if ( $space_conv ) {
  1775. $c = '=20';
  1776. }
  1777. } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
  1778. $h2 = floor($dec/16);
  1779. $h1 = floor($dec%16);
  1780. $c = $escape.$hex[$h2].$hex[$h1];
  1781. }
  1782. if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
  1783. $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
  1784. $newline = '';
  1785. // check if newline first character will be point or not
  1786. if ( $dec == 46 ) {
  1787. $c = '=2E';
  1788. }
  1789. }
  1790. $newline .= $c;
  1791. } // end of for
  1792. $output .= $newline.$eol;
  1793. } // end of while
  1794. return $output;
  1795. }
  1796. /**
  1797. * Encode string to RFC2045 (6.7) quoted-printable format
  1798. * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
  1799. * Also results in same content as you started with after decoding
  1800. * @see EncodeQPphp()
  1801. * @access public
  1802. * @param string $string the text to encode
  1803. * @param integer $line_max Number of chars allowed on a line before wrapping
  1804. * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
  1805. * @return string
  1806. * @author Marcus Bointon
  1807. */
  1808. public function EncodeQP($string, $line_max = 76, $space_conv = false) {
  1809. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  1810. return quoted_printable_encode($string);
  1811. }
  1812. $filters = stream_get_filters();
  1813. if (!in_array('convert.*', $filters)) { //Got convert stream filter?
  1814. return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
  1815. }
  1816. $fp = fopen('php://temp/', 'r+');
  1817. $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
  1818. $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
  1819. $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
  1820. fputs($fp, $string);
  1821. rewind($fp);
  1822. $out = stream_get_contents($fp);
  1823. stream_filter_remove($s);
  1824. $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
  1825. fclose($fp);
  1826. return $out;
  1827. }
  1828. /**
  1829. * Encode string to q encoding.
  1830. * @link http://tools.ietf.org/html/rfc2047
  1831. * @param string $str the text to encode
  1832. * @param string $position Where the text is going to be used, see the RFC for what that means
  1833. * @access public
  1834. * @return string
  1835. */
  1836. public function EncodeQ($str, $position = 'text') {
  1837. //There should not be any EOL in the string
  1838. $pattern="";
  1839. $encoded = str_replace(array("\r", "\n"), '', $str);
  1840. switch (strtolower($position)) {
  1841. case 'phrase':
  1842. $pattern = '^A-Za-z0-9!*+\/ -';
  1843. break;
  1844. case 'comment':
  1845. $pattern = '\(\)"';
  1846. //note that we dont break here!
  1847. //for this reason we build the $pattern withoud including delimiters and []
  1848. case 'text':
  1849. default:
  1850. //Replace every high ascii, control =, ? and _ characters
  1851. //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
  1852. $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
  1853. break;
  1854. }
  1855. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  1856. foreach (array_unique($matches[0]) as $char) {
  1857. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  1858. }
  1859. }
  1860. //Replace every spaces to _ (more readable than =20)
  1861. return str_replace(' ', '_', $encoded);
  1862. }
  1863. /**
  1864. * Adds a string or binary attachment (non-filesystem) to the list.
  1865. * This method can be used to attach ascii or binary data,
  1866. * such as a BLOB record from a database.
  1867. * @param string $string String attachment data.
  1868. * @param string $filename Name of the attachment.
  1869. * @param string $encoding File encoding (see $Encoding).
  1870. * @param string $type File extension (MIME) type.
  1871. * @return void
  1872. */
  1873. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
  1874. // Append to $attachment array
  1875. $this->attachment[] = array(
  1876. 0 => $string,
  1877. 1 => $filename,
  1878. 2 => basename($filename),
  1879. 3 => $encoding,
  1880. 4 => $type,
  1881. 5 => true, // isStringAttachment
  1882. 6 => 'attachment',
  1883. 7 => 0
  1884. );
  1885. }
  1886. /**
  1887. * Adds an embedded attachment. This can include images, sounds, and
  1888. * just about any other document. Make sure to set the $type to an
  1889. * image type. For JPEG images use "image/jpeg" and for GIF images
  1890. * use "image/gif".
  1891. * @param string $path Path to the attachment.
  1892. * @param string $cid Content ID of the attachment. Use this to identify
  1893. * the Id for accessing the image in an HTML form.
  1894. * @param string $name Overrides the attachment name.
  1895. * @param string $encoding File encoding (see $Encoding).
  1896. * @param string $type File extension (MIME) type.
  1897. * @return bool
  1898. */
  1899. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1900. if ( !@is_file($path) ) {
  1901. $this->SetError($this->Lang('file_access') . $path);
  1902. return false;
  1903. }
  1904. $filename = basename($path);
  1905. if ( $name == '' ) {
  1906. $name = $filename;
  1907. }
  1908. // Append to $attachment array
  1909. $this->attachment[] = array(
  1910. 0 => $path,
  1911. 1 => $filename,
  1912. 2 => $name,
  1913. 3 => $encoding,
  1914. 4 => $type,
  1915. 5 => false, // isStringAttachment
  1916. 6 => 'inline',
  1917. 7 => $cid
  1918. );
  1919. return true;
  1920. }
  1921. public function AddStringEmbeddedImage($string, $cid, $filename = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1922. // Append to $attachment array
  1923. $this->attachment[] = array(
  1924. 0 => $string,
  1925. 1 => $filename,
  1926. 2 => basename($filename),
  1927. 3 => $encoding,
  1928. 4 => $type,
  1929. 5 => true, // isStringAttachment
  1930. 6 => 'inline',
  1931. 7 => $cid
  1932. );
  1933. }
  1934. /**
  1935. * Returns true if an inline attachment is present.
  1936. * @access public
  1937. * @return bool
  1938. */
  1939. public function InlineImageExists() {
  1940. foreach($this->attachment as $attachment) {
  1941. if ($attachment[6] == 'inline') {
  1942. return true;
  1943. }
  1944. }
  1945. return false;
  1946. }
  1947. public function AttachmentExists() {
  1948. foreach($this->attachment as $attachment) {
  1949. if ($attachment[6] == 'attachment') {
  1950. return true;
  1951. }
  1952. }
  1953. return false;
  1954. }
  1955. public function AlternativeExists() {
  1956. return !empty($this->AltBody);
  1957. }
  1958. /////////////////////////////////////////////////
  1959. // CLASS METHODS, MESSAGE RESET
  1960. /////////////////////////////////////////////////
  1961. /**
  1962. * Clears all recipients assigned in the TO array. Returns void.
  1963. * @return void
  1964. */
  1965. public function ClearAddresses() {
  1966. foreach($this->to as $to) {
  1967. unset($this->all_recipients[strtolower($to[0])]);
  1968. }
  1969. $this->to = array();
  1970. }
  1971. /**
  1972. * Clears all recipients assigned in the CC array. Returns void.
  1973. * @return void
  1974. */
  1975. public function ClearCCs() {
  1976. foreach($this->cc as $cc) {
  1977. unset($this->all_recipients[strtolower($cc[0])]);
  1978. }
  1979. $this->cc = array();
  1980. }
  1981. /**
  1982. * Clears all recipients assigned in the BCC array. Returns void.
  1983. * @return void
  1984. */
  1985. public function ClearBCCs() {
  1986. foreach($this->bcc as $bcc) {
  1987. unset($this->all_recipients[strtolower($bcc[0])]);
  1988. }
  1989. $this->bcc = array();
  1990. }
  1991. /**
  1992. * Clears all recipients assigned in the ReplyTo array. Returns void.
  1993. * @return void
  1994. */
  1995. public function ClearReplyTos() {
  1996. $this->ReplyTo = array();
  1997. }
  1998. /**
  1999. * Clears all recipients assigned in the TO, CC and BCC
  2000. * array. Returns void.
  2001. * @return void
  2002. */
  2003. public function ClearAllRecipients() {
  2004. $this->to = array();
  2005. $this->cc = array();
  2006. $this->bcc = array();
  2007. $this->all_recipients = array();
  2008. }
  2009. /**
  2010. * Clears all previously set filesystem, string, and binary
  2011. * attachments. Returns void.
  2012. * @return void
  2013. */
  2014. public function ClearAttachments() {
  2015. $this->attachment = array();
  2016. }
  2017. /**
  2018. * Clears all custom headers. Returns void.
  2019. * @return void
  2020. */
  2021. public function ClearCustomHeaders() {
  2022. $this->CustomHeader = array();
  2023. }
  2024. /////////////////////////////////////////////////
  2025. // CLASS METHODS, MISCELLANEOUS
  2026. /////////////////////////////////////////////////
  2027. /**
  2028. * Adds the error message to the error container.
  2029. * @access protected
  2030. * @return void
  2031. */
  2032. protected function SetError($msg) {
  2033. $this->error_count++;
  2034. if (($this->Mailer == 'smtp') and ($this->smtp !== null)) {
  2035. $lasterror = $this->smtp->getError();
  2036. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2037. $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  2038. }
  2039. }
  2040. $this->ErrorInfo = $msg;
  2041. }
  2042. /**
  2043. * Returns the proper RFC 822 formatted date.
  2044. * @access public
  2045. * @return string
  2046. * @static
  2047. */
  2048. public static function RFCDate() {
  2049. $tz = date('Z');
  2050. $tzs = ($tz < 0) ? '-' : '+';
  2051. $tz = abs($tz);
  2052. $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
  2053. $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
  2054. return $result;
  2055. }
  2056. /**
  2057. * Returns the server hostname or 'localhost.localdomain' if unknown.
  2058. * @access protected
  2059. * @return string
  2060. */
  2061. protected function ServerHostname() {
  2062. if (!empty($this->Hostname)) {
  2063. $result = $this->Hostname;
  2064. } elseif (isset($_SERVER['SERVER_NAME'])) {
  2065. $result = $_SERVER['SERVER_NAME'];
  2066. } else {
  2067. $result = 'localhost.localdomain';
  2068. }
  2069. return $result;
  2070. }
  2071. /**
  2072. * Returns a message in the appropriate language.
  2073. * @access protected
  2074. * @return string
  2075. */
  2076. protected function Lang($key) {
  2077. if(count($this->language) < 1) {
  2078. $this->SetLanguage('en'); // set the default language
  2079. }
  2080. if(isset($this->language[$key])) {
  2081. return $this->language[$key];
  2082. } else {
  2083. return 'Language string failed to load: ' . $key;
  2084. }
  2085. }
  2086. /**
  2087. * Returns true if an error occurred.
  2088. * @access public
  2089. * @return bool
  2090. */
  2091. public function IsError() {
  2092. return ($this->error_count > 0);
  2093. }
  2094. /**
  2095. * Changes every end of line from CRLF, CR or LF to $this->LE.
  2096. * @access public
  2097. * @param string $str String to FixEOL
  2098. * @return string
  2099. */
  2100. public function FixEOL($str) {
  2101. // condense down to \n
  2102. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  2103. // Now convert LE as needed
  2104. if ($this->LE !== "\n") {
  2105. $nstr = str_replace("\n", $this->LE, $nstr);
  2106. }
  2107. return $nstr;
  2108. }
  2109. /**
  2110. * Adds a custom header. $name value can be overloaded to contain
  2111. * both header name and value (name:value)
  2112. * @access public
  2113. * @param string $name custom header name
  2114. * @param string $value header value
  2115. * @return void
  2116. */
  2117. public function AddCustomHeader($name, $value=null) {
  2118. if ($value === null) {
  2119. // Value passed in as name:value
  2120. $this->CustomHeader[] = explode(':', $name, 2);
  2121. } else {
  2122. $this->CustomHeader[] = array($name, $value);
  2123. }
  2124. }
  2125. /**
  2126. * Evaluates the message and returns modifications for inline images and backgrounds
  2127. * @access public
  2128. * @param string $message Text to be HTML modified
  2129. * @param string $basedir baseline directory for path
  2130. * @return $message
  2131. */
  2132. public function MsgHTML($message, $basedir = '') {
  2133. preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
  2134. if(isset($images[2])) {
  2135. foreach($images[2] as $i => $url) {
  2136. // do not change urls for absolute images (thanks to corvuscorax)
  2137. if (!preg_match('#^[A-z]+://#', $url)) {
  2138. $filename = basename($url);
  2139. $directory = dirname($url);
  2140. ($directory == '.') ? $directory='': '';
  2141. $cid = 'cid:' . md5($filename);
  2142. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  2143. $mimeType = self::_mime_types($ext);
  2144. if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; }
  2145. if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
  2146. if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType) ) {
  2147. $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"".$cid."\"", $message);
  2148. }
  2149. }
  2150. }
  2151. }
  2152. $this->IsHTML(true);
  2153. $this->Body = $message;
  2154. if (empty($this->AltBody)) {
  2155. $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
  2156. if (!empty($textMsg)) {
  2157. $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet);
  2158. }
  2159. }
  2160. if (empty($this->AltBody)) {
  2161. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
  2162. }
  2163. return $message;
  2164. }
  2165. /**
  2166. * Gets the MIME type of the embedded or inline image
  2167. * @param string $ext File extension
  2168. * @access public
  2169. * @return string MIME type of ext
  2170. * @static
  2171. */
  2172. public static function _mime_types($ext = '') {
  2173. $mimes = array(
  2174. 'xl' => 'application/excel',
  2175. 'hqx' => 'application/mac-binhex40',
  2176. 'cpt' => 'application/mac-compactpro',
  2177. 'bin' => 'application/macbinary',
  2178. 'doc' => 'application/msword',
  2179. 'doc' => 'application/msword',
  2180. 'word' => 'application/msword',
  2181. 'class' => 'application/octet-stream',
  2182. 'dll' => 'application/octet-stream',
  2183. 'dms' => 'application/octet-stream',
  2184. 'exe' => 'application/octet-stream',
  2185. 'lha' => 'application/octet-stream',
  2186. 'lzh' => 'application/octet-stream',
  2187. 'psd' => 'application/octet-stream',
  2188. 'sea' => 'application/octet-stream',
  2189. 'so' => 'application/octet-stream',
  2190. 'oda' => 'application/oda',
  2191. 'pdf' => 'application/pdf',
  2192. 'ai' => 'application/postscript',
  2193. 'eps' => 'application/postscript',
  2194. 'ps' => 'application/postscript',
  2195. 'smi' => 'application/smil',
  2196. 'smil' => 'application/smil',
  2197. 'mif' => 'application/vnd.mif',
  2198. 'xls' => 'application/vnd.ms-excel',
  2199. 'ppt' => 'application/vnd.ms-powerpoint',
  2200. 'wbxml' => 'application/vnd.wap.wbxml',
  2201. 'wmlc' => 'application/vnd.wap.wmlc',
  2202. 'dcr' => 'application/x-director',
  2203. 'dir' => 'application/x-director',
  2204. 'dxr' => 'application/x-director',
  2205. 'dvi' => 'application/x-dvi',
  2206. 'gtar' => 'application/x-gtar',
  2207. 'php3' => 'application/x-httpd-php',
  2208. 'php4' => 'application/x-httpd-php',
  2209. 'php' => 'application/x-httpd-php',
  2210. 'phtml' => 'application/x-httpd-php',
  2211. 'phps' => 'application/x-httpd-php-source',
  2212. 'js' => 'application/x-javascript',
  2213. 'swf' => 'application/x-shockwave-flash',
  2214. 'sit' => 'application/x-stuffit',
  2215. 'tar' => 'application/x-tar',
  2216. 'tgz' => 'application/x-tar',
  2217. 'xht' => 'application/xhtml+xml',
  2218. 'xhtml' => 'application/xhtml+xml',
  2219. 'zip' => 'application/zip',
  2220. 'mid' => 'audio/midi',
  2221. 'midi' => 'audio/midi',
  2222. 'mp2' => 'audio/mpeg',
  2223. 'mp3' => 'audio/mpeg',
  2224. 'mpga' => 'audio/mpeg',
  2225. 'aif' => 'audio/x-aiff',
  2226. 'aifc' => 'audio/x-aiff',
  2227. 'aiff' => 'audio/x-aiff',
  2228. 'ram' => 'audio/x-pn-realaudio',
  2229. 'rm' => 'audio/x-pn-realaudio',
  2230. 'rpm' => 'audio/x-pn-realaudio-plugin',
  2231. 'ra' => 'audio/x-realaudio',
  2232. 'wav' => 'audio/x-wav',
  2233. 'bmp' => 'image/bmp',
  2234. 'gif' => 'image/gif',
  2235. 'jpeg' => 'image/jpeg',
  2236. 'jpe' => 'image/jpeg',
  2237. 'jpg' => 'image/jpeg',
  2238. 'png' => 'image/png',
  2239. 'tiff' => 'image/tiff',
  2240. 'tif' => 'image/tiff',
  2241. 'eml' => 'message/rfc822',
  2242. 'css' => 'text/css',
  2243. 'html' => 'text/html',
  2244. 'htm' => 'text/html',
  2245. 'shtml' => 'text/html',
  2246. 'log' => 'text/plain',
  2247. 'text' => 'text/plain',
  2248. 'txt' => 'text/plain',
  2249. 'rtx' => 'text/richtext',
  2250. 'rtf' => 'text/rtf',
  2251. 'xml' => 'text/xml',
  2252. 'xsl' => 'text/xml',
  2253. 'mpeg' => 'video/mpeg',
  2254. 'mpe' => 'video/mpeg',
  2255. 'mpg' => 'video/mpeg',
  2256. 'mov' => 'video/quicktime',
  2257. 'qt' => 'video/quicktime',
  2258. 'rv' => 'video/vnd.rn-realvideo',
  2259. 'avi' => 'video/x-msvideo',
  2260. 'movie' => 'video/x-sgi-movie'
  2261. );
  2262. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  2263. }
  2264. /**
  2265. * Set (or reset) Class Objects (variables)
  2266. *
  2267. * Usage Example:
  2268. * $page->set('X-Priority', '3');
  2269. *
  2270. * @access public
  2271. * @param string $name Parameter Name
  2272. * @param mixed $value Parameter Value
  2273. * NOTE: will not work with arrays, there are no arrays to set/reset
  2274. * @todo Should this not be using __set() magic function?
  2275. */
  2276. public function set($name, $value = '') {
  2277. try {
  2278. if (isset($this->$name) ) {
  2279. $this->$name = $value;
  2280. } else {
  2281. throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
  2282. }
  2283. } catch (Exception $e) {
  2284. $this->SetError($e->getMessage());
  2285. if ($e->getCode() == self::STOP_CRITICAL) {
  2286. return false;
  2287. }
  2288. }
  2289. return true;
  2290. }
  2291. /**
  2292. * Strips newlines to prevent header injection.
  2293. * @access public
  2294. * @param string $str String
  2295. * @return string
  2296. */
  2297. public function SecureHeader($str) {
  2298. return trim(str_replace(array("\r", "\n"), '', $str));
  2299. }
  2300. /**
  2301. * Set the private key file and password to sign the message.
  2302. *
  2303. * @access public
  2304. * @param string $key_filename Parameter File Name
  2305. * @param string $key_pass Password for private key
  2306. */
  2307. public function Sign($cert_filename, $key_filename, $key_pass) {
  2308. $this->sign_cert_file = $cert_filename;
  2309. $this->sign_key_file = $key_filename;
  2310. $this->sign_key_pass = $key_pass;
  2311. }
  2312. /**
  2313. * Set the private key file and password to sign the message.
  2314. *
  2315. * @access public
  2316. * @param string $key_filename Parameter File Name
  2317. * @param string $key_pass Password for private key
  2318. */
  2319. public function DKIM_QP($txt) {
  2320. $tmp = '';
  2321. $line = '';
  2322. for ($i = 0; $i < strlen($txt); $i++) {
  2323. $ord = ord($txt[$i]);
  2324. if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
  2325. $line .= $txt[$i];
  2326. } else {
  2327. $line .= "=".sprintf("%02X", $ord);
  2328. }
  2329. }
  2330. return $line;
  2331. }
  2332. /**
  2333. * Generate DKIM signature
  2334. *
  2335. * @access public
  2336. * @param string $s Header
  2337. */
  2338. public function DKIM_Sign($s) {
  2339. $privKeyStr = file_get_contents($this->DKIM_private);
  2340. if ($this->DKIM_passphrase != '') {
  2341. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2342. } else {
  2343. $privKey = $privKeyStr;
  2344. }
  2345. if (openssl_sign($s, $signature, $privKey)) {
  2346. return base64_encode($signature);
  2347. }
  2348. }
  2349. /**
  2350. * Generate DKIM Canonicalization Header
  2351. *
  2352. * @access public
  2353. * @param string $s Header
  2354. */
  2355. public function DKIM_HeaderC($s) {
  2356. $s = preg_replace("/\r\n\s+/", " ", $s);
  2357. $lines = explode("\r\n", $s);
  2358. foreach ($lines as $key => $line) {
  2359. list($heading, $value) = explode(":", $line, 2);
  2360. $heading = strtolower($heading);
  2361. $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
  2362. $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
  2363. }
  2364. $s = implode("\r\n", $lines);
  2365. return $s;
  2366. }
  2367. /**
  2368. * Generate DKIM Canonicalization Body
  2369. *
  2370. * @access public
  2371. * @param string $body Message Body
  2372. */
  2373. public function DKIM_BodyC($body) {
  2374. if ($body == '') return "\r\n";
  2375. // stabilize line endings
  2376. $body = str_replace("\r\n", "\n", $body);
  2377. $body = str_replace("\n", "\r\n", $body);
  2378. // END stabilize line endings
  2379. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  2380. $body = substr($body, 0, strlen($body) - 2);
  2381. }
  2382. return $body;
  2383. }
  2384. /**
  2385. * Create the DKIM header, body, as new header
  2386. *
  2387. * @access public
  2388. * @param string $headers_line Header lines
  2389. * @param string $subject Subject
  2390. * @param string $body Body
  2391. */
  2392. public function DKIM_Add($headers_line, $subject, $body) {
  2393. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2394. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2395. $DKIMquery = 'dns/txt'; // Query method
  2396. $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2397. $subject_header = "Subject: $subject";
  2398. $headers = explode($this->LE, $headers_line);
  2399. foreach($headers as $header) {
  2400. if (strpos($header, 'From:') === 0) {
  2401. $from_header = $header;
  2402. } elseif (strpos($header, 'To:') === 0) {
  2403. $to_header = $header;
  2404. }
  2405. }
  2406. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  2407. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  2408. $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
  2409. $body = $this->DKIM_BodyC($body);
  2410. $DKIMlen = strlen($body) ; // Length of body
  2411. $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
  2412. $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
  2413. $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
  2414. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
  2415. "\th=From:To:Subject;\r\n".
  2416. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
  2417. "\tz=$from\r\n".
  2418. "\t|$to\r\n".
  2419. "\t|$subject;\r\n".
  2420. "\tbh=" . $DKIMb64 . ";\r\n".
  2421. "\tb=";
  2422. $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
  2423. $signed = $this->DKIM_Sign($toSign);
  2424. return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
  2425. }
  2426. /**
  2427. * Perform callback
  2428. */
  2429. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from=null) {
  2430. if (!empty($this->action_function) && is_callable($this->action_function)) {
  2431. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  2432. call_user_func_array($this->action_function, $params);
  2433. }
  2434. }
  2435. }
  2436. /**
  2437. * Exception handling
  2438. */
  2439. class phpmailerException extends Exception {
  2440. public function errorMessage() {
  2441. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2442. return $errorMsg;
  2443. }
  2444. }
  2445. ?>