class.phpmailer.php 82 KB

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