PageRenderTime 41ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/ojs/ojs-2.1.1/classes/mail/MailTemplate.inc.php

https://github.com/mcrider/pkpUpgradeTestSuite
PHP | 438 lines | 254 code | 71 blank | 113 comment | 62 complexity | e7add123cfecf23f167bb648e9a6044d MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * MailTemplate.inc.php
  4. *
  5. * Copyright (c) 2003-2006 John Willinsky
  6. * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  7. *
  8. * @package mail
  9. *
  10. * Subclass of Mail for mailing a template email.
  11. *
  12. * $Id: MailTemplate.inc.php,v 1.50 2006/06/12 23:25:51 alec Exp $
  13. */
  14. import('mail.Mail');
  15. define('MAIL_ERROR_INVALID_EMAIL', 0x000001);
  16. class MailTemplate extends Mail {
  17. /** @var $emailKey string Key of the email template we are using */
  18. var $emailKey;
  19. /** @var $locale string locale of this template */
  20. var $locale;
  21. /** @var $enabled boolean email template is enabled */
  22. var $enabled;
  23. /** @var $errorMessages array List of errors to display to the user */
  24. var $errorMessages;
  25. /** @var $persistAttachments array List of temporary files belonging to
  26. email; these are maintained between requests and only sent to the
  27. attachment handling functions in Mail.inc.php at time of send. */
  28. var $persistAttachments;
  29. var $attachmentsEnabled;
  30. /** @var $skip boolean If set to true, this message has been skipped
  31. during the editing process by the user. */
  32. var $skip;
  33. /** @var $bccSender boolean whether or not to bcc the sender */
  34. var $bccSender;
  35. /** @var boolean Whether or not email fields are disabled */
  36. var $addressFieldsEnabled;
  37. /**
  38. * Constructor.
  39. * @param $emailKey string unique identifier for the template
  40. * @param $locale string locale of the template
  41. * @param $enableAttachments boolean optional Whether or not to enable article attachments in the template
  42. * @param $journal object optional The journal this message relates to
  43. */
  44. function MailTemplate($emailKey = null, $locale = null, $enableAttachments = null, $journal = null) {
  45. $this->emailKey = isset($emailKey) ? $emailKey : null;
  46. // Use current user's locale if none specified
  47. $this->locale = isset($locale) ? $locale : Locale::getLocale();
  48. // If a journal wasn't specified, use the current request.
  49. if ($journal === null) $journal = &Request::getJournal();
  50. if (isset($this->emailKey)) {
  51. $emailTemplateDao = &DAORegistry::getDAO('EmailTemplateDAO');
  52. $emailTemplate = &$emailTemplateDao->getEmailTemplate($this->emailKey, $this->locale, $journal == null ? 0 : $journal->getJournalId());
  53. }
  54. if (isset($emailTemplate) && Request::getUserVar('subject')==null && Request::getUserVar('body')==null) {
  55. $this->setSubject($emailTemplate->getSubject());
  56. $this->setBody($emailTemplate->getBody());
  57. $this->enabled = $emailTemplate->getEnabled();
  58. if (Request::getUserVar('usePostedAddresses')) {
  59. $to = Request::getUserVar('to');
  60. if (is_array($to)) {
  61. $this->setRecipients($this->processAddresses ($this->getRecipients(), $to));
  62. }
  63. $cc = Request::getUserVar('cc');
  64. if (is_array($cc)) {
  65. $this->setCcs($this->processAddresses ($this->getCcs(), $cc));
  66. }
  67. $bcc = Request::getUserVar('bcc');
  68. if (is_array($bcc)) {
  69. $this->setBccs($this->processAddresses ($this->getBccs(), $bcc));
  70. }
  71. }
  72. } else {
  73. $this->setSubject(Request::getUserVar('subject'));
  74. $this->setBody(Request::getUserVar('body'));
  75. $this->skip = (($tmp = Request::getUserVar('send')) && is_array($tmp) && isset($tmp['skip']));
  76. $this->enabled = true;
  77. if (is_array($toEmails = Request::getUserVar('to'))) {
  78. $this->setRecipients($this->processAddresses ($this->getRecipients(), $toEmails));
  79. }
  80. if (is_array($ccEmails = Request::getUserVar('cc'))) {
  81. $this->setCcs($this->processAddresses ($this->getCcs(), $ccEmails));
  82. }
  83. if (is_array($bccEmails = Request::getUserVar('bcc'))) {
  84. $this->setBccs($this->processAddresses ($this->getBccs(), $bccEmails));
  85. }
  86. }
  87. // Record whether or not to BCC the sender when sending message
  88. $this->bccSender = Request::getUserVar('bccSender');
  89. // Default "From" to user if available, otherwise site/journal principal contact
  90. $user = &Request::getUser();
  91. if ($user) {
  92. $this->setFrom($user->getEmail(), $user->getFullName());
  93. } elseif ($journal == null) {
  94. $site = &Request::getSite();
  95. $this->setFrom($site->getContactEmail(), $site->getContactName());
  96. } else {
  97. $this->setFrom($journal->getSetting('contactEmail'), $journal->getSetting('contactName'));
  98. }
  99. if ($journal && !Request::getUserVar('continued')) {
  100. $this->setSubject('[' . $journal->getSetting('journalInitials') . '] ' . $this->getSubject());
  101. }
  102. // If enableAttachments is null, use the default value from the
  103. // configuration file
  104. if ($enableAttachments === null) {
  105. $enableAttachments = Config::getVar('email', 'enable_attachments')?true:false;
  106. }
  107. if ($enableAttachments && $user) {
  108. $this->_handleAttachments($user->getUserId());
  109. } else {
  110. $this->attachmentsEnabled = false;
  111. }
  112. $this->addressFieldsEnabled = true;
  113. $this->journal =& $journal;
  114. }
  115. /**
  116. * Disable or enable the address fields on the email form.
  117. * NOTE: This affects the displayed form ONLY; if disabling the address
  118. * fields, callers should manually clearAllRecipients and add/set
  119. * recipients just prior to sending.
  120. * @param $addressFieldsEnabled boolean
  121. */
  122. function setAddressFieldsEnabled($addressFieldsEnabled) {
  123. $this->addressFieldsEnabled = $addressFieldsEnabled;
  124. }
  125. /**
  126. * Get the enabled/disabled state of address fields on the email form.
  127. * @return boolean
  128. */
  129. function getAddressFieldsEnabled() {
  130. return $this->addressFieldsEnabled;
  131. }
  132. /**
  133. * Check whether or not there were errors in the user input for this form.
  134. * @return boolean true iff one or more error messages are stored.
  135. */
  136. function hasErrors() {
  137. return ($this->errorMessages != null);
  138. }
  139. /**
  140. * Assigns values to e-mail parameters.
  141. * @param $paramArray array
  142. * @return void
  143. */
  144. function assignParams($paramArray = array()) {
  145. $subject = $this->getSubject();
  146. $body = $this->getBody();
  147. // Add commonly-used variables to the list
  148. $journal = &Request::getJournal();
  149. if (isset($journal)) {
  150. // FIXME Include affiliation, title, etc. in signature?
  151. $paramArray['journalName'] = $journal->getTitle();
  152. $paramArray['principalContactSignature'] = $journal->getSetting('contactName');
  153. } else {
  154. $site = &Request::getSite();
  155. $paramArray['principalContactSignature'] = $site->getContactName();
  156. }
  157. if (!isset($paramArray['journalUrl'])) $paramArray['journalUrl'] = Request::url(Request::getRequestedJournalPath());
  158. // Replace variables in message with values
  159. foreach ($paramArray as $key => $value) {
  160. if (!is_object($value)) {
  161. $subject = str_replace('{$' . $key . '}', $value, $subject);
  162. $body = str_replace('{$' . $key . '}', $value, $body);
  163. }
  164. }
  165. $this->setSubject($subject);
  166. $this->setBody($body);
  167. }
  168. /**
  169. * Returns true if the email template is enabled; false otherwise.
  170. * @return boolean
  171. */
  172. function isEnabled() {
  173. return $this->enabled;
  174. }
  175. /**
  176. * Processes form-submitted addresses for inclusion in
  177. * the recipient list
  178. * @param $currentList array Current recipient/cc/bcc list
  179. * @param $newAddresses array "Raw" form parameter for additional addresses
  180. */
  181. function &processAddresses($currentList, &$newAddresses) {
  182. foreach ($newAddresses as $newAddress) {
  183. $regs = array();
  184. // Match the form "My Name <my_email@my.domain.com>"
  185. if (ereg('^([^<>' . "\n" . ']*[^<> ' . "\n" . '])[ ]*<([-A-Za-z0-9]+([-_\+\.][A-Za-z0-9]+)*@[A-Za-z0-9]+([-_\.][A-Za-z0-9]+)*\.[A-Za-z]{2,})>$', $newAddress, $regs)) {
  186. $currentList[] = array('name' => $regs[1], 'email' => $regs[2]);
  187. } elseif (ereg('^[A-Za-z0-9]+([-_\+\.][A-Za-z0-9]+)*@[A-Za-z0-9]+([-_\.][A-Za-z0-9]+)*\.[A-Za-z]{2,}$', $newAddress)) {
  188. $currentList[] = array('name' => '', 'email' => $newAddress);
  189. } else if ($newAddress != '') {
  190. $this->errorMessages[] = array('type' => MAIL_ERROR_INVALID_EMAIL, 'address' => $newAddress);
  191. }
  192. }
  193. return $currentList;
  194. }
  195. /**
  196. * Displays an edit form to customize the email.
  197. * @param $formActionUrl string
  198. * @param $hiddenFormParams array
  199. * @return void
  200. */
  201. function displayEditForm($formActionUrl, $hiddenFormParams = null, $alternateTemplate = null, $additionalParameters = array()) {
  202. $journal = &Request::getJournal();
  203. import('form.Form');
  204. $form = &new Form($alternateTemplate!=null?$alternateTemplate:'email/email.tpl');
  205. $form->setData('formActionUrl', $formActionUrl);
  206. $form->setData('subject', $this->getSubject());
  207. $form->setData('body', $this->getBody());
  208. $form->setData('to', $this->getRecipients());
  209. $form->setData('cc', $this->getCcs());
  210. $form->setData('bcc', $this->getBccs());
  211. $form->setData('blankTo', Request::getUserVar('blankTo'));
  212. $form->setData('blankCc', Request::getUserVar('blankCc'));
  213. $form->setData('blankBcc', Request::getUserVar('blankBcc'));
  214. $form->setData('from', $this->getFromString());
  215. $form->setData('addressFieldsEnabled', $this->getAddressFieldsEnabled());
  216. $user = &Request::getUser();
  217. if ($user) {
  218. $form->setData('senderEmail', $user->getEmail());
  219. $form->setData('bccSender', $this->bccSender);
  220. }
  221. if ($this->attachmentsEnabled) {
  222. $form->setData('attachmentsEnabled', true);
  223. $form->setData('persistAttachments', $this->persistAttachments);
  224. }
  225. $form->setData('errorMessages', $this->errorMessages);
  226. if ($hiddenFormParams != null) {
  227. $form->setData('hiddenFormParams', $hiddenFormParams);
  228. }
  229. foreach ($additionalParameters as $key => $value) {
  230. $form->setData($key, $value);
  231. }
  232. $templateMgr = &TemplateManager::getManager();
  233. $templateMgr->assign('helpTopicId', 'journal.managementPages.emails');
  234. $form->display();
  235. }
  236. /**
  237. * Send the email.
  238. * Aside from calling the parent method, this actually attaches
  239. * the persistent attachments if they are used.
  240. */
  241. function send($clearAttachments = true) {
  242. $journal = Request::getJournal();
  243. if (isset($journal)) {
  244. //If {$templateSignature} exists in the body of the
  245. // message, replace it with the journal signature;
  246. // otherwise just append it. This is here to
  247. // accomodate MIME-encoded messages or other cases
  248. // where the signature cannot just be appended.
  249. $searchString = '{$templateSignature}';
  250. if (strstr($this->getBody(), $searchString) === false) {
  251. $this->setBody($this->getBody() . "\n" . $journal->getSetting('emailSignature'));
  252. } else {
  253. $this->setBody(str_replace($searchString, $journal->getSetting('emailSignature'), $this->getBody()));
  254. }
  255. $envelopeSender = $journal->getSetting('envelopeSender');
  256. if (!empty($envelopeSender) && Config::getVar('email', 'allow_envelope_sender')) $this->setEnvelopeSender($envelopeSender);
  257. }
  258. if ($this->attachmentsEnabled) {
  259. foreach ($this->persistAttachments as $persistentAttachment) {
  260. $this->addAttachment(
  261. $persistentAttachment->getFilePath(),
  262. $persistentAttachment->getOriginalFileName(),
  263. $persistentAttachment->getFileType()
  264. );
  265. }
  266. }
  267. $user = &Request::getUser();
  268. if ($user && $this->bccSender) {
  269. $this->addBcc($user->getEmail(), $user->getFullName());
  270. }
  271. if (isset($this->skip) && $this->skip) {
  272. $result = true;
  273. } else {
  274. $result = parent::send();
  275. }
  276. if ($clearAttachments && $this->attachmentsEnabled) {
  277. $this->_clearAttachments($user->getUserId());
  278. }
  279. return $result;
  280. }
  281. /**
  282. * Assigns user-specific values to email parameters, sends
  283. * the email, then clears those values.
  284. * @param $paramArray array
  285. * @return void
  286. */
  287. function sendWithParams($paramArray) {
  288. $savedHeaders = $this->getHeaders();
  289. $savedSubject = $this->getSubject();
  290. $savedBody = $this->getBody();
  291. $this->assignParams($paramArray);
  292. $ret = $this->send();
  293. $this->setHeaders($savedHeaders);
  294. $this->setSubject($savedSubject);
  295. $this->setBody($savedBody);
  296. return $ret;
  297. }
  298. /**
  299. * Clears the recipient, cc, and bcc lists.
  300. * @param $clearHeaders boolean if true, also clear headers
  301. * @return void
  302. */
  303. function clearRecipients($clearHeaders = true) {
  304. $this->setData('recipients', null);
  305. $this->setData('ccs', null);
  306. $this->setData('bccs', null);
  307. if ($clearHeaders) {
  308. $this->setData('headers', null);
  309. }
  310. }
  311. /**
  312. * Adds a persistent attachment to the current list.
  313. * Persistent attachments MUST be previously initialized
  314. * with handleAttachments.
  315. */
  316. function addPersistAttachment($temporaryFile) {
  317. $this->persistAttachments[] = $temporaryFile;
  318. }
  319. /**
  320. * Handles attachments in a generalized manner in situations where
  321. * an email message must span several requests. Called from the
  322. * constructor when attachments are enabled.
  323. */
  324. function _handleAttachments($userId) {
  325. import('file.TemporaryFileManager');
  326. $temporaryFileManager = &new TemporaryFileManager();
  327. $this->attachmentsEnabled = true;
  328. $this->persistAttachments = array();
  329. $deleteAttachment = Request::getUserVar('deleteAttachment');
  330. if (Request::getUserVar('persistAttachments') != null) foreach (Request::getUserVar('persistAttachments') as $fileId) {
  331. $temporaryFile = $temporaryFileManager->getFile($fileId, $userId);
  332. if (!empty($temporaryFile)) {
  333. if ($deleteAttachment != $temporaryFile->getFileId()) {
  334. $this->persistAttachments[] = $temporaryFile;
  335. } else {
  336. // This file is being deleted.
  337. $temporaryFileManager->deleteFile($temporaryFile->getFileId(), $userId);
  338. }
  339. }
  340. }
  341. if (Request::getUserVar('addAttachment')) {
  342. $user = &Request::getUser();
  343. $this->persistAttachments[] = $temporaryFileManager->handleUpload('newAttachment', $user->getUserId());
  344. }
  345. }
  346. function getAttachmentFiles() {
  347. if ($this->attachmentsEnabled) return $this->persistAttachments;
  348. return array();
  349. }
  350. /**
  351. * Delete all attachments associated with this message.
  352. * Called from send().
  353. * @param $userId int
  354. */
  355. function _clearAttachments($userId) {
  356. import('file.TemporaryFileManager');
  357. $temporaryFileManager = &new TemporaryFileManager();
  358. $persistAttachments = Request::getUserVar('persistAttachments');
  359. if (is_array($persistAttachments)) foreach ($persistAttachments as $fileId) {
  360. $temporaryFile = $temporaryFileManager->getFile($fileId, $userId);
  361. if (!empty($temporaryFile)) {
  362. $temporaryFileManager->deleteFile($temporaryFile->getFileId(), $userId);
  363. }
  364. }
  365. }
  366. }
  367. ?>