Message.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. <?php // phpcs:disable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps,PSR12.Files.FileHeader.SpacingAfterBlock,PSR2.Methods.MethodDeclaration.Underscore
  2. namespace Laminas\Mime;
  3. use Laminas\Mail\Header\HeaderInterface;
  4. use Laminas\Mime\Mime;
  5. use Laminas\Mime\Part;
  6. use function array_keys;
  7. use function base64_decode;
  8. use function count;
  9. use function current;
  10. use function quoted_printable_decode;
  11. use function sprintf;
  12. use function strlen;
  13. use function strpos;
  14. use function strtolower;
  15. use function substr;
  16. use function trim;
  17. class Message
  18. {
  19. /** @var Part[] */
  20. protected $parts = [];
  21. /** @var null|Mime */
  22. protected $mime;
  23. /**
  24. * Returns the list of all Laminas\Mime\Part in the message
  25. *
  26. * @return Part[]
  27. */
  28. public function getParts()
  29. {
  30. return $this->parts;
  31. }
  32. /**
  33. * Sets the given array of Laminas\Mime\Part as the array for the message
  34. *
  35. * @param array $parts
  36. * @return self
  37. */
  38. public function setParts($parts)
  39. {
  40. $this->parts = $parts;
  41. return $this;
  42. }
  43. /**
  44. * Append a new Laminas\Mime\Part to the current message
  45. *
  46. * @throws Exception\InvalidArgumentException
  47. * @return self
  48. */
  49. public function addPart(Part $part)
  50. {
  51. foreach ($this->getParts() as $row) {
  52. if ($part === $row) {
  53. throw new Exception\InvalidArgumentException(sprintf(
  54. 'Provided part %s already defined.',
  55. $part->getId()
  56. ));
  57. }
  58. }
  59. $this->parts[] = $part;
  60. return $this;
  61. }
  62. /**
  63. * Check if message needs to be sent as multipart
  64. * MIME message or if it has only one part.
  65. *
  66. * @return bool
  67. */
  68. public function isMultiPart()
  69. {
  70. return count($this->parts) > 1;
  71. }
  72. /**
  73. * Set Laminas\Mime\Mime object for the message
  74. *
  75. * This can be used to set the boundary specifically or to use a subclass of
  76. * Laminas\Mime for generating the boundary.
  77. *
  78. * @return self
  79. */
  80. public function setMime(Mime $mime)
  81. {
  82. $this->mime = $mime;
  83. return $this;
  84. }
  85. /**
  86. * Returns the Laminas\Mime\Mime object in use by the message
  87. *
  88. * If the object was not present, it is created and returned. Can be used to
  89. * determine the boundary used in this message.
  90. *
  91. * @return Mime
  92. */
  93. public function getMime()
  94. {
  95. if ($this->mime === null) {
  96. $this->mime = new Mime();
  97. }
  98. return $this->mime;
  99. }
  100. /**
  101. * Generate MIME-compliant message from the current configuration
  102. *
  103. * This can be a multipart message if more than one MIME part was added. If
  104. * only one part is present, the content of this part is returned. If no
  105. * part had been added, an empty string is returned.
  106. *
  107. * Parts are separated by the mime boundary as defined in Laminas\Mime\Mime. If
  108. * {@link setMime()} has been called before this method, the Laminas\Mime\Mime
  109. * object set by this call will be used. Otherwise, a new Laminas\Mime\Mime object
  110. * is generated and used.
  111. *
  112. * @param string $EOL EOL string; defaults to {@link Laminas\Mime\Mime::LINEEND}
  113. * @return string
  114. */
  115. public function generateMessage($EOL = Mime::LINEEND)
  116. {
  117. if (! $this->isMultiPart()) {
  118. if (empty($this->parts)) {
  119. return '';
  120. }
  121. $part = current($this->parts);
  122. $body = $part->getContent($EOL);
  123. } else {
  124. $mime = $this->getMime();
  125. $boundaryLine = $mime->boundaryLine($EOL);
  126. $body = 'This is a message in Mime Format. If you see this, '
  127. . "your mail reader does not support this format." . $EOL;
  128. foreach (array_keys($this->parts) as $p) {
  129. $body .= $boundaryLine
  130. . $this->getPartHeaders($p, $EOL)
  131. . $EOL
  132. . $this->getPartContent($p, $EOL);
  133. }
  134. $body .= $mime->mimeEnd($EOL);
  135. }
  136. return trim($body);
  137. }
  138. /**
  139. * Get the headers of a given part as an array
  140. *
  141. * @param int $partnum
  142. * @return array
  143. */
  144. public function getPartHeadersArray($partnum)
  145. {
  146. return $this->parts[$partnum]->getHeadersArray();
  147. }
  148. /**
  149. * Get the headers of a given part as a string
  150. *
  151. * @param int $partnum
  152. * @param string $EOL
  153. * @return string
  154. */
  155. public function getPartHeaders($partnum, $EOL = Mime::LINEEND)
  156. {
  157. return $this->parts[$partnum]->getHeaders($EOL);
  158. }
  159. /**
  160. * Get the (encoded) content of a given part as a string
  161. *
  162. * @param int $partnum
  163. * @param string $EOL
  164. * @return string
  165. */
  166. public function getPartContent($partnum, $EOL = Mime::LINEEND)
  167. {
  168. return $this->parts[$partnum]->getContent($EOL);
  169. }
  170. /**
  171. * Explode MIME multipart string into separate parts
  172. *
  173. * Parts consist of the header and the body of each MIME part.
  174. *
  175. * @param string $body
  176. * @param string $boundary
  177. * @throws Exception\RuntimeException
  178. * @return array
  179. */
  180. protected static function _disassembleMime($body, $boundary)
  181. {
  182. $start = 0;
  183. $res = [];
  184. // find every mime part limiter and cut out the
  185. // string before it.
  186. // the part before the first boundary string is discarded:
  187. $p = strpos($body, '--' . $boundary . "\n", $start);
  188. if ($p === false) {
  189. // no parts found!
  190. return [];
  191. }
  192. // position after first boundary line
  193. $start = $p + 3 + strlen($boundary);
  194. while (($p = strpos($body, '--' . $boundary . "\n", $start)) !== false) {
  195. $res[] = substr($body, $start, $p - $start);
  196. $start = $p + 3 + strlen($boundary);
  197. }
  198. // no more parts, find end boundary
  199. $p = strpos($body, '--' . $boundary . '--', $start);
  200. if ($p === false) {
  201. throw new Exception\RuntimeException('Not a valid Mime Message: End Missing');
  202. }
  203. // the remaining part also needs to be parsed:
  204. $res[] = substr($body, $start, $p - $start);
  205. return $res;
  206. }
  207. /**
  208. * Decodes a MIME encoded string and returns a Laminas\Mime\Message object with
  209. * all the MIME parts set according to the given string
  210. *
  211. * @param string $message
  212. * @param string $boundary Multipart boundary; if omitted, $message will be
  213. * treated as a single part.
  214. * @param string $EOL EOL string; defaults to {@link Laminas\Mime\Mime::LINEEND}
  215. * @throws Exception\RuntimeException
  216. * @return Message
  217. */
  218. public static function createFromMessage($message, $boundary = null, $EOL = Mime::LINEEND)
  219. {
  220. if ($boundary) {
  221. $parts = Decode::splitMessageStruct($message, $boundary, $EOL);
  222. } else {
  223. Decode::splitMessage($message, $headers, $body, $EOL);
  224. $parts = [
  225. [
  226. 'header' => $headers,
  227. 'body' => $body,
  228. ],
  229. ];
  230. }
  231. $res = new static();
  232. foreach ($parts as $part) {
  233. // now we build a new MimePart for the current Message Part:
  234. $properties = [];
  235. foreach ($part['header'] as $header) {
  236. /** @var HeaderInterface $header */
  237. /**
  238. * @todo check for characterset and filename
  239. */
  240. $fieldName = $header->getFieldName();
  241. $fieldValue = $header->getFieldValue();
  242. switch (strtolower($fieldName)) {
  243. case 'content-type':
  244. $properties['type'] = $fieldValue;
  245. break;
  246. case 'content-transfer-encoding':
  247. $properties['encoding'] = $fieldValue;
  248. break;
  249. case 'content-id':
  250. $properties['id'] = trim($fieldValue, '<>');
  251. break;
  252. case 'content-disposition':
  253. $properties['disposition'] = $fieldValue;
  254. break;
  255. case 'content-description':
  256. $properties['description'] = $fieldValue;
  257. break;
  258. case 'content-location':
  259. $properties['location'] = $fieldValue;
  260. break;
  261. case 'content-language':
  262. $properties['language'] = $fieldValue;
  263. break;
  264. default:
  265. // Ignore unknown header
  266. break;
  267. }
  268. }
  269. $body = $part['body'];
  270. if (isset($properties['encoding'])) {
  271. switch ($properties['encoding']) {
  272. case 'quoted-printable':
  273. $body = quoted_printable_decode($body);
  274. break;
  275. case 'base64':
  276. $body = base64_decode($body);
  277. break;
  278. }
  279. }
  280. $newPart = new Part($body);
  281. foreach ($properties as $key => $value) {
  282. $newPart->$key = $value;
  283. }
  284. $res->addPart($newPart);
  285. }
  286. return $res;
  287. }
  288. }