@@ -520,27 +520,8 @@ protected function processStructure($structure, $partIdentifier = null)
520
520
521
521
$ messageBody = self ::decode ($ messageBody , $ structure ->encoding );
522
522
523
- if (!empty ($ parameters ['charset ' ]) && $ parameters ['charset ' ] !== self ::$ charset ) {
524
- $ mb_converted = false ;
525
- if (function_exists ('mb_convert_encoding ' )) {
526
- if (!in_array ($ parameters ['charset ' ], mb_list_encodings ())) {
527
- if ($ structure ->encoding === 0 ) {
528
- $ parameters ['charset ' ] = 'US-ASCII ' ;
529
- } else {
530
- $ parameters ['charset ' ] = 'UTF-8 ' ;
531
- }
532
- }
533
-
534
- $ messageBody = @mb_convert_encoding ($ messageBody , self ::$ charset , $ parameters ['charset ' ]);
535
- $ mb_converted = true ;
536
- }
537
- if (!$ mb_converted ) {
538
- $ messageBodyConv = @iconv ($ parameters ['charset ' ], self ::$ charset . self ::$ charsetFlag , $ messageBody );
539
-
540
- if ($ messageBodyConv !== false ) {
541
- $ messageBody = $ messageBodyConv ;
542
- }
543
- }
523
+ if (!empty ($ parameters ['charset ' ])) {
524
+ $ messageBody = self ::charsetConvert ($ messageBody , $ parameters ['charset ' ], self ::$ charset ) ?: $ messageBody ;
544
525
}
545
526
546
527
if (strtolower ($ structure ->subtype ) === 'plain ' || ($ structure ->type == 1 && strtolower ($ structure ->subtype ) !== 'alternative ' )) {
@@ -575,6 +556,46 @@ protected function processStructure($structure, $partIdentifier = null)
575
556
}
576
557
}
577
558
559
+ /**
560
+ * @param string $text
561
+ * @param string $from
562
+ * @param string $to
563
+ *
564
+ * @return string|null
565
+ */
566
+ public static function charsetConvert ($ text , $ from , $ to = null )
567
+ {
568
+ if (!$ text ) {
569
+ return '' ;
570
+ }
571
+
572
+ if (null === $ to ) {
573
+ $ to = self ::$ charset ;
574
+ }
575
+
576
+ $ from = strtolower ($ from );
577
+ $ to = strtolower ($ to );
578
+
579
+ if ($ from === $ to ) {
580
+ return $ text ;
581
+ }
582
+
583
+ $ converted = null ;
584
+ if (!$ converted && function_exists ('mb_convert_encoding ' ) && @mb_check_encoding ($ text , $ from )) {
585
+ $ converted = @mb_convert_encoding ($ text , $ to , $ from );
586
+ }
587
+
588
+ if (!$ converted && function_exists ('iconv ' )) {
589
+ $ converted = @iconv ($ from , $ to . self ::$ charsetFlag , $ text );
590
+ }
591
+
592
+ if ($ converted ) {
593
+ return $ converted ;
594
+ }
595
+
596
+ return null ;
597
+ }
598
+
578
599
/**
579
600
* This function takes in the message data and encoding type and returns the decoded data.
580
601
*
0 commit comments