This page lists files in the current directory. You can view content, get download/execute commands for Wget, Curl, or PowerShell, or filter the list using wildcards (e.g., `*.sh`).
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/ConvertCharset.class.php'
<?php
/**
* @author Mikolaj Jedrzejak <mikolajj@op.pl>
* @copyright Copyright Mikolaj Jedrzejak (c) 2003-2004
* @version 1.0 2004-07-27 00:37
* @link http://www.unicode.org Unicode Homepage
* @link http://www.mikkom.pl My Homepage
*
**/
$PATH_TO_CLASS = dirname(ereg_replace("\\\\","/",__FILE__)) . "/" . "ConvertTables" . "/";
define ("CONVERT_TABLES_DIR", $PATH_TO_CLASS);
define ("DEBUG_MODE", 1);
/**
* -- 1.0 2004-07-28 --
*
* -- The most important thing --
* I want to thank all people who helped me fix all bugs, small and big once.
* I hope that you don't mind that your names are in this file.
*
* -- Some Apache issues --
* I get info from Lukas Lisa, that in some cases with special apache configuration
* you have to put header() function with proper encoding to get your result
* displayed correctly.
* If you want to see what I mean, go to demo.php and demo1.php
*
* -- BETA 1.0 2003-10-21 --
*
* -- You should know about... --
* For good understanding this class you shouls read all this stuff first :) but if you are
* in a hurry just start the demo.php and see what's inside.
* 1. That I'm not good in english at 03:45 :) - so forgive me all mistakes
* 2. This class is a BETA version because I haven't tested it enough
* 3. Feel free to contact me with questions, bug reports and mistakes in PHP and this documentation (email below)
*
* -- In a few words... --
* Why ConvertCharset class?
*
* I have made this class because I had a lot of problems with diferent charsets. First because people
* from Microsoft wanted to have thair own encoding, second because people from Macromedia didn't
* thought about other languages, third because sometimes I need to use text written on MAC, and of course
* it has its own encoding :)
*
* Notice & remember:
* - When I'm saying 1 byte string I mean 1 byte per char.
* - When I'm saying multibyte string I mean more than one byte per char.
*
* So, this are main FEATURES of this class:
* - conversion between 1 byte charsets
* - conversion from 1 byte to multi byte charset (utf-8)
* - conversion from multibyte charset (utf-8) to 1 byte charset
* - every conversion output can be save with numeric entities (browser charset independent - not a full truth)
*
* This is a list of charsets you can operate with, the basic rule is that a char have to be in both charsets,
* otherwise you'll get an error.
*
* - WINDOWS
* - windows-1250 - Central Europe
* - windows-1251 - Cyrillic
* - windows-1252 - Latin I
* - windows-1253 - Greek
* - windows-1254 - Turkish
* - windows-1255 - Hebrew
* - windows-1256 - Arabic
* - windows-1257 - Baltic
* - windows-1258 - Viet Nam
* - cp874 - Thai - this file is also for DOS
*
* - DOS
* - cp437 - Latin US
* - cp737 - Greek
* - cp775 - BaltRim
* - cp850 - Latin1
* - cp852 - Latin2
* - cp855 - Cyrylic
* - cp857 - Turkish
* - cp860 - Portuguese
* - cp861 - Iceland
* - cp862 - Hebrew
* - cp863 - Canada
* - cp864 - Arabic
* - cp865 - Nordic
* - cp866 - Cyrylic Russian (this is the one, used in IE "Cyrillic (DOS)" )
* - cp869 - Greek2
*
* - MAC (Apple)
* - x-mac-cyrillic
* - x-mac-greek
* - x-mac-icelandic
* - x-mac-ce
* - x-mac-roman
*
* - ISO (Unix/Linux)
* - iso-8859-1
* - iso-8859-2
* - iso-8859-3
* - iso-8859-4
* - iso-8859-5
* - iso-8859-6
* - iso-8859-7
* - iso-8859-8
* - iso-8859-9
* - iso-8859-10
* - iso-8859-11
* - iso-8859-12
* - iso-8859-13
* - iso-8859-14
* - iso-8859-15
* - iso-8859-16
*
* - MISCELLANEOUS
* - gsm0338 (ETSI GSM 03.38)
* - cp037
* - cp424
* - cp500
* - cp856
* - cp875
* - cp1006
* - cp1026
* - koi8-r (Cyrillic)
* - koi8-u (Cyrillic Ukrainian)
* - nextstep
* - us-ascii
* - us-ascii-quotes
*
* - DSP implementation for NeXT
* - stdenc
* - symbol
* - zdingbat
*
* - And specially for old Polish programs
* - mazovia
*
* -- Now, to the point... --
* Here are main variables.
*
* DEBUG_MODE
*
* You can set this value to:
* - -1 - No errors or comments
* - 0 - Only error messages, no comments
* - 1 - Error messages and comments
*
* Default value is 1, and during first steps with class it should be left as is.
*
* CONVERT_TABLES_DIR
*
* This is a place where you store all files with charset encodings. Filenames should have
* the same names as encodings. My advise is to keep existing names, because thay
* were taken from unicode.org (www.unicode.org), and after update to unicode 3.0 or 4.0
* the names of files will be the same, so if you want to save your time...uff, leave the
* names as thay are for future updates.
*
* The directory with edings files should be in a class location directory by default,
* but of course you can change it if you like.
*
* @package All about charset...
* @author Mikolaj Jedrzejak <mikolajj@op.pl>
* @copyright Copyright Mikolaj Jedrzejak (c) 2003-2004
* @version 1.0 2004-07-27 23:11
* @access public
*
* @link http://www.unicode.org Unicode Homepage
**/
class ConvertCharset {
var $RecognizedEncoding; //This value keeps information if string contains multibyte chars.
var $Entities; // This value keeps information if output should be with numeric entities.
/**
* CharsetChange::NumUnicodeEntity()
*
* Unicode encoding bytes, bits representation.
* Each b represents a bit that can be used to store character data.
* - bytes, bits, binary representation
* - 1, 7, 0bbbbbbb
* - 2, 11, 110bbbbb 10bbbbbb
* - 3, 16, 1110bbbb 10bbbbbb 10bbbbbb
* - 4, 21, 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
*
* This function is written in a "long" way, for everyone who woluld like to analize
* the process of unicode encoding and understand it. All other functions like HexToUtf
* will be written in a "shortest" way I can write tham :) it does'n mean thay are short
* of course. You can chech it in HexToUtf() (link below) - very similar function.
*
* IMPORTANT: Remember that $UnicodeString input CANNOT have single byte upper half
* extended ASCII codes, why? Because there is a posibility that this function will eat
* the following char thinking it's miltibyte unicode char.
*
* @param string $UnicodeString Input Unicode string (1 char can take more than 1 byte)
* @return string This is an input string olso with unicode chars, bus saved as entities
* @see HexToUtf()
**/
function UnicodeEntity ($UnicodeString)
{
$OutString = "";
$StringLenght = strlen ($UnicodeString);
for ($CharPosition = 0; $CharPosition < $StringLenght; $CharPosition++)
{
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
if ($AsciiChar < 128) //1 7 0bbbbbbb (127)
{
$OutString .= $Char;
}
else if ($AsciiChar >> 5 == 6) //2 11 110bbbbb 10bbbbbb (2047)
{
$FirstByte = ($AsciiChar & 31);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$SecondByte = ($AsciiChar & 63);
$AsciiChar = ($FirstByte * 64) + $SecondByte;
$Entity = sprintf ("&#%d;", $AsciiChar);
$OutString .= $Entity;
}
else if ($AsciiChar >> 4 == 14) //3 16 1110bbbb 10bbbbbb 10bbbbbb
{
$FirstByte = ($AsciiChar & 31);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$SecondByte = ($AsciiChar & 63);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$ThidrByte = ($AsciiChar & 63);
$AsciiChar = ((($FirstByte * 64) + $SecondByte) * 64) + $ThidrByte;
$Entity = sprintf ("&#%d;", $AsciiChar);
$OutString .= $Entity;
}
else if ($AsciiChar >> 3 == 30) //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
{
$FirstByte = ($AsciiChar & 31);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$SecondByte = ($AsciiChar & 63);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$ThidrByte = ($AsciiChar & 63);
$CharPosition++;
$Char = $UnicodeString [$CharPosition];
$AsciiChar = ord ($Char);
$FourthByte = ($AsciiChar & 63);
$AsciiChar = ((((($FirstByte * 64) + $SecondByte) * 64) + $ThidrByte) * 64) + $FourthByte;
$Entity = sprintf ("&#%d;", $AsciiChar);
$OutString .= $Entity;
}
}
return $OutString;
}
/**
* ConvertCharset::HexToUtf()
*
* This simple function gets unicode char up to 4 bytes and return it as a regular char.
* It is very similar to UnicodeEntity function (link below). There is one difference
* in returned format. This time it's a regular char(s), in most cases it will be one or two chars.
*
* @param string $UtfCharInHex Hexadecimal value of a unicode char.
* @return string Encoded hexadecimal value as a regular char.
* @see UnicodeEntity()
**/
function HexToUtf ($UtfCharInHex)
{
$OutputChar = "";
$UtfCharInDec = hexdec($UtfCharInHex);
if($UtfCharInDec<128) $OutputChar .= chr($UtfCharInDec);
else if($UtfCharInDec<2048)$OutputChar .= chr(($UtfCharInDec>>6)+192).chr(($UtfCharInDec&63)+128);
else if($UtfCharInDec<65536)$OutputChar .= chr(($UtfCharInDec>>12)+224).chr((($UtfCharInDec>>6)&63)+128).chr(($UtfCharInDec&63)+128);
else if($UtfCharInDec<2097152)$OutputChar .= chr($UtfCharInDec>>18+240).chr((($UtfCharInDec>>12)&63)+128).chr(($UtfCharInDec>>6)&63+128). chr($UtfCharInDec&63+128);
return $OutputChar;
}
/**
* CharsetChange::MakeConvertTable()
*
* This function creates table with two SBCS (Single Byte Character Set). Every conversion
* is through this table.
*
* - The file with encoding tables have to be save in "Format A" of unicode.org charset table format! This is usualy writen in a header of every charset file.
* - BOTH charsets MUST be SBCS
* - The files with encoding tables have to be complet (Non of chars can be missing, unles you are sure you are not going to use it)
*
* "Format A" encoding file, if you have to build it by yourself should aplly these rules:
* - you can comment everything with #
* - first column contains 1 byte chars in hex starting from 0x..
* - second column contains unicode equivalent in hex starting from 0x....
* - then every next column is optional, but in "Format A" it should contain unicode char name or/and your own comment
* - the columns can be splited by "spaces", "tabs", "," or any combination of these
* - below is an example
*
* <code>
* #
* # The entries are in ANSI X3.4 order.
* #
* 0x00 0x0000 # NULL end extra comment, if needed
* 0x01 0x0001 # START OF HEADING
* # Oh, one more thing, you can make comments inside of a rows if you like.
* 0x02 0x0002 # START OF TEXT
* 0x03 0x0003 # END OF TEXT
* next line, and so on...
* </code>
*
* You can get full tables with encodings from http://www.unicode.org
*
* @param string $FirstEncoding Name of first encoding and first encoding filename (thay have to be the same)
* @param string $SecondEncoding Name of second encoding and second encoding filename (thay have to be the same). Optional for building a joined table.
* @return array Table necessary to change one encoding to another.
**/
function MakeConvertTable ($FirstEncoding, $SecondEncoding = "")
{
$ConvertTable = array();
for($i = 0; $i < func_num_args(); $i++)
{
/**
* Because func_*** can't be used inside of another function call
* we have to save it as a separate value.
**/
$FileName = func_get_arg($i);
if (!is_file(CONVERT_TABLES_DIR . $FileName))
{
print $this->DebugOutput(0, 0, CONVERT_TABLES_DIR . $FileName); //Print an error message
exit;
}
$FileWithEncTabe = fopen(CONVERT_TABLES_DIR . $FileName, "r") or die(); //This die(); is just to make sure...
while(!feof($FileWithEncTabe))
{
/**
* We asume that line is not longer
* than 1024 which is the default value for fgets function
**/
if($OneLine=trim(fgets($FileWithEncTabe, 1024)))
{
/**
* We don't need all comment lines. I check only for "#" sign, because
* this is a way of making comments by unicode.org in thair encoding files
* and that's where the files are from :-)
**/
if (substr($OneLine, 0, 1) != "#")
{
/**
* Sometimes inside the charset file the hex walues are separated by
* "space" and sometimes by "tab", the below preg_split can also be used
* to split files where separator is a ",", "\r", "\n" and "\f"
**/
$HexValue = preg_split ("/[\s,]+/", $OneLine, 3); //We need only first 2 values
/**
* Sometimes char is UNDEFINED, or missing so we can't use it for convertion
**/
if (substr($HexValue[1], 0, 1) != "#")
{
$ArrayKey = strtoupper(str_replace(strtolower("0x"), "", $HexValue[1]));
$ArrayValue = strtoupper(str_replace(strtolower("0x"), "", $HexValue[0]));
$ConvertTable[func_get_arg($i)][$ArrayKey] = $ArrayValue;
}
} //if (substr($OneLine,...
} //if($OneLine=trim(f...
} //while(!feof($FirstFileWi...
} //for($i = 0; $i < func_...
/**
* The last thing is to check if by any reason both encoding tables are not the same.
* For example, it will happen when you save the encoding table file with a wrong name
* - of another charset.
**/
if ((func_num_args() > 1) && (count($ConvertTable[$FirstEncoding]) == count($ConvertTable[$SecondEncoding])) && (count(array_diff_assoc($ConvertTable[$FirstEncoding], $ConvertTable[$SecondEncoding])) == 0))
{
print $this->DebugOutput(1, 1, "$FirstEncoding, $SecondEncoding");
}
return $ConvertTable;
}
/**
* ConvertCharset::Convert()
*
* This is a basic function you are using. I hope that you can figure out this function syntax :-)
*
* @param string $StringToChange The string you want to change :)
* @param string $FromCharset Name of $StringToChange encoding, you have to know it.
* @param string $ToCharset Name of a charset you want to get for $StringToChange.
* @param boolean $TurnOnEntities Set to true or 1 if you want to use numeric entities insted of regular chars.
* @return string Converted string in brand new encoding :)
* @version 1.0 2004-07-27 01:09
**/
function Convert ($StringToChange, $FromCharset, $ToCharset, $TurnOnEntities = false)
{
/**
* Check are there all variables
**/
if ($StringToChange == "")
{
print $this->DebugOutput(0, 3, "\$StringToChange");
}
else if ($FromCharset == "")
{
print $this->DebugOutput(0, 3, "\$FromCharset");
}
else if ($ToCharset == "")
{
print $this->DebugOutput(0, 3, "\$ToCharset");
}
/**
* Now a few variables need to be set.
**/
$NewString = "";
$this->Entities = $TurnOnEntities;
/**
* For all people who like to use uppercase for charset encoding names :)
**/
$FromCharset = strtolower($FromCharset);
$ToCharset = strtolower($ToCharset);
/**
* Of course you can make a conversion from one charset to the same one :)
* but I feel obligate to let you know about it.
**/
if ($FromCharset == $ToCharset)
{
print $this->DebugOutput(1, 0, $FromCharset);
}
if (($FromCharset == $ToCharset) AND ($FromCharset == "utf-8"))
{
print $this->DebugOutput(0, 4, $FromCharset);
exit;
}
/**
* This divison was made to prevent errors during convertion to/from utf-8 with
* "entities" enabled, because we need to use proper destination(to)/source(from)
* encoding table to write proper entities.
*
* This is the first case. We are convertinf from 1byte chars...
**/
if ($FromCharset != "utf-8")
{
/**
* Now build table with both charsets for encoding change.
**/
if ($ToCharset != "utf-8")
{
$CharsetTable = $this->MakeConvertTable ($FromCharset, $ToCharset);
}
else
{
$CharsetTable = $this->MakeConvertTable ($FromCharset);
}
/**
* For each char in a string...
**/
for ($i = 0; $i < strlen($StringToChange); $i++)
{
$HexChar = "";
$UnicodeHexChar = "";
$HexChar = strtoupper(dechex(ord($StringToChange[$i])));
// This is fix from Mario Klingemann, it prevents
// droping chars below 16 because of missing leading 0 [zeros]
if (strlen($HexChar)==1) $HexChar = "0".$HexChar;
//end of fix by Mario Klingemann
// This is quick fix of 10 chars in gsm0338
// Thanks goes to Andrea Carpani who pointed on this problem
// and solve it ;)
if (($FromCharset == "gsm0338") && ($HexChar == '1B')) {
$i++;
$HexChar .= strtoupper(dechex(ord($StringToChange[$i])));
}
// end of workarround on 10 chars from gsm0338
if ($ToCharset != "utf-8")
{
if (in_array($HexChar, $CharsetTable[$FromCharset]))
{
$UnicodeHexChar = array_search($HexChar, $CharsetTable[$FromCharset]);
$UnicodeHexChars = explode("+",$UnicodeHexChar);
for($UnicodeHexCharElement = 0; $UnicodeHexCharElement < count($UnicodeHexChars); $UnicodeHexCharElement++)
{
if (array_key_exists($UnicodeHexChars[$UnicodeHexCharElement], $CharsetTable[$ToCharset]))
{
if ($this->Entities == true)
{
$NewString .= $this->UnicodeEntity($this->HexToUtf($UnicodeHexChars[$UnicodeHexCharElement]));
}
else
{
$NewString .= chr(hexdec($CharsetTable[$ToCharset][$UnicodeHexChars[$UnicodeHexCharElement]]));
}
}
else
{
print $this->DebugOutput(0, 1, $StringToChange[$i]);
}
} //for($UnicodeH...
}
else
{
print $this->DebugOutput(0, 2,$StringToChange[$i]);
}
}
else
{
if (in_array("$HexChar", $CharsetTable[$FromCharset]))
{
$UnicodeHexChar = array_search($HexChar, $CharsetTable[$FromCharset]);
/**
* Sometimes there are two or more utf-8 chars per one regular char.
* Extream, example is polish old Mazovia encoding, where one char contains
* two lettes 007a (z) and 0142 (l slash), we need to figure out how to
* solve this problem.
* The letters are merge with "plus" sign, there can be more than two chars.
* In Mazowia we have 007A+0142, but sometimes it can look like this
* 0x007A+0x0142+0x2034 (that string means nothing, it just shows the possibility...)
**/
$UnicodeHexChars = explode("+",$UnicodeHexChar);
for($UnicodeHexCharElement = 0; $UnicodeHexCharElement < count($UnicodeHexChars); $UnicodeHexCharElement++)
{
if ($this->Entities == true)
{
$NewString .= $this->UnicodeEntity($this->HexToUtf($UnicodeHexChars[$UnicodeHexCharElement]));
}
else
{
$NewString .= $this->HexToUtf($UnicodeHexChars[$UnicodeHexCharElement]);
}
} // for
}
else
{
print $this->DebugOutput(0, 2, $StringToChange[$i]);
}
}
}
}
/**
* This is second case. We are encoding from multibyte char string.
**/
else if($FromCharset == "utf-8")
{
$HexChar = "";
$UnicodeHexChar = "";
$CharsetTable = $this->MakeConvertTable ($ToCharset);
foreach ($CharsetTable[$ToCharset] as $UnicodeHexChar => $HexChar)
{
if ($this->Entities == true) {
$EntitieOrChar = $this->UnicodeEntity($this->HexToUtf($UnicodeHexChar));
}
else
{
$EntitieOrChar = chr(hexdec($HexChar));
}
$StringToChange = str_replace($this->HexToUtf($UnicodeHexChar), $EntitieOrChar, $StringToChange);
}
$NewString = $StringToChange;
}
return $NewString;
}
/**
* ConvertCharset::DebugOutput()
*
* This function is not really necessary, the debug output could stay inside of
* source code but like this, it's easier to manage and translate.
* Besides I couldn't find good coment/debug class :-) Maybe I'll write one someday...
*
* All messages depend on DEBUG_MODE level, as I was writing before you can set this value to:
* - -1 - No errors or notces are shown
* - 0 - Only error messages are shown, no notices
* - 1 - Error messages and notices are shown
*
* @param int $Group Message groupe: error - 0, notice - 1
* @param int $Number Following message number
* @param mix $Value This walue is whatever you want, usualy it's some parameter value, for better message understanding.
* @return string String with a proper message.
**/
function DebugOutput ($Group, $Number, $Value = false)
{
//$Debug [$Group][$Number] = "Message, can by with $Value";
//$Group[0] - Errors
//$Group[1] - Notice
$Debug[0][0] = "Error, can NOT read file: " . $Value . "<br>";
$Debug[0][1] = "Error, can't find maching char \"". $Value ."\" in destination encoding table!" . "<br>";
$Debug[0][2] = "Error, can't find maching char \"". $Value ."\" in source encoding table!" . "<br>";
$Debug[0][3] = "Error, you did NOT set variable " . $Value . " in Convert() function." . "<br>";
$Debug[0][4] = "You can NOT convert string from " . $Value . " to " . $Value . "!" . "<BR>";
$Debug[1][0] = "Notice, you are trying to convert string from ". $Value ." to ". $Value .", don't you feel it's strange? ;-)" . "<br>";
$Debug[1][1] = "Notice, both charsets " . $Value . " are identical! Check encoding tables files." . "<br>";
$Debug[1][2] = "Notice, there is no unicode char in the string you are trying to convert." . "<br>";
if (DEBUG_MODE >= $Group)
{
return $Debug[$Group][$Number];
}
} // function DebugOutput
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/PHPMailerAutoload.php'
<?php
/**
* PHPMailer SPL autoloader.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer SPL autoloader.
* @param string $classname The name of the class to load
*/
function PHPMailerAutoload($classname)
{
//Can't use __DIR__ as it's only in PHP 5.3+
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
if (is_readable($filename)) {
require $filename;
}
}
if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
//SPL autoloading was introduced in PHP 5.1.2
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
spl_autoload_register('PHPMailerAutoload', true, true);
} else {
spl_autoload_register('PHPMailerAutoload');
}
} else {
/**
* Fall back to traditional autoload for old PHP versions
* @param string $classname The name of the class to load
*/
function __autoload($classname)
{
PHPMailerAutoload($classname);
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/VERSION'
5.2.26
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.bkpmnl.php'
<?php
class BackupMySQL extends mysqli {
protected $dossier;
protected $nom_fichier;
protected $gz_fichier;
public function __construct($options = array()) {
$default = array(
'host' => ini_get('mysqli.default_host'),
'username' => ini_get('mysqli.default_user'),
'passwd' => ini_get('mysqli.default_pw'),
'dbname' => '',
'port' => ini_get('mysqli.default_port'),
'socket' => ini_get('mysqli.default_socket'),
'dossier' => './',
'nbr_fichiers' => 5,
'nom_fichier' => 'backup_pmnl',
'prefixe' => 'ps_',
'racine' => 'pmnl',
'token' => false
);
$options = array_merge($default, $options);
extract($options);
@parent::__construct($host, $username, $passwd, $dbname, $port, $socket);
if ( $this->connect_error) {
$this->message('error','Erreur de connexion (' . $this->connect_errno . ') '. $this->connect_error);
return;
}
$this->token = $token;
if ( !($this->token)||$this->token=='') {
$this->message('error','Erreur sur accès au script de sauvegarde');
return;
}
$this->dossier = $dossier;
if ( !is_dir($this->dossier)) {
$this->message('error','Erreur de dossier "' . htmlspecialchars($this->dossier) . '"');
return;
}
$this->nom_fichier = $nom_fichier .'-'. date('Ymd-His') . '-' . $token . '.sql.gz';
$this->gz_fichier = @gzopen($this->dossier . $this->nom_fichier, 'w');
if ( !$this->gz_fichier) {
$this->message('error','Erreur de fichier "' . htmlspecialchars($this->nom_fichier) . '"');
return;
}
$this->prefixe = $prefixe;
$this->racine = $racine;
$this->purger_fichiers($nbr_fichiers);
if ( $this->sauvegarder())
$this->message('success',$this->nom_fichier);
}
protected function message($level,$message = ' ') {
$arr=array(
'status'=>$level,
'successmsg'=>$message
);
echo json_encode($arr, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
protected function insert_clean($string) {
$s1 = array( "\\" , "'" , "\r", "\n", );
$s2 = array( "\\\\" , "''" , '\r', '\n', );
return str_replace($s1, $s2, $string);
}
protected function sauvegarder() {
$sql = '--' ."\n";
$sql .= '-- '. $this->nom_fichier ."\n";
gzwrite($this->gz_fichier, $sql);
$result_tables = $this->query('SHOW TABLE STATUS WHERE name LIKE "' . $this->prefixe . $this->racine . '%"');
if ( $result_tables && $result_tables->num_rows) {
while($obj_table = $result_tables->fetch_object()) {
$sql = "\n\n";
$sql .= 'DROP TABLE IF EXISTS `'. $obj_table->{'Name'} .'`' .";\n";
$result_create = $this->query('SHOW CREATE TABLE `'. $obj_table->{'Name'} .'`');
if ( $result_create && $result_create->num_rows) {
$obj_create = $result_create->fetch_object();
$sql .= $obj_create->{'Create Table'} .";\n";
$result_create->free_result();
}
$result_insert = $this->query('SELECT * FROM `'. $obj_table->{'Name'} .'`');
if ( $result_insert && $result_insert->num_rows) {
$sql .= "\n";
while($obj_insert = $result_insert->fetch_object()) {
$virgule = false;
$sql .= 'INSERT INTO `'. $obj_table->{'Name'} .'` VALUES (';
foreach($obj_insert as $val) {
$sql .= ($virgule ? ',' : '');
if ( is_null($val)) {
$sql .= 'NULL';
} else {
$sql .= '\''. $this->insert_clean($val) . '\'';
}
$virgule = true;
}
$sql .= ')' .";\n";
}
$result_insert->free_result();
}
gzwrite($this->gz_fichier, $sql);
}
$result_tables->free_result();
}
if ( gzclose($this->gz_fichier))
return true;
}
protected function purger_fichiers($nbr_fichiers_max) {
$fichiers = array();
if ( $dossier = dir($this->dossier)) {
while(false !== ($fichier = $dossier->read())) {
if ( $fichier != '.' && $fichier != '..') {
if ( is_dir($this->dossier . $fichier)) {
continue;
} else {
if ( preg_match('/\.gz$/i', $fichier)) {
$fichiers[] = $fichier;
}
}
}
}
$dossier->close();
}
$nbr_fichiers_total = count($fichiers);
if ( $nbr_fichiers_total >= $nbr_fichiers_max) {
rsort($fichiers);
for($i = $nbr_fichiers_max; $i < $nbr_fichiers_total; $i++) {
unlink($this->dossier . $fichiers[$i]);
}
}
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.browser.php'
<?php
/**
* File: Browser.php
* Author: Chris Schuld (http://chrisschuld.com/)
* Last Modified: July 22nd, 2016
* @version 2.0
* @package PegasusPHP
*
* Copyright (C) 2008-2010 Chris Schuld (chris@chrisschuld.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at:
* http://www.gnu.org/copyleft/gpl.html
*
*
* Typical Usage:
*
* $browser = new Browser();
* if( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) {
* echo 'You have FireFox version 2 or greater';
* }
*
* User Agents Sampled from: http://www.useragentstring.com/
*
* This implementation is based on the original work from Gary White
* http://apptools.com/phptools/browser/
*
*/
class Browser
{
private $_agent = '';
private $_browser_name = '';
private $_version = '';
private $_platform = '';
private $_os = '';
private $_is_aol = false;
private $_is_mobile = false;
private $_is_tablet = false;
private $_is_robot = false;
private $_is_facebook = false;
private $_aol_version = '';
const BROWSER_UNKNOWN = 'unknown';
const VERSION_UNKNOWN = 'unknown';
const BROWSER_OPERA = 'Opera'; // http://www.opera.com/
const BROWSER_OPERA_MINI = 'Opera Mini'; // http://www.opera.com/mini/
const BROWSER_WEBTV = 'WebTV'; // http://www.webtv.net/pc/
const BROWSER_EDGE = 'Edge'; // https://www.microsoft.com/edge
const BROWSER_IE = 'Internet Explorer'; // http://www.microsoft.com/ie/
const BROWSER_POCKET_IE = 'Pocket Internet Explorer'; // http://en.wikipedia.org/wiki/Internet_Explorer_Mobile
const BROWSER_KONQUEROR = 'Konqueror'; // http://www.konqueror.org/
const BROWSER_ICAB = 'iCab'; // http://www.icab.de/
const BROWSER_OMNIWEB = 'OmniWeb'; // http://www.omnigroup.com/applications/omniweb/
const BROWSER_FIREBIRD = 'Firebird'; // http://www.ibphoenix.com/
const BROWSER_FIREFOX = 'Firefox'; // http://www.mozilla.com/en-US/firefox/firefox.html
const BROWSER_ICEWEASEL = 'Iceweasel'; // http://www.geticeweasel.org/
const BROWSER_SHIRETOKO = 'Shiretoko'; // http://wiki.mozilla.org/Projects/shiretoko
const BROWSER_MOZILLA = 'Mozilla'; // http://www.mozilla.com/en-US/
const BROWSER_AMAYA = 'Amaya'; // http://www.w3.org/Amaya/
const BROWSER_LYNX = 'Lynx'; // http://en.wikipedia.org/wiki/Lynx
const BROWSER_SAFARI = 'Safari'; // http://apple.com
const BROWSER_IPHONE = 'iPhone'; // http://apple.com
const BROWSER_IPOD = 'iPod'; // http://apple.com
const BROWSER_IPAD = 'iPad'; // http://apple.com
const BROWSER_CHROME = 'Chrome'; // http://www.google.com/chrome
const BROWSER_ANDROID = 'Android'; // http://www.android.com/
const BROWSER_GOOGLEBOT = 'GoogleBot'; // http://en.wikipedia.org/wiki/Googlebot
const BROWSER_YANDEXBOT = 'YandexBot'; // http://yandex.com/bots
const BROWSER_YANDEXIMAGERESIZER_BOT = 'YandexImageResizer'; // http://yandex.com/bots
const BROWSER_YANDEXIMAGES_BOT = 'YandexImages'; // http://yandex.com/bots
const BROWSER_YANDEXVIDEO_BOT = 'YandexVideo'; // http://yandex.com/bots
const BROWSER_YANDEXMEDIA_BOT = 'YandexMedia'; // http://yandex.com/bots
const BROWSER_YANDEXBLOGS_BOT = 'YandexBlogs'; // http://yandex.com/bots
const BROWSER_YANDEXFAVICONS_BOT = 'YandexFavicons'; // http://yandex.com/bots
const BROWSER_YANDEXWEBMASTER_BOT = 'YandexWebmaster'; // http://yandex.com/bots
const BROWSER_YANDEXDIRECT_BOT = 'YandexDirect'; // http://yandex.com/bots
const BROWSER_YANDEXMETRIKA_BOT = 'YandexMetrika'; // http://yandex.com/bots
const BROWSER_YANDEXNEWS_BOT = 'YandexNews'; // http://yandex.com/bots
const BROWSER_YANDEXCATALOG_BOT = 'YandexCatalog'; // http://yandex.com/bots
const BROWSER_SLURP = 'Yahoo! Slurp'; // http://en.wikipedia.org/wiki/Yahoo!_Slurp
const BROWSER_W3CVALIDATOR = 'W3C Validator'; // http://validator.w3.org/
const BROWSER_BLACKBERRY = 'BlackBerry'; // http://www.blackberry.com/
const BROWSER_ICECAT = 'IceCat'; // http://en.wikipedia.org/wiki/GNU_IceCat
const BROWSER_NOKIA_S60 = 'Nokia S60 OSS Browser'; // http://en.wikipedia.org/wiki/Web_Browser_for_S60
const BROWSER_NOKIA = 'Nokia Browser'; // * all other WAP-based browsers on the Nokia Platform
const BROWSER_MSN = 'MSN Browser'; // http://explorer.msn.com/
const BROWSER_MSNBOT = 'MSN Bot'; // http://search.msn.com/msnbot.htm
const BROWSER_BINGBOT = 'Bing Bot'; // http://en.wikipedia.org/wiki/Bingbot
const BROWSER_VIVALDI = 'Vivalidi'; // https://vivaldi.com/
const BROWSER_YANDEX = 'Yandex'; // https://browser.yandex.ua/
const BROWSER_NETSCAPE_NAVIGATOR = 'Netscape Navigator'; // http://browser.netscape.com/ (DEPRECATED)
const BROWSER_GALEON = 'Galeon'; // http://galeon.sourceforge.net/ (DEPRECATED)
const BROWSER_NETPOSITIVE = 'NetPositive'; // http://en.wikipedia.org/wiki/NetPositive (DEPRECATED)
const BROWSER_PHOENIX = 'Phoenix'; // http://en.wikipedia.org/wiki/History_of_Mozilla_Firefox (DEPRECATED)
const BROWSER_PLAYSTATION = "PlayStation";
const BROWSER_SAMSUNG = "SamsungBrowser";
const BROWSER_SILK = "Silk";
const BROWSER_I_FRAME = "Iframely";
const BROWSER_COCOA = "CocoaRestClient";
const PLATFORM_UNKNOWN = 'unknown';
const PLATFORM_WINDOWS = 'Windows';
const PLATFORM_WINDOWS_CE = 'Windows CE';
const PLATFORM_APPLE = 'Apple';
const PLATFORM_LINUX = 'Linux';
const PLATFORM_OS2 = 'OS/2';
const PLATFORM_BEOS = 'BeOS';
const PLATFORM_IPHONE = 'iPhone';
const PLATFORM_IPOD = 'iPod';
const PLATFORM_IPAD = 'iPad';
const PLATFORM_BLACKBERRY = 'BlackBerry';
const PLATFORM_NOKIA = 'Nokia';
const PLATFORM_FREEBSD = 'FreeBSD';
const PLATFORM_OPENBSD = 'OpenBSD';
const PLATFORM_NETBSD = 'NetBSD';
const PLATFORM_SUNOS = 'SunOS';
const PLATFORM_OPENSOLARIS = 'OpenSolaris';
const PLATFORM_ANDROID = 'Android';
const PLATFORM_PLAYSTATION = "Sony PlayStation";
const PLATFORM_ROKU = "Roku";
const PLATFORM_APPLE_TV = "Apple TV";
const PLATFORM_TERMINAL = "Terminal";
const PLATFORM_FIRE_OS = "Fire OS";
const PLATFORM_SMART_TV = "SMART-TV";
const PLATFORM_CHROME_OS = "Chrome OS";
const PLATFORM_JAVA_ANDROID = "Java/Android";
const PLATFORM_POSTMAN = "Postman";
const PLATFORM_I_FRAME = "Iframely";
const OPERATING_SYSTEM_UNKNOWN = 'unknown';
/**
* Class constructor
*/
public function __construct($userAgent = "")
{
$this->reset();
if ($userAgent != "") {
$this->setUserAgent($userAgent);
} else {
$this->determine();
}
}
/**
* Reset all properties
*/
public function reset()
{
$this->_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
$this->_browser_name = self::BROWSER_UNKNOWN;
$this->_version = self::VERSION_UNKNOWN;
$this->_platform = self::PLATFORM_UNKNOWN;
$this->_os = self::OPERATING_SYSTEM_UNKNOWN;
$this->_is_aol = false;
$this->_is_mobile = false;
$this->_is_tablet = false;
$this->_is_robot = false;
$this->_is_facebook = false;
$this->_aol_version = self::VERSION_UNKNOWN;
}
/**
* Check to see if the specific browser is valid
* @param string $browserName
* @return bool True if the browser is the specified browser
*/
function isBrowser($browserName)
{
return (0 == strcasecmp($this->_browser_name, trim($browserName)));
}
/**
* The name of the browser. All return types are from the class contants
* @return string Name of the browser
*/
public function getBrowser()
{
return $this->_browser_name;
}
/**
* Set the name of the browser
* @param $browser string The name of the Browser
*/
public function setBrowser($browser)
{
$this->_browser_name = $browser;
}
/**
* The name of the platform. All return types are from the class contants
* @return string Name of the browser
*/
public function getPlatform()
{
return $this->_platform;
}
/**
* Set the name of the platform
* @param string $platform The name of the Platform
*/
public function setPlatform($platform)
{
$this->_platform = $platform;
}
/**
* The version of the browser.
* @return string Version of the browser (will only contain alpha-numeric characters and a period)
*/
public function getVersion()
{
return $this->_version;
}
/**
* Set the version of the browser
* @param string $version The version of the Browser
*/
public function setVersion($version)
{
$this->_version = preg_replace('/[^0-9,.,a-z,A-Z-]/', '', $version);
}
/**
* The version of AOL.
* @return string Version of AOL (will only contain alpha-numeric characters and a period)
*/
public function getAolVersion()
{
return $this->_aol_version;
}
/**
* Set the version of AOL
* @param string $version The version of AOL
*/
public function setAolVersion($version)
{
$this->_aol_version = preg_replace('/[^0-9,.,a-z,A-Z]/', '', $version);
}
/**
* Is the browser from AOL?
* @return boolean True if the browser is from AOL otherwise false
*/
public function isAol()
{
return $this->_is_aol;
}
/**
* Is the browser from a mobile device?
* @return boolean True if the browser is from a mobile device otherwise false
*/
public function isMobile()
{
return $this->_is_mobile;
}
/**
* Is the browser from a tablet device?
* @return boolean True if the browser is from a tablet device otherwise false
*/
public function isTablet()
{
return $this->_is_tablet;
}
/**
* Is the browser from a robot (ex Slurp,GoogleBot)?
* @return boolean True if the browser is from a robot otherwise false
*/
public function isRobot()
{
return $this->_is_robot;
}
/**
* Is the browser from facebook?
* @return boolean True if the browser is from facebook otherwise false
*/
public function isFacebook()
{
return $this->_is_facebook;
}
/**
* Set the browser to be from AOL
* @param $isAol
*/
public function setAol($isAol)
{
$this->_is_aol = $isAol;
}
/**
* Set the Browser to be mobile
* @param boolean $value is the browser a mobile browser or not
*/
protected function setMobile($value = true)
{
$this->_is_mobile = $value;
}
/**
* Set the Browser to be tablet
* @param boolean $value is the browser a tablet browser or not
*/
protected function setTablet($value = true)
{
$this->_is_tablet = $value;
}
/**
* Set the Browser to be a robot
* @param boolean $value is the browser a robot or not
*/
protected function setRobot($value = true)
{
$this->_is_robot = $value;
}
/**
* Set the Browser to be a Facebook request
* @param boolean $value is the browser a robot or not
*/
protected function setFacebook($value = true)
{
$this->_is_facebook = $value;
}
/**
* Get the user agent value in use to determine the browser
* @return string The user agent from the HTTP header
*/
public function getUserAgent()
{
return $this->_agent;
}
/**
* Set the user agent value (the construction will use the HTTP header value - this will overwrite it)
* @param string $agent_string The value for the User Agent
*/
public function setUserAgent($agent_string)
{
$this->reset();
$this->_agent = $agent_string;
$this->determine();
}
/**
* Used to determine if the browser is actually "chromeframe"
* @since 1.7
* @return boolean True if the browser is using chromeframe
*/
public function isChromeFrame()
{
return (strpos($this->_agent, "chromeframe") !== false);
}
/**
* Returns a formatted string with a summary of the details of the browser.
* @return string formatted string with a summary of the browser
*/
public function __toString()
{
return "<strong>Browser Name:</strong> {$this->getBrowser()}<br/>\n" .
"<strong>Browser Version:</strong> {$this->getVersion()}<br/>\n" .
"<strong>Browser User Agent String:</strong> {$this->getUserAgent()}<br/>\n" .
"<strong>Platform:</strong> {$this->getPlatform()}<br/>";
}
/**
* Protected routine to calculate and determine what the browser is in use (including platform)
*/
protected function determine()
{
$this->checkPlatform();
$this->checkBrowsers();
$this->checkForAol();
}
/**
* Protected routine to determine the browser type
* @return boolean True if the browser was detected otherwise false
*/
protected function checkBrowsers()
{
return (
// well-known, well-used
// Special Notes:
// (1) Opera must be checked before FireFox due to the odd
// user agents used in some older versions of Opera
// (2) WebTV is strapped onto Internet Explorer so we must
// check for WebTV before IE
// (3) (deprecated) Galeon is based on Firefox and needs to be
// tested before Firefox is tested
// (4) OmniWeb is based on Safari so OmniWeb check must occur
// before Safari
// (5) Netscape 9+ is based on Firefox so Netscape checks
// before FireFox are necessary
// (6) Vivalid is UA contains both Firefox and Chrome so Vivalid checks
// before Firefox and Chrome
$this->checkBrowserWebTv() ||
$this->checkBrowserEdge() ||
$this->checkBrowserInternetExplorer() ||
$this->checkBrowserOpera() ||
$this->checkBrowserGaleon() ||
$this->checkBrowserNetscapeNavigator9Plus() ||
$this->checkBrowserVivaldi() ||
$this->checkBrowserYandex() ||
$this->checkBrowserFirefox() ||
$this->checkBrowserChrome() ||
$this->checkBrowserOmniWeb() ||
// common mobile
$this->checkBrowserAndroid() ||
$this->checkBrowseriPad() ||
$this->checkBrowseriPod() ||
$this->checkBrowseriPhone() ||
$this->checkBrowserBlackBerry() ||
$this->checkBrowserNokia() ||
// common bots
$this->checkBrowserGoogleBot() ||
$this->checkBrowserMSNBot() ||
$this->checkBrowserBingBot() ||
$this->checkBrowserSlurp() ||
// Yandex bots
$this->checkBrowserYandexBot() ||
$this->checkBrowserYandexImageResizerBot() ||
$this->checkBrowserYandexBlogsBot() ||
$this->checkBrowserYandexCatalogBot() ||
$this->checkBrowserYandexDirectBot() ||
$this->checkBrowserYandexFaviconsBot() ||
$this->checkBrowserYandexImagesBot() ||
$this->checkBrowserYandexMediaBot() ||
$this->checkBrowserYandexMetrikaBot() ||
$this->checkBrowserYandexNewsBot() ||
$this->checkBrowserYandexVideoBot() ||
$this->checkBrowserYandexWebmasterBot() ||
// check for facebook external hit when loading URL
$this->checkFacebookExternalHit() ||
// WebKit base check (post mobile and others)
$this->checkBrowserSamsung() ||
$this->checkBrowserSilk() ||
$this->checkBrowserSafari() ||
// everyone else
$this->checkBrowserNetPositive() ||
$this->checkBrowserFirebird() ||
$this->checkBrowserKonqueror() ||
$this->checkBrowserIcab() ||
$this->checkBrowserPhoenix() ||
$this->checkBrowserAmaya() ||
$this->checkBrowserLynx() ||
$this->checkBrowserShiretoko() ||
$this->checkBrowserIceCat() ||
$this->checkBrowserIceweasel() ||
$this->checkBrowserW3CValidator() ||
$this->checkBrowserPlayStation() ||
$this->checkBrowserIframely() ||
$this->checkBrowserCocoa() ||
$this->checkBrowserMozilla() /* Mozilla is such an open standard that you must check it last */
);
}
/**
* Determine if the user is using a BlackBerry (last updated 1.7)
* @return boolean True if the browser is the BlackBerry browser otherwise false
*/
protected function checkBrowserBlackBerry()
{
if (stripos($this->_agent, 'blackberry') !== false) {
$aresult = explode("/", stristr($this->_agent, "BlackBerry"));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->_browser_name = self::BROWSER_BLACKBERRY;
$this->setMobile(true);
return true;
}
}
return false;
}
/**
* Determine if the user is using an AOL User Agent (last updated 1.7)
* @return boolean True if the browser is from AOL otherwise false
*/
protected function checkForAol()
{
$this->setAol(false);
$this->setAolVersion(self::VERSION_UNKNOWN);
if (stripos($this->_agent, 'aol') !== false) {
$aversion = explode(' ', stristr($this->_agent, 'AOL'));
if (isset($aversion[1])) {
$this->setAol(true);
$this->setAolVersion(preg_replace('/[^0-9\.a-z]/i', '', $aversion[1]));
return true;
}
}
return false;
}
/**
* Determine if the browser is the GoogleBot or not (last updated 1.7)
* @return boolean True if the browser is the GoogletBot otherwise false
*/
protected function checkBrowserGoogleBot()
{
if (stripos($this->_agent, 'googlebot') !== false) {
$aresult = explode('/', stristr($this->_agent, 'googlebot'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_GOOGLEBOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexBot or not
* @return boolean True if the browser is the YandexBot otherwise false
*/
protected function checkBrowserYandexBot()
{
if (stripos($this->_agent, 'YandexBot') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexBot'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXBOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexImageResizer or not
* @return boolean True if the browser is the YandexImageResizer otherwise false
*/
protected function checkBrowserYandexImageResizerBot()
{
if (stripos($this->_agent, 'YandexImageResizer') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexImageResizer'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXIMAGERESIZER_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexCatalog or not
* @return boolean True if the browser is the YandexCatalog otherwise false
*/
protected function checkBrowserYandexCatalogBot()
{
if (stripos($this->_agent, 'YandexCatalog') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexCatalog'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXCATALOG_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexNews or not
* @return boolean True if the browser is the YandexNews otherwise false
*/
protected function checkBrowserYandexNewsBot()
{
if (stripos($this->_agent, 'YandexNews') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexNews'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXNEWS_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexMetrika or not
* @return boolean True if the browser is the YandexMetrika otherwise false
*/
protected function checkBrowserYandexMetrikaBot()
{
if (stripos($this->_agent, 'YandexMetrika') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexMetrika'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXMETRIKA_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexDirect or not
* @return boolean True if the browser is the YandexDirect otherwise false
*/
protected function checkBrowserYandexDirectBot()
{
if (stripos($this->_agent, 'YandexDirect') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexDirect'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXDIRECT_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexWebmaster or not
* @return boolean True if the browser is the YandexWebmaster otherwise false
*/
protected function checkBrowserYandexWebmasterBot()
{
if (stripos($this->_agent, 'YandexWebmaster') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexWebmaster'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXWEBMASTER_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexFavicons or not
* @return boolean True if the browser is the YandexFavicons otherwise false
*/
protected function checkBrowserYandexFaviconsBot()
{
if (stripos($this->_agent, 'YandexFavicons') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexFavicons'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXFAVICONS_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexBlogs or not
* @return boolean True if the browser is the YandexBlogs otherwise false
*/
protected function checkBrowserYandexBlogsBot()
{
if (stripos($this->_agent, 'YandexBlogs') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexBlogs'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXBLOGS_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexMedia or not
* @return boolean True if the browser is the YandexMedia otherwise false
*/
protected function checkBrowserYandexMediaBot()
{
if (stripos($this->_agent, 'YandexMedia') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexMedia'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXMEDIA_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexVideo or not
* @return boolean True if the browser is the YandexVideo otherwise false
*/
protected function checkBrowserYandexVideoBot()
{
if (stripos($this->_agent, 'YandexVideo') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexVideo'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXVIDEO_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the YandexImages or not
* @return boolean True if the browser is the YandexImages otherwise false
*/
protected function checkBrowserYandexImagesBot()
{
if (stripos($this->_agent, 'YandexImages') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YandexImages'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(';', '', $aversion[0]));
$this->_browser_name = self::BROWSER_YANDEXIMAGES_BOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the MSNBot or not (last updated 1.9)
* @return boolean True if the browser is the MSNBot otherwise false
*/
protected function checkBrowserMSNBot()
{
if (stripos($this->_agent, "msnbot") !== false) {
$aresult = explode("/", stristr($this->_agent, "msnbot"));
if (isset($aresult[1])) {
$aversion = explode(" ", $aresult[1]);
$this->setVersion(str_replace(";", "", $aversion[0]));
$this->_browser_name = self::BROWSER_MSNBOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the BingBot or not (last updated 1.9)
* @return boolean True if the browser is the BingBot otherwise false
*/
protected function checkBrowserBingBot()
{
if (stripos($this->_agent, "bingbot") !== false) {
$aresult = explode("/", stristr($this->_agent, "bingbot"));
if (isset($aresult[1])) {
$aversion = explode(" ", $aresult[1]);
$this->setVersion(str_replace(";", "", $aversion[0]));
$this->_browser_name = self::BROWSER_BINGBOT;
$this->setRobot(true);
return true;
}
}
return false;
}
/**
* Determine if the browser is the W3C Validator or not (last updated 1.7)
* @return boolean True if the browser is the W3C Validator otherwise false
*/
protected function checkBrowserW3CValidator()
{
if (stripos($this->_agent, 'W3C-checklink') !== false) {
$aresult = explode('/', stristr($this->_agent, 'W3C-checklink'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->_browser_name = self::BROWSER_W3CVALIDATOR;
return true;
}
} else if (stripos($this->_agent, 'W3C_Validator') !== false) {
// Some of the Validator versions do not delineate w/ a slash - add it back in
$ua = str_replace("W3C_Validator ", "W3C_Validator/", $this->_agent);
$aresult = explode('/', stristr($ua, 'W3C_Validator'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->_browser_name = self::BROWSER_W3CVALIDATOR;
return true;
}
} else if (stripos($this->_agent, 'W3C-mobileOK') !== false) {
$this->_browser_name = self::BROWSER_W3CVALIDATOR;
$this->setMobile(true);
return true;
}
return false;
}
/**
* Determine if the browser is the Yahoo! Slurp Robot or not (last updated 1.7)
* @return boolean True if the browser is the Yahoo! Slurp Robot otherwise false
*/
protected function checkBrowserSlurp()
{
if (stripos($this->_agent, 'slurp') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Slurp'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->_browser_name = self::BROWSER_SLURP;
$this->setRobot(true);
$this->setMobile(false);
return true;
}
}
return false;
}
/**
* Determine if the browser is Edge or not
* @return boolean True if the browser is Edge otherwise false
*/
protected function checkBrowserEdge()
{
if (stripos($this->_agent, 'Edge/') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Edge'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_EDGE);
if (stripos($this->_agent, 'Windows Phone') !== false || stripos($this->_agent, 'Android') !== false) {
$this->setMobile(true);
}
return true;
}
}
return false;
}
/**
* Determine if the browser is Internet Explorer or not (last updated 1.7)
* @return boolean True if the browser is Internet Explorer otherwise false
*/
protected function checkBrowserInternetExplorer()
{
// Test for IE11
if (stripos($this->_agent, 'Trident/7.0; rv:11.0') !== false) {
$this->setBrowser(self::BROWSER_IE);
$this->setVersion('11.0');
return true;
} // Test for v1 - v1.5 IE
else if (stripos($this->_agent, 'microsoft internet explorer') !== false) {
$this->setBrowser(self::BROWSER_IE);
$this->setVersion('1.0');
$aresult = stristr($this->_agent, '/');
if (preg_match('/308|425|426|474|0b1/i', $aresult)) {
$this->setVersion('1.5');
}
return true;
} // Test for versions > 1.5
else if (stripos($this->_agent, 'msie') !== false && stripos($this->_agent, 'opera') === false) {
// See if the browser is the odd MSN Explorer
if (stripos($this->_agent, 'msnb') !== false) {
$aresult = explode(' ', stristr(str_replace(';', '; ', $this->_agent), 'MSN'));
if (isset($aresult[1])) {
$this->setBrowser(self::BROWSER_MSN);
$this->setVersion(str_replace(array('(', ')', ';'), '', $aresult[1]));
return true;
}
}
$aresult = explode(' ', stristr(str_replace(';', '; ', $this->_agent), 'msie'));
if (isset($aresult[1])) {
$this->setBrowser(self::BROWSER_IE);
$this->setVersion(str_replace(array('(', ')', ';'), '', $aresult[1]));
if(preg_match('#trident/([0-9\.]+);#i', $this->_agent, $aresult)){
if($aresult[1] == '3.1'){
$this->setVersion('7.0');
}
else if($aresult[1] == '4.0'){
$this->setVersion('8.0');
}
else if($aresult[1] == '5.0'){
$this->setVersion('9.0');
}
else if($aresult[1] == '6.0'){
$this->setVersion('10.0');
}
else if($aresult[1] == '7.0'){
$this->setVersion('11.0');
}
else if($aresult[1] == '8.0'){
$this->setVersion('11.0');
}
}
if(stripos($this->_agent, 'IEMobile') !== false) {
$this->setBrowser(self::BROWSER_POCKET_IE);
$this->setMobile(true);
}
return true;
}
} // Test for versions > IE 10
else if (stripos($this->_agent, 'trident') !== false) {
$this->setBrowser(self::BROWSER_IE);
$result = explode('rv:', $this->_agent);
if (isset($result[1])) {
$this->setVersion(preg_replace('/[^0-9.]+/', '', $result[1]));
$this->_agent = str_replace(array("Mozilla", "Gecko"), "MSIE", $this->_agent);
}
} // Test for Pocket IE
else if (stripos($this->_agent, 'mspie') !== false || stripos($this->_agent, 'pocket') !== false) {
$aresult = explode(' ', stristr($this->_agent, 'mspie'));
if (isset($aresult[1])) {
$this->setPlatform(self::PLATFORM_WINDOWS_CE);
$this->setBrowser(self::BROWSER_POCKET_IE);
$this->setMobile(true);
if (stripos($this->_agent, 'mspie') !== false) {
$this->setVersion($aresult[1]);
} else {
$aversion = explode('/', $this->_agent);
if (isset($aversion[1])) {
$this->setVersion($aversion[1]);
}
}
return true;
}
}
return false;
}
/**
* Determine if the browser is Opera or not (last updated 1.7)
* @return boolean True if the browser is Opera otherwise false
*/
protected function checkBrowserOpera()
{
if (stripos($this->_agent, 'opera mini') !== false) {
$resultant = stristr($this->_agent, 'opera mini');
if (preg_match('/\//', $resultant)) {
$aresult = explode('/', $resultant);
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
}
} else {
$aversion = explode(' ', stristr($resultant, 'opera mini'));
if (isset($aversion[1])) {
$this->setVersion($aversion[1]);
}
}
$this->_browser_name = self::BROWSER_OPERA_MINI;
$this->setMobile(true);
return true;
} else if (stripos($this->_agent, 'opera') !== false) {
$resultant = stristr($this->_agent, 'opera');
if (preg_match('/Version\/(1*.*)$/', $resultant, $matches)) {
$this->setVersion($matches[1]);
} else if (preg_match('/\//', $resultant)) {
$aresult = explode('/', str_replace("(", " ", $resultant));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
}
} else {
$aversion = explode(' ', stristr($resultant, 'opera'));
$this->setVersion(isset($aversion[1]) ? $aversion[1] : "");
}
if (stripos($this->_agent, 'Opera Mobi') !== false) {
$this->setMobile(true);
}
$this->_browser_name = self::BROWSER_OPERA;
return true;
} else if (stripos($this->_agent, 'OPR') !== false) {
$resultant = stristr($this->_agent, 'OPR');
if (preg_match('/\//', $resultant)) {
$aresult = explode('/', str_replace("(", " ", $resultant));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
}
}
if (stripos($this->_agent, 'Mobile') !== false) {
$this->setMobile(true);
}
$this->_browser_name = self::BROWSER_OPERA;
return true;
}
return false;
}
/**
* Determine if the browser is Chrome or not (last updated 1.7)
* @return boolean True if the browser is Chrome otherwise false
*/
protected function checkBrowserChrome()
{
if (stripos($this->_agent, 'Chrome') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Chrome'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_CHROME);
//Chrome on Android
if (stripos($this->_agent, 'Android') !== false) {
if (stripos($this->_agent, 'Mobile') !== false) {
$this->setMobile(true);
} else {
$this->setTablet(true);
}
}
return true;
}
}
return false;
}
/**
* Determine if the browser is WebTv or not (last updated 1.7)
* @return boolean True if the browser is WebTv otherwise false
*/
protected function checkBrowserWebTv()
{
if (stripos($this->_agent, 'webtv') !== false) {
$aresult = explode('/', stristr($this->_agent, 'webtv'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_WEBTV);
return true;
}
}
return false;
}
/**
* Determine if the browser is NetPositive or not (last updated 1.7)
* @return boolean True if the browser is NetPositive otherwise false
*/
protected function checkBrowserNetPositive()
{
if (stripos($this->_agent, 'NetPositive') !== false) {
$aresult = explode('/', stristr($this->_agent, 'NetPositive'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion(str_replace(array('(', ')', ';'), '', $aversion[0]));
$this->setBrowser(self::BROWSER_NETPOSITIVE);
return true;
}
}
return false;
}
/**
* Determine if the browser is Galeon or not (last updated 1.7)
* @return boolean True if the browser is Galeon otherwise false
*/
protected function checkBrowserGaleon()
{
if (stripos($this->_agent, 'galeon') !== false) {
$aresult = explode(' ', stristr($this->_agent, 'galeon'));
$aversion = explode('/', $aresult[0]);
if (isset($aversion[1])) {
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_GALEON);
return true;
}
}
return false;
}
/**
* Determine if the browser is Konqueror or not (last updated 1.7)
* @return boolean True if the browser is Konqueror otherwise false
*/
protected function checkBrowserKonqueror()
{
if (stripos($this->_agent, 'Konqueror') !== false) {
$aresult = explode(' ', stristr($this->_agent, 'Konqueror'));
$aversion = explode('/', $aresult[0]);
if (isset($aversion[1])) {
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_KONQUEROR);
return true;
}
}
return false;
}
/**
* Determine if the browser is iCab or not (last updated 1.7)
* @return boolean True if the browser is iCab otherwise false
*/
protected function checkBrowserIcab()
{
if (stripos($this->_agent, 'icab') !== false) {
$aversion = explode(' ', stristr(str_replace('/', ' ', $this->_agent), 'icab'));
if (isset($aversion[1])) {
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_ICAB);
return true;
}
}
return false;
}
/**
* Determine if the browser is OmniWeb or not (last updated 1.7)
* @return boolean True if the browser is OmniWeb otherwise false
*/
protected function checkBrowserOmniWeb()
{
if (stripos($this->_agent, 'omniweb') !== false) {
$aresult = explode('/', stristr($this->_agent, 'omniweb'));
$aversion = explode(' ', isset($aresult[1]) ? $aresult[1] : "");
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_OMNIWEB);
return true;
}
return false;
}
/**
* Determine if the browser is Phoenix or not (last updated 1.7)
* @return boolean True if the browser is Phoenix otherwise false
*/
protected function checkBrowserPhoenix()
{
if (stripos($this->_agent, 'Phoenix') !== false) {
$aversion = explode('/', stristr($this->_agent, 'Phoenix'));
if (isset($aversion[1])) {
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_PHOENIX);
return true;
}
}
return false;
}
/**
* Determine if the browser is Firebird or not (last updated 1.7)
* @return boolean True if the browser is Firebird otherwise false
*/
protected function checkBrowserFirebird()
{
if (stripos($this->_agent, 'Firebird') !== false) {
$aversion = explode('/', stristr($this->_agent, 'Firebird'));
if (isset($aversion[1])) {
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_FIREBIRD);
return true;
}
}
return false;
}
/**
* Determine if the browser is Netscape Navigator 9+ or not (last updated 1.7)
* NOTE: (http://browser.netscape.com/ - Official support ended on March 1st, 2008)
* @return boolean True if the browser is Netscape Navigator 9+ otherwise false
*/
protected function checkBrowserNetscapeNavigator9Plus()
{
if (stripos($this->_agent, 'Firefox') !== false && preg_match('/Navigator\/([^ ]*)/i', $this->_agent, $matches)) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
return true;
} else if (stripos($this->_agent, 'Firefox') === false && preg_match('/Netscape6?\/([^ ]*)/i', $this->_agent, $matches)) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
return true;
}
return false;
}
/**
* Determine if the browser is Shiretoko or not (https://wiki.mozilla.org/Projects/shiretoko) (last updated 1.7)
* @return boolean True if the browser is Shiretoko otherwise false
*/
protected function checkBrowserShiretoko()
{
if (stripos($this->_agent, 'Mozilla') !== false && preg_match('/Shiretoko\/([^ ]*)/i', $this->_agent, $matches)) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_SHIRETOKO);
return true;
}
return false;
}
/**
* Determine if the browser is Ice Cat or not (http://en.wikipedia.org/wiki/GNU_IceCat) (last updated 1.7)
* @return boolean True if the browser is Ice Cat otherwise false
*/
protected function checkBrowserIceCat()
{
if (stripos($this->_agent, 'Mozilla') !== false && preg_match('/IceCat\/([^ ]*)/i', $this->_agent, $matches)) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_ICECAT);
return true;
}
return false;
}
/**
* Determine if the browser is Nokia or not (last updated 1.7)
* @return boolean True if the browser is Nokia otherwise false
*/
protected function checkBrowserNokia()
{
if (preg_match("/Nokia([^\/]+)\/([^ SP]+)/i", $this->_agent, $matches)) {
$this->setVersion($matches[2]);
if (stripos($this->_agent, 'Series60') !== false || strpos($this->_agent, 'S60') !== false) {
$this->setBrowser(self::BROWSER_NOKIA_S60);
} else {
$this->setBrowser(self::BROWSER_NOKIA);
}
$this->setMobile(true);
return true;
}
return false;
}
/**
* Determine if the browser is Firefox or not (last updated 1.7)
* @return boolean True if the browser is Firefox otherwise false
*/
protected function checkBrowserFirefox()
{
if (stripos($this->_agent, 'safari') === false) {
if (preg_match("/Firefox[\/ \(]([^ ;\)]+)/i", $this->_agent, $matches)) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_FIREFOX);
//Firefox on Android
if (stripos($this->_agent, 'Android') !== false) {
if (stripos($this->_agent, 'Mobile') !== false) {
$this->setMobile(true);
} else {
$this->setTablet(true);
}
}
return true;
} else if (preg_match("/Firefox$/i", $this->_agent, $matches)) {
$this->setVersion("");
$this->setBrowser(self::BROWSER_FIREFOX);
return true;
}
}
return false;
}
/**
* Determine if the browser is Firefox or not (last updated 1.7)
* @return boolean True if the browser is Firefox otherwise false
*/
protected function checkBrowserIceweasel()
{
if (stripos($this->_agent, 'Iceweasel') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Iceweasel'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_ICEWEASEL);
return true;
}
}
return false;
}
/**
* Determine if the browser is Mozilla or not (last updated 1.7)
* @return boolean True if the browser is Mozilla otherwise false
*/
protected function checkBrowserMozilla()
{
if (stripos($this->_agent, 'mozilla') !== false && preg_match('/rv:[0-9].[0-9][a-b]?/i', $this->_agent) && stripos($this->_agent, 'netscape') === false) {
$aversion = explode(' ', stristr($this->_agent, 'rv:'));
preg_match('/rv:[0-9].[0-9][a-b]?/i', $this->_agent, $aversion);
$this->setVersion(str_replace('rv:', '', $aversion[0]));
$this->setBrowser(self::BROWSER_MOZILLA);
return true;
} else if (stripos($this->_agent, 'mozilla') !== false && preg_match('/rv:[0-9]\.[0-9]/i', $this->_agent) && stripos($this->_agent, 'netscape') === false) {
$aversion = explode('', stristr($this->_agent, 'rv:'));
$this->setVersion(str_replace('rv:', '', $aversion[0]));
$this->setBrowser(self::BROWSER_MOZILLA);
return true;
} else if (stripos($this->_agent, 'mozilla') !== false && preg_match('/mozilla\/([^ ]*)/i', $this->_agent, $matches) && stripos($this->_agent, 'netscape') === false) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_MOZILLA);
return true;
}
return false;
}
/**
* Determine if the browser is Lynx or not (last updated 1.7)
* @return boolean True if the browser is Lynx otherwise false
*/
protected function checkBrowserLynx()
{
if (stripos($this->_agent, 'lynx') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Lynx'));
$aversion = explode(' ', (isset($aresult[1]) ? $aresult[1] : ""));
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_LYNX);
return true;
}
return false;
}
/**
* Determine if the browser is Amaya or not (last updated 1.7)
* @return boolean True if the browser is Amaya otherwise false
*/
protected function checkBrowserAmaya()
{
if (stripos($this->_agent, 'amaya') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Amaya'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_AMAYA);
return true;
}
}
return false;
}
/**
* Determine if the browser is Safari or not (last updated 1.7)
* @return boolean True if the browser is Safari otherwise false
*/
protected function checkBrowserSafari()
{
if (stripos($this->_agent, 'Safari') !== false
&& stripos($this->_agent, 'iPhone') === false
&& stripos($this->_agent, 'iPod') === false
) {
$aresult = explode('/', stristr($this->_agent, 'Version'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
} else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setBrowser(self::BROWSER_SAFARI);
return true;
}
return false;
}
protected function checkBrowserSamsung()
{
if (stripos($this->_agent, 'SamsungBrowser') !== false) {
$aresult = explode('/', stristr($this->_agent, 'SamsungBrowser'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
} else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setBrowser(self::BROWSER_SAMSUNG);
return true;
}
return false;
}
protected function checkBrowserSilk()
{
if (stripos($this->_agent, 'Silk') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Silk'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
} else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setBrowser(self::BROWSER_SILK);
return true;
}
return false;
}
protected function checkBrowserIframely()
{
if (stripos($this->_agent, 'Iframely') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Iframely'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
} else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setBrowser(self::BROWSER_I_FRAME);
return true;
}
return false;
}
protected function checkBrowserCocoa()
{
if (stripos($this->_agent, 'CocoaRestClient') !== false) {
$aresult = explode('/', stristr($this->_agent, 'CocoaRestClient'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
} else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setBrowser(self::BROWSER_COCOA);
return true;
}
return false;
}
/**
* Detect if URL is loaded from FacebookExternalHit
* @return boolean True if it detects FacebookExternalHit otherwise false
*/
protected function checkFacebookExternalHit()
{
if (stristr($this->_agent, 'FacebookExternalHit')) {
$this->setRobot(true);
$this->setFacebook(true);
return true;
}
return false;
}
/**
* Detect if URL is being loaded from internal Facebook browser
* @return boolean True if it detects internal Facebook browser otherwise false
*/
protected function checkForFacebookIos()
{
if (stristr($this->_agent, 'FBIOS')) {
$this->setFacebook(true);
return true;
}
return false;
}
/**
* Detect Version for the Safari browser on iOS devices
* @return boolean True if it detects the version correctly otherwise false
*/
protected function getSafariVersionOnIos()
{
$aresult = explode('/', stristr($this->_agent, 'Version'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
return true;
}
return false;
}
/**
* Detect Version for the Chrome browser on iOS devices
* @return boolean True if it detects the version correctly otherwise false
*/
protected function getChromeVersionOnIos()
{
$aresult = explode('/', stristr($this->_agent, 'CriOS'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_CHROME);
return true;
}
return false;
}
/**
* Determine if the browser is iPhone or not (last updated 1.7)
* @return boolean True if the browser is iPhone otherwise false
*/
protected function checkBrowseriPhone()
{
if (stripos($this->_agent, 'iPhone') !== false) {
$this->setVersion(self::VERSION_UNKNOWN);
$this->setBrowser(self::BROWSER_IPHONE);
$this->getSafariVersionOnIos();
$this->getChromeVersionOnIos();
$this->checkForFacebookIos();
$this->setMobile(true);
return true;
}
return false;
}
/**
* Determine if the browser is iPad or not (last updated 1.7)
* @return boolean True if the browser is iPad otherwise false
*/
protected function checkBrowseriPad()
{
if (stripos($this->_agent, 'iPad') !== false) {
$this->setVersion(self::VERSION_UNKNOWN);
$this->setBrowser(self::BROWSER_IPAD);
$this->getSafariVersionOnIos();
$this->getChromeVersionOnIos();
$this->checkForFacebookIos();
$this->setTablet(true);
return true;
}
return false;
}
/**
* Determine if the browser is iPod or not (last updated 1.7)
* @return boolean True if the browser is iPod otherwise false
*/
protected function checkBrowseriPod()
{
if (stripos($this->_agent, 'iPod') !== false) {
$this->setVersion(self::VERSION_UNKNOWN);
$this->setBrowser(self::BROWSER_IPOD);
$this->getSafariVersionOnIos();
$this->getChromeVersionOnIos();
$this->checkForFacebookIos();
$this->setMobile(true);
return true;
}
return false;
}
/**
* Determine if the browser is Android or not (last updated 1.7)
* @return boolean True if the browser is Android otherwise false
*/
protected function checkBrowserAndroid()
{
if (stripos($this->_agent, 'Android') !== false) {
$aresult = explode(' ', stristr($this->_agent, 'Android'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
} else {
$this->setVersion(self::VERSION_UNKNOWN);
}
if (stripos($this->_agent, 'Mobile') !== false) {
$this->setMobile(true);
} else {
$this->setTablet(true);
}
$this->setBrowser(self::BROWSER_ANDROID);
return true;
}
return false;
}
/**
* Determine if the browser is Vivaldi
* @return boolean True if the browser is Vivaldi otherwise false
*/
protected function checkBrowserVivaldi()
{
if (stripos($this->_agent, 'Vivaldi') !== false) {
$aresult = explode('/', stristr($this->_agent, 'Vivaldi'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_VIVALDI);
return true;
}
}
return false;
}
/**
* Determine if the browser is Yandex
* @return boolean True if the browser is Yandex otherwise false
*/
protected function checkBrowserYandex()
{
if (stripos($this->_agent, 'YaBrowser') !== false) {
$aresult = explode('/', stristr($this->_agent, 'YaBrowser'));
if (isset($aresult[1])) {
$aversion = explode(' ', $aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_YANDEX);
if (stripos($this->_agent, 'iPad') !== false) {
$this->setTablet(true);
} elseif (stripos($this->_agent, 'Mobile') !== false) {
$this->setMobile(true);
} elseif (stripos($this->_agent, 'Android') !== false) {
$this->setTablet(true);
}
return true;
}
}
return false;
}
/**
* Determine if the browser is a PlayStation
* @return boolean True if the browser is PlayStation otherwise false
*/
protected function checkBrowserPlayStation()
{
if (stripos($this->_agent, 'PlayStation ') !== false) {
$aresult = explode(' ', stristr($this->_agent, 'PlayStation '));
$this->setBrowser(self::BROWSER_PLAYSTATION);
if (isset($aresult[0])) {
$aversion = explode(')', $aresult[2]);
$this->setVersion($aversion[0]);
if (stripos($this->_agent, 'Portable)') !== false || stripos($this->_agent, 'Vita') !== false) {
$this->setMobile(true);
}
return true;
}
}
return false;
}
/**
* Determine the user's platform (last updated 2.0)
*/
protected function checkPlatform()
{
if (stripos($this->_agent, 'windows') !== false) {
$this->_platform = self::PLATFORM_WINDOWS;
} else if (stripos($this->_agent, 'iPad') !== false) {
$this->_platform = self::PLATFORM_IPAD;
} else if (stripos($this->_agent, 'iPod') !== false) {
$this->_platform = self::PLATFORM_IPOD;
} else if (stripos($this->_agent, 'iPhone') !== false) {
$this->_platform = self::PLATFORM_IPHONE;
} elseif (stripos($this->_agent, 'mac') !== false) {
$this->_platform = self::PLATFORM_APPLE;
} elseif (stripos($this->_agent, 'android') !== false) {
$this->_platform = self::PLATFORM_ANDROID;
} elseif (stripos($this->_agent, 'Silk') !== false) {
$this->_platform = self::PLATFORM_FIRE_OS;
} elseif (stripos($this->_agent, 'linux') !== false && stripos($this->_agent, 'SMART-TV') !== false ) {
$this->_platform = self::PLATFORM_LINUX .'/'.self::PLATFORM_SMART_TV;
} elseif (stripos($this->_agent, 'linux') !== false) {
$this->_platform = self::PLATFORM_LINUX;
} else if (stripos($this->_agent, 'Nokia') !== false) {
$this->_platform = self::PLATFORM_NOKIA;
} else if (stripos($this->_agent, 'BlackBerry') !== false) {
$this->_platform = self::PLATFORM_BLACKBERRY;
} elseif (stripos($this->_agent, 'FreeBSD') !== false) {
$this->_platform = self::PLATFORM_FREEBSD;
} elseif (stripos($this->_agent, 'OpenBSD') !== false) {
$this->_platform = self::PLATFORM_OPENBSD;
} elseif (stripos($this->_agent, 'NetBSD') !== false) {
$this->_platform = self::PLATFORM_NETBSD;
} elseif (stripos($this->_agent, 'OpenSolaris') !== false) {
$this->_platform = self::PLATFORM_OPENSOLARIS;
} elseif (stripos($this->_agent, 'SunOS') !== false) {
$this->_platform = self::PLATFORM_SUNOS;
} elseif (stripos($this->_agent, 'OS\/2') !== false) {
$this->_platform = self::PLATFORM_OS2;
} elseif (stripos($this->_agent, 'BeOS') !== false) {
$this->_platform = self::PLATFORM_BEOS;
} elseif (stripos($this->_agent, 'win') !== false) {
$this->_platform = self::PLATFORM_WINDOWS;
} elseif (stripos($this->_agent, 'Playstation') !== false) {
$this->_platform = self::PLATFORM_PLAYSTATION;
} elseif (stripos($this->_agent, 'Roku') !== false) {
$this->_platform = self::PLATFORM_ROKU;
} elseif (stripos($this->_agent, 'iOS') !== false) {
$this->_platform = self::PLATFORM_IPHONE . '/' . self::PLATFORM_IPAD;
} elseif (stripos($this->_agent, 'tvOS') !== false) {
$this->_platform = self::PLATFORM_APPLE_TV;
} elseif (stripos($this->_agent, 'curl') !== false) {
$this->_platform = self::PLATFORM_TERMINAL;
} elseif (stripos($this->_agent, 'CrOS') !== false) {
$this->_platform = self::PLATFORM_CHROME_OS;
} elseif (stripos($this->_agent, 'okhttp') !== false) {
$this->_platform = self::PLATFORM_JAVA_ANDROID;
} elseif (stripos($this->_agent, 'PostmanRuntime') !== false) {
$this->_platform = self::PLATFORM_POSTMAN;
} elseif (stripos($this->_agent, 'Iframely') !== false) {
$this->_platform = self::PLATFORM_I_FRAME;
}
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.cws.mbh.php'
<?php
/**
* CwsMailBounceHandler
*
* CwsMailBounceHandler is a PHP class to help webmasters handle bounce-back,
* feedback loop and ARF mails in standard DSN (Delivery Status Notification, RFC-1894).
* It checks your IMAP/POP3 inbox or eml files and delete or move all 'hard' bounced emails.
* If a bounce is malformed, it tries to extract some useful information to parse status.
* A result array is available to process custom post-actions.
*
* CwsMailBounceHandler is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CwsMailBounceHandler is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Related post: http://goo.gl/Wrq8J
*
* @package CwsMailBounceHandler
* @author Cr@zy
* @copyright 2013-2014, Cr@zy
* @license GNU LESSER GENERAL PUBLIC LICENSE
* @version 1.5
* @link https://github.com/crazy-max/CwsMailBounceHandler
*
*/
define('CWSMBH_OPEN_MODE_IMAP', 0); // if you open a mailbox via imap.
define('CWSMBH_OPEN_MODE_FILE', 1); // if you open a eml file or a folder containing eml files.
define('CWSMBH_VERBOSE_QUIET', 0); // means no output at all.
define('CWSMBH_VERBOSE_SIMPLE', 1); // means only output simple report.
define('CWSMBH_VERBOSE_REPORT', 2); // means output a detail report.
define('CWSMBH_VERBOSE_DEBUG', 3); // means output detail report as well as debug info.
define('CWSMBH_CERT_NOVALIDATE', 'novalidate-cert'); // do not validate certificates from TLS/SSL server
define('CWSMBH_CERT_VALIDATE', 'validate-cert'); // validate certificates from TLS/SSL server (default behavior)
define('CWSMBH_BOUNCE_AUTOREPLY', 'autoreply');
define('CWSMBH_BOUNCE_BLOCKED', 'blocked');
define('CWSMBH_BOUNCE_GENERIC', 'generic');
define('CWSMBH_BOUNCE_HARD', 'hard');
define('CWSMBH_BOUNCE_SOFT', 'soft');
define('CWSMBH_BOUNCE_TEMPORARY', 'temporary');
define('CWSMBH_CAT_ANTISPAM', 'antispam');
define('CWSMBH_CAT_AUTOREPLY', 'autoreply');
define('CWSMBH_CAT_CONCURRENT', 'concurrent');
define('CWSMBH_CAT_CONTENT_REJECT', 'content_reject');
define('CWSMBH_CAT_COMMAND_REJECT', 'command_reject');
define('CWSMBH_CAT_DEFER', 'defer');
define('CWSMBH_CAT_DELAYED', 'delayed');
define('CWSMBH_CAT_DNS_LOOP', 'dns_loop');
define('CWSMBH_CAT_DNS_UNKNOWN', 'dns_unknown');
define('CWSMBH_CAT_FULL', 'full');
define('CWSMBH_CAT_INACTIVE', 'inactive');
define('CWSMBH_CAT_INTERNAL_ERROR', 'internal_error');
define('CWSMBH_CAT_LATIN_ONLY', 'latin_only');
define('CWSMBH_CAT_OTHER', 'other');
define('CWSMBH_CAT_OVERSIZE', 'oversize');
define('CWSMBH_CAT_TIMEOUT', 'timeout');
define('CWSMBH_CAT_UNKNOWN', 'unknown');
define('CWSMBH_CAT_UNRECOGNIZED', 'unrecognized');
define('CWSMBH_CAT_USER_REJECT', 'user_reject');
define('CWSMBH_CAT_WARNING', 'warning');
define('CWSMBH_STATUS_FIRST_SUBCODE', 'first_subcode');
define('CWSMBH_STATUS_SECOND_SUBCODE', 'second_subcode');
define('CWSMBH_STATUS_THIRD_SUBCODE', 'third_subcode');
class CwsMailBounceHandler {
/**
* CwsMailBounceHandler version.
* @var string
*/
public $version = "1.5";
/**
* Mail host server.
* default 'localhost'
* @var string
*/
public $host = 'localhost';
/**
* The username of mailbox.
* @var string
*/
public $username;
/**
* The password needed to access mailbox.
* @var string
*/
public $password;
/**
* Defines port number, other common choices are '110' (pop3), '143' (imap), '995' (tls/ssl)
* default 143
* @var integer
*/
public $port = 143;
/**
* Defines service, choice includes 'pop3' and 'imap'.
* default 'imap'
* @var string
*/
public $service = 'imap';
/**
* Defines service option, choices are 'none', 'notls', 'tls', 'ssl'.
* default 'notls'
* @var string
*/
public $service_option = 'notls';
/**
* Control certificates validation if service_option is 'tls' or 'ssl'.
* default CWSMBH_CERT_NOVALIDATE
* @var string
*/
public $cert = CWSMBH_CERT_NOVALIDATE;
/**
* Control the method to open e-mail(s).
* default CWSMBH_OPEN_MODE_IMAP
* @var int
*/
public $open_mode = CWSMBH_OPEN_MODE_IMAP;
/**
* Mailbox type, other choices are (Tasks, Spam, Replies, etc.)
* default 'INBOX'
* @var string
*/
public $boxname = 'INBOX';
/**
* Determines if soft bounces will be moved to another mailbox or folder.
* default false
* @var boolean
*/
public $move_soft = false;
/**
* Mailbox or folder to move soft bounces to.
* default 'INBOX.soft'
* @var string
*/
public $folder_soft = 'INBOX.soft';
/**
* Determines if hard bounces will be moved to another mailbox or folder.
* NOTE: If true, this will disable delete and perform a move operation instead.
* default false
* @var boolean
*/
public $move_hard = false;
/**
* Mailbox or folder to move hard bounces to.
* default 'INBOX.hard'
* @var string
*/
public $folder_hard = 'INBOX.hard';
/**
* Maximum limit messages processed in one batch (0 for unlimited).
* default 0
* @var int
*/
public $max_messages = 0;
/**
* The last error message.
* @var string
*/
public $error_msg;
/**
* Test mode, if true will not delete messages.
* default false
* @var boolean
*/
public $test_mode = false;
/**
* Purge unknown messages. Be careful with this option.
* default false
* @var boolean
*/
public $purge = false;
/**
* Control the debug output.
* default CWSMBH_VERBOSE_QUIET
* @var int
*/
public $debug_verbose = CWSMBH_VERBOSE_QUIET;
/**
* If true, it will disable the delete function.
* default false
* @var boolean
*/
public $disable_delete = false;
/**
* If true, it will active functions to move mails to trash
*/
public $gmail = false;
/**
* The resource handler for the opened mailbox (POP3/IMAP/NNTP/etc.)
* @var object
*/
private $_handler = false;
/**
* The eml files opened.
* @var array
*/
private $_files = array();
/**
* The folder path opened.
* @var string
*/
private $_folder = '';
/**
* The header of the message.
* @var string
*/
private $_header = array();
/**
* * The body of the message.
* @var string
*/
private $_body = array();
/**
* Defines new line ending.
*/
private $_newline = "<br />\n";
/**
* Result array of the process
* This var returns an array with the following values :
* array 'counter' see $_counter_result.
* array 'msg' see $_msg_result.
* @var array
*/
public $result = array('counter' => array(), 'msgs' => array());
/**
* Result array of the final counter
* This var returns an array with the following values :
* int 'total' total messages in the mailbox/folder.
* int 'fetched' fetched messages from the mailbox/folder.
* int 'processed' messages processed.
* int 'unprocessed' messages unprocessed.
* int 'deleted' messages deleted.
* int 'moved' messages moved.
* @var array
*/
private $_counter_result = array('total' => 0, 'fetched' => 0, 'processed' => 0, 'unprocessed' => 0, 'deleted' => 0, 'moved' => 0);
/**
* Result array of a msg process
* This var returns an array with the following values :
* string 'token' message number or filename.
* boolean 'processed' was processed during bounce/fbl analyze.
* string 'subject' message subject.
* array 'type' type detected (bounce or fbl).
* array 'recipients' see $_recipient_result.
* @var array
*/
private $_msg_result = array('token' => null, 'processed' => true, 'subject' => null, 'type' => null, 'recipients' => array());
/**
* Result array of recipients found
* This var returns an array with the following values :
* string 'action' the DSN action (only for DSN process).
* string 'status' the status code.
* string 'email' the recipient e-mail.
* string 'bounce_type' type of bounce (see CWSMBH_BOUNCE_ defines)
* string 'bounce_cat' bounce category.
* string 'remove' is removed.
* @var array
*/
private $_recipient_result = array('action' => null, 'status' => null, 'email' => null, 'bounce_type' => null, 'bounce_cat' => CWSMBH_CAT_UNRECOGNIZED, 'remove' => false);
/**
* Result array of status
* This var returns an array with the following values :
* string 'code' the status code.
* array CWSMBH_STATUS_FIRST_SUBCODE array containing title and description of the first subcode.
* array CWSMBH_STATUS_SECOND_SUBCODE array containing title and description of the second subcode.
* array CWSMBH_STATUS_THIRD_SUBCODE array containing title and description of the third subcode.
* @var array
*/
private $_status_result = array('code' => null, CWSMBH_STATUS_FIRST_SUBCODE => array(), CWSMBH_STATUS_SECOND_SUBCODE => array(), CWSMBH_STATUS_THIRD_SUBCODE => array());
/**
* Defines rules categories
* @var array
*/
private $_rules_cats = array(CWSMBH_CAT_ANTISPAM => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_BLOCKED), CWSMBH_CAT_AUTOREPLY => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_AUTOREPLY), CWSMBH_CAT_CONCURRENT => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_SOFT), CWSMBH_CAT_CONTENT_REJECT => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_SOFT), CWSMBH_CAT_COMMAND_REJECT => array('remove' => true, 'bounce_type' => CWSMBH_BOUNCE_HARD), CWSMBH_CAT_DEFER => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_SOFT), CWSMBH_CAT_DELAYED => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_TEMPORARY), CWSMBH_CAT_DNS_LOOP => array('remove' => true, 'bounce_type' => CWSMBH_BOUNCE_HARD), CWSMBH_CAT_DNS_UNKNOWN => array('remove' => true, 'bounce_type' => CWSMBH_BOUNCE_HARD), CWSMBH_CAT_FULL => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_SOFT), CWSMBH_CAT_INACTIVE => array('remove' => true, 'bounce_type' => CWSMBH_BOUNCE_HARD), CWSMBH_CAT_INTERNAL_ERROR => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_TEMPORARY), CWSMBH_CAT_LATIN_ONLY => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_SOFT), CWSMBH_CAT_OTHER => array('remove' => true, 'bounce_type' => CWSMBH_BOUNCE_GENERIC), CWSMBH_CAT_OVERSIZE => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_SOFT), CWSMBH_CAT_TIMEOUT => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_SOFT), CWSMBH_CAT_UNKNOWN => array('remove' => true, 'bounce_type' => CWSMBH_BOUNCE_HARD), CWSMBH_CAT_UNRECOGNIZED => array('remove' => false, 'bounce_type' => null), CWSMBH_CAT_USER_REJECT => array('remove' => true, 'bounce_type' => CWSMBH_BOUNCE_HARD), CWSMBH_CAT_WARNING => array('remove' => false, 'bounce_type' => CWSMBH_BOUNCE_SOFT));
/**
* Find status code from regexp
* @var array
*/
private $_status_code_resolver = array(
// get from regexp
'[45]\d\d[- ]\#?([45]\.\d\.\d)' => 'x',
'Diagnostic[- ][Cc]ode: smtp; ?\d\d\ ([45]\.\d\.\d)' => 'x',
'Status: ([45]\.\d\.\d)' => 'x',
// 4.2.0
'not yet been delivered' => '4.2.0',
'message will be retried for' => '4.2.0',
// 4.2.2
'benutzer hat zuviele mails auf dem server' => '4.2.2',
'exceeded storage allocation' => '4.2.2',
'mailbox full' => '4.2.2',
'mailbox is full' => '4.2.2',
'mailbox quota usage exceeded' => '4.2.2',
'mailbox size limit exceeded' => '4.2.2',
'mailfolder is full' => '4.2.2',
'not enough storage space' => '4.2.2',
'over ?quota' => '4.2.2',
'quota exceeded' => '4.2.2',
'quota violation' => '4.2.2',
'user has exhausted allowed storage space' => '4.2.2',
'user has too many messages on the server' => '4.2.2',
'user mailbox exceeds allowed size' => '4.2.2',
'user has Exceeded' => '4.2.2',
// 4.3.2
'delivery attempts will continue to be made for' => '4.3.2',
'delivery temporarily suspended' => '4.3.2',
'greylisted for 5 minutes' => '4.3.2',
'greylisting in action' => '4.3.2',
'server busy' => '4.3.2',
'server too busy' => '4.3.2',
'system load is too high' => '4.3.2',
'temporarily deferred' => '4.3.2',
'temporarily unavailable' => '4.3.2',
'throttling' => '4.3.2',
'too busy to accept mail' => '4.3.2',
'too many connections' => '4.3.2',
'too many sessions' => '4.3.2',
'too much load' => '4.3.2',
'try again later' => '4.3.2',
'try later' => '4.3.2',
// 4.4.7
'retry timeout exceeded' => '4.4.7',
'queue too long' => '4.4.7',
// 5.1.1
'554 delivery error:' => '5.1.1',
'account has been disabled' => '5.1.1',
'account is unavailable' => '5.1.1',
'account not found' => '5.1.1',
'address invalid' => '5.1.1',
'address is unknown' => '5.1.1',
'address unknown' => '5.1.1',
'addressee unknown' => '5.1.1',
'address_not_found' => '5.1.1',
'bad address' => '5.1.1',
'bad destination mailbox address' => '5.1.1',
'destin. Sconosciuto' => '5.1.1',
'destinatario errato' => '5.1.1',
'destinatario sconosciuto o mailbox disatttivata' => '5.1.1',
'does not exist' => '5.1.1',
'email Address was not found' => '5.1.1',
'excessive userid unknowns' => '5.1.1',
'Indirizzo inesistente' => '5.1.1',
'Invalid account' => '5.1.1',
'invalid address' => '5.1.1',
'invalid or unknown virtual user' => '5.1.1',
'invalid mailbox' => '5.1.1',
'invalid recipient' => '5.1.1',
'mailbox not found' => '5.1.1',
'mailbox unavailable' => '5.1.1',
'nie istnieje' => '5.1.1',
'nie ma takiego konta' => '5.1.1',
'no mail box available for this user' => '5.1.1',
'no mailbox here' => '5.1.1',
'no one with that email address here' => '5.1.1',
'no such address' => '5.1.1',
'no such email address' => '5.1.1',
'no such mail drop defined' => '5.1.1',
'no such mailbox' => '5.1.1',
'no such person at this address' => '5.1.1',
'no such recipient' => '5.1.1',
'no such user' => '5.1.1',
'not a known user' => '5.1.1',
'not a valid mailbox' => '5.1.1',
'not a valid user' => '5.1.1',
'not available' => '5.1.1',
'not exists' => '5.1.1',
'recipient address rejected' => '5.1.1',
'recipient not allowed' => '5.1.1',
'recipient not found' => '5.1.1',
'recipient rejected' => '5.1.1',
'recipient unknown' => '5.1.1',
'server doesn\'t handle mail for that user' => '5.1.1',
'this account is disabled' => '5.1.1',
'this address no longer accepts mail' => '5.1.1',
'this email address is not known to this system' => '5.1.1',
'email account that you tried to reach does not exist' => '5.1.1',
'unknown account' => '5.1.1',
'unknown address or alias' => '5.1.1',
'unknown email address' => '5.1.1',
'unknown local part' => '5.1.1',
'unknown or illegal alias' => '5.1.1',
'unknown or illegal user' => '5.1.1',
'unknown recipient' => '5.1.1',
'unknown user' => '5.1.1',
'user disabled' => '5.1.1',
'user doesn\'t exist in this server' => '5.1.1',
'user invalid' => '5.1.1',
'user is suspended' => '5.1.1',
'user is unknown' => '5.1.1',
'user not found' => '5.1.1',
'user not known' => '5.1.1',
'user unknown' => '5.1.1',
'valid RCPT command must precede data' => '5.1.1',
'was not found in ldap server' => '5.1.1',
'we are sorry but the address is invalid' => '5.1.1',
'unable to find alias user' => '5.1.1',
// 5.1.2
'domain isn\'t in my list of allowed rcpthosts' => '5.1.2',
'esta casilla ha expirado por falta de uso' => '5.1.2',
'host ?name is unknown' => '5.1.2',
'no relaying allowed' => '5.1.2',
'no such domain' => '5.1.2',
'not our customer' => '5.1.2',
'relay not permitted' => '5.1.2',
'relay access denied' => '5.1.2',
'relaying denied' => '5.1.2',
'relaying not allowed' => '5.1.2',
'this system is not configured to relay mail' => '5.1.2',
'unable to relay' => '5.1.2',
'unrouteable mail domain' => '5.1.2',
'we do not relay' => '5.1.2',
// 5.1.6
'old address no longer valid' => '5.1.6',
'recipient no longer on server' => '5.1.6',
// 5.1.8
'dender address rejected' => '5.1.8',
// 5.2.0
'delivery failed' => '5.2.0',
'exceeded the rate limit' => '5.2.0',
'local Policy Violation' => '5.2.0',
'mailbox currently suspended' => '5.2.0',
'mailbox unavailable' => '5.2.0',
'mail can not be delivered' => '5.2.0',
'mail couldn\'t be delivered' => '5.2.0',
'the account or domain may not exist' => '5.2.0',
// 5.2.1
'account disabled' => '5.2.1',
'account has been disabled' => '5.2.1',
'account inactive' => '5.2.1',
'inactive account' => '5.2.1',
'adressat unbekannt oder mailbox deaktiviert' => '5.2.1',
'destinataire inconnu ou boite aux lettres desactivee' => '5.2.1',
'mail is not currently being accepted for this mailbox' => '5.2.1',
'el usuario esta en estado: inactivo' => '5.2.1',
'email account that you tried to reach is disabled' => '5.2.1',
'inactive user' => '5.2.1',
'user is inactive' => '5.2.1',
'mailbox disabled for this recipient' => '5.2.1',
'mailbox has been blocked due to inactivity' => '5.2.1',
'mailbox is currently unavailable' => '5.2.1',
'mailbox is disabled' => '5.2.1',
'mailbox is inactive' => '5.2.1',
'mailbox locked or suspended' => '5.2.1',
'mailbox temporarily disabled' => '5.2.1',
'podane konto jest zablokowane administracyjnie lub nieaktywne' => '5.2.1',
'questo indirizzo e\' bloccato per inutilizzo' => '5.2.1',
'recipient mailbox was disabled' => '5.2.1',
'domain name not found' => '5.2.1',
// 5.4.4
'couldn\'t find any host named' => '5.4.4',
'couldn\'t find any host by that name' => '5.4.4',
'perm_failure: dns error' => '5.4.4',
'temporary lookup failure' => '5.4.4',
'unrouteable address' => '5.4.4',
'can\'t connect to' => '5.4.4',
// 5.4.6
'too many hops' => '5.4.6',
// 5.5.0
'content reject' => '5.5.0',
'requested action aborted' => '5.5.0',
// 5.5.2
'mime/reject' => '5.5.2',
// 5.5.3
'mail data refused' => '5.5.3',
// 5.5.4
'mime error' => '5.5.4',
// 5.6.2
'rejecting password protected file attachment' => '5.6.2',
// 5.7.1
'550 OU-00' => '5.7.1',
'550 SC-00' => '5.7.1',
'550 DY-00' => '5.7.1',
'554 denied' => '5.7.1',
'you have been blocked by the recipient' => '5.7.1',
'requires that you verify' => '5.7.1',
'access denied' => '5.7.1',
'administrative prohibition - unable to validate recipient' => '5.7.1',
'blacklisted' => '5.7.1',
'blocke?d? for spam' => '5.7.1',
'conection refused' => '5.7.1',
'connection refused due to abuse' => '5.7.1',
'dial-up or dynamic-ip denied' => '5.7.1',
'domain has received too many bounces' => '5.7.1',
'failed several antispam checks' => '5.7.1',
'found in a dns blacklist' => '5.7.1',
'ips blocked' => '5.7.1',
'is blocked by' => '5.7.1',
'mail Refused' => '5.7.1',
'message does not pass domainkeys' => '5.7.1',
'message looks like spam' => '5.7.1',
'message refused by' => '5.7.1',
'not allowed access from your location' => '5.7.1',
'permanently deferred' => '5.7.1',
'rejected by policy' => '5.7.1',
'rejected by windows live hotmail for policy reasons' => '5.7.1',
'rejected for policy reasons' => '5.7.1',
'rejecting banned content' => '5.7.1',
'sorry, looks like spam' => '5.7.1',
'spam message discarded' => '5.7.1',
'too many spams from your ip' => '5.7.1',
'transaction failed' => '5.7.1',
'transaction rejected' => '5.7.1',
'wiadomosc zostala odrzucona przez system antyspamowy' => '5.7.1',
'your message was declared spam' => '5.7.1'
);
/**
* Find rule cat from status code
* @var array
*/
private $_rule_cat_resolver = array('4.2.0' => CWSMBH_CAT_DEFER, '4.2.2' => CWSMBH_CAT_FULL, '4.3.2' => CWSMBH_CAT_DEFER, '4.4.7' => CWSMBH_CAT_TIMEOUT, '4.5.1' => CWSMBH_CAT_COMMAND_REJECT, '5.0.0' => CWSMBH_CAT_UNKNOWN, '5.1.1' => CWSMBH_CAT_UNKNOWN, '5.1.2' => CWSMBH_CAT_UNKNOWN, '5.1.3' => CWSMBH_CAT_UNKNOWN, '5.1.4' => CWSMBH_CAT_UNKNOWN, '5.1.6' => CWSMBH_CAT_UNKNOWN, '5.1.8' => CWSMBH_CAT_ANTISPAM, '5.2.0' => CWSMBH_CAT_FULL, '5.2.1' => CWSMBH_CAT_USER_REJECT, '5.2.2' => CWSMBH_CAT_FULL, '5.2.3' => CWSMBH_CAT_UNKNOWN, '5.4.4' => CWSMBH_CAT_UNKNOWN, '5.4.6' => CWSMBH_CAT_ANTISPAM, '5.5.0' => CWSMBH_CAT_CONTENT_REJECT, '5.5.2' => CWSMBH_CAT_CONTENT_REJECT, '5.5.3' => CWSMBH_CAT_CONTENT_REJECT, '5.5.4' => CWSMBH_CAT_CONTENT_REJECT, '5.6.2' => CWSMBH_CAT_CONTENT_REJECT, '5.7.1' => CWSMBH_CAT_USER_REJECT);
/**
* Output additional msg for debug
* @param string $msg : if not given, output the last error msg
* @param int $verbose_level : the output level of this message
*/
private function output($msg = false, $verbose_level = CWSMBH_VERBOSE_SIMPLE, $newline = true, $code = false) {
if ($this->debug_verbose >= $verbose_level) {
if (empty($msg)) {
echo 'ERROR: ' . $this->error_msg;
} else {
if ($code) {
echo '<textarea style="width:100%;height:300px;">';
print_r($msg);
echo '</textarea>';
} else {
echo $msg;
}
}
if ($newline) {
echo $this->_newline;
}
}
}
/**
* Open a folder containing eml files on your system
* @param string $eml_folder_path : the eml folder path
* @return boolean
*/
public function openFolder($eml_folder_path) {
$this->output('<h2>Init openFolder</h2>', CWSMBH_VERBOSE_SIMPLE, false);
if (!$this->endWith($eml_folder_path, '/')) {
$eml_folder_path .= '/';
}
$this->_folder = $eml_folder_path;
set_time_limit(30000);
$handle = @opendir($this->_folder);
if (!$handle) {
$this->error_msg = '<strong>Cannot open the eml folder ' . $this->_folder . '</strong>.';
$this->output();
return false;
}
$nb_files = 0;
while ($file = readdir($handle)) {
if ($file == '.' || $file == '..' || !$this->endWith($file, '.eml')) {
continue;
}
$eml_path = $this->_folder . '/' . $file;
$content = @file_get_contents($eml_path, false, stream_context_create(array(
'http' => array(
'method' => 'GET'
)
)));
if (!empty($content)) {
$this->_files[] = array(
'name' => $file,
'content' => $content
);
}
$nb_files++;
}
closedir($handle);
if (empty($this->_files)) {
$this->error_msg = '<strong>no eml file found in ' . $this->_folder . '</strong>.';
$this->output();
return false;
} else {
$this->output('<strong>Opened:</strong> ' . count($this->_files) . ' / ' . $nb_files . ' files.');
return true;
}
}
/**
* Open an eml file on your system
* @param string $eml_path : the eml file path
* @return boolean
*/
public function openFile($eml_path) {
$this->output('<h2>Init openFile</h2>', CWSMBH_VERBOSE_SIMPLE, false);
set_time_limit(6000);
$content = @file_get_contents($eml_path, false, stream_context_create(array(
'http' => array(
'method' => 'GET'
)
)));
if (!empty($content)) {
$this->_files[] = array(
'name' => $file,
'content' => $content
);
}
if (empty($this->_files)) {
$this->error_msg = '<strong>Cannot open the eml file ' . $eml_path . '</strong>.';
$this->output();
return false;
} else {
$this->output('<strong>Opened:</strong> ' . $eml_path . '.');
return true;
}
}
/**
* Open a mail box in local file system
* @param string $file_path : the local mailbox file path
* @return boolean
*/
public function openImapLocal($file_path) {
$this->output('<h2>Init openImapLocal</h2>', CWSMBH_VERBOSE_SIMPLE, false);
set_time_limit(6000);
$this->_handler = imap_open($file_path, '', '', !$this->test_mode ? CL_EXPUNGE : null);
if (!$this->_handler) {
$this->error_msg = '<strong>Cannot open the mailbox file to ' . $file_path . '</strong>' . $this->_newline . 'Error MSG: ' . imap_last_error();
$this->output();
return false;
} else {
$this->output('<strong>Opened:</strong> ' . $file_path . '.');
return true;
}
}
/**
* Open a remote mail box
* @return boolean
*/
public function openImapRemote() {
$this->output('<h2>Init openImapRemote</h2>', CWSMBH_VERBOSE_SIMPLE, false);
// disable move operations if server is Gmail... Gmail does not support mailbox creation
if (stristr($this->host, 'gmail')) {
//$this->move_soft = false;
//$this->move_hard = false;
$this->gmail = true;
}
// required options for imap_open connection.
$opts = '/' . $this->service . '/' . $this->service_option;
if ($this->service_option == 'tls' || $this->service_option == 'ssl') {
$opts .= '/' . $this->cert;
}
set_time_limit(6000);
$this->_handler = imap_open("{" . $this->host . ":" . $this->port . $opts . "}" . $this->boxname, $this->username, $this->password, !$this->test_mode ? CL_EXPUNGE : null);
if (!$this->_handler) {
$this->error_msg = '<strong>Cannot create ' . $this->service . ' connection</strong> to ' . $this->host . $this->_newline . 'Error MSG: ' . imap_last_error();
$this->output();
return false;
} else {
$this->output('<strong>Connected to:</strong> ' . $this->host . ":" . $this->port . $opts . ' on mailbox ' . $this->boxname . ' (' . $this->username . ')');
return true;
}
}
/**
* Process the messages in a mailbox or a file/folder
* @param int $max : maximum limit messages processed in one batch, if not given uses the property $max_messages.
* @return boolean
*/
public function processMails($max = 0) {
$this->output('<h2>Init processMails</h2>', CWSMBH_VERBOSE_SIMPLE, false);
if ($this->isImapOpenMode()) {
if (!$this->_handler) {
$this->error_msg = '<strong>Mailbox not opened</strong>';
$this->output();
exit();
}
} else {
if (empty($this->_files)) {
$this->error_msg = '<strong>File(s) not opened</strong>';
$this->output();
exit();
}
}
if ($this->move_hard && $this->disable_delete === false) {
$this->disable_delete = true;
}
if (!empty($max)) {
$this->max_messages = $max;
}
// initialize counter
$this->result['counter'] = $this->_counter_result;
$this->result['counter']['total'] = $this->isImapOpenMode() ? imap_num_msg($this->_handler) : count($this->_files);
$this->result['counter']['fetched'] = $this->result['counter']['total'];
$this->output('<strong>Total:</strong> ' . $this->result['counter']['total'] . ' messages.');
// process maximum number of messages
if (!empty($this->max_messages) && $this->result['counter']['fetched'] > $this->max_messages) {
$this->result['counter']['fetched'] = $this->max_messages;
$this->output('Processing first <strong>' . $this->result['counter']['fetched'] . ' messages</strong>...');
}
if ($this->test_mode) {
$this->output('Running in <strong>test mode</strong>, not deleting messages from mailbox.');
} else {
if ($this->disable_delete) {
if ($this->move_hard) {
$this->output('Running in <strong>move mode</strong>.');
} else {
$this->output('Running in <strong>disable_delete mode</strong>, not deleting messages from mailbox.');
}
} else {
$this->output('<strong>Processed messages will be deleted</strong> from mailbox.');
}
}
if ($this->isImapOpenMode()) {
for ($msg_no = 1; $msg_no <= $this->result['counter']['fetched']; $msg_no++) {
$this->output('<h3>Msg #' . $msg_no . '</h3>', CWSMBH_VERBOSE_REPORT, false);
$header = @imap_fetchheader($this->_handler, $msg_no);
$body = @imap_body($this->_handler, $msg_no);
if ($this->gmail) {
$info = @imap_headerinfo($this->_handler, $msg_no);
$this->result['uid'][] = imap_uid($this->_handler, $msg_no);
}
$this->result['msgs'][] = $this->processParsing($msg_no, $header . '\r\n\r\n' . $body);
}
} else {
foreach ($this->_files as $file) {
$this->output('<h3>Msg #' . $file['name'] . '</h3>', CWSMBH_VERBOSE_REPORT, false);
$this->result['msgs'][] = $this->processParsing($file['name'], $file['content']);
}
}
foreach ($this->result['msgs'] as $msg) {
if ($msg['processed']) {
$this->result['counter']['processed']++;
if (!$this->test_mode && !$this->disable_delete) {
$this->processDelete($msg['token']);
$this->result['counter']['deleted']++;
} elseif ($this->move_hard) {
$this->processMove($msg['token'], 'hard');
$this->result['counter']['moved']++;
} elseif ($this->move_soft) {
$this->processMove($msg['token'], 'soft');
$this->result['counter']['moved']++;
} elseif ($this->gmail) {
if ($this->move_hard) {
$this->processMove($msg['uid'], 'hard');
$this->result['counter']['moved']++;
} elseif ($this->move_soft) {
$this->processMove($msg['uid'], 'soft');
$this->result['counter']['moved']++;
}
}
} else {
$this->result['counter']['unprocessed']++;
if (!$this->test_mode && !$this->disable_delete && $this->purge) {
$this->processDelete($msg['token']);
$this->result['counter']['deleted']++;
}
}
}
$this->output('<h2>End of process</h2>', CWSMBH_VERBOSE_SIMPLE, false);
if ($this->isImapOpenMode()) {
$this->output('Closing mailbox, and purging messages');
@imap_expunge($this->_handler);
@imap_clearflag_full($this->_handler, $this->result['counter']['fetched'], '\\Seen');
@imap_close($this->_handler);
}
$this->output($this->result['counter']['fetched'] . ' messages read');
$this->output($this->result['counter']['processed'] . ' action taken');
$this->output($this->result['counter']['unprocessed'] . ' no action taken');
$this->output($this->result['counter']['deleted'] . ' messages deleted');
$this->output($this->result['counter']['moved'] . ' messages moved');
$this->output($this->_newline . '<strong>Full result:</strong>', CWSMBH_VERBOSE_REPORT);
$this->output($this->result, CWSMBH_VERBOSE_REPORT, false, true);
//return true;
return $this->result;
}
/**
* Function to process parsing of each individual message
* @param string $token : message number or filename.
* @param string $content : message content.
* @return array
*/
private function processParsing($token, $content) {
$result = $this->_msg_result;
$result['token'] = $token;
// format content
$content = $this->formatContent($content);
// split head and body
if (preg_match('#\r\n\r\n#is', $content)) {
list($header, $body) = preg_split('#\r\n\r\n#', $content, 2);
} else {
list($header, $body) = preg_split('#\n\n#', $content, 2);
}
$this->output('<strong>Header:</strong>', CWSMBH_VERBOSE_DEBUG);
$this->output($header, CWSMBH_VERBOSE_DEBUG, false, true);
$this->output('<strong>Body:</strong>', CWSMBH_VERBOSE_DEBUG);
$this->output($body, CWSMBH_VERBOSE_DEBUG, false, true);
$this->output(' ', CWSMBH_VERBOSE_DEBUG);
// parse header
$header = $this->parseHeader($header); // contient ["List-unsubscribe"]
// parse body sections
$body_sections = $this->parseBodySections($header, $body);
// check bounce and fbl
$is_bounce = $this->isBounce($header);
$is_fbl = $this->isFbl($header, $body_sections);
if ($is_bounce) {
$result['type'] = 'bounce';
} elseif ($is_fbl) {
$result['type'] = 'fbl';
}
// begin process
$result['recipients'] = array();
if ($is_fbl) {
$this->output('<strong>Feedback loop</strong> detected', CWSMBH_VERBOSE_DEBUG);
$result['subject'] = trim(str_ireplace('Fw:', '', $header['Subject']));
if ($this->isHotmailFbl($body_sections)) {
$this->output('This message is an <strong>Hotmail fbl</strong>', CWSMBH_VERBOSE_DEBUG);
$body_sections['ar_machine']['Content-disposition'] = 'inline';
$body_sections['ar_machine']['Content-type'] = 'message/feedback-report';
$body_sections['ar_machine']['Feedback-type'] = 'abuse';
$body_sections['ar_machine']['User-agent'] = 'Hotmail FBL';
if (!$this->isEmpty($body_sections['ar_first'], 'Date')) {
$body_sections['ar_machine']['Received-date'] = $body_sections['ar_first']['Date'];
}
if (!$this->isEmpty($body_sections['ar_first'], 'X-HmXmrOriginalRecipient')) {
$body_sections['ar_machine']['Original-rcpt-to'] = $body_sections['ar_first']['X-HmXmrOriginalRecipient'];
}
if (!$this->isEmpty($body_sections['ar_first'], 'X-sid-pra')) {
$body_sections['ar_machine']['Original-mail-from'] = $body_sections['ar_first']['X-sid-pra'];
}
} else {
if (!$this->isEmpty($body_sections, 'machine')) {
$body_sections['ar_machine'] = $this->parseLines($body_sections['machine']);
}
if (!$this->isEmpty($body_sections, 'returned')) {
$body_sections['ar_returned'] = $this->parseLines($body_sections['returned']);
}
if ($this->isEmpty($body_sections['ar_machine'], 'Original-mail-from') && !$this->isEmpty($body_sections['ar_returned'], 'From')) {
$body_sections['ar_machine']['Original-mail-from'] = $body_sections['ar_returned']['From'];
}
if ($this->isEmpty($body_sections['ar_machine'], 'Original-rcpt-to') && !$this->isEmpty($body_sections['ar_machine'], 'Removal-recipient')) {
$body_sections['ar_machine']['Original-rcpt-to'] = $body_sections['ar_machine']['Removal-recipient'];
} elseif (!$this->isEmpty($body_sections['ar_returned'], 'To')) {
$body_sections['ar_machine']['Original-rcpt-to'] = $body_sections['ar_returned']['To'];
}
// try to get the actual intended recipient if possible
if (preg_match('#Undisclosed|redacted#i', $body_sections['ar_machine']['Original-mail-from']) && !$this->isEmpty($body_sections['ar_machine'], 'Removal-recipient')) {
$body_sections['ar_machine']['Original-rcpt-to'] = $body_sections['ar_machine']['Removal-recipient'];
}
if ($this->isEmpty($body_sections['ar_machine'], 'Received-date') && !$this->isEmpty($body_sections['ar_machine'], 'Arrival-date')) {
$body_sections['ar_machine']['Received-date'] = $body_sections['ar_machine']['Arrival-date'];
}
if (!$this->isEmpty($body_sections['ar_machine'], 'Original-mail-from')) {
$body_sections['ar_machine']['Original-mail-from'] = $this->extractEmail($body_sections['ar_machine']['Original-mail-from']);
}
if (!$this->isEmpty($body_sections['ar_machine'], 'Original-rcpt-to')) {
$body_sections['ar_machine']['Original-rcpt-to'] = $this->extractEmail($body_sections['ar_machine']['Original-rcpt-to']);
}
}
$recipient = $this->_recipient_result;
$recipient['email'] = $body_sections['ar_machine']['Original-rcpt-to'];
$recipient['status'] = '5.7.1';
$recipient['action'] = 'failed';
$result['recipients'][] = $recipient;
} elseif (!$this->isEmpty($header, 'Subject') && preg_match('#auto.{0,20}reply|vacation|(out|away|on holiday).*office#i', $header['Subject'])) {
$this->output('<strong>Autoreply</strong> engaged', CWSMBH_VERBOSE_DEBUG);
$recipient = $this->_recipient_result;
$recipient['bounce_cat'] = CWSMBH_CAT_AUTOREPLY;
$result['recipients'][] = $recipient;
} elseif ($this->isRfc1892Report($header)) {
$this->output('<strong>RFC 1892 report</strong> engaged', CWSMBH_VERBOSE_DEBUG);
$ar_body_machine = $this->parseBodySectionMachine($body_sections['machine']);
if (!$this->isEmpty($ar_body_machine['per_recipient'])) {
foreach ($ar_body_machine['per_recipient'] as $ar_recipient) {
$recipient = $this->_recipient_result;
$recipient['email'] = $this->findEmail($ar_recipient);
$recipient['status'] = isset($ar_recipient['Status']) ? $ar_recipient['Status'] : null;
$recipient['action'] = isset($ar_recipient['Action']) ? $ar_recipient['Action'] : null;
$result['recipients'][] = $recipient;
}
}
} elseif (!$this->isEmpty($header, 'X-failed-recipients')) {
$this->output('<strong>X-failed-recipients</strong> engaged', CWSMBH_VERBOSE_DEBUG);
$ar_emails = explode(",", $header['X-failed-recipients']);
foreach ($ar_emails as $email) {
$recipient = $this->_recipient_result;
$recipient['email'] = trim($email);
$result['recipients'][] = $recipient;
}
} elseif (isset($header['Content-type']) && !$this->isEmpty($header['Content-type'], 'boundary') && $this->isBounce($header)) {
$this->output('<strong>First body part</strong> engaged', CWSMBH_VERBOSE_DEBUG);
$ar_emails = $this->findEmails($body_sections['first']);
foreach ($ar_emails as $email) {
$recipient = $this->_recipient_result;
$recipient['email'] = trim($email);
$result['recipients'][] = $recipient;
}
} elseif ($this->isBounce($header)) {
$this->output('<strong>Other bounces</strong> engaged', CWSMBH_VERBOSE_DEBUG);
$ar_emails = $this->findEmails($body);
foreach ($ar_emails as $email) {
$recipient = $this->_recipient_result;
$recipient['email'] = trim($email);
$result['recipients'][] = $recipient;
}
} else {
$result['processed'] = false;
}
if (empty($result['subject']) && isset($header['Subject'])) {
$result['subject'] = $header['Subject'];
}
if (!empty($result['recipients'])) {
$tmp_recipient = $result['recipients'];
$result['recipients'] = array();
foreach ($tmp_recipient as $recipient) {
if (empty($recipient['status'])) {
$recipient['status'] = $this->findStatusCodeByRecipient($body);
} else {
$recipient['status'] = $this->formatStatusCode($recipient['status']);
}
if (empty($recipient['action'])) {
$recipient['action'] = $this->findActionByStatusCode($recipient['status']);
}
if ($recipient['bounce_cat'] == CWSMBH_CAT_UNRECOGNIZED && !empty($recipient['status'])) {
foreach ($this->_rule_cat_resolver as $key => $value) {
if ($key == $recipient['status']) {
$recipient['bounce_cat'] = $value;
}
$recipient['bounce_type'] = $this->_rules_cats[$recipient['bounce_cat']]['bounce_type'];
$recipient['remove'] = $this->_rules_cats[$recipient['bounce_cat']]['remove'];
}
}
/*
<hr noshade='' color='#D4D4D4' width='90%' size='1'>Je ne souhaite plus recevoir la newsletter :
<a href='https://www.phpmynewsletter.com/dev/subscription.php?i=387&list_id=6&op=leave&email_addr=arnaud@phpmynewsletter.com&h=718a6bf088eb121906f33738bddb50c4' style='' target='_blank'> désinscription</a></div></body></html><img style='border:0' src='https://www.phpmynewsletter.com/dev/trc.php?i=387&h=718a6bf088eb121906f33738bddb50c4' width='1' height='1 alt='6' /></body> </html>
*/
if (preg_match("/(.*)i=([0-9]{1,9})&list_id=([0-9]{1,9})&op=leave&email_addr=(.*)&h=(?P<name>\w+)>/i", $body_sections['returned'])) {
preg_match("/(.*)i=([0-9]{1,9})&list_id=([0-9]{1,9})&op=leave&email_addr=(.*)&h=(?P<name>\w+)>/i", $body_sections['returned'], $arg);
if ($arg[3] != NULL) {
$recipient['id_mail'] = $arg[2];
;
$recipient['list_id'] = $arg[3];
$recipient['hash'] = $arg[5];
}
} elseif (preg_match("/(.*)i=([0-9]{1,9})&list_id=([0-9]{1,9})&op=leave&email_addr=(.*)&h=(?P<name>\w+)>/i", $body)) {
preg_match("/(.*)i=([0-9]{1,9})&list_id=([0-9]{1,9})&op=leave&email_addr=(.*)&h=(?P<name>\w+)>/i", $body, $arg);
if ($arg[3] != NULL) {
$recipient['id_mail'] = $arg[2];
$recipient['email'] = $arg[4];
$recipient['list_id'] = $arg[3];
$recipient['hash'] = $arg[5];
}
}
$result['recipients'][] = $recipient;
}
}
$this->output('<strong>Result:</strong>', CWSMBH_VERBOSE_REPORT);
$this->output($result, CWSMBH_VERBOSE_REPORT, false, true);
return $result;
}
/**
* Function to delete a message
* @param string $token : message number or filename.
* @return boolean
*/
private function processDelete($token) {
if ($this->isImapOpenMode()) {
$this->output('Process <strong>delete</strong> message <strong>' . $token . '</strong>', CWSMBH_VERBOSE_DEBUG);
return @imap_delete($this->_handler, $token);
} else {
$this->output('Process <strong>delete</strong> message <strong>' . $token . '</strong>', CWSMBH_VERBOSE_DEBUG);
return @unlink($this->_folder . $token);
}
}
/**
* Function to move a message
* @param string $token : message number or filename.
* @param string $type : 'soft' or 'hard' bounce type.
* @return boolean
*/
private function processMove($token, $type) {
if ($this->isImapOpenMode()) {
if ($type == 'soft' && !empty($this->folder_soft)) {
$this->output('Process <strong>move soft</strong> in ' . $this->folder_soft, CWSMBH_VERBOSE_DEBUG);
$this->isMailboxExists($this->folder_soft);
return @imap_mail_move($this->_handler, $token, $this->folder_soft);
} elseif ($type == 'hard' && !empty($this->folder_hard)) {
$this->output('Process <strong>move hard</strong> in ' . $this->folder_hard, CWSMBH_VERBOSE_DEBUG);
$this->isMailboxExists($this->folder_hard);
return @imap_mail_move($this->_handler, $token, $this->folder_hard);
} else {
$this->error_msg = 'The folder ' . $type . ' var is empty.';
$this->output();
return false;
}
} else {
if ($type == 'soft' && !empty($this->folder_soft)) {
if (!$this->endWith($this->folder_soft, '/')) {
$this->folder_soft .= '/';
}
if (!is_dir($this->folder_soft)) {
mkdir($this->folder_soft);
}
$this->output('Process <strong>move soft</strong> in ' . $this->folder_soft, CWSMBH_VERBOSE_DEBUG);
return @rename($this->_folder . $token, $this->folder_soft . $token);
} elseif ($type == 'hard' && !empty($this->folder_hard)) {
if (!$this->endWith($this->folder_hard, '/')) {
$this->folder_hard .= '/';
}
if (!is_dir($this->folder_hard)) {
mkdir($this->folder_hard);
}
$this->output('Process <strong>move hard</strong> in ' . $this->folder_hard, CWSMBH_VERBOSE_DEBUG);
return @rename($this->_folder . $token, $this->folder_hard . $token);
} else {
$this->error_msg = 'The folder ' . $type . ' var is empty.';
$this->output();
return false;
}
}
}
/**
* Function to determine the current open mode
* @return boolean
*/
private function isImapOpenMode() {
return $this->open_mode == CWSMBH_OPEN_MODE_IMAP;
}
/**
* Function to check if a mailbox exists. If not found, it will create it.
* @param string $mailbox : the mailbox name, must be in 'INBOX.checkmailbox' format
* @param boolean $create : whether or not to create the checkmailbox if not found, defaults to true
* @return boolean
*/
private function isMailboxExists($mailbox, $create = true) {
if (trim($mailbox) == '' || !strstr($mailbox, 'INBOX.')) {
// this is a critical error with either the mailbox name blank or an invalid mailbox name need to stop processing and exit at this point
$this->error_msg = "Invalid mailbox name for move operation. Cannot continue." . $this->_newline . "TIP: the mailbox you want to move the message to must include 'INBOX.' at the start.";
$this->output();
exit();
}
// required options for imap_open connection.
$opts = '/' . $this->service . '/' . $this->service_option;
if ($this->service_option == 'tls' || $this->service_option == 'ssl') {
$opts .= '/' . $this->cert;
}
$handler = imap_open('{' . $this->host . ':' . $this->port . $opts . '}', $this->username, $this->password, !$this->test_mode ? CL_EXPUNGE : null);
$list = imap_getmailboxes($handler, '{' . $this->host . ":" . $this->port . $opts . '}', '*');
$mailbox_found = false;
if (is_array($list)) {
foreach ($list as $key => $val) {
// get the mailbox name only
$nameArr = split('}', imap_utf7_decode($val->name));
$nameRaw = $nameArr[count($nameArr) - 1];
if ($mailbox == $nameRaw) {
$mailbox_found = true;
}
}
if ($mailbox_found === false && $create) {
@imap_createmailbox($handler, imap_utf7_encode('{' . $this->host . ':' . $this->port . $opts . '}' . $mailbox));
imap_close($handler);
return true;
} else {
imap_close($handler);
return false;
}
} else {
imap_close($handler);
return false;
}
}
/**
* Function to parse the header with some custom fields.
* @param array $ar_header : the array or plain text headers
* @return array
*/
private function parseHeader($ar_header) {
if (!is_array($ar_header)) {
$ar_header = explode("\r\n", $ar_header);
}
$ar_header = $this->parseLines($ar_header);
if (isset($ar_header['Received'])) {
$arrRec = explode("|", $ar_header['Received']);
$ar_header['Received'] = $arrRec;
}
if (isset($ar_header['Content-type'])) {
$ar_mr = explode(";", $ar_header['Content-type']);
//$ar_header['Content-type'] = '';
$ar_header['Content-type'] = array();
$ar_header['Content-type']['type'] = strtolower($ar_mr[0]);
foreach ($ar_mr as $mr) {
if (preg_match('#([^=.]*?)=(.*)#i', $mr, $matches)) {
$ar_header['Content-type'][strtolower(trim($matches[1]))] = str_replace('"', '', $matches[2]);
}
}
}
foreach ($ar_header as $key => $value) {
if (strtolower($key) == 'x-hmxmroriginalrecipient') {
unset($ar_header[$key]);
$ar_header['X-HmXmrOriginalRecipient'] = $value;
}
}
return $ar_header;
}
/**
* Function to parse body by sections.
* @param array $ar_header : the array headers
* @param string $body : the body content
* @return array
*/
private function parseBodySections($ar_header, $body) {
$sections = array();
if (is_array($ar_header) && isset($ar_header['Content-type']) && isset($ar_header['Content-type']['boundary'])) {
$ar_boundary = explode($ar_header['Content-type']['boundary'], $body);
$sections['first'] = isset($ar_boundary[1]) ? $ar_boundary[1] : null;
$sections['ar_first'] = isset($ar_boundary[1]) ? $this->parseHeader($ar_boundary[1]) : null;
$sections['machine'] = isset($ar_boundary[2]) ? $ar_boundary[2] : null;
$sections['returned'] = isset($ar_boundary[3]) ? $ar_boundary[3] : null;
}
return $sections;
}
/**
* Function to parse and process the body section machine.
* @param string $body_section_machine : the body section machine
* @return array
*/
private function parseBodySectionMachine($body_section_machine) {
$result = $this->parseDsnFields($body_section_machine);
$result['mime_header'] = $this->parseLines($result['mime_header']);
$result['per_message'] = $this->parseLines($result['per_message']);
if (!$this->isEmpty($result['per_message'], 'X-postfix-sender')) {
$ar_tmp = explode(";", $result['per_message']['X-postfix-sender']);
$result['per_message']['X-postfix-sender'] = array(
'type' => isset($ar_tmp[0]) ? trim($ar_tmp[0]) : null,
'addr' => isset($ar_tmp[1]) ? trim($ar_tmp[1]) : null
);
}
if (!$this->isEmpty($result['per_message'], 'Reporting-mta')) {
$ar_tmp = explode(";", $result['per_message']['Reporting-mta']);
$result['per_message']['Reporting-mta'] = array(
'type' => isset($ar_tmp[0]) ? trim($ar_tmp[0]) : null,
'addr' => isset($ar_tmp[1]) ? trim($ar_tmp[1]) : null
);
}
$tmp_per_recipient = array();
foreach ($result['per_recipient'] as $per_recipient) {
$ar_per_recipient = $this->parseLines(explode("\r\n", $per_recipient));
$ar_per_recipient['Final-recipient'] = isset($ar_per_recipient['Final-recipient']) ? $this->formatFinalRecipient($ar_per_recipient['Final-recipient']) : null;
$ar_per_recipient['Original-recipient'] = isset($ar_per_recipient['Original-recipient']) ? $this->formatOriginalRecipient($ar_per_recipient['Original-recipient']) : null;
$ar_per_recipient['Diagnostic-code'] = isset($ar_per_recipient['Diagnostic-code']) ? $this->formatDiagnosticCode($ar_per_recipient['Diagnostic-code']) : null;
// check if diagnostic code is a temporary failure
if (isset($ar_per_recipient['Diagnostic-code'])) {
$status_code = $this->formatStatusCode($ar_per_recipient['Diagnostic-code']['text']);
$action = $this->findActionByStatusCode($status_code);
if ($action == 'transient' && stristr($ar_per_recipient['Action'], 'failed') !== false) {
$ar_per_recipient['Action'] = 'transient';
$ar_per_recipient['Status'] = '4.3.0';
}
}
$tmp_per_recipient[] = $ar_per_recipient;
}
$result['per_recipient'] = $tmp_per_recipient;
return $result;
}
/**
* Function to parse DSN fields.
* @param string $body_section_machine : the body section machine
* @return array
*/
private function parseDsnFields($body_section_machine) {
$result = array(
'mime_header' => null,
'per_message' => null,
'per_recipient' => null
);
$dsn_fields = explode("\r\n\r\n", $body_section_machine);
$j = 0;
for ($i = 0; $i < count($dsn_fields); $i++) {
$dsn_fields[$i] = trim($dsn_fields[$i]);
if ($i == 0) {
$result['mime_header'] = $dsn_fields[$i];
} elseif ($i == 1 && !preg_match('#(Final|Original)-Recipient#', $dsn_fields[$i])) {
// second element in the array should be a per_recipient
$result['per_message'] = $dsn_fields[$i];
} else {
if ($dsn_fields[$i] == '--') {
continue;
}
$result['per_recipient'][$j] = $dsn_fields[$i];
$j++;
}
}
return $result;
}
/**
* Function to parse standard fields.
* @param string $content : a generic content
* @return array
*/
private function parseLines($content) {
$result = array();
if (!is_array($content)) {
$content = explode("\r\n", $content);
}
foreach ($content as $line) {
if (preg_match('#^([^\s.]*):\s*(.*)\s*#', trim($line), $matches)) {
$entity = ucfirst(strtolower($matches[1]));
if (empty($result[$entity])) {
$result[$entity] = trim($matches[2]);
} elseif (isset($hash['Received']) && $hash['Received']) {
if ($entity && $matches[2] && $matches[2] != $hash[$entity]) {
$result[$entity] .= "|" . trim($matches[2]);
}
}
} elseif (preg_match('/^\s+(.+)\s*/', $line) && isset($entity)) {
$result[$entity] .= ' ' . $line;
}
}
return $result;
}
/**
* Function to check if a message is a bounce via headers informations.
* @param array $ar_header : the array headers
* @return boolean
*/
private function isBounce($ar_header) {
if (!empty($ar_header)) {
if (isset($ar_header['Subject']) && preg_match('#(mail delivery failed|failure notice|warning: message|delivery status notif|delivery failure|delivery problem|spam eater|returned mail|undeliverable|returned mail|delivery errors|mail status report|mail system error|failure delivery|delivery notification|delivery has failed|undelivered mail|returned email|returning message to sender|returned to sender|message delayed|mdaemon notification|mailserver notification|mail delivery system|nondeliverable mail|mail transaction failed)|auto.{0,20}reply|vacation|(out|away|on holiday).*office#i', $ar_header['Subject'])) {
return true;
} elseif (isset($ar_header['Precedence']) && preg_match('#auto_reply#', $ar_header['Precedence'])) {
return true;
} elseif (isset($ar_header['From']) && preg_match('#auto_reply#', $ar_header['From'])) {
return true;
}
}
return false;
}
/**
* Function to check if a message is a feedback loop via headers and body informations.
* @param array $ar_header : the array headers
* @param array $body_sections : the array body sections
* @return boolean
*/
private function isFbl($ar_header, $body_sections = array()) {
if (!empty($ar_header)) {
if (isset($ar_header['Content-type']) && isset($ar_header['Content-type']['report-type']) && preg_match('#feedback-report#', $ar_header['Content-type']['report-type'])) {
return true;
} elseif (isset($ar_header['X-loop']) && preg_match('#scomp#', $ar_header['X-loop'])) {
return true;
} elseif ($this->isHotmailFbl($body_sections)) {
return true;
}
}
return false;
}
/**
* Function to check if a message is a hotmail feedback loop via body informations.
* @param array $body_sections : the array body sections
* @return boolean
*/
private function isHotmailFbl($body_sections) {
return !empty($body_sections) && isset($body_sections['ar_first']) && isset($body_sections['ar_first']['X-HmXmrOriginalRecipient']);
}
/**
* Function to check if a message is a specific RFC 1892 report via headers informations.
* @param array $ar_header : the array headers
* @return boolean
*/
private function isRfc1892Report($ar_header) {
if (!empty($ar_header)) {
if (!$this->isEmpty($ar_header, 'Content-type') && !$this->isEmpty($ar_header['Content-type'], 'type') && $ar_header['Content-type']['type'] == 'multipart/report') {
if (!$this->isEmpty($ar_header['Content-type'], 'report-type') && $ar_header['Content-type']['report-type'] == 'delivery-status') {
if (!$this->isEmpty($ar_header['Content-type'], 'boundary') && $ar_header['Content-type']['boundary'] !== '') {
return true;
}
}
}
}
return false;
}
/**
* Format the content of a message.
* @param string $content : a generic content
* @return string
*/
private static function formatContent($content) {
if (!empty($content)) {
$content = str_replace("\r\n", "\n", $content);
$content = str_replace("\n", "\r\n", $content);
$content = str_replace("=\r\n", "", $content);
$content = str_replace("=3D", "=", $content);
$content = str_replace("=09", " ", $content);
}
return $content;
}
/**
* Format the final recipient with e-mail and type
* @param string $final_recipient : the final recipient
* @return array
*/
private function formatFinalRecipient($final_recipient) {
$result = array(
'addr' => '',
'type' => ''
);
$ar_final_recipient = explode(";", $final_recipient);
if (!empty($ar_final_recipient)) {
if (strpos($ar_final_recipient[0], '@') !== false) {
$result['addr'] = $this->extractEmail($ar_final_recipient[0]);
$result['type'] = !$this->isEmpty($ar_final_recipient, 1) ? trim($ar_final_recipient[1]) : 'unknown';
} else {
$result['addr'] = $this->extractEmail($ar_final_recipient[1]);
$result['type'] = !$this->isEmpty($ar_final_recipient, 0) ? trim($ar_final_recipient[0]) : '';
}
}
return $result;
}
/**
* Format the original recipient with e-mail and type
* @param string $original_recipient : the original recipient
* @return array
*/
private function formatOriginalRecipient($original_recipient) {
$result = array(
'addr' => '',
'type' => ''
);
$ar_original_recipient = explode(";", $original_recipient);
if (!empty($ar_original_recipient)) {
$result['addr'] = $this->extractEmail($ar_original_recipient[1]);
$result['type'] = !$this->isEmpty($ar_original_recipient, 0) ? trim($ar_original_recipient[0]) : '';
}
return $result;
}
/**
* Format the diagnostic code with type and text
* @param string $diag_code : the diagnostic recipient
* @return array
*/
private function formatDiagnosticCode($diag_code) {
$result = array(
'type' => '',
'text' => ''
);
$ar_diag_code = explode(";", $diag_code);
if (!empty($ar_diag_code)) {
$result['type'] = !$this->isEmpty($ar_diag_code, 0) ? trim($ar_diag_code[0]) : '';
$result['text'] = !$this->isEmpty($ar_diag_code, 1) ? trim($ar_diag_code[1]) : '';
}
return $result;
}
/**
* Find the recipient e-mail
* @param string $rcpt : the recipient headers
* @return string
*/
private function findEmail($rcpt) {
if (isset($rcpt['Original-recipient']) && !$this->isEmpty($rcpt['Original-recipient'], 'addr')) {
return $this->extractEmail($rcpt['Original-recipient']['addr']);
} elseif (isset($rcpt['Final-recipient']) && !$this->isEmpty($rcpt['Final-recipient'], 'addr')) {
return $this->extractEmail($rcpt['Final-recipient']['addr']);
}
return null;
}
/**
* Find the e-mail(s) from the body section first
* @param string $body_section_first : the body section first
* @return array
*/
private function findEmails($body_section_first) {
$result = array();
if (!empty($body_section_first)) {
$ar_body_section_first = explode("\r\n", $body_section_first);
foreach ($ar_body_section_first as $line) {
if (preg_match("/\b([A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b/i", $line, $match)) {
if (!in_array($match[1], $result)) {
$result[] = $match[1];
}
}
}
}
return $result;
}
/**
* Find an action by the status code.
* @param string $status_code : the status code
* @return string
*/
private function findActionByStatusCode($status_code) {
$result = null;
if (!empty($status_code)) {
$status_code = $this->formatStatusCode($status_code);
$ar_status_code = explode(".", $status_code);
switch ($ar_status_code[0]) {
case '2':
$result = 'success';
break;
case '4':
$result = 'transient';
break;
case '5':
$result = 'failed';
break;
default:
return '';
break;
}
}
if (!empty($result)) {
$this->output('Action type <strong>' . $result . '</strong> found via status code', CWSMBH_VERBOSE_DEBUG);
}
return $result;
}
/**
* Find an status code in body content.
* @param string $body : the body
* @return string
*/
private function findStatusCodeByRecipient($body) {
$ar_body = explode("\r\n", $body);
foreach ($ar_body as $body_line) {
$body_line = trim($body_line);
foreach ($this->_status_code_resolver as $bounce_body => $bounce_code) {
if (preg_match('#' . $bounce_body . '#is', $body_line, $matches)) {
$status_code = isset($matches[1]) ? $matches[1] : $bounce_code;
$status_code = $this->formatStatusCode($status_code);
$this->output('Status code <strong>' . $status_code . '</strong> found via code resolver pattern : <i>' . $bounce_body . '</i>', CWSMBH_VERBOSE_DEBUG);
return $status_code;
}
}
// RFC 1893 (http://www.ietf.org/rfc/rfc1893.txt) return code
if (preg_match('#\W([245]\.[01234567]\.[012345678])\W#', $body_line, $matches)) {
if (stripos($body_line, 'Message-ID') !== false) {
break;
}
$status_code = $matches[1];
$status_code = $this->formatStatusCode($status_code);
$this->output('Status code <strong>' . $status_code . '</strong> found via RFC 1893.', CWSMBH_VERBOSE_DEBUG);
return $status_code;
}
// RFC 821 (http://www.ietf.org/rfc/rfc821.txt) return code
if (preg_match('#\]?: ([45][01257][012345]) #', $body_line, $matches) || preg_match('#^([45][01257][012345]) (?:.*?)(?:denied|inactive|deactivated|rejected|disabled|unknown|no such|not (?:our|activated|a valid))+#i', $body_line, $matches)) {
$status_code = $matches[1];
// map to new RFC
if ($status_code == '450' || $status_code == '550' || $status_code == '551' || $status_code == '554') {
$status_code = '511';
} elseif ($status_code == '452' || $status_code == '552') {
$status_code = '422';
} elseif ($status_code == '421') {
$status_code = '432';
}
$status_code = $this->formatStatusCode($status_code);
$this->output('Status code <strong>' . $status_code . '</strong> found and converted via RFC 821.', CWSMBH_VERBOSE_DEBUG);
return $status_code;
}
}
return null;
}
/**
* Get explanations from DSN status code via the RFC 1893 : http://www.ietf.org/rfc/rfc1893.txt
* @param string $status_code : consist of three numerical fields separated by ".".
* @return array $result : an array include the following fields : 'code', 'first_subcode', 'second_subcode', 'third_subcode'.
*/
public function findStatusExplanationsByCode($status_code) {
$result = $this->_status_result;
$status_code = $this->formatStatusCode($status_code);
if (!$this->isEmpty($status_code)) {
$ar_status_code = explode(".", $status_code);
if ($ar_status_code != null && count($ar_status_code) == 3) {
$result['code'] = $status_code;
// First sub-code : indicates whether the delivery attempt was successful
switch ($ar_status_code[0]) {
case '2':
$result[CWSMBH_STATUS_FIRST_SUBCODE] = array(
'title' => 'Success',
'desc' => 'Success specifies that the DSN is reporting a positive delivery action. Detail sub-codes may provide notification of transformations required for delivery.'
);
break;
case '4':
$result[CWSMBH_STATUS_FIRST_SUBCODE] = array(
'title' => 'Persistent Transient Failure',
'desc' => 'A persistent transient failure is one in which the message as sent is valid, but some temporary event prevents the successful sending of the message. Sending in the future may be successful.'
);
break;
case '5':
$result[CWSMBH_STATUS_FIRST_SUBCODE] = array(
'title' => 'Permanent Failure',
'desc' => 'A permanent failure is one which is not likely to be resolved by resending the message in the current form. Some change to the message or the destination must be made for successful delivery.'
);
break;
default:
break;
}
// Second sub-code : indicates the probable source of any delivery anomalies
switch ($ar_status_code[1]) {
case '0':
$result[CWSMBH_STATUS_SECOND_SUBCODE] = array(
'title' => 'Other or Undefined Status',
'desc' => 'There is no additional subject information available.'
);
break;
case '1':
$result[CWSMBH_STATUS_SECOND_SUBCODE] = array(
'title' => 'Addressing Status',
'desc' => 'The address status reports on the originator or destination address. It may include address syntax or validity. These errors can generally be corrected by the sender and retried.'
);
break;
case '2':
$result[CWSMBH_STATUS_SECOND_SUBCODE] = array(
'title' => 'Mailbox Status',
'desc' => 'Mailbox status indicates that something having to do with the mailbox has cause this DSN. Mailbox issues are assumed to be under the general control of the recipient.'
);
break;
case '3':
$result[CWSMBH_STATUS_SECOND_SUBCODE] = array(
'title' => 'Mail System Status',
'desc' => 'Mail system status indicates that something having to do with the destination system has caused this DSN. System issues are assumed to be under the general control of the destination system administrator.'
);
break;
case '4':
$result[CWSMBH_STATUS_SECOND_SUBCODE] = array(
'title' => 'Network and Routing Status',
'desc' => 'The networking or routing codes report status about the delivery system itself. These system components include any necessary infrastructure such as directory and routing services. Network issues are assumed to be under the control of the destination or intermediate system administrator.'
);
break;
case '5':
$result[CWSMBH_STATUS_SECOND_SUBCODE] = array(
'title' => 'Mail Delivery Protocol Status',
'desc' => 'The mail delivery protocol status codes report failures involving the message delivery protocol. These failures include the full range of problems resulting from implementation errors or an unreliable connection. Mail delivery protocol issues may be controlled by many parties including the originating system, destination system, or intermediate system administrators.'
);
break;
case '6':
$result[CWSMBH_STATUS_SECOND_SUBCODE] = array(
'title' => 'Message Content or Media Status',
'desc' => 'The message content or media status codes report failures involving the content of the message. These codes report failures due to translation, transcoding, or otherwise unsupported message media. Message content or media issues are under the control of both the sender and the receiver, both of whom must support a common set of supported content-types.'
);
break;
case '7':
$result[CWSMBH_STATUS_SECOND_SUBCODE] = array(
'title' => 'Security or Policy Status',
'desc' => 'The security or policy status codes report failures involving policies such as per-recipient or per-host filtering and cryptographic operations. Security and policy status issues are assumed to be under the control of either or both the sender and recipient. Both the sender and recipient must permit the exchange of messages and arrange the exchange of necessary keys and certificates for cryptographic operations.'
);
break;
default:
break;
}
// Second and Third sub-code : indicates a precise error condition
switch ($ar_status_code[1] . '.' . $ar_status_code[2]) {
case '0.0':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Other undefined Status',
'desc' => 'Other undefined status is the only undefined error code. It should be used for all errors for which only the class of the error is known.'
);
break;
case '1.0':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Other address status',
'desc' => 'Something about the address specified in the message caused this DSN.'
);
break;
case '1.1':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Bad destination mailbox address',
'desc' => 'The mailbox specified in the address does not exist. For Internet mail names, this means the address portion to the left of the @ sign is invalid. This code is only useful for permanent failures.'
);
break;
case '1.2':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Bad destination system address',
'desc' => 'The destination system specified in the address does not exist or is incapable of accepting mail. For Internet mail names, this means the address portion to the right of the @ is invalid for mail. This codes is only useful for permanent failures.'
);
break;
case '1.3':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Bad destination mailbox address syntax',
'desc' => 'The destination address was syntactically invalid. This can apply to any field in the address. This code is only useful for permanent failures.'
);
break;
case '1.4':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Destination mailbox address ambiguous',
'desc' => 'The mailbox address as specified matches one or more recipients on the destination system. This may result if a heuristic address mapping algorithm is used to map the specified address to a local mailbox name.'
);
break;
case '1.5':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Destination address valid',
'desc' => 'This mailbox address as specified was valid. This status code should be used for positive delivery reports.'
);
break;
case '1.6':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Destination mailbox has moved, No forwarding address',
'desc' => 'The mailbox address provided was at one time valid, but mail is no longer being accepted for that address. This code is only useful for permanent failures.'
);
break;
case '1.7':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Bad sender\'s mailbox address syntax',
'desc' => 'The sender\'s address was syntactically invalid. This can apply to any field in the address.'
);
break;
case '1.8':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Bad sender\'s system address',
'desc' => 'The sender\'s system specified in the address does not exist or is incapable of accepting return mail. For domain names, this means the address portion to the right of the @ is invalid for mail.'
);
break;
case '2.0':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Other or undefined mailbox status',
'desc' => 'The mailbox exists, but something about the destination mailbox has caused the sending of this DSN.'
);
break;
case '2.1':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Mailbox disabled, not accepting messages',
'desc' => 'The mailbox exists, but is not accepting messages. This may be a permanent error if the mailbox will never be re-enabled or a transient error if the mailbox is only temporarily disabled.'
);
break;
case '2.2':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Mailbox full',
'desc' => 'The mailbox is full because the user has exceeded a per-mailbox administrative quota or physical capacity. The general semantics implies that the recipient can delete messages to make more space available. This code should be used as a persistent transient failure.'
);
break;
case '2.3':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Message length exceeds administrative limit',
'desc' => 'A per-mailbox administrative message length limit has been exceeded. This status code should be used when the per-mailbox message length limit is less than the general system limit. This code should be used as a permanent failure.'
);
break;
case '2.4':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Mailing list expansion problem',
'desc' => 'The mailbox is a mailing list address and the mailing list was unable to be expanded. This code may represent a permanent failure or a persistent transient failure.'
);
break;
case '3.0':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Other or undefined mail system status',
'desc' => 'The destination system exists and normally accepts mail, but something about the system has caused the generation of this DSN.'
);
break;
case '3.1':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Mail system full',
'desc' => 'Mail system storage has been exceeded. The general semantics imply that the individual recipient may not be able to delete material to make room for additional messages. This is useful only as a persistent transient error.'
);
break;
case '3.2':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'System not accepting network messages',
'desc' => 'The host on which the mailbox is resident is not accepting messages. Examples of such conditions include an immanent shutdown, excessive load, or system maintenance. This is useful for both permanent and permanent transient errors.'
);
break;
case '3.3':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'System not capable of selected features',
'desc' => 'Selected features specified for the message are not supported by the destination system. This can occur in gateways when features from one domain cannot be mapped onto the supported feature in another.'
);
break;
case '3.4':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Message too big for system',
'desc' => 'The message is larger than per-message size limit. This limit may either be for physical or administrative reasons. This is useful only as a permanent error.'
);
break;
case '3.5':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'System incorrectly configured',
'desc' => 'The system is not configured in a manner which will permit it to accept this message.'
);
break;
case '4.0':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Other or undefined network or routing status',
'desc' => 'Something went wrong with the networking, but it is not clear what the problem is, or the problem cannot be well expressed with any of the other provided detail codes.'
);
break;
case '4.1':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'No answer from host',
'desc' => 'The outbound connection attempt was not answered, either because the remote system was busy, or otherwise unable to take a call. This is useful only as a persistent transient error.'
);
break;
case '4.2':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Bad connection',
'desc' => 'The outbound connection was established, but was otherwise unable to complete the message transaction, either because of time-out, or inadequate connection quality. This is useful only as a persistent transient error.'
);
break;
case '4.3':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Directory server failure',
'desc' => 'The network system was unable to forward the message, because a directory server was unavailable. This is useful only as a persistent transient error. The inability to connect to an Internet DNS server is one example of the directory server failure error.'
);
break;
case '4.4':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Unable to route',
'desc' => 'The mail system was unable to determine the next hop for the message because the necessary routing information was unavailable from the directory server. This is useful for both permanent and persistent transient errors. A DNS lookup returning only an SOA (Start of Administration) record for a domain name is one example of the unable to route error.'
);
break;
case '4.5':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Mail system congestion',
'desc' => 'The mail system was unable to deliver the message because the mail system was congested. This is useful only as a persistent transient error.'
);
break;
case '4.6':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Routing loop detected',
'desc' => 'A routing loop caused the message to be forwarded too many times, either because of incorrect routing tables or a user forwarding loop. This is useful only as a persistent transient error.'
);
break;
case '4.7':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Delivery time expired',
'desc' => 'The message was considered too old by the rejecting system, either because it remained on that host too long or because the time-to-live value specified by the sender of the message was exceeded. If possible, the code for the actual problem found when delivery was attempted should be returned rather than this code. This is useful only as a persistent transient error.'
);
break;
case '5.0':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Other or undefined protocol status',
'desc' => 'Something was wrong with the protocol necessary to deliver the message to the next hop and the problem cannot be well expressed with any of the other provided detail codes.'
);
break;
case '5.1':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Invalid command',
'desc' => 'A mail transaction protocol command was issued which was either out of sequence or unsupported. This is useful only as a permanent error.'
);
break;
case '5.2':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Syntax error',
'desc' => 'A mail transaction protocol command was issued which could not be interpreted, either because the syntax was wrong or the command is unrecognized. This is useful only as a permanent error.'
);
break;
case '5.3':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Too many recipients',
'desc' => 'More recipients were specified for the message than could have been delivered by the protocol. This error should normally result in the segmentation of the message into two, the remainder of the recipients to be delivered on a subsequent delivery attempt. It is included in this list in the event that such segmentation is not possible.'
);
break;
case '5.4':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Invalid command arguments',
'desc' => 'A valid mail transaction protocol command was issued with invalid arguments, either because the arguments were out of range or represented unrecognized features. This is useful only as a permanent error.'
);
break;
case '5.5':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Wrong protocol version',
'desc' => 'A protocol version mis-match existed which could not be automatically resolved by the communicating parties.'
);
break;
case '6.0':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Other or undefined media error',
'desc' => 'Something about the content of a message caused it to be considered undeliverable and the problem cannot be well expressed with any of the other provided detail codes.'
);
break;
case '6.1':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Media not supported',
'desc' => 'The media of the message is not supported by either the delivery protocol or the next system in the forwarding path. This is useful only as a permanent error.'
);
break;
case '6.2':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Conversion required and prohibited',
'desc' => 'The content of the message must be converted before it can be delivered and such conversion is not permitted. Such prohibitions may be the expression of the sender in the message itself or the policy of the sending host.'
);
break;
case '6.3':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Conversion required but not supported',
'desc' => 'The message content must be converted to be forwarded but such conversion is not possible or is not practical by a host in the forwarding path. This condition may result when an ESMTP gateway supports 8bit transport but is not able to downgrade the message to 7 bit as required for the next hop.'
);
break;
case '6.4':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Conversion with loss performed',
'desc' => 'This is a warning sent to the sender when message delivery was successfully but when the delivery required a conversion in which some data was lost. This may also be a permanant error if the sender has indicated that conversion with loss is prohibited for the message.'
);
break;
case '6.5':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Conversion Failed',
'desc' => 'A conversion was required but was unsuccessful. This may be useful as a permanent or persistent temporary notification.'
);
break;
case '7.0':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Other or undefined security status',
'desc' => 'Something related to security caused the message to be returned, and the problem cannot be well expressed with any of the other provided detail codes. This status code may also be used when the condition cannot be further described because of security policies in force.'
);
break;
case '7.1':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Delivery not authorized, message refused',
'desc' => 'The sender is not authorized to send to the destination. This can be the result of per-host or per-recipient filtering. This memo does not discuss the merits of any such filtering, but provides a mechanism to report such. This is useful only as a permanent error.'
);
break;
case '7.2':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Mailing list expansion prohibited',
'desc' => 'The sender is not authorized to send a message to the intended mailing list. This is useful only as a permanent error.'
);
break;
case '7.3':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Security conversion required but not possible',
'desc' => 'A conversion from one secure messaging protocol to another was required for delivery and such conversion was not possible. This is useful only as a permanent error.'
);
break;
case '7.4':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Security features not supported',
'desc' => 'A message contained security features such as secure authentication which could not be supported on the delivery protocol. This is useful only as a permanent error.'
);
break;
case '7.5':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Cryptographic failure',
'desc' => 'A transport system otherwise authorized to validate or decrypt a message in transport was unable to do so because necessary information such as key was not available or such information was invalid.'
);
break;
case '7.6':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Cryptographic algorithm not supported',
'desc' => 'A transport system otherwise authorized to validate or decrypt a message was unable to do so because the necessary algorithm was not supported.'
);
break;
case '7.7':
$result[CWSMBH_STATUS_THIRD_SUBCODE] = array(
'title' => 'Message integrity failure',
'desc' => 'A transport system otherwise authorized to validate a message was unable to do so because the message was corrupted or altered. This may be useful as a permanent, transient persistent, or successful delivery code.'
);
break;
default:
break;
}
}
}
return $result;
}
private static function endWith($string, $search) {
$length = strlen($search);
$start = $length * -1;
return (substr($string, $start) === $search);
}
private static function isEmpty($value, $key = '') {
if (!empty($key) && is_array($value)) {
return !array_key_exists($key, $value) || empty($value[$key]);
} else {
return !isset($value) || empty($value);
}
}
private static function extractEmail($string) {
$result = $string;
$ar_result = preg_split('#[ \"\'\<\>:\(\)\[\]]#', $string);
foreach ($ar_result as $result) {
if (strpos($result, '@') !== false) {
return $result;
}
}
return $result;
}
private static function formatStatusCode($status_code) {
if (!empty($status_code)) {
if (preg_match('#(\d\d\d)\s#', $status_code, $match)) {
$status_code = $match[1];
} elseif (preg_match('#(\d\.\d\.\d)\s#', $status_code, $match)) {
$status_code = $match[1];
}
if (preg_match('#([245]\.[01234567]\.[012345678])(.*)#', $status_code, $match)) {
return $match[1];
} elseif (preg_match('#([245][01234567][012345678])(.*)#', $status_code, $match)) {
preg_match_all('#.#', $match[1], $ar_status_code);
if (is_array($ar_status_code[0]) && count($ar_status_code[0]) == 3) {
return implode(".", $ar_status_code[0]);
}
}
}
return null;
}
}
?>
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.mobile.php'
<?php
/**
* Mobile Detect Library
* =====================
*
* Motto: "Every business should have a mobile detection script to detect mobile readers"
*
* Mobile_Detect is a lightweight PHP class for detecting mobile devices (including tablets).
* It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.
*
* @author Current authors: Serban Ghita <serbanghita@gmail.com>
* Nick Ilyin <nick.ilyin@gmail.com>
*
* Original author: Victor Stanciu <vic.stanciu@gmail.com>
*
* @license Code and contributions have 'MIT License'
* More details: https://github.com/serbanghita/Mobile-Detect/blob/master/LICENSE.txt
*
* @link Homepage: http://mobiledetect.net
* GitHub Repo: https://github.com/serbanghita/Mobile-Detect
* Google Code: http://code.google.com/p/php-mobile-detect/
* README: https://github.com/serbanghita/Mobile-Detect/blob/master/README.md
* HOWTO: https://github.com/serbanghita/Mobile-Detect/wiki/Code-examples
*
* @version 2.8.30
*/
class Mobile_Detect
{
/**
* Mobile detection type.
*
* @deprecated since version 2.6.9
*/
const DETECTION_TYPE_MOBILE = 'mobile';
/**
* Extended detection type.
*
* @deprecated since version 2.6.9
*/
const DETECTION_TYPE_EXTENDED = 'extended';
/**
* A frequently used regular expression to extract version #s.
*
* @deprecated since version 2.6.9
*/
const VER = '([\w._\+]+)';
/**
* Top-level device.
*/
const MOBILE_GRADE_A = 'A';
/**
* Mid-level device.
*/
const MOBILE_GRADE_B = 'B';
/**
* Low-level device.
*/
const MOBILE_GRADE_C = 'C';
/**
* Stores the version number of the current release.
*/
const VERSION = '2.8.30';
/**
* A type for the version() method indicating a string return value.
*/
const VERSION_TYPE_STRING = 'text';
/**
* A type for the version() method indicating a float return value.
*/
const VERSION_TYPE_FLOAT = 'float';
/**
* A cache for resolved matches
* @var array
*/
protected $cache = array();
/**
* The User-Agent HTTP header is stored in here.
* @var string
*/
protected $userAgent = null;
/**
* HTTP headers in the PHP-flavor. So HTTP_USER_AGENT and SERVER_SOFTWARE.
* @var array
*/
protected $httpHeaders = array();
/**
* CloudFront headers. E.g. CloudFront-Is-Desktop-Viewer, CloudFront-Is-Mobile-Viewer & CloudFront-Is-Tablet-Viewer.
* @var array
*/
protected $cloudfrontHeaders = array();
/**
* The matching Regex.
* This is good for debug.
* @var string
*/
protected $matchingRegex = null;
/**
* The matches extracted from the regex expression.
* This is good for debug.
* @var string
*/
protected $matchesArray = null;
/**
* The detection type, using self::DETECTION_TYPE_MOBILE or self::DETECTION_TYPE_EXTENDED.
*
* @deprecated since version 2.6.9
*
* @var string
*/
protected $detectionType = self::DETECTION_TYPE_MOBILE;
/**
* HTTP headers that trigger the 'isMobile' detection
* to be true.
*
* @var array
*/
protected static $mobileHeaders = array(
'HTTP_ACCEPT' => array('matches' => array(
// Opera Mini; @reference: http://dev.opera.com/articles/view/opera-binary-markup-language/
'application/x-obml2d',
// BlackBerry devices.
'application/vnd.rim.html',
'text/vnd.wap.wml',
'application/vnd.wap.xhtml+xml'
)),
'HTTP_X_WAP_PROFILE' => null,
'HTTP_X_WAP_CLIENTID' => null,
'HTTP_WAP_CONNECTION' => null,
'HTTP_PROFILE' => null,
// Reported by Opera on Nokia devices (eg. C3).
'HTTP_X_OPERAMINI_PHONE_UA' => null,
'HTTP_X_NOKIA_GATEWAY_ID' => null,
'HTTP_X_ORANGE_ID' => null,
'HTTP_X_VODAFONE_3GPDPCONTEXT' => null,
'HTTP_X_HUAWEI_USERID' => null,
// Reported by Windows Smartphones.
'HTTP_UA_OS' => null,
// Reported by Verizon, Vodafone proxy system.
'HTTP_X_MOBILE_GATEWAY' => null,
// Seen this on HTC Sensation. SensationXE_Beats_Z715e.
'HTTP_X_ATT_DEVICEID' => null,
// Seen this on a HTC.
'HTTP_UA_CPU' => array('matches' => array('ARM')),
);
/**
* List of mobile devices (phones).
*
* @var array
*/
protected static $phoneDevices = array(
'iPhone' => '\biPhone\b|\biPod\b', // |\biTunes
'BlackBerry' => 'BlackBerry|\bBB10\b|rim[0-9]+',
'HTC' => 'HTC|HTC.*(Sensation|Evo|Vision|Explorer|6800|8100|8900|A7272|S510e|C110e|Legend|Desire|T8282)|APX515CKT|Qtek9090|APA9292KT|HD_mini|Sensation.*Z710e|PG86100|Z715e|Desire.*(A8181|HD)|ADR6200|ADR6400L|ADR6425|001HT|Inspire 4G|Android.*\bEVO\b|T-Mobile G1|Z520m|Android [0-9.]+; Pixel',
'Nexus' => 'Nexus One|Nexus S|Galaxy.*Nexus|Android.*Nexus.*Mobile|Nexus 4|Nexus 5|Nexus 6',
// @todo: Is 'Dell Streak' a tablet or a phone? ;)
'Dell' => 'Dell[;]? (Streak|Aero|Venue|Venue Pro|Flash|Smoke|Mini 3iX)|XCD28|XCD35|\b001DL\b|\b101DL\b|\bGS01\b',
'Motorola' => 'Motorola|DROIDX|DROID BIONIC|\bDroid\b.*Build|Android.*Xoom|HRI39|MOT-|A1260|A1680|A555|A853|A855|A953|A955|A956|Motorola.*ELECTRIFY|Motorola.*i1|i867|i940|MB200|MB300|MB501|MB502|MB508|MB511|MB520|MB525|MB526|MB611|MB612|MB632|MB810|MB855|MB860|MB861|MB865|MB870|ME501|ME502|ME511|ME525|ME600|ME632|ME722|ME811|ME860|ME863|ME865|MT620|MT710|MT716|MT720|MT810|MT870|MT917|Motorola.*TITANIUM|WX435|WX445|XT300|XT301|XT311|XT316|XT317|XT319|XT320|XT390|XT502|XT530|XT531|XT532|XT535|XT603|XT610|XT611|XT615|XT681|XT701|XT702|XT711|XT720|XT800|XT806|XT860|XT862|XT875|XT882|XT883|XT894|XT901|XT907|XT909|XT910|XT912|XT928|XT926|XT915|XT919|XT925|XT1021|\bMoto E\b|XT1068|XT1092',
'Samsung' => '\bSamsung\b|SM-G950F|SM-G955F|SM-G9250|GT-19300|SGH-I337|BGT-S5230|GT-B2100|GT-B2700|GT-B2710|GT-B3210|GT-B3310|GT-B3410|GT-B3730|GT-B3740|GT-B5510|GT-B5512|GT-B5722|GT-B6520|GT-B7300|GT-B7320|GT-B7330|GT-B7350|GT-B7510|GT-B7722|GT-B7800|GT-C3010|GT-C3011|GT-C3060|GT-C3200|GT-C3212|GT-C3212I|GT-C3262|GT-C3222|GT-C3300|GT-C3300K|GT-C3303|GT-C3303K|GT-C3310|GT-C3322|GT-C3330|GT-C3350|GT-C3500|GT-C3510|GT-C3530|GT-C3630|GT-C3780|GT-C5010|GT-C5212|GT-C6620|GT-C6625|GT-C6712|GT-E1050|GT-E1070|GT-E1075|GT-E1080|GT-E1081|GT-E1085|GT-E1087|GT-E1100|GT-E1107|GT-E1110|GT-E1120|GT-E1125|GT-E1130|GT-E1160|GT-E1170|GT-E1175|GT-E1180|GT-E1182|GT-E1200|GT-E1210|GT-E1225|GT-E1230|GT-E1390|GT-E2100|GT-E2120|GT-E2121|GT-E2152|GT-E2220|GT-E2222|GT-E2230|GT-E2232|GT-E2250|GT-E2370|GT-E2550|GT-E2652|GT-E3210|GT-E3213|GT-I5500|GT-I5503|GT-I5700|GT-I5800|GT-I5801|GT-I6410|GT-I6420|GT-I7110|GT-I7410|GT-I7500|GT-I8000|GT-I8150|GT-I8160|GT-I8190|GT-I8320|GT-I8330|GT-I8350|GT-I8530|GT-I8700|GT-I8703|GT-I8910|GT-I9000|GT-I9001|GT-I9003|GT-I9010|GT-I9020|GT-I9023|GT-I9070|GT-I9082|GT-I9100|GT-I9103|GT-I9220|GT-I9250|GT-I9300|GT-I9305|GT-I9500|GT-I9505|GT-M3510|GT-M5650|GT-M7500|GT-M7600|GT-M7603|GT-M8800|GT-M8910|GT-N7000|GT-S3110|GT-S3310|GT-S3350|GT-S3353|GT-S3370|GT-S3650|GT-S3653|GT-S3770|GT-S3850|GT-S5210|GT-S5220|GT-S5229|GT-S5230|GT-S5233|GT-S5250|GT-S5253|GT-S5260|GT-S5263|GT-S5270|GT-S5300|GT-S5330|GT-S5350|GT-S5360|GT-S5363|GT-S5369|GT-S5380|GT-S5380D|GT-S5560|GT-S5570|GT-S5600|GT-S5603|GT-S5610|GT-S5620|GT-S5660|GT-S5670|GT-S5690|GT-S5750|GT-S5780|GT-S5830|GT-S5839|GT-S6102|GT-S6500|GT-S7070|GT-S7200|GT-S7220|GT-S7230|GT-S7233|GT-S7250|GT-S7500|GT-S7530|GT-S7550|GT-S7562|GT-S7710|GT-S8000|GT-S8003|GT-S8500|GT-S8530|GT-S8600|SCH-A310|SCH-A530|SCH-A570|SCH-A610|SCH-A630|SCH-A650|SCH-A790|SCH-A795|SCH-A850|SCH-A870|SCH-A890|SCH-A930|SCH-A950|SCH-A970|SCH-A990|SCH-I100|SCH-I110|SCH-I400|SCH-I405|SCH-I500|SCH-I510|SCH-I515|SCH-I600|SCH-I730|SCH-I760|SCH-I770|SCH-I830|SCH-I910|SCH-I920|SCH-I959|SCH-LC11|SCH-N150|SCH-N300|SCH-R100|SCH-R300|SCH-R351|SCH-R400|SCH-R410|SCH-T300|SCH-U310|SCH-U320|SCH-U350|SCH-U360|SCH-U365|SCH-U370|SCH-U380|SCH-U410|SCH-U430|SCH-U450|SCH-U460|SCH-U470|SCH-U490|SCH-U540|SCH-U550|SCH-U620|SCH-U640|SCH-U650|SCH-U660|SCH-U700|SCH-U740|SCH-U750|SCH-U810|SCH-U820|SCH-U900|SCH-U940|SCH-U960|SCS-26UC|SGH-A107|SGH-A117|SGH-A127|SGH-A137|SGH-A157|SGH-A167|SGH-A177|SGH-A187|SGH-A197|SGH-A227|SGH-A237|SGH-A257|SGH-A437|SGH-A517|SGH-A597|SGH-A637|SGH-A657|SGH-A667|SGH-A687|SGH-A697|SGH-A707|SGH-A717|SGH-A727|SGH-A737|SGH-A747|SGH-A767|SGH-A777|SGH-A797|SGH-A817|SGH-A827|SGH-A837|SGH-A847|SGH-A867|SGH-A877|SGH-A887|SGH-A897|SGH-A927|SGH-B100|SGH-B130|SGH-B200|SGH-B220|SGH-C100|SGH-C110|SGH-C120|SGH-C130|SGH-C140|SGH-C160|SGH-C170|SGH-C180|SGH-C200|SGH-C207|SGH-C210|SGH-C225|SGH-C230|SGH-C417|SGH-C450|SGH-D307|SGH-D347|SGH-D357|SGH-D407|SGH-D415|SGH-D780|SGH-D807|SGH-D980|SGH-E105|SGH-E200|SGH-E315|SGH-E316|SGH-E317|SGH-E335|SGH-E590|SGH-E635|SGH-E715|SGH-E890|SGH-F300|SGH-F480|SGH-I200|SGH-I300|SGH-I320|SGH-I550|SGH-I577|SGH-I600|SGH-I607|SGH-I617|SGH-I627|SGH-I637|SGH-I677|SGH-I700|SGH-I717|SGH-I727|SGH-i747M|SGH-I777|SGH-I780|SGH-I827|SGH-I847|SGH-I857|SGH-I896|SGH-I897|SGH-I900|SGH-I907|SGH-I917|SGH-I927|SGH-I937|SGH-I997|SGH-J150|SGH-J200|SGH-L170|SGH-L700|SGH-M110|SGH-M150|SGH-M200|SGH-N105|SGH-N500|SGH-N600|SGH-N620|SGH-N625|SGH-N700|SGH-N710|SGH-P107|SGH-P207|SGH-P300|SGH-P310|SGH-P520|SGH-P735|SGH-P777|SGH-Q105|SGH-R210|SGH-R220|SGH-R225|SGH-S105|SGH-S307|SGH-T109|SGH-T119|SGH-T139|SGH-T209|SGH-T219|SGH-T229|SGH-T239|SGH-T249|SGH-T259|SGH-T309|SGH-T319|SGH-T329|SGH-T339|SGH-T349|SGH-T359|SGH-T369|SGH-T379|SGH-T409|SGH-T429|SGH-T439|SGH-T459|SGH-T469|SGH-T479|SGH-T499|SGH-T509|SGH-T519|SGH-T539|SGH-T559|SGH-T589|SGH-T609|SGH-T619|SGH-T629|SGH-T639|SGH-T659|SGH-T669|SGH-T679|SGH-T709|SGH-T719|SGH-T729|SGH-T739|SGH-T746|SGH-T749|SGH-T759|SGH-T769|SGH-T809|SGH-T819|SGH-T839|SGH-T919|SGH-T929|SGH-T939|SGH-T959|SGH-T989|SGH-U100|SGH-U200|SGH-U800|SGH-V205|SGH-V206|SGH-X100|SGH-X105|SGH-X120|SGH-X140|SGH-X426|SGH-X427|SGH-X475|SGH-X495|SGH-X497|SGH-X507|SGH-X600|SGH-X610|SGH-X620|SGH-X630|SGH-X700|SGH-X820|SGH-X890|SGH-Z130|SGH-Z150|SGH-Z170|SGH-ZX10|SGH-ZX20|SHW-M110|SPH-A120|SPH-A400|SPH-A420|SPH-A460|SPH-A500|SPH-A560|SPH-A600|SPH-A620|SPH-A660|SPH-A700|SPH-A740|SPH-A760|SPH-A790|SPH-A800|SPH-A820|SPH-A840|SPH-A880|SPH-A900|SPH-A940|SPH-A960|SPH-D600|SPH-D700|SPH-D710|SPH-D720|SPH-I300|SPH-I325|SPH-I330|SPH-I350|SPH-I500|SPH-I600|SPH-I700|SPH-L700|SPH-M100|SPH-M220|SPH-M240|SPH-M300|SPH-M305|SPH-M320|SPH-M330|SPH-M350|SPH-M360|SPH-M370|SPH-M380|SPH-M510|SPH-M540|SPH-M550|SPH-M560|SPH-M570|SPH-M580|SPH-M610|SPH-M620|SPH-M630|SPH-M800|SPH-M810|SPH-M850|SPH-M900|SPH-M910|SPH-M920|SPH-M930|SPH-N100|SPH-N200|SPH-N240|SPH-N300|SPH-N400|SPH-Z400|SWC-E100|SCH-i909|GT-N7100|GT-N7105|SCH-I535|SM-N900A|SGH-I317|SGH-T999L|GT-S5360B|GT-I8262|GT-S6802|GT-S6312|GT-S6310|GT-S5312|GT-S5310|GT-I9105|GT-I8510|GT-S6790N|SM-G7105|SM-N9005|GT-S5301|GT-I9295|GT-I9195|SM-C101|GT-S7392|GT-S7560|GT-B7610|GT-I5510|GT-S7582|GT-S7530E|GT-I8750|SM-G9006V|SM-G9008V|SM-G9009D|SM-G900A|SM-G900D|SM-G900F|SM-G900H|SM-G900I|SM-G900J|SM-G900K|SM-G900L|SM-G900M|SM-G900P|SM-G900R4|SM-G900S|SM-G900T|SM-G900V|SM-G900W8|SHV-E160K|SCH-P709|SCH-P729|SM-T2558|GT-I9205|SM-G9350|SM-J120F|SM-G920F|SM-G920V|SM-G930F|SM-N910C|SM-A310F|GT-I9190|SM-J500FN|SM-G903F',
'LG' => '\bLG\b;|LG[- ]?(C800|C900|E400|E610|E900|E-900|F160|F180K|F180L|F180S|730|855|L160|LS740|LS840|LS970|LU6200|MS690|MS695|MS770|MS840|MS870|MS910|P500|P700|P705|VM696|AS680|AS695|AX840|C729|E970|GS505|272|C395|E739BK|E960|L55C|L75C|LS696|LS860|P769BK|P350|P500|P509|P870|UN272|US730|VS840|VS950|LN272|LN510|LS670|LS855|LW690|MN270|MN510|P509|P769|P930|UN200|UN270|UN510|UN610|US670|US740|US760|UX265|UX840|VN271|VN530|VS660|VS700|VS740|VS750|VS910|VS920|VS930|VX9200|VX11000|AX840A|LW770|P506|P925|P999|E612|D955|D802|MS323)',
'Sony' => 'SonyST|SonyLT|SonyEricsson|SonyEricssonLT15iv|LT18i|E10i|LT28h|LT26w|SonyEricssonMT27i|C5303|C6902|C6903|C6906|C6943|D2533',
'Asus' => 'Asus.*Galaxy|PadFone.*Mobile',
'NokiaLumia' => 'Lumia [0-9]{3,4}',
// http://www.micromaxinfo.com/mobiles/smartphones
// Added because the codes might conflict with Acer Tablets.
'Micromax' => 'Micromax.*\b(A210|A92|A88|A72|A111|A110Q|A115|A116|A110|A90S|A26|A51|A35|A54|A25|A27|A89|A68|A65|A57|A90)\b',
// @todo Complete the regex.
'Palm' => 'PalmSource|Palm', // avantgo|blazer|elaine|hiptop|plucker|xiino ;
'Vertu' => 'Vertu|Vertu.*Ltd|Vertu.*Ascent|Vertu.*Ayxta|Vertu.*Constellation(F|Quest)?|Vertu.*Monika|Vertu.*Signature', // Just for fun ;)
// http://www.pantech.co.kr/en/prod/prodList.do?gbrand=VEGA (PANTECH)
// Most of the VEGA devices are legacy. PANTECH seem to be newer devices based on Android.
'Pantech' => 'PANTECH|IM-A850S|IM-A840S|IM-A830L|IM-A830K|IM-A830S|IM-A820L|IM-A810K|IM-A810S|IM-A800S|IM-T100K|IM-A725L|IM-A780L|IM-A775C|IM-A770K|IM-A760S|IM-A750K|IM-A740S|IM-A730S|IM-A720L|IM-A710K|IM-A690L|IM-A690S|IM-A650S|IM-A630K|IM-A600S|VEGA PTL21|PT003|P8010|ADR910L|P6030|P6020|P9070|P4100|P9060|P5000|CDM8992|TXT8045|ADR8995|IS11PT|P2030|P6010|P8000|PT002|IS06|CDM8999|P9050|PT001|TXT8040|P2020|P9020|P2000|P7040|P7000|C790',
// http://www.fly-phone.com/devices/smartphones/ ; Included only smartphones.
'Fly' => 'IQ230|IQ444|IQ450|IQ440|IQ442|IQ441|IQ245|IQ256|IQ236|IQ255|IQ235|IQ245|IQ275|IQ240|IQ285|IQ280|IQ270|IQ260|IQ250',
// http://fr.wikomobile.com
'Wiko' => 'KITE 4G|HIGHWAY|GETAWAY|STAIRWAY|DARKSIDE|DARKFULL|DARKNIGHT|DARKMOON|SLIDE|WAX 4G|RAINBOW|BLOOM|SUNSET|GOA(?!nna)|LENNY|BARRY|IGGY|OZZY|CINK FIVE|CINK PEAX|CINK PEAX 2|CINK SLIM|CINK SLIM 2|CINK +|CINK KING|CINK PEAX|CINK SLIM|SUBLIM',
'iMobile' => 'i-mobile (IQ|i-STYLE|idea|ZAA|Hitz)',
// Added simvalley mobile just for fun. They have some interesting devices.
// http://www.simvalley.fr/telephonie---gps-_22_telephonie-mobile_telephones_.html
'SimValley' => '\b(SP-80|XT-930|SX-340|XT-930|SX-310|SP-360|SP60|SPT-800|SP-120|SPT-800|SP-140|SPX-5|SPX-8|SP-100|SPX-8|SPX-12)\b',
// Wolfgang - a brand that is sold by Aldi supermarkets.
// http://www.wolfgangmobile.com/
'Wolfgang' => 'AT-B24D|AT-AS50HD|AT-AS40W|AT-AS55HD|AT-AS45q2|AT-B26D|AT-AS50Q',
'Alcatel' => 'Alcatel',
'Nintendo' => 'Nintendo 3DS',
// http://en.wikipedia.org/wiki/Amoi
'Amoi' => 'Amoi',
// http://en.wikipedia.org/wiki/INQ
'INQ' => 'INQ',
// @Tapatalk is a mobile app; http://support.tapatalk.com/threads/smf-2-0-2-os-and-browser-detection-plugin-and-tapatalk.15565/#post-79039
'GenericPhone' => 'Tapatalk|PDA;|SAGEM|\bmmp\b|pocket|\bpsp\b|symbian|Smartphone|smartfon|treo|up.browser|up.link|vodafone|\bwap\b|nokia|Series40|Series60|S60|SonyEricsson|N900|MAUI.*WAP.*Browser',
);
/**
* List of tablet devices.
*
* @var array
*/
protected static $tabletDevices = array(
// @todo: check for mobile friendly emails topic.
'iPad' => 'iPad|iPad.*Mobile',
// Removed |^.*Android.*Nexus(?!(?:Mobile).)*$
// @see #442
'NexusTablet' => 'Android.*Nexus[\s]+(7|9|10)',
'SamsungTablet' => 'SAMSUNG.*Tablet|Galaxy.*Tab|SC-01C|GT-P1000|GT-P1003|GT-P1010|GT-P3105|GT-P6210|GT-P6800|GT-P6810|GT-P7100|GT-P7300|GT-P7310|GT-P7500|GT-P7510|SCH-I800|SCH-I815|SCH-I905|SGH-I957|SGH-I987|SGH-T849|SGH-T859|SGH-T869|SPH-P100|GT-P3100|GT-P3108|GT-P3110|GT-P5100|GT-P5110|GT-P6200|GT-P7320|GT-P7511|GT-N8000|GT-P8510|SGH-I497|SPH-P500|SGH-T779|SCH-I705|SCH-I915|GT-N8013|GT-P3113|GT-P5113|GT-P8110|GT-N8010|GT-N8005|GT-N8020|GT-P1013|GT-P6201|GT-P7501|GT-N5100|GT-N5105|GT-N5110|SHV-E140K|SHV-E140L|SHV-E140S|SHV-E150S|SHV-E230K|SHV-E230L|SHV-E230S|SHW-M180K|SHW-M180L|SHW-M180S|SHW-M180W|SHW-M300W|SHW-M305W|SHW-M380K|SHW-M380S|SHW-M380W|SHW-M430W|SHW-M480K|SHW-M480S|SHW-M480W|SHW-M485W|SHW-M486W|SHW-M500W|GT-I9228|SCH-P739|SCH-I925|GT-I9200|GT-P5200|GT-P5210|GT-P5210X|SM-T311|SM-T310|SM-T310X|SM-T210|SM-T210R|SM-T211|SM-P600|SM-P601|SM-P605|SM-P900|SM-P901|SM-T217|SM-T217A|SM-T217S|SM-P6000|SM-T3100|SGH-I467|XE500|SM-T110|GT-P5220|GT-I9200X|GT-N5110X|GT-N5120|SM-P905|SM-T111|SM-T2105|SM-T315|SM-T320|SM-T320X|SM-T321|SM-T520|SM-T525|SM-T530NU|SM-T230NU|SM-T330NU|SM-T900|XE500T1C|SM-P605V|SM-P905V|SM-T337V|SM-T537V|SM-T707V|SM-T807V|SM-P600X|SM-P900X|SM-T210X|SM-T230|SM-T230X|SM-T325|GT-P7503|SM-T531|SM-T330|SM-T530|SM-T705|SM-T705C|SM-T535|SM-T331|SM-T800|SM-T700|SM-T537|SM-T807|SM-P907A|SM-T337A|SM-T537A|SM-T707A|SM-T807A|SM-T237|SM-T807P|SM-P607T|SM-T217T|SM-T337T|SM-T807T|SM-T116NQ|SM-T116BU|SM-P550|SM-T350|SM-T550|SM-T9000|SM-P9000|SM-T705Y|SM-T805|GT-P3113|SM-T710|SM-T810|SM-T815|SM-T360|SM-T533|SM-T113|SM-T335|SM-T715|SM-T560|SM-T670|SM-T677|SM-T377|SM-T567|SM-T357T|SM-T555|SM-T561|SM-T713|SM-T719|SM-T813|SM-T819|SM-T580|SM-T355Y?|SM-T280|SM-T817A|SM-T820|SM-W700|SM-P580|SM-T587|SM-P350|SM-P555M|SM-P355M|SM-T113NU|SM-T815Y', // SCH-P709|SCH-P729|SM-T2558|GT-I9205 - Samsung Mega - treat them like a regular phone.
// http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html
'Kindle' => 'Kindle|Silk.*Accelerated|Android.*\b(KFOT|KFTT|KFJWI|KFJWA|KFOTE|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|WFJWAE|KFSAWA|KFSAWI|KFASWI|KFARWI|KFFOWI|KFGIWI|KFMEWI)\b|Android.*Silk/[0-9.]+ like Chrome/[0-9.]+ (?!Mobile)',
// Only the Surface tablets with Windows RT are considered mobile.
// http://msdn.microsoft.com/en-us/library/ie/hh920767(v=vs.85).aspx
'SurfaceTablet' => 'Windows NT [0-9.]+; ARM;.*(Tablet|ARMBJS)',
// http://shopping1.hp.com/is-bin/INTERSHOP.enfinity/WFS/WW-USSMBPublicStore-Site/en_US/-/USD/ViewStandardCatalog-Browse?CatalogCategoryID=JfIQ7EN5lqMAAAEyDcJUDwMT
'HPTablet' => 'HP Slate (7|8|10)|HP ElitePad 900|hp-tablet|EliteBook.*Touch|HP 8|Slate 21|HP SlateBook 10',
// Watch out for PadFone, see #132.
// http://www.asus.com/de/Tablets_Mobile/Memo_Pad_Products/
'AsusTablet' => '^.*PadFone((?!Mobile).)*$|Transformer|TF101|TF101G|TF300T|TF300TG|TF300TL|TF700T|TF700KL|TF701T|TF810C|ME171|ME301T|ME302C|ME371MG|ME370T|ME372MG|ME172V|ME173X|ME400C|Slider SL101|\bK00F\b|\bK00C\b|\bK00E\b|\bK00L\b|TX201LA|ME176C|ME102A|\bM80TA\b|ME372CL|ME560CG|ME372CG|ME302KL| K010 | K011 | K017 | K01E |ME572C|ME103K|ME170C|ME171C|\bME70C\b|ME581C|ME581CL|ME8510C|ME181C|P01Y|PO1MA|P01Z|\bP027\b',
'BlackBerryTablet' => 'PlayBook|RIM Tablet',
'HTCtablet' => 'HTC_Flyer_P512|HTC Flyer|HTC Jetstream|HTC-P715a|HTC EVO View 4G|PG41200|PG09410',
'MotorolaTablet' => 'xoom|sholest|MZ615|MZ605|MZ505|MZ601|MZ602|MZ603|MZ604|MZ606|MZ607|MZ608|MZ609|MZ615|MZ616|MZ617',
'NookTablet' => 'Android.*Nook|NookColor|nook browser|BNRV200|BNRV200A|BNTV250|BNTV250A|BNTV400|BNTV600|LogicPD Zoom2',
// http://www.acer.ro/ac/ro/RO/content/drivers
// http://www.packardbell.co.uk/pb/en/GB/content/download (Packard Bell is part of Acer)
// http://us.acer.com/ac/en/US/content/group/tablets
// http://www.acer.de/ac/de/DE/content/models/tablets/
// Can conflict with Micromax and Motorola phones codes.
'AcerTablet' => 'Android.*; \b(A100|A101|A110|A200|A210|A211|A500|A501|A510|A511|A700|A701|W500|W500P|W501|W501P|W510|W511|W700|G100|G100W|B1-A71|B1-710|B1-711|A1-810|A1-811|A1-830)\b|W3-810|\bA3-A10\b|\bA3-A11\b|\bA3-A20\b|\bA3-A30',
// http://eu.computers.toshiba-europe.com/innovation/family/Tablets/1098744/banner_id/tablet_footerlink/
// http://us.toshiba.com/tablets/tablet-finder
// http://www.toshiba.co.jp/regza/tablet/
'ToshibaTablet' => 'Android.*(AT100|AT105|AT200|AT205|AT270|AT275|AT300|AT305|AT1S5|AT500|AT570|AT700|AT830)|TOSHIBA.*FOLIO',
// http://www.nttdocomo.co.jp/english/service/developer/smart_phone/technical_info/spec/index.html
// http://www.lg.com/us/tablets
'LGTablet' => '\bL-06C|LG-V909|LG-V900|LG-V700|LG-V510|LG-V500|LG-V410|LG-V400|LG-VK810\b',
'FujitsuTablet' => 'Android.*\b(F-01D|F-02F|F-05E|F-10D|M532|Q572)\b',
// Prestigio Tablets http://www.prestigio.com/support
'PrestigioTablet' => 'PMP3170B|PMP3270B|PMP3470B|PMP7170B|PMP3370B|PMP3570C|PMP5870C|PMP3670B|PMP5570C|PMP5770D|PMP3970B|PMP3870C|PMP5580C|PMP5880D|PMP5780D|PMP5588C|PMP7280C|PMP7280C3G|PMP7280|PMP7880D|PMP5597D|PMP5597|PMP7100D|PER3464|PER3274|PER3574|PER3884|PER5274|PER5474|PMP5097CPRO|PMP5097|PMP7380D|PMP5297C|PMP5297C_QUAD|PMP812E|PMP812E3G|PMP812F|PMP810E|PMP880TD|PMT3017|PMT3037|PMT3047|PMT3057|PMT7008|PMT5887|PMT5001|PMT5002',
// http://support.lenovo.com/en_GB/downloads/default.page?#
'LenovoTablet' => 'Lenovo TAB|Idea(Tab|Pad)( A1|A10| K1|)|ThinkPad([ ]+)?Tablet|YT3-850M|YT3-X90L|YT3-X90F|YT3-X90X|Lenovo.*(S2109|S2110|S5000|S6000|K3011|A3000|A3500|A1000|A2107|A2109|A1107|A5500|A7600|B6000|B8000|B8080)(-|)(FL|F|HV|H|)|TB-X103F|TB-X304F|TB-8703F',
// http://www.dell.com/support/home/us/en/04/Products/tab_mob/tablets
'DellTablet' => 'Venue 11|Venue 8|Venue 7|Dell Streak 10|Dell Streak 7',
// http://www.yarvik.com/en/matrix/tablets/
'YarvikTablet' => 'Android.*\b(TAB210|TAB211|TAB224|TAB250|TAB260|TAB264|TAB310|TAB360|TAB364|TAB410|TAB411|TAB420|TAB424|TAB450|TAB460|TAB461|TAB464|TAB465|TAB467|TAB468|TAB07-100|TAB07-101|TAB07-150|TAB07-151|TAB07-152|TAB07-200|TAB07-201-3G|TAB07-210|TAB07-211|TAB07-212|TAB07-214|TAB07-220|TAB07-400|TAB07-485|TAB08-150|TAB08-200|TAB08-201-3G|TAB08-201-30|TAB09-100|TAB09-211|TAB09-410|TAB10-150|TAB10-201|TAB10-211|TAB10-400|TAB10-410|TAB13-201|TAB274EUK|TAB275EUK|TAB374EUK|TAB462EUK|TAB474EUK|TAB9-200)\b',
'MedionTablet' => 'Android.*\bOYO\b|LIFE.*(P9212|P9514|P9516|S9512)|LIFETAB',
'ArnovaTablet' => '97G4|AN10G2|AN7bG3|AN7fG3|AN8G3|AN8cG3|AN7G3|AN9G3|AN7dG3|AN7dG3ST|AN7dG3ChildPad|AN10bG3|AN10bG3DT|AN9G2',
// http://www.intenso.de/kategorie_en.php?kategorie=33
// @todo: http://www.nbhkdz.com/read/b8e64202f92a2df129126bff.html - investigate
'IntensoTablet' => 'INM8002KP|INM1010FP|INM805ND|Intenso Tab|TAB1004',
// IRU.ru Tablets http://www.iru.ru/catalog/soho/planetable/
'IRUTablet' => 'M702pro',
'MegafonTablet' => 'MegaFon V9|\bZTE V9\b|Android.*\bMT7A\b',
// http://www.e-boda.ro/tablete-pc.html
'EbodaTablet' => 'E-Boda (Supreme|Impresspeed|Izzycomm|Essential)',
// http://www.allview.ro/produse/droseries/lista-tablete-pc/
'AllViewTablet' => 'Allview.*(Viva|Alldro|City|Speed|All TV|Frenzy|Quasar|Shine|TX1|AX1|AX2)',
// http://wiki.archosfans.com/index.php?title=Main_Page
// @note Rewrite the regex format after we add more UAs.
'ArchosTablet' => '\b(101G9|80G9|A101IT)\b|Qilive 97R|Archos5|\bARCHOS (70|79|80|90|97|101|FAMILYPAD|)(b|c|)(G10| Cobalt| TITANIUM(HD|)| Xenon| Neon|XSK| 2| XS 2| PLATINUM| CARBON|GAMEPAD)\b',
// http://www.ainol.com/plugin.php?identifier=ainol&module=product
'AinolTablet' => 'NOVO7|NOVO8|NOVO10|Novo7Aurora|Novo7Basic|NOVO7PALADIN|novo9-Spark',
'NokiaLumiaTablet' => 'Lumia 2520',
// @todo: inspect http://esupport.sony.com/US/p/select-system.pl?DIRECTOR=DRIVER
// Readers http://www.atsuhiro-me.net/ebook/sony-reader/sony-reader-web-browser
// http://www.sony.jp/support/tablet/
'SonyTablet' => 'Sony.*Tablet|Xperia Tablet|Sony Tablet S|SO-03E|SGPT12|SGPT13|SGPT114|SGPT121|SGPT122|SGPT123|SGPT111|SGPT112|SGPT113|SGPT131|SGPT132|SGPT133|SGPT211|SGPT212|SGPT213|SGP311|SGP312|SGP321|EBRD1101|EBRD1102|EBRD1201|SGP351|SGP341|SGP511|SGP512|SGP521|SGP541|SGP551|SGP621|SGP612|SOT31',
// http://www.support.philips.com/support/catalog/worldproducts.jsp?userLanguage=en&userCountry=cn&categoryid=3G_LTE_TABLET_SU_CN_CARE&title=3G%20tablets%20/%20LTE%20range&_dyncharset=UTF-8
'PhilipsTablet' => '\b(PI2010|PI3000|PI3100|PI3105|PI3110|PI3205|PI3210|PI3900|PI4010|PI7000|PI7100)\b',
// db + http://www.cube-tablet.com/buy-products.html
'CubeTablet' => 'Android.*(K8GT|U9GT|U10GT|U16GT|U17GT|U18GT|U19GT|U20GT|U23GT|U30GT)|CUBE U8GT',
// http://www.cobyusa.com/?p=pcat&pcat_id=3001
'CobyTablet' => 'MID1042|MID1045|MID1125|MID1126|MID7012|MID7014|MID7015|MID7034|MID7035|MID7036|MID7042|MID7048|MID7127|MID8042|MID8048|MID8127|MID9042|MID9740|MID9742|MID7022|MID7010',
// http://www.match.net.cn/products.asp
'MIDTablet' => 'M9701|M9000|M9100|M806|M1052|M806|T703|MID701|MID713|MID710|MID727|MID760|MID830|MID728|MID933|MID125|MID810|MID732|MID120|MID930|MID800|MID731|MID900|MID100|MID820|MID735|MID980|MID130|MID833|MID737|MID960|MID135|MID860|MID736|MID140|MID930|MID835|MID733|MID4X10',
// http://www.msi.com/support
// @todo Research the Windows Tablets.
'MSITablet' => 'MSI \b(Primo 73K|Primo 73L|Primo 81L|Primo 77|Primo 93|Primo 75|Primo 76|Primo 73|Primo 81|Primo 91|Primo 90|Enjoy 71|Enjoy 7|Enjoy 10)\b',
// @todo http://www.kyoceramobile.com/support/drivers/
// 'KyoceraTablet' => null,
// @todo http://intexuae.com/index.php/category/mobile-devices/tablets-products/
// 'IntextTablet' => null,
// http://pdadb.net/index.php?m=pdalist&list=SMiT (NoName Chinese Tablets)
// http://www.imp3.net/14/show.php?itemid=20454
'SMiTTablet' => 'Android.*(\bMID\b|MID-560|MTV-T1200|MTV-PND531|MTV-P1101|MTV-PND530)',
// http://www.rock-chips.com/index.php?do=prod&pid=2
'RockChipTablet' => 'Android.*(RK2818|RK2808A|RK2918|RK3066)|RK2738|RK2808A',
// http://www.fly-phone.com/devices/tablets/ ; http://www.fly-phone.com/service/
'FlyTablet' => 'IQ310|Fly Vision',
// http://www.bqreaders.com/gb/tablets-prices-sale.html
'bqTablet' => 'Android.*(bq)?.*(Elcano|Curie|Edison|Maxwell|Kepler|Pascal|Tesla|Hypatia|Platon|Newton|Livingstone|Cervantes|Avant|Aquaris ([E|M]10|M8))|Maxwell.*Lite|Maxwell.*Plus',
// http://www.huaweidevice.com/worldwide/productFamily.do?method=index&directoryId=5011&treeId=3290
// http://www.huaweidevice.com/worldwide/downloadCenter.do?method=index&directoryId=3372&treeId=0&tb=1&type=software (including legacy tablets)
'HuaweiTablet' => 'MediaPad|MediaPad 7 Youth|IDEOS S7|S7-201c|S7-202u|S7-101|S7-103|S7-104|S7-105|S7-106|S7-201|S7-Slim|M2-A01L',
// Nec or Medias Tab
'NecTablet' => '\bN-06D|\bN-08D',
// Pantech Tablets: http://www.pantechusa.com/phones/
'PantechTablet' => 'Pantech.*P4100',
// Broncho Tablets: http://www.broncho.cn/ (hard to find)
'BronchoTablet' => 'Broncho.*(N701|N708|N802|a710)',
// http://versusuk.com/support.html
'VersusTablet' => 'TOUCHPAD.*[78910]|\bTOUCHTAB\b',
// http://www.zync.in/index.php/our-products/tablet-phablets
'ZyncTablet' => 'z1000|Z99 2G|z99|z930|z999|z990|z909|Z919|z900',
// http://www.positivoinformatica.com.br/www/pessoal/tablet-ypy/
'PositivoTablet' => 'TB07STA|TB10STA|TB07FTA|TB10FTA',
// https://www.nabitablet.com/
'NabiTablet' => 'Android.*\bNabi',
'KoboTablet' => 'Kobo Touch|\bK080\b|\bVox\b Build|\bArc\b Build',
// French Danew Tablets http://www.danew.com/produits-tablette.php
'DanewTablet' => 'DSlide.*\b(700|701R|702|703R|704|802|970|971|972|973|974|1010|1012)\b',
// Texet Tablets and Readers http://www.texet.ru/tablet/
'TexetTablet' => 'NaviPad|TB-772A|TM-7045|TM-7055|TM-9750|TM-7016|TM-7024|TM-7026|TM-7041|TM-7043|TM-7047|TM-8041|TM-9741|TM-9747|TM-9748|TM-9751|TM-7022|TM-7021|TM-7020|TM-7011|TM-7010|TM-7023|TM-7025|TM-7037W|TM-7038W|TM-7027W|TM-9720|TM-9725|TM-9737W|TM-1020|TM-9738W|TM-9740|TM-9743W|TB-807A|TB-771A|TB-727A|TB-725A|TB-719A|TB-823A|TB-805A|TB-723A|TB-715A|TB-707A|TB-705A|TB-709A|TB-711A|TB-890HD|TB-880HD|TB-790HD|TB-780HD|TB-770HD|TB-721HD|TB-710HD|TB-434HD|TB-860HD|TB-840HD|TB-760HD|TB-750HD|TB-740HD|TB-730HD|TB-722HD|TB-720HD|TB-700HD|TB-500HD|TB-470HD|TB-431HD|TB-430HD|TB-506|TB-504|TB-446|TB-436|TB-416|TB-146SE|TB-126SE',
// Avoid detecting 'PLAYSTATION 3' as mobile.
'PlaystationTablet' => 'Playstation.*(Portable|Vita)',
// http://www.trekstor.de/surftabs.html
'TrekstorTablet' => 'ST10416-1|VT10416-1|ST70408-1|ST702xx-1|ST702xx-2|ST80208|ST97216|ST70104-2|VT10416-2|ST10216-2A|SurfTab',
// http://www.pyleaudio.com/Products.aspx?%2fproducts%2fPersonal-Electronics%2fTablets
'PyleAudioTablet' => '\b(PTBL10CEU|PTBL10C|PTBL72BC|PTBL72BCEU|PTBL7CEU|PTBL7C|PTBL92BC|PTBL92BCEU|PTBL9CEU|PTBL9CUK|PTBL9C)\b',
// http://www.advandigital.com/index.php?link=content-product&jns=JP001
// because of the short codenames we have to include whitespaces to reduce the possible conflicts.
'AdvanTablet' => 'Android.* \b(E3A|T3X|T5C|T5B|T3E|T3C|T3B|T1J|T1F|T2A|T1H|T1i|E1C|T1-E|T5-A|T4|E1-B|T2Ci|T1-B|T1-D|O1-A|E1-A|T1-A|T3A|T4i)\b ',
// http://www.danytech.com/category/tablet-pc
'DanyTechTablet' => 'Genius Tab G3|Genius Tab S2|Genius Tab Q3|Genius Tab G4|Genius Tab Q4|Genius Tab G-II|Genius TAB GII|Genius TAB GIII|Genius Tab S1',
// http://www.galapad.net/product.html
'GalapadTablet' => 'Android.*\bG1\b',
// http://www.micromaxinfo.com/tablet/funbook
'MicromaxTablet' => 'Funbook|Micromax.*\b(P250|P560|P360|P362|P600|P300|P350|P500|P275)\b',
// http://www.karbonnmobiles.com/products_tablet.php
'KarbonnTablet' => 'Android.*\b(A39|A37|A34|ST8|ST10|ST7|Smart Tab3|Smart Tab2)\b',
// http://www.myallfine.com/Products.asp
'AllFineTablet' => 'Fine7 Genius|Fine7 Shine|Fine7 Air|Fine8 Style|Fine9 More|Fine10 Joy|Fine11 Wide',
// http://www.proscanvideo.com/products-search.asp?itemClass=TABLET&itemnmbr=
'PROSCANTablet' => '\b(PEM63|PLT1023G|PLT1041|PLT1044|PLT1044G|PLT1091|PLT4311|PLT4311PL|PLT4315|PLT7030|PLT7033|PLT7033D|PLT7035|PLT7035D|PLT7044K|PLT7045K|PLT7045KB|PLT7071KG|PLT7072|PLT7223G|PLT7225G|PLT7777G|PLT7810K|PLT7849G|PLT7851G|PLT7852G|PLT8015|PLT8031|PLT8034|PLT8036|PLT8080K|PLT8082|PLT8088|PLT8223G|PLT8234G|PLT8235G|PLT8816K|PLT9011|PLT9045K|PLT9233G|PLT9735|PLT9760G|PLT9770G)\b',
// http://www.yonesnav.com/products/products.php
'YONESTablet' => 'BQ1078|BC1003|BC1077|RK9702|BC9730|BC9001|IT9001|BC7008|BC7010|BC708|BC728|BC7012|BC7030|BC7027|BC7026',
// http://www.cjshowroom.com/eproducts.aspx?classcode=004001001
// China manufacturer makes tablets for different small brands (eg. http://www.zeepad.net/index.html)
'ChangJiaTablet' => 'TPC7102|TPC7103|TPC7105|TPC7106|TPC7107|TPC7201|TPC7203|TPC7205|TPC7210|TPC7708|TPC7709|TPC7712|TPC7110|TPC8101|TPC8103|TPC8105|TPC8106|TPC8203|TPC8205|TPC8503|TPC9106|TPC9701|TPC97101|TPC97103|TPC97105|TPC97106|TPC97111|TPC97113|TPC97203|TPC97603|TPC97809|TPC97205|TPC10101|TPC10103|TPC10106|TPC10111|TPC10203|TPC10205|TPC10503',
// http://www.gloryunion.cn/products.asp
// http://www.allwinnertech.com/en/apply/mobile.html
// http://www.ptcl.com.pk/pd_content.php?pd_id=284 (EVOTAB)
// @todo: Softwiner tablets?
// aka. Cute or Cool tablets. Not sure yet, must research to avoid collisions.
'GUTablet' => 'TX-A1301|TX-M9002|Q702|kf026', // A12R|D75A|D77|D79|R83|A95|A106C|R15|A75|A76|D71|D72|R71|R73|R77|D82|R85|D92|A97|D92|R91|A10F|A77F|W71F|A78F|W78F|W81F|A97F|W91F|W97F|R16G|C72|C73E|K72|K73|R96G
// http://www.pointofview-online.com/showroom.php?shop_mode=product_listing&category_id=118
'PointOfViewTablet' => 'TAB-P506|TAB-navi-7-3G-M|TAB-P517|TAB-P-527|TAB-P701|TAB-P703|TAB-P721|TAB-P731N|TAB-P741|TAB-P825|TAB-P905|TAB-P925|TAB-PR945|TAB-PL1015|TAB-P1025|TAB-PI1045|TAB-P1325|TAB-PROTAB[0-9]+|TAB-PROTAB25|TAB-PROTAB26|TAB-PROTAB27|TAB-PROTAB26XL|TAB-PROTAB2-IPS9|TAB-PROTAB30-IPS9|TAB-PROTAB25XXL|TAB-PROTAB26-IPS10|TAB-PROTAB30-IPS10',
// http://www.overmax.pl/pl/katalog-produktow,p8/tablety,c14/
// @todo: add more tests.
'OvermaxTablet' => 'OV-(SteelCore|NewBase|Basecore|Baseone|Exellen|Quattor|EduTab|Solution|ACTION|BasicTab|TeddyTab|MagicTab|Stream|TB-08|TB-09)|Qualcore 1027',
// http://hclmetablet.com/India/index.php
'HCLTablet' => 'HCL.*Tablet|Connect-3G-2.0|Connect-2G-2.0|ME Tablet U1|ME Tablet U2|ME Tablet G1|ME Tablet X1|ME Tablet Y2|ME Tablet Sync',
// http://www.edigital.hu/Tablet_es_e-book_olvaso/Tablet-c18385.html
'DPSTablet' => 'DPS Dream 9|DPS Dual 7',
// http://www.visture.com/index.asp
'VistureTablet' => 'V97 HD|i75 3G|Visture V4( HD)?|Visture V5( HD)?|Visture V10',
// http://www.mijncresta.nl/tablet
'CrestaTablet' => 'CTP(-)?810|CTP(-)?818|CTP(-)?828|CTP(-)?838|CTP(-)?888|CTP(-)?978|CTP(-)?980|CTP(-)?987|CTP(-)?988|CTP(-)?989',
// MediaTek - http://www.mediatek.com/_en/01_products/02_proSys.php?cata_sn=1&cata1_sn=1&cata2_sn=309
'MediatekTablet' => '\bMT8125|MT8389|MT8135|MT8377\b',
// Concorde tab
'ConcordeTablet' => 'Concorde([ ]+)?Tab|ConCorde ReadMan',
// GoClever Tablets - http://www.goclever.com/uk/products,c1/tablet,c5/
'GoCleverTablet' => 'GOCLEVER TAB|A7GOCLEVER|M1042|M7841|M742|R1042BK|R1041|TAB A975|TAB A7842|TAB A741|TAB A741L|TAB M723G|TAB M721|TAB A1021|TAB I921|TAB R721|TAB I720|TAB T76|TAB R70|TAB R76.2|TAB R106|TAB R83.2|TAB M813G|TAB I721|GCTA722|TAB I70|TAB I71|TAB S73|TAB R73|TAB R74|TAB R93|TAB R75|TAB R76.1|TAB A73|TAB A93|TAB A93.2|TAB T72|TAB R83|TAB R974|TAB R973|TAB A101|TAB A103|TAB A104|TAB A104.2|R105BK|M713G|A972BK|TAB A971|TAB R974.2|TAB R104|TAB R83.3|TAB A1042',
// Modecom Tablets - http://www.modecom.eu/tablets/portal/
'ModecomTablet' => 'FreeTAB 9000|FreeTAB 7.4|FreeTAB 7004|FreeTAB 7800|FreeTAB 2096|FreeTAB 7.5|FreeTAB 1014|FreeTAB 1001 |FreeTAB 8001|FreeTAB 9706|FreeTAB 9702|FreeTAB 7003|FreeTAB 7002|FreeTAB 1002|FreeTAB 7801|FreeTAB 1331|FreeTAB 1004|FreeTAB 8002|FreeTAB 8014|FreeTAB 9704|FreeTAB 1003',
// Vonino Tablets - http://www.vonino.eu/tablets
'VoninoTablet' => '\b(Argus[ _]?S|Diamond[ _]?79HD|Emerald[ _]?78E|Luna[ _]?70C|Onyx[ _]?S|Onyx[ _]?Z|Orin[ _]?HD|Orin[ _]?S|Otis[ _]?S|SpeedStar[ _]?S|Magnet[ _]?M9|Primus[ _]?94[ _]?3G|Primus[ _]?94HD|Primus[ _]?QS|Android.*\bQ8\b|Sirius[ _]?EVO[ _]?QS|Sirius[ _]?QS|Spirit[ _]?S)\b',
// ECS Tablets - http://www.ecs.com.tw/ECSWebSite/Product/Product_Tablet_List.aspx?CategoryID=14&MenuID=107&childid=M_107&LanID=0
'ECSTablet' => 'V07OT2|TM105A|S10OT1|TR10CS1',
// Storex Tablets - http://storex.fr/espace_client/support.html
// @note: no need to add all the tablet codes since they are guided by the first regex.
'StorexTablet' => 'eZee[_\']?(Tab|Go)[0-9]+|TabLC7|Looney Tunes Tab',
// Generic Vodafone tablets.
'VodafoneTablet' => 'SmartTab([ ]+)?[0-9]+|SmartTabII10|SmartTabII7|VF-1497',
// French tablets - Essentiel B http://www.boulanger.fr/tablette_tactile_e-book/tablette_tactile_essentiel_b/cl_68908.htm?multiChoiceToDelete=brand&mc_brand=essentielb
// Aka: http://www.essentielb.fr/
'EssentielBTablet' => 'Smart[ \']?TAB[ ]+?[0-9]+|Family[ \']?TAB2',
// Ross & Moor - http://ross-moor.ru/
'RossMoorTablet' => 'RM-790|RM-997|RMD-878G|RMD-974R|RMT-705A|RMT-701|RME-601|RMT-501|RMT-711',
// i-mobile http://product.i-mobilephone.com/Mobile_Device
'iMobileTablet' => 'i-mobile i-note',
// http://www.tolino.de/de/vergleichen/
'TolinoTablet' => 'tolino tab [0-9.]+|tolino shine',
// AudioSonic - a Kmart brand
// http://www.kmart.com.au/webapp/wcs/stores/servlet/Search?langId=-1&storeId=10701&catalogId=10001&categoryId=193001&pageSize=72¤tPage=1&searchCategory=193001%2b4294965664&sortBy=p_MaxPrice%7c1
'AudioSonicTablet' => '\bC-22Q|T7-QC|T-17B|T-17P\b',
// AMPE Tablets - http://www.ampe.com.my/product-category/tablets/
// @todo: add them gradually to avoid conflicts.
'AMPETablet' => 'Android.* A78 ',
// Skk Mobile - http://skkmobile.com.ph/product_tablets.php
'SkkTablet' => 'Android.* (SKYPAD|PHOENIX|CYCLOPS)',
// Tecno Mobile (only tablet) - http://www.tecno-mobile.com/index.php/product?filterby=smart&list_order=all&page=1
'TecnoTablet' => 'TECNO P9',
// JXD (consoles & tablets) - http://jxd.hk/products.asp?selectclassid=009008&clsid=3
'JXDTablet' => 'Android.* \b(F3000|A3300|JXD5000|JXD3000|JXD2000|JXD300B|JXD300|S5800|S7800|S602b|S5110b|S7300|S5300|S602|S603|S5100|S5110|S601|S7100a|P3000F|P3000s|P101|P200s|P1000m|P200m|P9100|P1000s|S6600b|S908|P1000|P300|S18|S6600|S9100)\b',
// i-Joy tablets - http://www.i-joy.es/en/cat/products/tablets/
'iJoyTablet' => 'Tablet (Spirit 7|Essentia|Galatea|Fusion|Onix 7|Landa|Titan|Scooby|Deox|Stella|Themis|Argon|Unique 7|Sygnus|Hexen|Finity 7|Cream|Cream X2|Jade|Neon 7|Neron 7|Kandy|Scape|Saphyr 7|Rebel|Biox|Rebel|Rebel 8GB|Myst|Draco 7|Myst|Tab7-004|Myst|Tadeo Jones|Tablet Boing|Arrow|Draco Dual Cam|Aurix|Mint|Amity|Revolution|Finity 9|Neon 9|T9w|Amity 4GB Dual Cam|Stone 4GB|Stone 8GB|Andromeda|Silken|X2|Andromeda II|Halley|Flame|Saphyr 9,7|Touch 8|Planet|Triton|Unique 10|Hexen 10|Memphis 4GB|Memphis 8GB|Onix 10)',
// http://www.intracon.eu/tablet
'FX2Tablet' => 'FX2 PAD7|FX2 PAD10',
// http://www.xoro.de/produkte/
// @note: Might be the same brand with 'Simply tablets'
'XoroTablet' => 'KidsPAD 701|PAD[ ]?712|PAD[ ]?714|PAD[ ]?716|PAD[ ]?717|PAD[ ]?718|PAD[ ]?720|PAD[ ]?721|PAD[ ]?722|PAD[ ]?790|PAD[ ]?792|PAD[ ]?900|PAD[ ]?9715D|PAD[ ]?9716DR|PAD[ ]?9718DR|PAD[ ]?9719QR|PAD[ ]?9720QR|TelePAD1030|Telepad1032|TelePAD730|TelePAD731|TelePAD732|TelePAD735Q|TelePAD830|TelePAD9730|TelePAD795|MegaPAD 1331|MegaPAD 1851|MegaPAD 2151',
// http://www1.viewsonic.com/products/computing/tablets/
'ViewsonicTablet' => 'ViewPad 10pi|ViewPad 10e|ViewPad 10s|ViewPad E72|ViewPad7|ViewPad E100|ViewPad 7e|ViewSonic VB733|VB100a',
// https://www.verizonwireless.com/tablets/verizon/
'VerizonTablet' => 'QTAQZ3|QTAIR7|QTAQTZ3|QTASUN1|QTASUN2|QTAXIA1',
// http://www.odys.de/web/internet-tablet_en.html
'OdysTablet' => 'LOOX|XENO10|ODYS[ -](Space|EVO|Xpress|NOON)|\bXELIO\b|Xelio10Pro|XELIO7PHONETAB|XELIO10EXTREME|XELIOPT2|NEO_QUAD10',
// http://www.captiva-power.de/products.html#tablets-en
'CaptivaTablet' => 'CAPTIVA PAD',
// IconBIT - http://www.iconbit.com/products/tablets/
'IconbitTablet' => 'NetTAB|NT-3702|NT-3702S|NT-3702S|NT-3603P|NT-3603P|NT-0704S|NT-0704S|NT-3805C|NT-3805C|NT-0806C|NT-0806C|NT-0909T|NT-0909T|NT-0907S|NT-0907S|NT-0902S|NT-0902S',
// http://www.teclast.com/topic.php?channelID=70&topicID=140&pid=63
'TeclastTablet' => 'T98 4G|\bP80\b|\bX90HD\b|X98 Air|X98 Air 3G|\bX89\b|P80 3G|\bX80h\b|P98 Air|\bX89HD\b|P98 3G|\bP90HD\b|P89 3G|X98 3G|\bP70h\b|P79HD 3G|G18d 3G|\bP79HD\b|\bP89s\b|\bA88\b|\bP10HD\b|\bP19HD\b|G18 3G|\bP78HD\b|\bA78\b|\bP75\b|G17s 3G|G17h 3G|\bP85t\b|\bP90\b|\bP11\b|\bP98t\b|\bP98HD\b|\bG18d\b|\bP85s\b|\bP11HD\b|\bP88s\b|\bA80HD\b|\bA80se\b|\bA10h\b|\bP89\b|\bP78s\b|\bG18\b|\bP85\b|\bA70h\b|\bA70\b|\bG17\b|\bP18\b|\bA80s\b|\bA11s\b|\bP88HD\b|\bA80h\b|\bP76s\b|\bP76h\b|\bP98\b|\bA10HD\b|\bP78\b|\bP88\b|\bA11\b|\bA10t\b|\bP76a\b|\bP76t\b|\bP76e\b|\bP85HD\b|\bP85a\b|\bP86\b|\bP75HD\b|\bP76v\b|\bA12\b|\bP75a\b|\bA15\b|\bP76Ti\b|\bP81HD\b|\bA10\b|\bT760VE\b|\bT720HD\b|\bP76\b|\bP73\b|\bP71\b|\bP72\b|\bT720SE\b|\bC520Ti\b|\bT760\b|\bT720VE\b|T720-3GE|T720-WiFi',
// Onda - http://www.onda-tablet.com/buy-android-onda.html?dir=desc&limit=all&order=price
'OndaTablet' => '\b(V975i|Vi30|VX530|V701|Vi60|V701s|Vi50|V801s|V719|Vx610w|VX610W|V819i|Vi10|VX580W|Vi10|V711s|V813|V811|V820w|V820|Vi20|V711|VI30W|V712|V891w|V972|V819w|V820w|Vi60|V820w|V711|V813s|V801|V819|V975s|V801|V819|V819|V818|V811|V712|V975m|V101w|V961w|V812|V818|V971|V971s|V919|V989|V116w|V102w|V973|Vi40)\b[\s]+',
'JaytechTablet' => 'TPC-PA762',
'BlaupunktTablet' => 'Endeavour 800NG|Endeavour 1010',
// http://www.digma.ru/support/download/
// @todo: Ebooks also (if requested)
'DigmaTablet' => '\b(iDx10|iDx9|iDx8|iDx7|iDxD7|iDxD8|iDsQ8|iDsQ7|iDsQ8|iDsD10|iDnD7|3TS804H|iDsQ11|iDj7|iDs10)\b',
// http://www.evolioshop.com/ro/tablete-pc.html
// http://www.evolio.ro/support/downloads_static.html?cat=2
// @todo: Research some more
'EvolioTablet' => 'ARIA_Mini_wifi|Aria[ _]Mini|Evolio X10|Evolio X7|Evolio X8|\bEvotab\b|\bNeura\b',
// @todo http://www.lavamobiles.com/tablets-data-cards
'LavaTablet' => 'QPAD E704|\bIvoryS\b|E-TAB IVORY|\bE-TAB\b',
// http://www.breezetablet.com/
'AocTablet' => 'MW0811|MW0812|MW0922|MTK8382|MW1031|MW0831|MW0821|MW0931|MW0712',
// http://www.mpmaneurope.com/en/products/internet-tablets-14/android-tablets-14/
'MpmanTablet' => 'MP11 OCTA|MP10 OCTA|MPQC1114|MPQC1004|MPQC994|MPQC974|MPQC973|MPQC804|MPQC784|MPQC780|\bMPG7\b|MPDCG75|MPDCG71|MPDC1006|MP101DC|MPDC9000|MPDC905|MPDC706HD|MPDC706|MPDC705|MPDC110|MPDC100|MPDC99|MPDC97|MPDC88|MPDC8|MPDC77|MP709|MID701|MID711|MID170|MPDC703|MPQC1010',
// https://www.celkonmobiles.com/?_a=categoryphones&sid=2
'CelkonTablet' => 'CT695|CT888|CT[\s]?910|CT7 Tab|CT9 Tab|CT3 Tab|CT2 Tab|CT1 Tab|C820|C720|\bCT-1\b',
// http://www.wolderelectronics.com/productos/manuales-y-guias-rapidas/categoria-2-miTab
'WolderTablet' => 'miTab \b(DIAMOND|SPACE|BROOKLYN|NEO|FLY|MANHATTAN|FUNK|EVOLUTION|SKY|GOCAR|IRON|GENIUS|POP|MINT|EPSILON|BROADWAY|JUMP|HOP|LEGEND|NEW AGE|LINE|ADVANCE|FEEL|FOLLOW|LIKE|LINK|LIVE|THINK|FREEDOM|CHICAGO|CLEVELAND|BALTIMORE-GH|IOWA|BOSTON|SEATTLE|PHOENIX|DALLAS|IN 101|MasterChef)\b',
// http://www.mi.com/en
'MiTablet' => '\bMI PAD\b|\bHM NOTE 1W\b',
// http://www.nbru.cn/index.html
'NibiruTablet' => 'Nibiru M1|Nibiru Jupiter One',
// http://navroad.com/products/produkty/tablety/
// http://navroad.com/products/produkty/tablety/
'NexoTablet' => 'NEXO NOVA|NEXO 10|NEXO AVIO|NEXO FREE|NEXO GO|NEXO EVO|NEXO 3G|NEXO SMART|NEXO KIDDO|NEXO MOBI',
// http://leader-online.com/new_site/product-category/tablets/
// http://www.leader-online.net.au/List/Tablet
'LeaderTablet' => 'TBLT10Q|TBLT10I|TBL-10WDKB|TBL-10WDKBO2013|TBL-W230V2|TBL-W450|TBL-W500|SV572|TBLT7I|TBA-AC7-8G|TBLT79|TBL-8W16|TBL-10W32|TBL-10WKB|TBL-W100',
// http://www.datawind.com/ubislate/
'UbislateTablet' => 'UbiSlate[\s]?7C',
// http://www.pocketbook-int.com/ru/support
'PocketBookTablet' => 'Pocketbook',
// http://www.kocaso.com/product_tablet.html
'KocasoTablet' => '\b(TB-1207)\b',
// http://global.hisense.com/product/asia/tablet/Sero7/201412/t20141215_91832.htm
'HisenseTablet' => '\b(F5281|E2371)\b',
// http://www.tesco.com/direct/hudl/
'Hudl' => 'Hudl HT7S3|Hudl 2',
// http://www.telstra.com.au/home-phone/thub-2/
'TelstraTablet' => 'T-Hub2',
'GenericTablet' => 'Android.*\b97D\b|Tablet(?!.*PC)|BNTV250A|MID-WCDMA|LogicPD Zoom2|\bA7EB\b|CatNova8|A1_07|CT704|CT1002|\bM721\b|rk30sdk|\bEVOTAB\b|M758A|ET904|ALUMIUM10|Smartfren Tab|Endeavour 1010|Tablet-PC-4|Tagi Tab|\bM6pro\b|CT1020W|arc 10HD|\bTP750\b|\bQTAQZ3\b'
);
/**
* List of mobile Operating Systems.
*
* @var array
*/
protected static $operatingSystems = array(
'AndroidOS' => 'Android',
'BlackBerryOS' => 'blackberry|\bBB10\b|rim tablet os',
'PalmOS' => 'PalmOS|avantgo|blazer|elaine|hiptop|palm|plucker|xiino',
'SymbianOS' => 'Symbian|SymbOS|Series60|Series40|SYB-[0-9]+|\bS60\b',
// @reference: http://en.wikipedia.org/wiki/Windows_Mobile
'WindowsMobileOS' => 'Windows CE.*(PPC|Smartphone|Mobile|[0-9]{3}x[0-9]{3})|Window Mobile|Windows Phone [0-9.]+|WCE;',
// @reference: http://en.wikipedia.org/wiki/Windows_Phone
// http://wifeng.cn/?r=blog&a=view&id=106
// http://nicksnettravels.builttoroam.com/post/2011/01/10/Bogus-Windows-Phone-7-User-Agent-String.aspx
// http://msdn.microsoft.com/library/ms537503.aspx
// https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
'WindowsPhoneOS' => 'Windows Phone 10.0|Windows Phone 8.1|Windows Phone 8.0|Windows Phone OS|XBLWP7|ZuneWP7|Windows NT 6.[23]; ARM;',
'iOS' => '\biPhone.*Mobile|\biPod|\biPad|AppleCoreMedia',
// http://en.wikipedia.org/wiki/MeeGo
// @todo: research MeeGo in UAs
'MeeGoOS' => 'MeeGo',
// http://en.wikipedia.org/wiki/Maemo
// @todo: research Maemo in UAs
'MaemoOS' => 'Maemo',
'JavaOS' => 'J2ME/|\bMIDP\b|\bCLDC\b', // '|Java/' produces bug #135
'webOS' => 'webOS|hpwOS',
'badaOS' => '\bBada\b',
'BREWOS' => 'BREW',
);
/**
* List of mobile User Agents.
*
* IMPORTANT: This is a list of only mobile browsers.
* Mobile Detect 2.x supports only mobile browsers,
* it was never designed to detect all browsers.
* The change will come in 2017 in the 3.x release for PHP7.
*
* @var array
*/
protected static $browsers = array(
//'Vivaldi' => 'Vivaldi',
// @reference: https://developers.google.com/chrome/mobile/docs/user-agent
'Chrome' => '\bCrMo\b|CriOS|Android.*Chrome/[.0-9]* (Mobile)?',
'Dolfin' => '\bDolfin\b',
'Opera' => 'Opera.*Mini|Opera.*Mobi|Android.*Opera|Mobile.*OPR/[0-9.]+|Coast/[0-9.]+',
'Skyfire' => 'Skyfire',
'Edge' => 'Mobile Safari/[.0-9]* Edge',
'IE' => 'IEMobile|MSIEMobile', // |Trident/[.0-9]+
'Firefox' => 'fennec|firefox.*maemo|(Mobile|Tablet).*Firefox|Firefox.*Mobile|FxiOS',
'Bolt' => 'bolt',
'TeaShark' => 'teashark',
'Blazer' => 'Blazer',
// @reference: http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html#//apple_ref/doc/uid/TP40006517-SW3
'Safari' => 'Version.*Mobile.*Safari|Safari.*Mobile|MobileSafari',
// http://en.wikipedia.org/wiki/Midori_(web_browser)
//'Midori' => 'midori',
//'Tizen' => 'Tizen',
'UCBrowser' => 'UC.*Browser|UCWEB',
'baiduboxapp' => 'baiduboxapp',
'baidubrowser' => 'baidubrowser',
// https://github.com/serbanghita/Mobile-Detect/issues/7
'DiigoBrowser' => 'DiigoBrowser',
// http://www.puffinbrowser.com/index.php
'Puffin' => 'Puffin',
// http://mercury-browser.com/index.html
'Mercury' => '\bMercury\b',
// http://en.wikipedia.org/wiki/Obigo_Browser
'ObigoBrowser' => 'Obigo',
// http://en.wikipedia.org/wiki/NetFront
'NetFront' => 'NF-Browser',
// @reference: http://en.wikipedia.org/wiki/Minimo
// http://en.wikipedia.org/wiki/Vision_Mobile_Browser
'GenericBrowser' => 'NokiaBrowser|OviBrowser|OneBrowser|TwonkyBeamBrowser|SEMC.*Browser|FlyFlow|Minimo|NetFront|Novarra-Vision|MQQBrowser|MicroMessenger',
// @reference: https://en.wikipedia.org/wiki/Pale_Moon_(web_browser)
'PaleMoon' => 'Android.*PaleMoon|Mobile.*PaleMoon',
);
/**
* Utilities.
*
* @var array
*/
protected static $utilities = array(
// Experimental. When a mobile device wants to switch to 'Desktop Mode'.
// http://scottcate.com/technology/windows-phone-8-ie10-desktop-or-mobile/
// https://github.com/serbanghita/Mobile-Detect/issues/57#issuecomment-15024011
// https://developers.facebook.com/docs/sharing/best-practices
'Bot' => 'Googlebot|facebookexternalhit|AdsBot-Google|Google Keyword Suggestion|Facebot|YandexBot|YandexMobileBot|bingbot|ia_archiver|AhrefsBot|Ezooms|GSLFbot|WBSearchBot|Twitterbot|TweetmemeBot|Twikle|PaperLiBot|Wotbox|UnwindFetchor|Exabot|MJ12bot|YandexImages|TurnitinBot|Pingdom',
'MobileBot' => 'Googlebot-Mobile|AdsBot-Google-Mobile|YahooSeeker/M1A1-R2D2',
'DesktopMode' => 'WPDesktop',
'TV' => 'SonyDTV|HbbTV', // experimental
'WebKit' => '(webkit)[ /]([\w.]+)',
// @todo: Include JXD consoles.
'Console' => '\b(Nintendo|Nintendo WiiU|Nintendo 3DS|PLAYSTATION|Xbox)\b',
'Watch' => 'SM-V700',
);
/**
* All possible HTTP headers that represent the
* User-Agent string.
*
* @var array
*/
protected static $uaHttpHeaders = array(
// The default User-Agent string.
'HTTP_USER_AGENT',
// Header can occur on devices using Opera Mini.
'HTTP_X_OPERAMINI_PHONE_UA',
// Vodafone specific header: http://www.seoprinciple.com/mobile-web-community-still-angry-at-vodafone/24/
'HTTP_X_DEVICE_USER_AGENT',
'HTTP_X_ORIGINAL_USER_AGENT',
'HTTP_X_SKYFIRE_PHONE',
'HTTP_X_BOLT_PHONE_UA',
'HTTP_DEVICE_STOCK_UA',
'HTTP_X_UCBROWSER_DEVICE_UA'
);
/**
* The individual segments that could exist in a User-Agent string. VER refers to the regular
* expression defined in the constant self::VER.
*
* @var array
*/
protected static $properties = array(
// Build
'Mobile' => 'Mobile/[VER]',
'Build' => 'Build/[VER]',
'Version' => 'Version/[VER]',
'VendorID' => 'VendorID/[VER]',
// Devices
'iPad' => 'iPad.*CPU[a-z ]+[VER]',
'iPhone' => 'iPhone.*CPU[a-z ]+[VER]',
'iPod' => 'iPod.*CPU[a-z ]+[VER]',
//'BlackBerry' => array('BlackBerry[VER]', 'BlackBerry [VER];'),
'Kindle' => 'Kindle/[VER]',
// Browser
'Chrome' => array('Chrome/[VER]', 'CriOS/[VER]', 'CrMo/[VER]'),
'Coast' => array('Coast/[VER]'),
'Dolfin' => 'Dolfin/[VER]',
// @reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox
'Firefox' => array('Firefox/[VER]', 'FxiOS/[VER]'),
'Fennec' => 'Fennec/[VER]',
// http://msdn.microsoft.com/en-us/library/ms537503(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx
'Edge' => 'Edge/[VER]',
'IE' => array('IEMobile/[VER];', 'IEMobile [VER]', 'MSIE [VER];', 'Trident/[0-9.]+;.*rv:[VER]'),
// http://en.wikipedia.org/wiki/NetFront
'NetFront' => 'NetFront/[VER]',
'NokiaBrowser' => 'NokiaBrowser/[VER]',
'Opera' => array( ' OPR/[VER]', 'Opera Mini/[VER]', 'Version/[VER]' ),
'Opera Mini' => 'Opera Mini/[VER]',
'Opera Mobi' => 'Version/[VER]',
'UCBrowser' => array( 'UCWEB[VER]', 'UC.*Browser/[VER]' ),
'MQQBrowser' => 'MQQBrowser/[VER]',
'MicroMessenger' => 'MicroMessenger/[VER]',
'baiduboxapp' => 'baiduboxapp/[VER]',
'baidubrowser' => 'baidubrowser/[VER]',
'SamsungBrowser' => 'SamsungBrowser/[VER]',
'Iron' => 'Iron/[VER]',
// @note: Safari 7534.48.3 is actually Version 5.1.
// @note: On BlackBerry the Version is overwriten by the OS.
'Safari' => array( 'Version/[VER]', 'Safari/[VER]' ),
'Skyfire' => 'Skyfire/[VER]',
'Tizen' => 'Tizen/[VER]',
'Webkit' => 'webkit[ /][VER]',
'PaleMoon' => 'PaleMoon/[VER]',
// Engine
'Gecko' => 'Gecko/[VER]',
'Trident' => 'Trident/[VER]',
'Presto' => 'Presto/[VER]',
'Goanna' => 'Goanna/[VER]',
// OS
'iOS' => ' \bi?OS\b [VER][ ;]{1}',
'Android' => 'Android [VER]',
'BlackBerry' => array('BlackBerry[\w]+/[VER]', 'BlackBerry.*Version/[VER]', 'Version/[VER]'),
'BREW' => 'BREW [VER]',
'Java' => 'Java/[VER]',
// @reference: http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/08/29/introducing-the-ie9-on-windows-phone-mango-user-agent-string.aspx
// @reference: http://en.wikipedia.org/wiki/Windows_NT#Releases
'Windows Phone OS' => array( 'Windows Phone OS [VER]', 'Windows Phone [VER]'),
'Windows Phone' => 'Windows Phone [VER]',
'Windows CE' => 'Windows CE/[VER]',
// http://social.msdn.microsoft.com/Forums/en-US/windowsdeveloperpreviewgeneral/thread/6be392da-4d2f-41b4-8354-8dcee20c85cd
'Windows NT' => 'Windows NT [VER]',
'Symbian' => array('SymbianOS/[VER]', 'Symbian/[VER]'),
'webOS' => array('webOS/[VER]', 'hpwOS/[VER];'),
);
/**
* Construct an instance of this class.
*
* @param array $headers Specify the headers as injection. Should be PHP _SERVER flavored.
* If left empty, will use the global _SERVER['HTTP_*'] vars instead.
* @param string $userAgent Inject the User-Agent header. If null, will use HTTP_USER_AGENT
* from the $headers array instead.
*/
public function __construct(
array $headers = null,
$userAgent = null
) {
$this->setHttpHeaders($headers);
$this->setUserAgent($userAgent);
}
/**
* Get the current script version.
* This is useful for the demo.php file,
* so people can check on what version they are testing
* for mobile devices.
*
* @return string The version number in semantic version format.
*/
public static function getScriptVersion()
{
return self::VERSION;
}
/**
* Set the HTTP Headers. Must be PHP-flavored. This method will reset existing headers.
*
* @param array $httpHeaders The headers to set. If null, then using PHP's _SERVER to extract
* the headers. The default null is left for backwards compatibility.
*/
public function setHttpHeaders($httpHeaders = null)
{
// use global _SERVER if $httpHeaders aren't defined
if (!is_array($httpHeaders) || !count($httpHeaders)) {
$httpHeaders = $_SERVER;
}
// clear existing headers
$this->httpHeaders = array();
// Only save HTTP headers. In PHP land, that means only _SERVER vars that
// start with HTTP_.
foreach ($httpHeaders as $key => $value) {
if (substr($key, 0, 5) === 'HTTP_') {
$this->httpHeaders[$key] = $value;
}
}
// In case we're dealing with CloudFront, we need to know.
$this->setCfHeaders($httpHeaders);
}
/**
* Retrieves the HTTP headers.
*
* @return array
*/
public function getHttpHeaders()
{
return $this->httpHeaders;
}
/**
* Retrieves a particular header. If it doesn't exist, no exception/error is caused.
* Simply null is returned.
*
* @param string $header The name of the header to retrieve. Can be HTTP compliant such as
* "User-Agent" or "X-Device-User-Agent" or can be php-esque with the
* all-caps, HTTP_ prefixed, underscore seperated awesomeness.
*
* @return string|null The value of the header.
*/
public function getHttpHeader($header)
{
// are we using PHP-flavored headers?
if (strpos($header, '_') === false) {
$header = str_replace('-', '_', $header);
$header = strtoupper($header);
}
// test the alternate, too
$altHeader = 'HTTP_' . $header;
//Test both the regular and the HTTP_ prefix
if (isset($this->httpHeaders[$header])) {
return $this->httpHeaders[$header];
} elseif (isset($this->httpHeaders[$altHeader])) {
return $this->httpHeaders[$altHeader];
}
return null;
}
public function getMobileHeaders()
{
return self::$mobileHeaders;
}
/**
* Get all possible HTTP headers that
* can contain the User-Agent string.
*
* @return array List of HTTP headers.
*/
public function getUaHttpHeaders()
{
return self::$uaHttpHeaders;
}
/**
* Set CloudFront headers
* http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-device
*
* @param array $cfHeaders List of HTTP headers
*
* @return boolean If there were CloudFront headers to be set
*/
public function setCfHeaders($cfHeaders = null) {
// use global _SERVER if $cfHeaders aren't defined
if (!is_array($cfHeaders) || !count($cfHeaders)) {
$cfHeaders = $_SERVER;
}
// clear existing headers
$this->cloudfrontHeaders = array();
// Only save CLOUDFRONT headers. In PHP land, that means only _SERVER vars that
// start with cloudfront-.
$response = false;
foreach ($cfHeaders as $key => $value) {
if (substr(strtolower($key), 0, 16) === 'http_cloudfront_') {
$this->cloudfrontHeaders[strtoupper($key)] = $value;
$response = true;
}
}
return $response;
}
/**
* Retrieves the cloudfront headers.
*
* @return array
*/
public function getCfHeaders()
{
return $this->cloudfrontHeaders;
}
/**
* @param string $userAgent
* @return string
*/
private function prepareUserAgent($userAgent) {
$userAgent = trim($userAgent);
$userAgent = substr($userAgent, 0, 500);
return $userAgent;
}
/**
* Set the User-Agent to be used.
*
* @param string $userAgent The user agent string to set.
*
* @return string|null
*/
public function setUserAgent($userAgent = null)
{
// Invalidate cache due to #375
$this->cache = array();
if (false === empty($userAgent)) {
return $this->userAgent = $this->prepareUserAgent($userAgent);
} else {
$this->userAgent = null;
foreach ($this->getUaHttpHeaders() as $altHeader) {
if (false === empty($this->httpHeaders[$altHeader])) { // @todo: should use getHttpHeader(), but it would be slow. (Serban)
$this->userAgent .= $this->httpHeaders[$altHeader] . " ";
}
}
if (!empty($this->userAgent)) {
return $this->userAgent = $this->prepareUserAgent($this->userAgent);
}
}
if (count($this->getCfHeaders()) > 0) {
return $this->userAgent = 'Amazon CloudFront';
}
return $this->userAgent = null;
}
/**
* Retrieve the User-Agent.
*
* @return string|null The user agent if it's set.
*/
public function getUserAgent()
{
return $this->userAgent;
}
/**
* Set the detection type. Must be one of self::DETECTION_TYPE_MOBILE or
* self::DETECTION_TYPE_EXTENDED. Otherwise, nothing is set.
*
* @deprecated since version 2.6.9
*
* @param string $type The type. Must be a self::DETECTION_TYPE_* constant. The default
* parameter is null which will default to self::DETECTION_TYPE_MOBILE.
*/
public function setDetectionType($type = null)
{
if ($type === null) {
$type = self::DETECTION_TYPE_MOBILE;
}
if ($type !== self::DETECTION_TYPE_MOBILE && $type !== self::DETECTION_TYPE_EXTENDED) {
return;
}
$this->detectionType = $type;
}
public function getMatchingRegex()
{
return $this->matchingRegex;
}
public function getMatchesArray()
{
return $this->matchesArray;
}
/**
* Retrieve the list of known phone devices.
*
* @return array List of phone devices.
*/
public static function getPhoneDevices()
{
return self::$phoneDevices;
}
/**
* Retrieve the list of known tablet devices.
*
* @return array List of tablet devices.
*/
public static function getTabletDevices()
{
return self::$tabletDevices;
}
/**
* Alias for getBrowsers() method.
*
* @return array List of user agents.
*/
public static function getUserAgents()
{
return self::getBrowsers();
}
/**
* Retrieve the list of known browsers. Specifically, the user agents.
*
* @return array List of browsers / user agents.
*/
public static function getBrowsers()
{
return self::$browsers;
}
/**
* Retrieve the list of known utilities.
*
* @return array List of utilities.
*/
public static function getUtilities()
{
return self::$utilities;
}
/**
* Method gets the mobile detection rules. This method is used for the magic methods $detect->is*().
*
* @deprecated since version 2.6.9
*
* @return array All the rules (but not extended).
*/
public static function getMobileDetectionRules()
{
static $rules;
if (!$rules) {
$rules = array_merge(
self::$phoneDevices,
self::$tabletDevices,
self::$operatingSystems,
self::$browsers
);
}
return $rules;
}
/**
* Method gets the mobile detection rules + utilities.
* The reason this is separate is because utilities rules
* don't necessary imply mobile. This method is used inside
* the new $detect->is('stuff') method.
*
* @deprecated since version 2.6.9
*
* @return array All the rules + extended.
*/
public function getMobileDetectionRulesExtended()
{
static $rules;
if (!$rules) {
// Merge all rules together.
$rules = array_merge(
self::$phoneDevices,
self::$tabletDevices,
self::$operatingSystems,
self::$browsers,
self::$utilities
);
}
return $rules;
}
/**
* Retrieve the current set of rules.
*
* @deprecated since version 2.6.9
*
* @return array
*/
public function getRules()
{
if ($this->detectionType == self::DETECTION_TYPE_EXTENDED) {
return self::getMobileDetectionRulesExtended();
} else {
return self::getMobileDetectionRules();
}
}
/**
* Retrieve the list of mobile operating systems.
*
* @return array The list of mobile operating systems.
*/
public static function getOperatingSystems()
{
return self::$operatingSystems;
}
/**
* Check the HTTP headers for signs of mobile.
* This is the fastest mobile check possible; it's used
* inside isMobile() method.
*
* @return bool
*/
public function checkHttpHeadersForMobile()
{
foreach ($this->getMobileHeaders() as $mobileHeader => $matchType) {
if (isset($this->httpHeaders[$mobileHeader])) {
if (is_array($matchType['matches'])) {
foreach ($matchType['matches'] as $_match) {
if (strpos($this->httpHeaders[$mobileHeader], $_match) !== false) {
return true;
}
}
return false;
} else {
return true;
}
}
}
return false;
}
/**
* Magic overloading method.
*
* @method boolean is[...]()
* @param string $name
* @param array $arguments
* @return mixed
* @throws BadMethodCallException when the method doesn't exist and doesn't start with 'is'
*/
public function __call($name, $arguments)
{
// make sure the name starts with 'is', otherwise
if (substr($name, 0, 2) !== 'is') {
throw new BadMethodCallException("No such method exists: $name");
}
$this->setDetectionType(self::DETECTION_TYPE_MOBILE);
$key = substr($name, 2);
return $this->matchUAAgainstKey($key);
}
/**
* Find a detection rule that matches the current User-agent.
*
* @param null $userAgent deprecated
* @return boolean
*/
protected function matchDetectionRulesAgainstUA($userAgent = null)
{
// Begin general search.
foreach ($this->getRules() as $_regex) {
if (empty($_regex)) {
continue;
}
if ($this->match($_regex, $userAgent)) {
return true;
}
}
return false;
}
/**
* Search for a certain key in the rules array.
* If the key is found then try to match the corresponding
* regex against the User-Agent.
*
* @param string $key
*
* @return boolean
*/
protected function matchUAAgainstKey($key)
{
// Make the keys lowercase so we can match: isIphone(), isiPhone(), isiphone(), etc.
$key = strtolower($key);
if (false === isset($this->cache[$key])) {
// change the keys to lower case
$_rules = array_change_key_case($this->getRules());
if (false === empty($_rules[$key])) {
$this->cache[$key] = $this->match($_rules[$key]);
}
if (false === isset($this->cache[$key])) {
$this->cache[$key] = false;
}
}
return $this->cache[$key];
}
/**
* Check if the device is mobile.
* Returns true if any type of mobile device detected, including special ones
* @param null $userAgent deprecated
* @param null $httpHeaders deprecated
* @return bool
*/
public function isMobile($userAgent = null, $httpHeaders = null)
{
if ($httpHeaders) {
$this->setHttpHeaders($httpHeaders);
}
if ($userAgent) {
$this->setUserAgent($userAgent);
}
// Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront'
if ($this->getUserAgent() === 'Amazon CloudFront') {
$cfHeaders = $this->getCfHeaders();
if(array_key_exists('HTTP_CLOUDFRONT_IS_MOBILE_VIEWER', $cfHeaders) && $cfHeaders['HTTP_CLOUDFRONT_IS_MOBILE_VIEWER'] === 'true') {
return true;
}
}
$this->setDetectionType(self::DETECTION_TYPE_MOBILE);
if ($this->checkHttpHeadersForMobile()) {
return true;
} else {
return $this->matchDetectionRulesAgainstUA();
}
}
/**
* Check if the device is a tablet.
* Return true if any type of tablet device is detected.
*
* @param string $userAgent deprecated
* @param array $httpHeaders deprecated
* @return bool
*/
public function isTablet($userAgent = null, $httpHeaders = null)
{
// Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront'
if ($this->getUserAgent() === 'Amazon CloudFront') {
$cfHeaders = $this->getCfHeaders();
if(array_key_exists('HTTP_CLOUDFRONT_IS_TABLET_VIEWER', $cfHeaders) && $cfHeaders['HTTP_CLOUDFRONT_IS_TABLET_VIEWER'] === 'true') {
return true;
}
}
$this->setDetectionType(self::DETECTION_TYPE_MOBILE);
foreach (self::$tabletDevices as $_regex) {
if ($this->match($_regex, $userAgent)) {
return true;
}
}
return false;
}
/**
* This method checks for a certain property in the
* userAgent.
* @todo: The httpHeaders part is not yet used.
*
* @param string $key
* @param string $userAgent deprecated
* @param string $httpHeaders deprecated
* @return bool|int|null
*/
public function is($key, $userAgent = null, $httpHeaders = null)
{
// Set the UA and HTTP headers only if needed (eg. batch mode).
if ($httpHeaders) {
$this->setHttpHeaders($httpHeaders);
}
if ($userAgent) {
$this->setUserAgent($userAgent);
}
$this->setDetectionType(self::DETECTION_TYPE_EXTENDED);
return $this->matchUAAgainstKey($key);
}
/**
* Some detection rules are relative (not standard),
* because of the diversity of devices, vendors and
* their conventions in representing the User-Agent or
* the HTTP headers.
*
* This method will be used to check custom regexes against
* the User-Agent string.
*
* @param $regex
* @param string $userAgent
* @return bool
*
* @todo: search in the HTTP headers too.
*/
public function match($regex, $userAgent = null)
{
$match = (bool) preg_match(sprintf('#%s#is', $regex), (false === empty($userAgent) ? $userAgent : $this->userAgent), $matches);
// If positive match is found, store the results for debug.
if ($match) {
$this->matchingRegex = $regex;
$this->matchesArray = $matches;
}
return $match;
}
/**
* Get the properties array.
*
* @return array
*/
public static function getProperties()
{
return self::$properties;
}
/**
* Prepare the version number.
*
* @todo Remove the error supression from str_replace() call.
*
* @param string $ver The string version, like "2.6.21.2152";
*
* @return float
*/
public function prepareVersionNo($ver)
{
$ver = str_replace(array('_', ' ', '/'), '.', $ver);
$arrVer = explode('.', $ver, 2);
if (isset($arrVer[1])) {
$arrVer[1] = @str_replace('.', '', $arrVer[1]); // @todo: treat strings versions.
}
return (float) implode('.', $arrVer);
}
/**
* Check the version of the given property in the User-Agent.
* Will return a float number. (eg. 2_0 will return 2.0, 4.3.1 will return 4.31)
*
* @param string $propertyName The name of the property. See self::getProperties() array
* keys for all possible properties.
* @param string $type Either self::VERSION_TYPE_STRING to get a string value or
* self::VERSION_TYPE_FLOAT indicating a float value. This parameter
* is optional and defaults to self::VERSION_TYPE_STRING. Passing an
* invalid parameter will default to the this type as well.
*
* @return string|float The version of the property we are trying to extract.
*/
public function version($propertyName, $type = self::VERSION_TYPE_STRING)
{
if (empty($propertyName)) {
return false;
}
// set the $type to the default if we don't recognize the type
if ($type !== self::VERSION_TYPE_STRING && $type !== self::VERSION_TYPE_FLOAT) {
$type = self::VERSION_TYPE_STRING;
}
$properties = self::getProperties();
// Check if the property exists in the properties array.
if (true === isset($properties[$propertyName])) {
// Prepare the pattern to be matched.
// Make sure we always deal with an array (string is converted).
$properties[$propertyName] = (array) $properties[$propertyName];
foreach ($properties[$propertyName] as $propertyMatchString) {
$propertyPattern = str_replace('[VER]', self::VER, $propertyMatchString);
// Identify and extract the version.
preg_match(sprintf('#%s#is', $propertyPattern), $this->userAgent, $match);
if (false === empty($match[1])) {
$version = ($type == self::VERSION_TYPE_FLOAT ? $this->prepareVersionNo($match[1]) : $match[1]);
return $version;
}
}
}
return false;
}
/**
* Retrieve the mobile grading, using self::MOBILE_GRADE_* constants.
*
* @return string One of the self::MOBILE_GRADE_* constants.
*/
public function mobileGrade()
{
$isMobile = $this->isMobile();
if (
// Apple iOS 4-7.0 – Tested on the original iPad (4.3 / 5.0), iPad 2 (4.3 / 5.1 / 6.1), iPad 3 (5.1 / 6.0), iPad Mini (6.1), iPad Retina (7.0), iPhone 3GS (4.3), iPhone 4 (4.3 / 5.1), iPhone 4S (5.1 / 6.0), iPhone 5 (6.0), and iPhone 5S (7.0)
$this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT) >= 4.3 ||
$this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT) >= 4.3 ||
$this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT) >= 4.3 ||
// Android 2.1-2.3 - Tested on the HTC Incredible (2.2), original Droid (2.2), HTC Aria (2.1), Google Nexus S (2.3). Functional on 1.5 & 1.6 but performance may be sluggish, tested on Google G1 (1.5)
// Android 3.1 (Honeycomb) - Tested on the Samsung Galaxy Tab 10.1 and Motorola XOOM
// Android 4.0 (ICS) - Tested on a Galaxy Nexus. Note: transition performance can be poor on upgraded devices
// Android 4.1 (Jelly Bean) - Tested on a Galaxy Nexus and Galaxy 7
( $this->version('Android', self::VERSION_TYPE_FLOAT)>2.1 && $this->is('Webkit') ) ||
// Windows Phone 7.5-8 - Tested on the HTC Surround (7.5), HTC Trophy (7.5), LG-E900 (7.5), Nokia 800 (7.8), HTC Mazaa (7.8), Nokia Lumia 520 (8), Nokia Lumia 920 (8), HTC 8x (8)
$this->version('Windows Phone OS', self::VERSION_TYPE_FLOAT) >= 7.5 ||
// Tested on the Torch 9800 (6) and Style 9670 (6), BlackBerry® Torch 9810 (7), BlackBerry Z10 (10)
$this->is('BlackBerry') && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) >= 6.0 ||
// Blackberry Playbook (1.0-2.0) - Tested on PlayBook
$this->match('Playbook.*Tablet') ||
// Palm WebOS (1.4-3.0) - Tested on the Palm Pixi (1.4), Pre (1.4), Pre 2 (2.0), HP TouchPad (3.0)
( $this->version('webOS', self::VERSION_TYPE_FLOAT) >= 1.4 && $this->match('Palm|Pre|Pixi') ) ||
// Palm WebOS 3.0 - Tested on HP TouchPad
$this->match('hp.*TouchPad') ||
// Firefox Mobile 18 - Tested on Android 2.3 and 4.1 devices
( $this->is('Firefox') && $this->version('Firefox', self::VERSION_TYPE_FLOAT) >= 18 ) ||
// Chrome for Android - Tested on Android 4.0, 4.1 device
( $this->is('Chrome') && $this->is('AndroidOS') && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 4.0 ) ||
// Skyfire 4.1 - Tested on Android 2.3 device
( $this->is('Skyfire') && $this->version('Skyfire', self::VERSION_TYPE_FLOAT) >= 4.1 && $this->is('AndroidOS') && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 ) ||
// Opera Mobile 11.5-12: Tested on Android 2.3
( $this->is('Opera') && $this->version('Opera Mobi', self::VERSION_TYPE_FLOAT) >= 11.5 && $this->is('AndroidOS') ) ||
// Meego 1.2 - Tested on Nokia 950 and N9
$this->is('MeeGoOS') ||
// Tizen (pre-release) - Tested on early hardware
$this->is('Tizen') ||
// Samsung Bada 2.0 - Tested on a Samsung Wave 3, Dolphin browser
// @todo: more tests here!
$this->is('Dolfin') && $this->version('Bada', self::VERSION_TYPE_FLOAT) >= 2.0 ||
// UC Browser - Tested on Android 2.3 device
( ($this->is('UC Browser') || $this->is('Dolfin')) && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 ) ||
// Kindle 3 and Fire - Tested on the built-in WebKit browser for each
( $this->match('Kindle Fire') ||
$this->is('Kindle') && $this->version('Kindle', self::VERSION_TYPE_FLOAT) >= 3.0 ) ||
// Nook Color 1.4.1 - Tested on original Nook Color, not Nook Tablet
$this->is('AndroidOS') && $this->is('NookTablet') ||
// Chrome Desktop 16-24 - Tested on OS X 10.7 and Windows 7
$this->version('Chrome', self::VERSION_TYPE_FLOAT) >= 16 && !$isMobile ||
// Safari Desktop 5-6 - Tested on OS X 10.7 and Windows 7
$this->version('Safari', self::VERSION_TYPE_FLOAT) >= 5.0 && !$isMobile ||
// Firefox Desktop 10-18 - Tested on OS X 10.7 and Windows 7
$this->version('Firefox', self::VERSION_TYPE_FLOAT) >= 10.0 && !$isMobile ||
// Internet Explorer 7-9 - Tested on Windows XP, Vista and 7
$this->version('IE', self::VERSION_TYPE_FLOAT) >= 7.0 && !$isMobile ||
// Opera Desktop 10-12 - Tested on OS X 10.7 and Windows 7
$this->version('Opera', self::VERSION_TYPE_FLOAT) >= 10 && !$isMobile
){
return self::MOBILE_GRADE_A;
}
if (
$this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT)<4.3 ||
$this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT)<4.3 ||
$this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT)<4.3 ||
// Blackberry 5.0: Tested on the Storm 2 9550, Bold 9770
$this->is('Blackberry') && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) >= 5 && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT)<6 ||
//Opera Mini (5.0-6.5) - Tested on iOS 3.2/4.3 and Android 2.3
($this->version('Opera Mini', self::VERSION_TYPE_FLOAT) >= 5.0 && $this->version('Opera Mini', self::VERSION_TYPE_FLOAT) <= 7.0 &&
($this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 || $this->is('iOS')) ) ||
// Nokia Symbian^3 - Tested on Nokia N8 (Symbian^3), C7 (Symbian^3), also works on N97 (Symbian^1)
$this->match('NokiaN8|NokiaC7|N97.*Series60|Symbian/3') ||
// @todo: report this (tested on Nokia N71)
$this->version('Opera Mobi', self::VERSION_TYPE_FLOAT) >= 11 && $this->is('SymbianOS')
){
return self::MOBILE_GRADE_B;
}
if (
// Blackberry 4.x - Tested on the Curve 8330
$this->version('BlackBerry', self::VERSION_TYPE_FLOAT) <= 5.0 ||
// Windows Mobile - Tested on the HTC Leo (WinMo 5.2)
$this->match('MSIEMobile|Windows CE.*Mobile') || $this->version('Windows Mobile', self::VERSION_TYPE_FLOAT) <= 5.2 ||
// Tested on original iPhone (3.1), iPhone 3 (3.2)
$this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT) <= 3.2 ||
$this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT) <= 3.2 ||
$this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT) <= 3.2 ||
// Internet Explorer 7 and older - Tested on Windows XP
$this->version('IE', self::VERSION_TYPE_FLOAT) <= 7.0 && !$isMobile
){
return self::MOBILE_GRADE_C;
}
// All older smartphone platforms and featurephones - Any device that doesn't support media queries
// will receive the basic, C grade experience.
return self::MOBILE_GRADE_C;
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.phpmailer.php'
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer - PHP email creation and transport class.
* @package PHPMailer
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
*/
class PHPMailer
{
/**
* The PHPMailer Version number.
* @var string
*/
public $Version = '5.2.26';
/**
* Email priority.
* Options: null (default), 1 = High, 3 = Normal, 5 = low.
* When null, the header is not set at all.
* @var integer
*/
public $Priority = null;
/**
* The character set of the message.
* @var string
*/
public $CharSet = 'iso-8859-1';
/**
* The MIME Content-type of the message.
* @var string
*/
public $ContentType = 'text/plain';
/**
* The message encoding.
* Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
* @var string
*/
public $Encoding = '8bit';
/**
* Holds the most recent mailer error message.
* @var string
*/
public $ErrorInfo = '';
/**
* The From email address for the message.
* @var string
*/
public $From = 'root@localhost';
/**
* The From name of the message.
* @var string
*/
public $FromName = 'Root User';
/**
* The Sender email (Return-Path) of the message.
* If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
* @var string
*/
public $Sender = '';
/**
* The Return-Path of the message.
* If empty, it will be set to either From or Sender.
* @var string
* @deprecated Email senders should never set a return-path header;
* it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
* @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
*/
public $ReturnPath = '';
/**
* The Subject of the message.
* @var string
*/
public $Subject = '';
/**
* An HTML or plain text message body.
* If HTML then call isHTML(true).
* @var string
*/
public $Body = '';
/**
* The plain-text message body.
* This body can be read by mail clients that do not have HTML email
* capability such as mutt & Eudora.
* Clients that can read HTML will view the normal Body.
* @var string
*/
public $AltBody = '';
/**
* An iCal message part body.
* Only supported in simple alt or alt_inline message types
* To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
* @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
* @link http://kigkonsult.se/iCalcreator/
* @var string
*/
public $Ical = '';
/**
* The complete compiled MIME message body.
* @access protected
* @var string
*/
protected $MIMEBody = '';
/**
* The complete compiled MIME message headers.
* @var string
* @access protected
*/
protected $MIMEHeader = '';
/**
* Extra headers that createHeader() doesn't fold in.
* @var string
* @access protected
*/
protected $mailHeader = '';
/**
* Word-wrap the message body to this number of chars.
* Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
* @var integer
*/
public $WordWrap = 0;
/**
* Which method to use to send mail.
* Options: "mail", "sendmail", or "smtp".
* @var string
*/
public $Mailer = 'mail';
/**
* The path to the sendmail program.
* @var string
*/
public $Sendmail = '/usr/sbin/sendmail';
/**
* Whether mail() uses a fully sendmail-compatible MTA.
* One which supports sendmail's "-oi -f" options.
* @var boolean
*/
public $UseSendmailOptions = true;
/**
* Path to PHPMailer plugins.
* Useful if the SMTP class is not in the PHP include path.
* @var string
* @deprecated Should not be needed now there is an autoloader.
*/
public $PluginDir = '';
/**
* The email address that a reading confirmation should be sent to, also known as read receipt.
* @var string
*/
public $ConfirmReadingTo = '';
/**
* The hostname to use in the Message-ID header and as default HELO string.
* If empty, PHPMailer attempts to find one with, in order,
* $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
* 'localhost.localdomain'.
* @var string
*/
public $Hostname = '';
/**
* An ID to be used in the Message-ID header.
* If empty, a unique id will be generated.
* You can set your own, but it must be in the format "<id@domain>",
* as defined in RFC5322 section 3.6.4 or it will be ignored.
* @see https://tools.ietf.org/html/rfc5322#section-3.6.4
* @var string
*/
public $MessageID = '';
/**
* The message Date to be used in the Date header.
* If empty, the current date will be added.
* @var string
*/
public $MessageDate = '';
/**
* SMTP hosts.
* Either a single hostname or multiple semicolon-delimited hostnames.
* You can also specify a different port
* for each host by using this format: [hostname:port]
* (e.g. "smtp1.example.com:25;smtp2.example.com").
* You can also specify encryption type, for example:
* (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
* Hosts will be tried in order.
* @var string
*/
public $Host = 'localhost';
/**
* The default SMTP server port.
* @var integer
* @TODO Why is this needed when the SMTP class takes care of it?
*/
public $Port = 25;
/**
* The SMTP HELO of the message.
* Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
* one with the same method described above for $Hostname.
* @var string
* @see PHPMailer::$Hostname
*/
public $Helo = '';
/**
* What kind of encryption to use on the SMTP connection.
* Options: '', 'ssl' or 'tls'
* @var string
*/
public $SMTPSecure = '';
/**
* Whether to enable TLS encryption automatically if a server supports it,
* even if `SMTPSecure` is not set to 'tls'.
* Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
* @var boolean
*/
public $SMTPAutoTLS = true;
/**
* Whether to use SMTP authentication.
* Uses the Username and Password properties.
* @var boolean
* @see PHPMailer::$Username
* @see PHPMailer::$Password
*/
public $SMTPAuth = false;
/**
* Options array passed to stream_context_create when connecting via SMTP.
* @var array
*/
public $SMTPOptions = array();
/**
* SMTP username.
* @var string
*/
public $Username = '';
/**
* SMTP password.
* @var string
*/
public $Password = '';
/**
* SMTP auth type.
* Options are CRAM-MD5, LOGIN, PLAIN, NTLM, XOAUTH2, attempted in that order if not specified
* @var string
*/
public $AuthType = '';
/**
* SMTP realm.
* Used for NTLM auth
* @var string
*/
public $Realm = '';
/**
* SMTP workstation.
* Used for NTLM auth
* @var string
*/
public $Workstation = '';
/**
* The SMTP server timeout in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* @var integer
*/
public $Timeout = 300;
/**
* SMTP class debug output mode.
* Debug output level.
* Options:
* * `0` No output
* * `1` Commands
* * `2` Data and commands
* * `3` As 2 plus connection status
* * `4` Low-level data output
* @var integer
* @see SMTP::$do_debug
*/
public $SMTPDebug = 0;
/**
* How to handle debug output.
* Options:
* * `echo` Output plain-text as-is, appropriate for CLI
* * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
* * `error_log` Output to error log as configured in php.ini
*
* Alternatively, you can provide a callable expecting two params: a message string and the debug level:
* <code>
* $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
* </code>
* @var string|callable
* @see SMTP::$Debugoutput
*/
public $Debugoutput = 'echo';
/**
* Whether to keep SMTP connection open after each message.
* If this is set to true then to close the connection
* requires an explicit call to smtpClose().
* @var boolean
*/
public $SMTPKeepAlive = false;
/**
* Whether to split multiple to addresses into multiple messages
* or send them all in one message.
* Only supported in `mail` and `sendmail` transports, not in SMTP.
* @var boolean
*/
public $SingleTo = false;
/**
* Storage for addresses when SingleTo is enabled.
* @var array
* @TODO This should really not be public
*/
public $SingleToArray = array();
/**
* Whether to generate VERP addresses on send.
* Only applicable when sending via SMTP.
* @link https://en.wikipedia.org/wiki/Variable_envelope_return_path
* @link http://www.postfix.org/VERP_README.html Postfix VERP info
* @var boolean
*/
public $do_verp = false;
/**
* Whether to allow sending messages with an empty body.
* @var boolean
*/
public $AllowEmpty = false;
/**
* The default line ending.
* @note The default remains "\n". We force CRLF where we know
* it must be used via self::CRLF.
* @var string
*/
public $LE = "\n";
/**
* DKIM selector.
* @var string
*/
public $DKIM_selector = '';
/**
* DKIM Identity.
* Usually the email address used as the source of the email.
* @var string
*/
public $DKIM_identity = '';
/**
* DKIM passphrase.
* Used if your key is encrypted.
* @var string
*/
public $DKIM_passphrase = '';
/**
* DKIM signing domain name.
* @example 'example.com'
* @var string
*/
public $DKIM_domain = '';
/**
* DKIM private key file path.
* @var string
*/
public $DKIM_private = '';
/**
* DKIM private key string.
* If set, takes precedence over `$DKIM_private`.
* @var string
*/
public $DKIM_private_string = '';
/**
* Callback Action function name.
*
* The function that handles the result of the send email action.
* It is called out by send() for each email sent.
*
* Value can be any php callable: http://www.php.net/is_callable
*
* Parameters:
* boolean $result result of the send action
* array $to email addresses of the recipients
* array $cc cc email addresses
* array $bcc bcc email addresses
* string $subject the subject
* string $body the email body
* string $from email address of sender
* @var string
*/
public $action_function = '';
/**
* What to put in the X-Mailer header.
* Options: An empty string for PHPMailer default, whitespace for none, or a string to use
* @var string
*/
public $XMailer = '';
/**
* Which validator to use by default when validating email addresses.
* May be a callable to inject your own validator, but there are several built-in validators.
* @see PHPMailer::validateAddress()
* @var string|callable
* @static
*/
public static $validator = 'auto';
/**
* An instance of the SMTP sender class.
* @var SMTP
* @access protected
*/
protected $smtp = null;
/**
* The array of 'to' names and addresses.
* @var array
* @access protected
*/
protected $to = array();
/**
* The array of 'cc' names and addresses.
* @var array
* @access protected
*/
protected $cc = array();
/**
* The array of 'bcc' names and addresses.
* @var array
* @access protected
*/
protected $bcc = array();
/**
* The array of reply-to names and addresses.
* @var array
* @access protected
*/
protected $ReplyTo = array();
/**
* An array of all kinds of addresses.
* Includes all of $to, $cc, $bcc
* @var array
* @access protected
* @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
*/
protected $all_recipients = array();
/**
* An array of names and addresses queued for validation.
* In send(), valid and non duplicate entries are moved to $all_recipients
* and one of $to, $cc, or $bcc.
* This array is used only for addresses with IDN.
* @var array
* @access protected
* @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
* @see PHPMailer::$all_recipients
*/
protected $RecipientsQueue = array();
/**
* An array of reply-to names and addresses queued for validation.
* In send(), valid and non duplicate entries are moved to $ReplyTo.
* This array is used only for addresses with IDN.
* @var array
* @access protected
* @see PHPMailer::$ReplyTo
*/
protected $ReplyToQueue = array();
/**
* The array of attachments.
* @var array
* @access protected
*/
protected $attachment = array();
/**
* The array of custom headers.
* @var array
* @access protected
*/
protected $CustomHeader = array();
/**
* The most recent Message-ID (including angular brackets).
* @var string
* @access protected
*/
protected $lastMessageID = '';
/**
* The message's MIME type.
* @var string
* @access protected
*/
protected $message_type = '';
/**
* The array of MIME boundary strings.
* @var array
* @access protected
*/
protected $boundary = array();
/**
* The array of available languages.
* @var array
* @access protected
*/
protected $language = array();
/**
* The number of errors encountered.
* @var integer
* @access protected
*/
protected $error_count = 0;
/**
* The S/MIME certificate file path.
* @var string
* @access protected
*/
protected $sign_cert_file = '';
/**
* The S/MIME key file path.
* @var string
* @access protected
*/
protected $sign_key_file = '';
/**
* The optional S/MIME extra certificates ("CA Chain") file path.
* @var string
* @access protected
*/
protected $sign_extracerts_file = '';
/**
* The S/MIME password for the key.
* Used only if the key is encrypted.
* @var string
* @access protected
*/
protected $sign_key_pass = '';
/**
* Whether to throw exceptions for errors.
* @var boolean
* @access protected
*/
protected $exceptions = false;
/**
* Unique ID used for message ID and boundaries.
* @var string
* @access protected
*/
protected $uniqueid = '';
/**
* Error severity: message only, continue processing.
*/
const STOP_MESSAGE = 0;
/**
* Error severity: message, likely ok to continue processing.
*/
const STOP_CONTINUE = 1;
/**
* Error severity: message, plus full stop, critical error reached.
*/
const STOP_CRITICAL = 2;
/**
* SMTP RFC standard line ending.
*/
const CRLF = "\r\n";
/**
* The maximum line length allowed by RFC 2822 section 2.1.1
* @var integer
*/
const MAX_LINE_LENGTH = 998;
/**
* Constructor.
* @param boolean $exceptions Should we throw external exceptions?
*/
public function __construct($exceptions = null)
{
if ($exceptions !== null) {
$this->exceptions = (boolean)$exceptions;
}
//Pick an appropriate debug output format automatically
$this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
}
/**
* Destructor.
*/
public function __destruct()
{
//Close any open SMTP connection nicely
$this->smtpClose();
}
/**
* Call mail() in a safe_mode-aware fashion.
* Also, unless sendmail_path points to sendmail (or something that
* claims to be sendmail), don't pass params (not a perfect fix,
* but it will do)
* @param string $to To
* @param string $subject Subject
* @param string $body Message Body
* @param string $header Additional Header(s)
* @param string $params Params
* @access private
* @return boolean
*/
private function mailPassthru($to, $subject, $body, $header, $params)
{
//Check overloading of mail function to avoid double-encoding
if (ini_get('mbstring.func_overload') & 1) {
$subject = $this->secureHeader($subject);
} else {
$subject = $this->encodeHeader($this->secureHeader($subject));
}
//Can't use additional_parameters in safe_mode, calling mail() with null params breaks
//@link http://php.net/manual/en/function.mail.php
if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) {
$result = @mail($to, $subject, $body, $header);
} else {
$result = @mail($to, $subject, $body, $header, $params);
}
return $result;
}
/**
* Output debugging info via user-defined method.
* Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
* @see PHPMailer::$Debugoutput
* @see PHPMailer::$SMTPDebug
* @param string $str
*/
protected function edebug($str)
{
if ($this->SMTPDebug <= 0) {
return;
}
//Avoid clash with built-in function names
if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
return;
}
switch ($this->Debugoutput) {
case 'error_log':
//Don't output, just log
error_log($str);
break;
case 'html':
//Cleans up output a bit for a better looking, HTML-safe output
echo htmlentities(
preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES,
'UTF-8'
)
. "<br>\n";
break;
case 'echo':
default:
//Normalize line breaks
$str = preg_replace('/\r\n?/ms', "\n", $str);
echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
"\n",
"\n \t ",
trim($str)
) . "\n";
}
}
/**
* Sets message type to HTML or plain.
* @param boolean $isHtml True for HTML mode.
* @return void
*/
public function isHTML($isHtml = true)
{
if ($isHtml) {
$this->ContentType = 'text/html';
} else {
$this->ContentType = 'text/plain';
}
}
/**
* Send messages using SMTP.
* @return void
*/
public function isSMTP()
{
$this->Mailer = 'smtp';
}
/**
* Send messages using PHP's mail() function.
* @return void
*/
public function isMail()
{
$this->Mailer = 'mail';
}
/**
* Send messages using $Sendmail.
* @return void
*/
public function isSendmail()
{
$ini_sendmail_path = ini_get('sendmail_path');
if (!stristr($ini_sendmail_path, 'sendmail')) {
$this->Sendmail = '/usr/sbin/sendmail';
} else {
$this->Sendmail = $ini_sendmail_path;
}
$this->Mailer = 'sendmail';
}
/**
* Send messages using qmail.
* @return void
*/
public function isQmail()
{
$ini_sendmail_path = ini_get('sendmail_path');
if (!stristr($ini_sendmail_path, 'qmail')) {
$this->Sendmail = '/var/qmail/bin/qmail-inject';
} else {
$this->Sendmail = $ini_sendmail_path;
}
$this->Mailer = 'qmail';
}
/**
* Add a "To" address.
* @param string $address The email address to send to
* @param string $name
* @return boolean true on success, false if address already used or invalid in some way
*/
public function addAddress($address, $name = '')
{
return $this->addOrEnqueueAnAddress('to', $address, $name);
}
/**
* Add a "CC" address.
* @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
* @param string $address The email address to send to
* @param string $name
* @return boolean true on success, false if address already used or invalid in some way
*/
public function addCC($address, $name = '')
{
return $this->addOrEnqueueAnAddress('cc', $address, $name);
}
/**
* Add a "BCC" address.
* @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
* @param string $address The email address to send to
* @param string $name
* @return boolean true on success, false if address already used or invalid in some way
*/
public function addBCC($address, $name = '')
{
return $this->addOrEnqueueAnAddress('bcc', $address, $name);
}
/**
* Add a "Reply-To" address.
* @param string $address The email address to reply to
* @param string $name
* @return boolean true on success, false if address already used or invalid in some way
*/
public function addReplyTo($address, $name = '')
{
return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
}
/**
* Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
* can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
* be modified after calling this function), addition of such addresses is delayed until send().
* Addresses that have been added already return false, but do not throw exceptions.
* @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
* @param string $address The email address to send, resp. to reply to
* @param string $name
* @throws phpmailerException
* @return boolean true on success, false if address already used or invalid in some way
* @access protected
*/
protected function addOrEnqueueAnAddress($kind, $address, $name)
{
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (($pos = strrpos($address, '@')) === false) {
// At-sign is misssing.
$error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new phpmailerException($error_message);
}
return false;
}
$params = array($kind, $address, $name);
// Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
if ($kind != 'Reply-To') {
if (!array_key_exists($address, $this->RecipientsQueue)) {
$this->RecipientsQueue[$address] = $params;
return true;
}
} else {
if (!array_key_exists($address, $this->ReplyToQueue)) {
$this->ReplyToQueue[$address] = $params;
return true;
}
}
return false;
}
// Immediately add standard addresses without IDN.
return call_user_func_array(array($this, 'addAnAddress'), $params);
}
/**
* Add an address to one of the recipient arrays or to the ReplyTo array.
* Addresses that have been added already return false, but do not throw exceptions.
* @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
* @param string $address The email address to send, resp. to reply to
* @param string $name
* @throws phpmailerException
* @return boolean true on success, false if address already used or invalid in some way
* @access protected
*/
protected function addAnAddress($kind, $address, $name = '')
{
if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) {
$error_message = $this->lang('Invalid recipient kind: ') . $kind;
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new phpmailerException($error_message);
}
return false;
}
if (!$this->validateAddress($address)) {
$error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new phpmailerException($error_message);
}
return false;
}
if ($kind != 'Reply-To') {
if (!array_key_exists(strtolower($address), $this->all_recipients)) {
array_push($this->$kind, array($address, $name));
$this->all_recipients[strtolower($address)] = true;
return true;
}
} else {
if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
$this->ReplyTo[strtolower($address)] = array($address, $name);
return true;
}
}
return false;
}
/**
* Parse and validate a string containing one or more RFC822-style comma-separated email addresses
* of the form "display name <address>" into an array of name/address pairs.
* Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
* Note that quotes in the name part are removed.
* @param string $addrstr The address list string
* @param bool $useimap Whether to use the IMAP extension to parse the list
* @return array
* @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
*/
public function parseAddresses($addrstr, $useimap = true)
{
$addresses = array();
if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
//Use this built-in parser if it's available
$list = imap_rfc822_parse_adrlist($addrstr, '');
foreach ($list as $address) {
if ($address->host != '.SYNTAX-ERROR.') {
if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
$addresses[] = array(
'name' => (property_exists($address, 'personal') ? $address->personal : ''),
'address' => $address->mailbox . '@' . $address->host
);
}
}
}
} else {
//Use this simpler parser
$list = explode(',', $addrstr);
foreach ($list as $address) {
$address = trim($address);
//Is there a separate name part?
if (strpos($address, '<') === false) {
//No separate name, just use the whole thing
if ($this->validateAddress($address)) {
$addresses[] = array(
'name' => '',
'address' => $address
);
}
} else {
list($name, $email) = explode('<', $address);
$email = trim(str_replace('>', '', $email));
if ($this->validateAddress($email)) {
$addresses[] = array(
'name' => trim(str_replace(array('"', "'"), '', $name)),
'address' => $email
);
}
}
}
}
return $addresses;
}
/**
* Set the From and FromName properties.
* @param string $address
* @param string $name
* @param boolean $auto Whether to also set the Sender address, defaults to true
* @throws phpmailerException
* @return boolean
*/
public function setFrom($address, $name = '', $auto = true)
{
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
// Don't validate now addresses with IDN. Will be done in send().
if (($pos = strrpos($address, '@')) === false or
(!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
!$this->validateAddress($address)) {
$error_message = $this->lang('invalid_address') . " (setFrom) $address";
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new phpmailerException($error_message);
}
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto) {
if (empty($this->Sender)) {
$this->Sender = $address;
}
}
return true;
}
/**
* Return the Message-ID header of the last email.
* Technically this is the value from the last time the headers were created,
* but it's also the message ID of the last sent message except in
* pathological cases.
* @return string
*/
public function getLastMessageID()
{
return $this->lastMessageID;
}
/**
* Check that a string looks like an email address.
* @param string $address The email address to check
* @param string|callable $patternselect A selector for the validation pattern to use :
* * `auto` Pick best pattern automatically;
* * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
* * `pcre` Use old PCRE implementation;
* * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
* * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
* * `noregex` Don't use a regex: super fast, really dumb.
* Alternatively you may pass in a callable to inject your own validator, for example:
* PHPMailer::validateAddress('user@example.com', function($address) {
* return (strpos($address, '@') !== false);
* });
* You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
* @return boolean
* @static
* @access public
*/
public static function validateAddress($address, $patternselect = null)
{
if (is_null($patternselect)) {
$patternselect = self::$validator;
}
if (is_callable($patternselect)) {
return call_user_func($patternselect, $address);
}
//Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
return false;
}
if (!$patternselect or $patternselect == 'auto') {
//Check this constant first so it works when extension_loaded() is disabled by safe mode
//Constant was added in PHP 5.2.4
if (defined('PCRE_VERSION')) {
//This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
$patternselect = 'pcre8';
} else {
$patternselect = 'pcre';
}
} elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
//Fall back to older PCRE
$patternselect = 'pcre';
} else {
//Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
$patternselect = 'php';
} else {
$patternselect = 'noregex';
}
}
}
switch ($patternselect) {
case 'pcre8':
/**
* Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
* @link http://squiloople.com/2009/12/20/email-address-validation/
* @copyright 2009-2010 Michael Rushton
* Feel free to use and redistribute this code. But please keep this copyright notice.
*/
return (boolean)preg_match(
'/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
'((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
'(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
'([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
'(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
'(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
'|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
'|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
'|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
$address
);
case 'pcre':
//An older regex that doesn't need a recent PCRE
return (boolean)preg_match(
'/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
'[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
'(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
'@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
'(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
'[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
'::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
'[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
'::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
'|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
$address
);
case 'html5':
/**
* This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
* @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
*/
return (boolean)preg_match(
'/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[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])?)*$/sD',
$address
);
case 'noregex':
//No PCRE! Do something _very_ approximate!
//Check the address is 3 chars or longer and contains an @ that's not the first or last char
return (strlen($address) >= 3
and strpos($address, '@') >= 1
and strpos($address, '@') != strlen($address) - 1);
case 'php':
default:
return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
}
}
/**
* Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
* "intl" and "mbstring" PHP extensions.
* @return bool "true" if required functions for IDN support are present
*/
public function idnSupported()
{
// @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2.
return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
}
/**
* Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
* Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
* This function silently returns unmodified address if:
* - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
* - Conversion to punycode is impossible (e.g. required PHP functions are not available)
* or fails for any reason (e.g. domain has characters not allowed in an IDN)
* @see PHPMailer::$CharSet
* @param string $address The email address to convert
* @return string The encoded address in ASCII form
*/
public function punyencodeAddress($address)
{
// Verify we have required functions, CharSet, and at-sign.
if ($this->idnSupported() and
!empty($this->CharSet) and
($pos = strrpos($address, '@')) !== false) {
$domain = substr($address, ++$pos);
// Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
$domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ?
idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) :
idn_to_ascii($domain)) !== false) {
return substr($address, 0, $pos) . $punycode;
}
}
}
return $address;
}
/**
* Create a message and send it.
* Uses the sending method specified by $Mailer.
* @throws phpmailerException
* @return boolean false on error - See the ErrorInfo property for details of the error.
*/
public function send()
{
try {
if (!$this->preSend()) {
return false;
}
return $this->postSend();
} catch (phpmailerException $exc) {
$this->mailHeader = '';
$this->setError($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
return false;
}
}
/**
* Prepare a message for sending.
* @throws phpmailerException
* @return boolean
*/
public function preSend()
{
try {
$this->error_count = 0; // Reset errors
$this->mailHeader = '';
// Dequeue recipient and Reply-To addresses with IDN
foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
$params[1] = $this->punyencodeAddress($params[1]);
call_user_func_array(array($this, 'addAnAddress'), $params);
}
if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
}
// Validate From, Sender, and ConfirmReadingTo addresses
foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) {
$this->$address_kind = trim($this->$address_kind);
if (empty($this->$address_kind)) {
continue;
}
$this->$address_kind = $this->punyencodeAddress($this->$address_kind);
if (!$this->validateAddress($this->$address_kind)) {
$error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind;
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new phpmailerException($error_message);
}
return false;
}
}
// Set whether the message is multipart/alternative
if ($this->alternativeExists()) {
$this->ContentType = 'multipart/alternative';
}
$this->setMessageType();
// Refuse to send an empty message unless we are specifically allowing it
if (!$this->AllowEmpty and empty($this->Body)) {
throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
}
// Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
$this->MIMEHeader = '';
$this->MIMEBody = $this->createBody();
// createBody may have added some headers, so retain them
$tempheaders = $this->MIMEHeader;
$this->MIMEHeader = $this->createHeader();
$this->MIMEHeader .= $tempheaders;
// To capture the complete message when using mail(), create
// an extra header list which createHeader() doesn't fold in
if ($this->Mailer == 'mail') {
if (count($this->to) > 0) {
$this->mailHeader .= $this->addrAppend('To', $this->to);
} else {
$this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
}
$this->mailHeader .= $this->headerLine(
'Subject',
$this->encodeHeader($this->secureHeader(trim($this->Subject)))
);
}
// Sign with DKIM if enabled
if (!empty($this->DKIM_domain)
&& !empty($this->DKIM_selector)
&& (!empty($this->DKIM_private_string)
|| (!empty($this->DKIM_private) && file_exists($this->DKIM_private))
)
) {
$header_dkim = $this->DKIM_Add(
$this->MIMEHeader . $this->mailHeader,
$this->encodeHeader($this->secureHeader($this->Subject)),
$this->MIMEBody
);
$this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
}
return true;
} catch (phpmailerException $exc) {
$this->setError($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
return false;
}
}
/**
* Actually send a message.
* Send the email via the selected mechanism
* @throws phpmailerException
* @return boolean
*/
public function postSend()
{
try {
// Choose the mailer and send through it
switch ($this->Mailer) {
case 'sendmail':
case 'qmail':
return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
case 'smtp':
return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
case 'mail':
return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
default:
$sendMethod = $this->Mailer.'Send';
if (method_exists($this, $sendMethod)) {
return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
}
return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
}
} catch (phpmailerException $exc) {
$this->setError($exc->getMessage());
$this->edebug($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
}
return false;
}
/**
* Send mail using the $Sendmail program.
* @param string $header The message headers
* @param string $body The message body
* @see PHPMailer::$Sendmail
* @throws phpmailerException
* @access protected
* @return boolean
*/
protected function sendmailSend($header, $body)
{
// CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
if ($this->Mailer == 'qmail') {
$sendmailFmt = '%s -f%s';
} else {
$sendmailFmt = '%s -oi -f%s -t';
}
} else {
if ($this->Mailer == 'qmail') {
$sendmailFmt = '%s';
} else {
$sendmailFmt = '%s -oi -t';
}
}
// TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing.
$sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
if ($this->SingleTo) {
foreach ($this->SingleToArray as $toAddr) {
if (!@$mail = popen($sendmail, 'w')) {
throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
fputs($mail, 'To: ' . $toAddr . "\n");
fputs($mail, $header);
fputs($mail, $body);
$result = pclose($mail);
$this->doCallback(
($result == 0),
array($toAddr),
$this->cc,
$this->bcc,
$this->Subject,
$body,
$this->From
);
if ($result != 0) {
throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
}
} else {
if (!@$mail = popen($sendmail, 'w')) {
throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
fputs($mail, $header);
fputs($mail, $body);
$result = pclose($mail);
$this->doCallback(
($result == 0),
$this->to,
$this->cc,
$this->bcc,
$this->Subject,
$body,
$this->From
);
if ($result != 0) {
throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
}
return true;
}
/**
* Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
*
* Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
* @param string $string The string to be validated
* @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
* @access protected
* @return boolean
*/
protected static function isShellSafe($string)
{
// Future-proof
if (escapeshellcmd($string) !== $string
or !in_array(escapeshellarg($string), array("'$string'", "\"$string\""))
) {
return false;
}
$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
$c = $string[$i];
// All other characters have a special meaning in at least one common shell, including = and +.
// Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
// Note that this does permit non-Latin alphanumeric characters based on the current locale.
if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
return false;
}
}
return true;
}
/**
* Send mail using the PHP mail() function.
* @param string $header The message headers
* @param string $body The message body
* @link http://www.php.net/manual/en/book.mail.php
* @throws phpmailerException
* @access protected
* @return boolean
*/
protected function mailSend($header, $body)
{
$toArr = array();
foreach ($this->to as $toaddr) {
$toArr[] = $this->addrFormat($toaddr);
}
$to = implode(', ', $toArr);
$params = null;
//This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
// CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
if (self::isShellSafe($this->Sender)) {
$params = sprintf('-f%s', $this->Sender);
}
}
if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) {
$old_from = ini_get('sendmail_from');
ini_set('sendmail_from', $this->Sender);
}
$result = false;
if ($this->SingleTo and count($toArr) > 1) {
foreach ($toArr as $toAddr) {
$result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
$this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
}
} else {
$result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
$this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
}
if (isset($old_from)) {
ini_set('sendmail_from', $old_from);
}
if (!$result) {
throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
}
return true;
}
/**
* Get an instance to use for SMTP operations.
* Override this function to load your own SMTP implementation
* @return SMTP
*/
public function getSMTPInstance()
{
if (!is_object($this->smtp)) {
$this->smtp = new SMTP;
}
return $this->smtp;
}
/**
* Send mail via SMTP.
* Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
* Uses the PHPMailerSMTP class by default.
* @see PHPMailer::getSMTPInstance() to use a different class.
* @param string $header The message headers
* @param string $body The message body
* @throws phpmailerException
* @uses SMTP
* @access protected
* @return boolean
*/
protected function smtpSend($header, $body)
{
$bad_rcpt = array();
if (!$this->smtpConnect($this->SMTPOptions)) {
throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
}
if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
$smtp_from = $this->Sender;
} else {
$smtp_from = $this->From;
}
if (!$this->smtp->mail($smtp_from)) {
$this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
}
// Attempt to send to all recipients
foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
foreach ($togroup as $to) {
if (!$this->smtp->recipient($to[0])) {
$error = $this->smtp->getError();
$bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
$isSent = false;
} else {
$isSent = true;
}
$this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
}
}
// Only send the DATA command if we have viable recipients
if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
}
if ($this->SMTPKeepAlive) {
$this->smtp->reset();
} else {
$this->smtp->quit();
$this->smtp->close();
}
//Create error message for any bad addresses
if (count($bad_rcpt) > 0) {
$errstr = '';
foreach ($bad_rcpt as $bad) {
$errstr .= $bad['to'] . ': ' . $bad['error'];
}
throw new phpmailerException(
$this->lang('recipients_failed') . $errstr,
self::STOP_CONTINUE
);
}
return true;
}
/**
* Initiate a connection to an SMTP server.
* Returns false if the operation failed.
* @param array $options An array of options compatible with stream_context_create()
* @uses SMTP
* @access public
* @throws phpmailerException
* @return boolean
*/
public function smtpConnect($options = null)
{
if (is_null($this->smtp)) {
$this->smtp = $this->getSMTPInstance();
}
//If no options are provided, use whatever is set in the instance
if (is_null($options)) {
$options = $this->SMTPOptions;
}
// Already connected?
if ($this->smtp->connected()) {
return true;
}
$this->smtp->setTimeout($this->Timeout);
$this->smtp->setDebugLevel($this->SMTPDebug);
$this->smtp->setDebugOutput($this->Debugoutput);
$this->smtp->setVerp($this->do_verp);
$hosts = explode(';', $this->Host);
$lastexception = null;
foreach ($hosts as $hostentry) {
$hostinfo = array();
if (!preg_match(
'/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/',
trim($hostentry),
$hostinfo
)) {
// Not a valid host entry
$this->edebug('Ignoring invalid host: ' . $hostentry);
continue;
}
// $hostinfo[2]: optional ssl or tls prefix
// $hostinfo[3]: the hostname
// $hostinfo[4]: optional port number
// The host string prefix can temporarily override the current setting for SMTPSecure
// If it's not specified, the default value is used
$prefix = '';
$secure = $this->SMTPSecure;
$tls = ($this->SMTPSecure == 'tls');
if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
$prefix = 'ssl://';
$tls = false; // Can't have SSL and TLS at the same time
$secure = 'ssl';
} elseif ($hostinfo[2] == 'tls') {
$tls = true;
// tls doesn't use a prefix
$secure = 'tls';
}
//Do we need the OpenSSL extension?
$sslext = defined('OPENSSL_ALGO_SHA1');
if ('tls' === $secure or 'ssl' === $secure) {
//Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
if (!$sslext) {
throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
}
}
$host = $hostinfo[3];
$port = $this->Port;
$tport = (integer)$hostinfo[4];
if ($tport > 0 and $tport < 65536) {
$port = $tport;
}
if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
try {
if ($this->Helo) {
$hello = $this->Helo;
} else {
$hello = $this->serverHostname();
}
$this->smtp->hello($hello);
//Automatically enable TLS encryption if:
// * it's not disabled
// * we have openssl extension
// * we are not already using SSL
// * the server offers STARTTLS
if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
$tls = true;
}
if ($tls) {
if (!$this->smtp->startTLS()) {
throw new phpmailerException($this->lang('connect_host'));
}
// We must resend EHLO after TLS negotiation
$this->smtp->hello($hello);
}
if ($this->SMTPAuth) {
if (!$this->smtp->authenticate(
$this->Username,
$this->Password,
$this->AuthType,
$this->Realm,
$this->Workstation
)
) {
throw new phpmailerException($this->lang('authenticate'));
}
}
return true;
} catch (phpmailerException $exc) {
$lastexception = $exc;
$this->edebug($exc->getMessage());
// We must have connected, but then failed TLS or Auth, so close connection nicely
$this->smtp->quit();
}
}
}
// If we get here, all connection attempts have failed, so close connection hard
$this->smtp->close();
// As we've caught all exceptions, just report whatever the last one was
if ($this->exceptions and !is_null($lastexception)) {
throw $lastexception;
}
return false;
}
/**
* Close the active SMTP session if one exists.
* @return void
*/
public function smtpClose()
{
if (is_a($this->smtp, 'SMTP')) {
if ($this->smtp->connected()) {
$this->smtp->quit();
$this->smtp->close();
}
}
}
/**
* Set the language for error messages.
* Returns false if it cannot load the language file.
* The default language is English.
* @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
* @param string $lang_path Path to the language file directory, with trailing separator (slash)
* @return boolean
* @access public
*/
public function setLanguage($langcode = 'en', $lang_path = '')
{
// Backwards compatibility for renamed language codes
$renamed_langcodes = array(
'br' => 'pt_br',
'cz' => 'cs',
'dk' => 'da',
'no' => 'nb',
'se' => 'sv',
'sr' => 'rs'
);
if (isset($renamed_langcodes[$langcode])) {
$langcode = $renamed_langcodes[$langcode];
}
// Define full set of translatable strings in English
$PHPMAILER_LANG = array(
'authenticate' => 'SMTP Error: Could not authenticate.',
'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
'data_not_accepted' => 'SMTP Error: data not accepted.',
'empty_message' => 'Message body empty',
'encoding' => 'Unknown encoding: ',
'execute' => 'Could not execute: ',
'file_access' => 'Could not access file: ',
'file_open' => 'File Error: Could not open file: ',
'from_failed' => 'The following From address failed: ',
'instantiate' => 'Could not instantiate mail function.',
'invalid_address' => 'Invalid address: ',
'mailer_not_supported' => ' mailer is not supported.',
'provide_address' => 'You must provide at least one recipient email address.',
'recipients_failed' => 'SMTP Error: The following recipients failed: ',
'signing' => 'Signing Error: ',
'smtp_connect_failed' => 'SMTP connect() failed.',
'smtp_error' => 'SMTP server error: ',
'variable_set' => 'Cannot set or reset variable: ',
'extension_missing' => 'Extension missing: '
);
if (empty($lang_path)) {
// Calculate an absolute path so it can work if CWD is not here
$lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
}
//Validate $langcode
if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
$langcode = 'en';
}
$foundlang = true;
$lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
// There is no English translation file
if ($langcode != 'en') {
// Make sure language file path is readable
if (!is_readable($lang_file)) {
$foundlang = false;
} else {
// Overwrite language-specific strings.
// This way we'll never have missing translation keys.
$foundlang = include $lang_file;
}
}
$this->language = $PHPMAILER_LANG;
return (boolean)$foundlang; // Returns false if language not found
}
/**
* Get the array of strings for the current language.
* @return array
*/
public function getTranslations()
{
return $this->language;
}
/**
* Create recipient headers.
* @access public
* @param string $type
* @param array $addr An array of recipient,
* where each recipient is a 2-element indexed array with element 0 containing an address
* and element 1 containing a name, like:
* array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
* @return string
*/
public function addrAppend($type, $addr)
{
$addresses = array();
foreach ($addr as $address) {
$addresses[] = $this->addrFormat($address);
}
return $type . ': ' . implode(', ', $addresses) . $this->LE;
}
/**
* Format an address for use in a message header.
* @access public
* @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
* like array('joe@example.com', 'Joe User')
* @return string
*/
public function addrFormat($addr)
{
if (empty($addr[1])) { // No name provided
return $this->secureHeader($addr[0]);
} else {
return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
$addr[0]
) . '>';
}
}
/**
* Word-wrap message.
* For use with mailers that do not automatically perform wrapping
* and for quoted-printable encoded messages.
* Original written by philippe.
* @param string $message The message to wrap
* @param integer $length The line length to wrap to
* @param boolean $qp_mode Whether to run in Quoted-Printable mode
* @access public
* @return string
*/
public function wrapText($message, $length, $qp_mode = false)
{
if ($qp_mode) {
$soft_break = sprintf(' =%s', $this->LE);
} else {
$soft_break = $this->LE;
}
// If utf-8 encoding is used, we will need to make sure we don't
// split multibyte characters when we wrap
$is_utf8 = (strtolower($this->CharSet) == 'utf-8');
$lelen = strlen($this->LE);
$crlflen = strlen(self::CRLF);
$message = $this->fixEOL($message);
//Remove a trailing line break
if (substr($message, -$lelen) == $this->LE) {
$message = substr($message, 0, -$lelen);
}
//Split message into lines
$lines = explode($this->LE, $message);
//Message will be rebuilt in here
$message = '';
foreach ($lines as $line) {
$words = explode(' ', $line);
$buf = '';
$firstword = true;
foreach ($words as $word) {
if ($qp_mode and (strlen($word) > $length)) {
$space_left = $length - strlen($buf) - $crlflen;
if (!$firstword) {
if ($space_left > 20) {
$len = $space_left;
if ($is_utf8) {
$len = $this->utf8CharBoundary($word, $len);
} elseif (substr($word, $len - 1, 1) == '=') {
$len--;
} elseif (substr($word, $len - 2, 1) == '=') {
$len -= 2;
}
$part = substr($word, 0, $len);
$word = substr($word, $len);
$buf .= ' ' . $part;
$message .= $buf . sprintf('=%s', self::CRLF);
} else {
$message .= $buf . $soft_break;
}
$buf = '';
}
while (strlen($word) > 0) {
if ($length <= 0) {
break;
}
$len = $length;
if ($is_utf8) {
$len = $this->utf8CharBoundary($word, $len);
} elseif (substr($word, $len - 1, 1) == '=') {
$len--;
} elseif (substr($word, $len - 2, 1) == '=') {
$len -= 2;
}
$part = substr($word, 0, $len);
$word = substr($word, $len);
if (strlen($word) > 0) {
$message .= $part . sprintf('=%s', self::CRLF);
} else {
$buf = $part;
}
}
} else {
$buf_o = $buf;
if (!$firstword) {
$buf .= ' ';
}
$buf .= $word;
if (strlen($buf) > $length and $buf_o != '') {
$message .= $buf_o . $soft_break;
$buf = $word;
}
}
$firstword = false;
}
$message .= $buf . self::CRLF;
}
return $message;
}
/**
* Find the last character boundary prior to $maxLength in a utf-8
* quoted-printable encoded string.
* Original written by Colin Brown.
* @access public
* @param string $encodedText utf-8 QP text
* @param integer $maxLength Find the last character boundary prior to this length
* @return integer
*/
public function utf8CharBoundary($encodedText, $maxLength)
{
$foundSplitPos = false;
$lookBack = 3;
while (!$foundSplitPos) {
$lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
$encodedCharPos = strpos($lastChunk, '=');
if (false !== $encodedCharPos) {
// Found start of encoded character byte within $lookBack block.
// Check the encoded byte value (the 2 chars after the '=')
$hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
$dec = hexdec($hex);
if ($dec < 128) {
// Single byte character.
// If the encoded char was found at pos 0, it will fit
// otherwise reduce maxLength to start of the encoded char
if ($encodedCharPos > 0) {
$maxLength = $maxLength - ($lookBack - $encodedCharPos);
}
$foundSplitPos = true;
} elseif ($dec >= 192) {
// First byte of a multi byte character
// Reduce maxLength to split at start of character
$maxLength = $maxLength - ($lookBack - $encodedCharPos);
$foundSplitPos = true;
} elseif ($dec < 192) {
// Middle byte of a multi byte character, look further back
$lookBack += 3;
}
} else {
// No encoded character found
$foundSplitPos = true;
}
}
return $maxLength;
}
/**
* Apply word wrapping to the message body.
* Wraps the message body to the number of chars set in the WordWrap property.
* You should only do this to plain-text bodies as wrapping HTML tags may break them.
* This is called automatically by createBody(), so you don't need to call it yourself.
* @access public
* @return void
*/
public function setWordWrap()
{
if ($this->WordWrap < 1) {
return;
}
switch ($this->message_type) {
case 'alt':
case 'alt_inline':
case 'alt_attach':
case 'alt_inline_attach':
$this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
break;
default:
$this->Body = $this->wrapText($this->Body, $this->WordWrap);
break;
}
}
/**
* Assemble message headers.
* @access public
* @return string The assembled headers
*/
public function createHeader()
{
$result = '';
$result .= $this->headerLine('Date', $this->MessageDate == '' ? self::rfcDate() : $this->MessageDate);
// To be created automatically by mail()
if ($this->SingleTo) {
if ($this->Mailer != 'mail') {
foreach ($this->to as $toaddr) {
$this->SingleToArray[] = $this->addrFormat($toaddr);
}
}
} else {
if (count($this->to) > 0) {
if ($this->Mailer != 'mail') {
$result .= $this->addrAppend('To', $this->to);
}
} elseif (count($this->cc) == 0) {
$result .= $this->headerLine('To', 'undisclosed-recipients:;');
}
}
$result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
// sendmail and mail() extract Cc from the header before sending
if (count($this->cc) > 0) {
$result .= $this->addrAppend('Cc', $this->cc);
}
// sendmail and mail() extract Bcc from the header before sending
if ((
$this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
)
and count($this->bcc) > 0
) {
$result .= $this->addrAppend('Bcc', $this->bcc);
}
if (count($this->ReplyTo) > 0) {
$result .= $this->addrAppend('Reply-To', $this->ReplyTo);
}
// mail() sets the subject itself
if ($this->Mailer != 'mail') {
$result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
}
// Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
// https://tools.ietf.org/html/rfc5322#section-3.6.4
if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
$this->lastMessageID = $this->MessageID;
} else {
$this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
}
$result .= $this->headerLine('Message-ID', $this->lastMessageID);
if (!is_null($this->Priority)) {
$result .= $this->headerLine('X-Priority', $this->Priority);
}
if ($this->XMailer == '') {
$result .= $this->headerLine(
'X-Mailer',
'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer)'
);
} else {
$myXmailer = trim($this->XMailer);
if ($myXmailer) {
$result .= $this->headerLine('X-Mailer', $myXmailer);
}
}
if ($this->ConfirmReadingTo != '') {
$result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
}
// Add custom headers
foreach ($this->CustomHeader as $header) {
$result .= $this->headerLine(
trim($header[0]),
$this->encodeHeader(trim($header[1]))
);
}
if (!$this->sign_key_file) {
$result .= $this->headerLine('MIME-Version', '1.0');
$result .= $this->getMailMIME();
}
return $result;
}
/**
* Get the message MIME type headers.
* @access public
* @return string
*/
public function getMailMIME()
{
$result = '';
$ismultipart = true;
switch ($this->message_type) {
case 'inline':
$result .= $this->headerLine('Content-Type', 'multipart/related;');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
case 'attach':
case 'inline_attach':
case 'alt_attach':
case 'alt_inline_attach':
$result .= $this->headerLine('Content-Type', 'multipart/mixed;');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
case 'alt':
case 'alt_inline':
$result .= $this->headerLine('Content-Type', 'multipart/alternative;');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
default:
// Catches case 'plain': and case '':
$result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
$ismultipart = false;
break;
}
// RFC1341 part 5 says 7bit is assumed if not specified
if ($this->Encoding != '7bit') {
// RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
if ($ismultipart) {
if ($this->Encoding == '8bit') {
$result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
}
// The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
} else {
$result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
}
}
if ($this->Mailer != 'mail') {
$result .= $this->LE;
}
return $result;
}
/**
* Returns the whole MIME message.
* Includes complete headers and body.
* Only valid post preSend().
* @see PHPMailer::preSend()
* @access public
* @return string
*/
public function getSentMIMEMessage()
{
return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody;
}
/**
* Create unique ID
* @return string
*/
protected function generateId() {
return md5(uniqid(time()));
}
/**
* Assemble the message body.
* Returns an empty string on failure.
* @access public
* @throws phpmailerException
* @return string The assembled message body
*/
public function createBody()
{
$body = '';
//Create unique IDs and preset boundaries
$this->uniqueid = $this->generateId();
$this->boundary[1] = 'b1_' . $this->uniqueid;
$this->boundary[2] = 'b2_' . $this->uniqueid;
$this->boundary[3] = 'b3_' . $this->uniqueid;
if ($this->sign_key_file) {
$body .= $this->getMailMIME() . $this->LE;
}
$this->setWordWrap();
$bodyEncoding = $this->Encoding;
$bodyCharSet = $this->CharSet;
//Can we do a 7-bit downgrade?
if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
$bodyEncoding = '7bit';
//All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
$bodyCharSet = 'us-ascii';
}
//If lines are too long, and we're not already using an encoding that will shorten them,
//change to quoted-printable transfer encoding for the body part only
if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
$bodyEncoding = 'quoted-printable';
}
$altBodyEncoding = $this->Encoding;
$altBodyCharSet = $this->CharSet;
//Can we do a 7-bit downgrade?
if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
$altBodyEncoding = '7bit';
//All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
$altBodyCharSet = 'us-ascii';
}
//If lines are too long, and we're not already using an encoding that will shorten them,
//change to quoted-printable transfer encoding for the alt body part only
if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) {
$altBodyEncoding = 'quoted-printable';
}
//Use this as a preamble in all multipart message types
$mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
switch ($this->message_type) {
case 'inline':
$body .= $mimepre;
$body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->attachAll('inline', $this->boundary[1]);
break;
case 'attach':
$body .= $mimepre;
$body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
case 'inline_attach':
$body .= $mimepre;
$body .= $this->textLine('--' . $this->boundary[1]);
$body .= $this->headerLine('Content-Type', 'multipart/related;');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
$body .= $this->LE;
$body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->attachAll('inline', $this->boundary[2]);
$body .= $this->LE;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
case 'alt':
$body .= $mimepre;
$body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
$body .= $this->encodeString($this->AltBody, $altBodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= $this->LE . $this->LE;
if (!empty($this->Ical)) {
$body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
$body .= $this->encodeString($this->Ical, $this->Encoding);
$body .= $this->LE . $this->LE;
}
$body .= $this->endBoundary($this->boundary[1]);
break;
case 'alt_inline':
$body .= $mimepre;
$body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
$body .= $this->encodeString($this->AltBody, $altBodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->textLine('--' . $this->boundary[1]);
$body .= $this->headerLine('Content-Type', 'multipart/related;');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
$body .= $this->LE;
$body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->attachAll('inline', $this->boundary[2]);
$body .= $this->LE;
$body .= $this->endBoundary($this->boundary[1]);
break;
case 'alt_attach':
$body .= $mimepre;
$body .= $this->textLine('--' . $this->boundary[1]);
$body .= $this->headerLine('Content-Type', 'multipart/alternative;');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
$body .= $this->LE;
$body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
$body .= $this->encodeString($this->AltBody, $altBodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->endBoundary($this->boundary[2]);
$body .= $this->LE;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
case 'alt_inline_attach':
$body .= $mimepre;
$body .= $this->textLine('--' . $this->boundary[1]);
$body .= $this->headerLine('Content-Type', 'multipart/alternative;');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
$body .= $this->LE;
$body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
$body .= $this->encodeString($this->AltBody, $altBodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->textLine('--' . $this->boundary[2]);
$body .= $this->headerLine('Content-Type', 'multipart/related;');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
$body .= $this->LE;
$body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= $this->LE . $this->LE;
$body .= $this->attachAll('inline', $this->boundary[3]);
$body .= $this->LE;
$body .= $this->endBoundary($this->boundary[2]);
$body .= $this->LE;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
default:
// Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
//Reset the `Encoding` property in case we changed it for line length reasons
$this->Encoding = $bodyEncoding;
$body .= $this->encodeString($this->Body, $this->Encoding);
break;
}
if ($this->isError()) {
$body = '';
} elseif ($this->sign_key_file) {
try {
if (!defined('PKCS7_TEXT')) {
throw new phpmailerException($this->lang('extension_missing') . 'openssl');
}
// @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
$file = tempnam(sys_get_temp_dir(), 'mail');
if (false === file_put_contents($file, $body)) {
throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
}
$signed = tempnam(sys_get_temp_dir(), 'signed');
//Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
if (empty($this->sign_extracerts_file)) {
$sign = @openssl_pkcs7_sign(
$file,
$signed,
'file://' . realpath($this->sign_cert_file),
array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
null
);
} else {
$sign = @openssl_pkcs7_sign(
$file,
$signed,
'file://' . realpath($this->sign_cert_file),
array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
null,
PKCS7_DETACHED,
$this->sign_extracerts_file
);
}
if ($sign) {
@unlink($file);
$body = file_get_contents($signed);
@unlink($signed);
//The message returned by openssl contains both headers and body, so need to split them up
$parts = explode("\n\n", $body, 2);
$this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
$body = $parts[1];
} else {
@unlink($file);
@unlink($signed);
throw new phpmailerException($this->lang('signing') . openssl_error_string());
}
} catch (phpmailerException $exc) {
$body = '';
if ($this->exceptions) {
throw $exc;
}
}
}
return $body;
}
/**
* Return the start of a message boundary.
* @access protected
* @param string $boundary
* @param string $charSet
* @param string $contentType
* @param string $encoding
* @return string
*/
protected function getBoundary($boundary, $charSet, $contentType, $encoding)
{
$result = '';
if ($charSet == '') {
$charSet = $this->CharSet;
}
if ($contentType == '') {
$contentType = $this->ContentType;
}
if ($encoding == '') {
$encoding = $this->Encoding;
}
$result .= $this->textLine('--' . $boundary);
$result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
$result .= $this->LE;
// RFC1341 part 5 says 7bit is assumed if not specified
if ($encoding != '7bit') {
$result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
}
$result .= $this->LE;
return $result;
}
/**
* Return the end of a message boundary.
* @access protected
* @param string $boundary
* @return string
*/
protected function endBoundary($boundary)
{
return $this->LE . '--' . $boundary . '--' . $this->LE;
}
/**
* Set the message type.
* PHPMailer only supports some preset message types, not arbitrary MIME structures.
* @access protected
* @return void
*/
protected function setMessageType()
{
$type = array();
if ($this->alternativeExists()) {
$type[] = 'alt';
}
if ($this->inlineImageExists()) {
$type[] = 'inline';
}
if ($this->attachmentExists()) {
$type[] = 'attach';
}
$this->message_type = implode('_', $type);
if ($this->message_type == '') {
//The 'plain' message_type refers to the message having a single body element, not that it is plain-text
$this->message_type = 'plain';
}
}
/**
* Format a header line.
* @access public
* @param string $name
* @param string $value
* @return string
*/
public function headerLine($name, $value)
{
return $name . ': ' . $value . $this->LE;
}
/**
* Return a formatted mail line.
* @access public
* @param string $value
* @return string
*/
public function textLine($value)
{
return $value . $this->LE;
}
/**
* Add an attachment from a path on the filesystem.
* Never use a user-supplied path to a file!
* Returns false if the file could not be found or read.
* @param string $path Path to the attachment.
* @param string $name Overrides the attachment name.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File extension (MIME) type.
* @param string $disposition Disposition to use
* @throws phpmailerException
* @return boolean
*/
public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
{
try {
if (!@is_file($path)) {
throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
}
// If a MIME type is not specified, try to work it out from the file name
if ($type == '') {
$type = self::filenameToType($path);
}
$filename = basename($path);
if ($name == '') {
$name = $filename;
}
$this->attachment[] = array(
0 => $path,
1 => $filename,
2 => $name,
3 => $encoding,
4 => $type,
5 => false, // isStringAttachment
6 => $disposition,
7 => 0
);
} catch (phpmailerException $exc) {
$this->setError($exc->getMessage());
$this->edebug($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
return false;
}
return true;
}
/**
* Return the array of attachments.
* @return array
*/
public function getAttachments()
{
return $this->attachment;
}
/**
* Attach all file, string, and binary attachments to the message.
* Returns an empty string on failure.
* @access protected
* @param string $disposition_type
* @param string $boundary
* @return string
*/
protected function attachAll($disposition_type, $boundary)
{
// Return text of body
$mime = array();
$cidUniq = array();
$incl = array();
// Add all attachments
foreach ($this->attachment as $attachment) {
// Check if it is a valid disposition_filter
if ($attachment[6] == $disposition_type) {
// Check for string attachment
$string = '';
$path = '';
$bString = $attachment[5];
if ($bString) {
$string = $attachment[0];
} else {
$path = $attachment[0];
}
$inclhash = md5(serialize($attachment));
if (in_array($inclhash, $incl)) {
continue;
}
$incl[] = $inclhash;
$name = $attachment[2];
$encoding = $attachment[3];
$type = $attachment[4];
$disposition = $attachment[6];
$cid = $attachment[7];
if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) {
continue;
}
$cidUniq[$cid] = true;
$mime[] = sprintf('--%s%s', $boundary, $this->LE);
//Only include a filename property if we have one
if (!empty($name)) {
$mime[] = sprintf(
'Content-Type: %s; name="%s"%s',
$type,
$this->encodeHeader($this->secureHeader($name)),
$this->LE
);
} else {
$mime[] = sprintf(
'Content-Type: %s%s',
$type,
$this->LE
);
}
// RFC1341 part 5 says 7bit is assumed if not specified
if ($encoding != '7bit') {
$mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
}
if ($disposition == 'inline') {
$mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
}
// If a filename contains any of these chars, it should be quoted,
// but not otherwise: RFC2183 & RFC2045 5.1
// Fixes a warning in IETF's msglint MIME checker
// Allow for bypassing the Content-Disposition header totally
if (!(empty($disposition))) {
$encoded_name = $this->encodeHeader($this->secureHeader($name));
if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
$mime[] = sprintf(
'Content-Disposition: %s; filename="%s"%s',
$disposition,
$encoded_name,
$this->LE . $this->LE
);
} else {
if (!empty($encoded_name)) {
$mime[] = sprintf(
'Content-Disposition: %s; filename=%s%s',
$disposition,
$encoded_name,
$this->LE . $this->LE
);
} else {
$mime[] = sprintf(
'Content-Disposition: %s%s',
$disposition,
$this->LE . $this->LE
);
}
}
} else {
$mime[] = $this->LE;
}
// Encode as string attachment
if ($bString) {
$mime[] = $this->encodeString($string, $encoding);
if ($this->isError()) {
return '';
}
$mime[] = $this->LE . $this->LE;
} else {
$mime[] = $this->encodeFile($path, $encoding);
if ($this->isError()) {
return '';
}
$mime[] = $this->LE . $this->LE;
}
}
}
$mime[] = sprintf('--%s--%s', $boundary, $this->LE);
return implode('', $mime);
}
/**
* Encode a file attachment in requested format.
* Returns an empty string on failure.
* @param string $path The full path to the file
* @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
* @throws phpmailerException
* @access protected
* @return string
*/
protected function encodeFile($path, $encoding = 'base64')
{
try {
if (!is_readable($path)) {
throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
}
$magic_quotes = get_magic_quotes_runtime();
if ($magic_quotes) {
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
set_magic_quotes_runtime(false);
} else {
//Doesn't exist in PHP 5.4, but we don't need to check because
//get_magic_quotes_runtime always returns false in 5.4+
//so it will never get here
ini_set('magic_quotes_runtime', false);
}
}
$file_buffer = file_get_contents($path);
$file_buffer = $this->encodeString($file_buffer, $encoding);
if ($magic_quotes) {
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
set_magic_quotes_runtime($magic_quotes);
} else {
ini_set('magic_quotes_runtime', $magic_quotes);
}
}
return $file_buffer;
} catch (Exception $exc) {
$this->setError($exc->getMessage());
return '';
}
}
/**
* Encode a string in requested format.
* Returns an empty string on failure.
* @param string $str The text to encode
* @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
* @access public
* @return string
*/
public function encodeString($str, $encoding = 'base64')
{
$encoded = '';
switch (strtolower($encoding)) {
case 'base64':
$encoded = chunk_split(base64_encode($str), 76, $this->LE);
break;
case '7bit':
case '8bit':
$encoded = $this->fixEOL($str);
// Make sure it ends with a line break
if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
$encoded .= $this->LE;
}
break;
case 'binary':
$encoded = $str;
break;
case 'quoted-printable':
$encoded = $this->encodeQP($str);
break;
default:
$this->setError($this->lang('encoding') . $encoding);
break;
}
return $encoded;
}
/**
* Encode a header string optimally.
* Picks shortest of Q, B, quoted-printable or none.
* @access public
* @param string $str
* @param string $position
* @return string
*/
public function encodeHeader($str, $position = 'text')
{
$matchcount = 0;
switch (strtolower($position)) {
case 'phrase':
if (!preg_match('/[\200-\377]/', $str)) {
// Can't use addslashes as we don't know the value of magic_quotes_sybase
$encoded = addcslashes($str, "\0..\37\177\\\"");
if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
return ($encoded);
} else {
return ("\"$encoded\"");
}
}
$matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
break;
/** @noinspection PhpMissingBreakStatementInspection */
case 'comment':
$matchcount = preg_match_all('/[()"]/', $str, $matches);
// Intentional fall-through
case 'text':
default:
$matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
break;
}
//There are no chars that need encoding
if ($matchcount == 0) {
return ($str);
}
$maxlen = 75 - 7 - strlen($this->CharSet);
// Try to select the encoding which should produce the shortest output
if ($matchcount > strlen($str) / 3) {
// More than a third of the content will need encoding, so B encoding will be most efficient
$encoding = 'B';
if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
// Use a custom function which correctly encodes and wraps long
// multibyte strings without breaking lines within a character
$encoded = $this->base64EncodeWrapMB($str, "\n");
} else {
$encoded = base64_encode($str);
$maxlen -= $maxlen % 4;
$encoded = trim(chunk_split($encoded, $maxlen, "\n"));
}
} else {
$encoding = 'Q';
$encoded = $this->encodeQ($str, $position);
$encoded = $this->wrapText($encoded, $maxlen, true);
$encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
}
$encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
$encoded = trim(str_replace("\n", $this->LE, $encoded));
return $encoded;
}
/**
* Check if a string contains multi-byte characters.
* @access public
* @param string $str multi-byte text to wrap encode
* @return boolean
*/
public function hasMultiBytes($str)
{
if (function_exists('mb_strlen')) {
return (strlen($str) > mb_strlen($str, $this->CharSet));
} else { // Assume no multibytes (we can't handle without mbstring functions anyway)
return false;
}
}
/**
* Does a string contain any 8-bit chars (in any charset)?
* @param string $text
* @return boolean
*/
public function has8bitChars($text)
{
return (boolean)preg_match('/[\x80-\xFF]/', $text);
}
/**
* Encode and wrap long multibyte strings for mail headers
* without breaking lines within a character.
* Adapted from a function by paravoid
* @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
* @access public
* @param string $str multi-byte text to wrap encode
* @param string $linebreak string to use as linefeed/end-of-line
* @return string
*/
public function base64EncodeWrapMB($str, $linebreak = null)
{
$start = '=?' . $this->CharSet . '?B?';
$end = '?=';
$encoded = '';
if ($linebreak === null) {
$linebreak = $this->LE;
}
$mb_length = mb_strlen($str, $this->CharSet);
// Each line must have length <= 75, including $start and $end
$length = 75 - strlen($start) - strlen($end);
// Average multi-byte ratio
$ratio = $mb_length / strlen($str);
// Base64 has a 4:3 ratio
$avgLength = floor($length * $ratio * .75);
for ($i = 0; $i < $mb_length; $i += $offset) {
$lookBack = 0;
do {
$offset = $avgLength - $lookBack;
$chunk = mb_substr($str, $i, $offset, $this->CharSet);
$chunk = base64_encode($chunk);
$lookBack++;
} while (strlen($chunk) > $length);
$encoded .= $chunk . $linebreak;
}
// Chomp the last linefeed
$encoded = substr($encoded, 0, -strlen($linebreak));
return $encoded;
}
/**
* Encode a string in quoted-printable format.
* According to RFC2045 section 6.7.
* @access public
* @param string $string The text to encode
* @param integer $line_max Number of chars allowed on a line before wrapping
* @return string
* @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
*/
public function encodeQP($string, $line_max = 76)
{
// Use native function if it's available (>= PHP5.3)
if (function_exists('quoted_printable_encode')) {
return quoted_printable_encode($string);
}
// Fall back to a pure PHP implementation
$string = str_replace(
array('%20', '%0D%0A.', '%0D%0A', '%'),
array(' ', "\r\n=2E", "\r\n", '='),
rawurlencode($string)
);
return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
}
/**
* Backward compatibility wrapper for an old QP encoding function that was removed.
* @see PHPMailer::encodeQP()
* @access public
* @param string $string
* @param integer $line_max
* @param boolean $space_conv
* @return string
* @deprecated Use encodeQP instead.
*/
public function encodeQPphp(
$string,
$line_max = 76,
/** @noinspection PhpUnusedParameterInspection */ $space_conv = false
) {
return $this->encodeQP($string, $line_max);
}
/**
* Encode a string using Q encoding.
* @link http://tools.ietf.org/html/rfc2047
* @param string $str the text to encode
* @param string $position Where the text is going to be used, see the RFC for what that means
* @access public
* @return string
*/
public function encodeQ($str, $position = 'text')
{
// There should not be any EOL in the string
$pattern = '';
$encoded = str_replace(array("\r", "\n"), '', $str);
switch (strtolower($position)) {
case 'phrase':
// RFC 2047 section 5.3
$pattern = '^A-Za-z0-9!*+\/ -';
break;
/** @noinspection PhpMissingBreakStatementInspection */
case 'comment':
// RFC 2047 section 5.2
$pattern = '\(\)"';
// intentional fall-through
// for this reason we build the $pattern without including delimiters and []
case 'text':
default:
// RFC 2047 section 5.1
// Replace every high ascii, control, =, ? and _ characters
$pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
break;
}
$matches = array();
if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
// If the string contains an '=', make sure it's the first thing we replace
// so as to avoid double-encoding
$eqkey = array_search('=', $matches[0]);
if (false !== $eqkey) {
unset($matches[0][$eqkey]);
array_unshift($matches[0], '=');
}
foreach (array_unique($matches[0]) as $char) {
$encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
}
}
// Replace every spaces to _ (more readable than =20)
return str_replace(' ', '_', $encoded);
}
/**
* Add a string or binary attachment (non-filesystem).
* This method can be used to attach ascii or binary data,
* such as a BLOB record from a database.
* @param string $string String attachment data.
* @param string $filename Name of the attachment.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File extension (MIME) type.
* @param string $disposition Disposition to use
* @return void
*/
public function addStringAttachment(
$string,
$filename,
$encoding = 'base64',
$type = '',
$disposition = 'attachment'
) {
// If a MIME type is not specified, try to work it out from the file name
if ($type == '') {
$type = self::filenameToType($filename);
}
// Append to $attachment array
$this->attachment[] = array(
0 => $string,
1 => $filename,
2 => basename($filename),
3 => $encoding,
4 => $type,
5 => true, // isStringAttachment
6 => $disposition,
7 => 0
);
}
/**
* Add an embedded (inline) attachment from a file.
* This can include images, sounds, and just about any other document type.
* These differ from 'regular' attachments in that they are intended to be
* displayed inline with the message, not just attached for download.
* This is used in HTML messages that embed the images
* the HTML refers to using the $cid value.
* Never use a user-supplied path to a file!
* @param string $path Path to the attachment.
* @param string $cid Content ID of the attachment; Use this to reference
* the content when using an embedded image in HTML.
* @param string $name Overrides the attachment name.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File MIME type.
* @param string $disposition Disposition to use
* @return boolean True on successfully adding an attachment
*/
public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
{
if (!@is_file($path)) {
$this->setError($this->lang('file_access') . $path);
return false;
}
// If a MIME type is not specified, try to work it out from the file name
if ($type == '') {
$type = self::filenameToType($path);
}
$filename = basename($path);
if ($name == '') {
$name = $filename;
}
// Append to $attachment array
$this->attachment[] = array(
0 => $path,
1 => $filename,
2 => $name,
3 => $encoding,
4 => $type,
5 => false, // isStringAttachment
6 => $disposition,
7 => $cid
);
return true;
}
/**
* Add an embedded stringified attachment.
* This can include images, sounds, and just about any other document type.
* Be sure to set the $type to an image type for images:
* JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
* @param string $string The attachment binary data.
* @param string $cid Content ID of the attachment; Use this to reference
* the content when using an embedded image in HTML.
* @param string $name
* @param string $encoding File encoding (see $Encoding).
* @param string $type MIME type.
* @param string $disposition Disposition to use
* @return boolean True on successfully adding an attachment
*/
public function addStringEmbeddedImage(
$string,
$cid,
$name = '',
$encoding = 'base64',
$type = '',
$disposition = 'inline'
) {
// If a MIME type is not specified, try to work it out from the name
if ($type == '' and !empty($name)) {
$type = self::filenameToType($name);
}
// Append to $attachment array
$this->attachment[] = array(
0 => $string,
1 => $name,
2 => $name,
3 => $encoding,
4 => $type,
5 => true, // isStringAttachment
6 => $disposition,
7 => $cid
);
return true;
}
/**
* Check if an inline attachment is present.
* @access public
* @return boolean
*/
public function inlineImageExists()
{
foreach ($this->attachment as $attachment) {
if ($attachment[6] == 'inline') {
return true;
}
}
return false;
}
/**
* Check if an attachment (non-inline) is present.
* @return boolean
*/
public function attachmentExists()
{
foreach ($this->attachment as $attachment) {
if ($attachment[6] == 'attachment') {
return true;
}
}
return false;
}
/**
* Check if this message has an alternative body set.
* @return boolean
*/
public function alternativeExists()
{
return !empty($this->AltBody);
}
/**
* Clear queued addresses of given kind.
* @access protected
* @param string $kind 'to', 'cc', or 'bcc'
* @return void
*/
public function clearQueuedAddresses($kind)
{
$RecipientsQueue = $this->RecipientsQueue;
foreach ($RecipientsQueue as $address => $params) {
if ($params[0] == $kind) {
unset($this->RecipientsQueue[$address]);
}
}
}
/**
* Clear all To recipients.
* @return void
*/
public function clearAddresses()
{
foreach ($this->to as $to) {
unset($this->all_recipients[strtolower($to[0])]);
}
$this->to = array();
$this->clearQueuedAddresses('to');
}
/**
* Clear all CC recipients.
* @return void
*/
public function clearCCs()
{
foreach ($this->cc as $cc) {
unset($this->all_recipients[strtolower($cc[0])]);
}
$this->cc = array();
$this->clearQueuedAddresses('cc');
}
/**
* Clear all BCC recipients.
* @return void
*/
public function clearBCCs()
{
foreach ($this->bcc as $bcc) {
unset($this->all_recipients[strtolower($bcc[0])]);
}
$this->bcc = array();
$this->clearQueuedAddresses('bcc');
}
/**
* Clear all ReplyTo recipients.
* @return void
*/
public function clearReplyTos()
{
$this->ReplyTo = array();
$this->ReplyToQueue = array();
}
/**
* Clear all recipient types.
* @return void
*/
public function clearAllRecipients()
{
$this->to = array();
$this->cc = array();
$this->bcc = array();
$this->all_recipients = array();
$this->RecipientsQueue = array();
}
/**
* Clear all filesystem, string, and binary attachments.
* @return void
*/
public function clearAttachments()
{
$this->attachment = array();
}
/**
* Clear all custom headers.
* @return void
*/
public function clearCustomHeaders()
{
$this->CustomHeader = array();
}
/**
* Add an error message to the error container.
* @access protected
* @param string $msg
* @return void
*/
protected function setError($msg)
{
$this->error_count++;
if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
$lasterror = $this->smtp->getError();
if (!empty($lasterror['error'])) {
$msg .= $this->lang('smtp_error') . $lasterror['error'];
if (!empty($lasterror['detail'])) {
$msg .= ' Detail: '. $lasterror['detail'];
}
if (!empty($lasterror['smtp_code'])) {
$msg .= ' SMTP code: ' . $lasterror['smtp_code'];
}
if (!empty($lasterror['smtp_code_ex'])) {
$msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
}
}
}
$this->ErrorInfo = $msg;
}
/**
* Return an RFC 822 formatted date.
* @access public
* @return string
* @static
*/
public static function rfcDate()
{
// Set the time zone to whatever the default is to avoid 500 errors
// Will default to UTC if it's not set properly in php.ini
date_default_timezone_set(@date_default_timezone_get());
return date('D, j M Y H:i:s O');
}
/**
* Get the server hostname.
* Returns 'localhost.localdomain' if unknown.
* @access protected
* @return string
*/
protected function serverHostname()
{
$result = 'localhost.localdomain';
if (!empty($this->Hostname)) {
$result = $this->Hostname;
} elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
$result = $_SERVER['SERVER_NAME'];
} elseif (function_exists('gethostname') && gethostname() !== false) {
$result = gethostname();
} elseif (php_uname('n') !== false) {
$result = php_uname('n');
}
return $result;
}
/**
* Get an error message in the current language.
* @access protected
* @param string $key
* @return string
*/
protected function lang($key)
{
if (count($this->language) < 1) {
$this->setLanguage('en'); // set the default language
}
if (array_key_exists($key, $this->language)) {
if ($key == 'smtp_connect_failed') {
//Include a link to troubleshooting docs on SMTP connection failure
//this is by far the biggest cause of support questions
//but it's usually not PHPMailer's fault.
return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
}
return $this->language[$key];
} else {
//Return the key as a fallback
return $key;
}
}
/**
* Check if an error occurred.
* @access public
* @return boolean True if an error did occur.
*/
public function isError()
{
return ($this->error_count > 0);
}
/**
* Ensure consistent line endings in a string.
* Changes every end of line from CRLF, CR or LF to $this->LE.
* @access public
* @param string $str String to fixEOL
* @return string
*/
public function fixEOL($str)
{
// Normalise to \n
$nstr = str_replace(array("\r\n", "\r"), "\n", $str);
// Now convert LE as needed
if ($this->LE !== "\n") {
$nstr = str_replace("\n", $this->LE, $nstr);
}
return $nstr;
}
/**
* Add a custom header.
* $name value can be overloaded to contain
* both header name and value (name:value)
* @access public
* @param string $name Custom header name
* @param string $value Header value
* @return void
*/
public function addCustomHeader($name, $value = null)
{
if ($value === null) {
// Value passed in as name:value
$this->CustomHeader[] = explode(':', $name, 2);
} else {
$this->CustomHeader[] = array($name, $value);
}
}
/**
* Returns all custom headers.
* @return array
*/
public function getCustomHeaders()
{
return $this->CustomHeader;
}
/**
* Create a message body from an HTML string.
* Automatically inlines images and creates a plain-text version by converting the HTML,
* overwriting any existing values in Body and AltBody.
* Do not source $message content from user input!
* $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
* will look for an image file in $basedir/images/a.png and convert it to inline.
* If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
* If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
* @access public
* @param string $message HTML message string
* @param string $basedir Absolute path to a base directory to prepend to relative paths to images
* @param boolean|callable $advanced Whether to use the internal HTML to text converter
* or your own custom converter @see PHPMailer::html2text()
* @return string $message The transformed message Body
*/
public function msgHTML($message, $basedir = '', $advanced = false)
{
preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
if (array_key_exists(2, $images)) {
if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
// Ensure $basedir has a trailing /
$basedir .= '/';
}
foreach ($images[2] as $imgindex => $url) {
// Convert data URIs into embedded images
if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
$data = substr($url, strpos($url, ','));
if ($match[2]) {
$data = base64_decode($data);
} else {
$data = rawurldecode($data);
}
$cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) {
$message = str_replace(
$images[0][$imgindex],
$images[1][$imgindex] . '="cid:' . $cid . '"',
$message
);
}
continue;
}
if (
// Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
!empty($basedir)
// Ignore URLs containing parent dir traversal (..)
&& (strpos($url, '..') === false)
// Do not change urls that are already inline images
&& substr($url, 0, 4) !== 'cid:'
// Do not change absolute URLs, including anonymous protocol
&& !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
) {
$filename = basename($url);
$directory = dirname($url);
if ($directory == '.') {
$directory = '';
}
$cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
if (strlen($directory) > 1 && substr($directory, -1) != '/') {
$directory .= '/';
}
if ($this->addEmbeddedImage(
$basedir . $directory . $filename,
$cid,
$filename,
'base64',
self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
)
) {
$message = preg_replace(
'/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
$images[1][$imgindex] . '="cid:' . $cid . '"',
$message
);
}
}
}
}
$this->isHTML(true);
// Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
$this->Body = $this->normalizeBreaks($message);
$this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
if (!$this->alternativeExists()) {
$this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
self::CRLF . self::CRLF;
}
return $this->Body;
}
/**
* Convert an HTML string into plain text.
* This is used by msgHTML().
* Note - older versions of this function used a bundled advanced converter
* which was been removed for license reasons in #232.
* Example usage:
* <code>
* // Use default conversion
* $plain = $mail->html2text($html);
* // Use your own custom converter
* $plain = $mail->html2text($html, function($html) {
* $converter = new MyHtml2text($html);
* return $converter->get_text();
* });
* </code>
* @param string $html The HTML text to convert
* @param boolean|callable $advanced Any boolean value to use the internal converter,
* or provide your own callable for custom conversion.
* @return string
*/
public function html2text($html, $advanced = false)
{
if (is_callable($advanced)) {
return call_user_func($advanced, $html);
}
return html_entity_decode(
trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
ENT_QUOTES,
$this->CharSet
);
}
/**
* Get the MIME type for a file extension.
* @param string $ext File extension
* @access public
* @return string MIME type of file.
* @static
*/
public static function _mime_types($ext = '')
{
$mimes = array(
'xl' => 'application/excel',
'js' => 'application/javascript',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'bin' => 'application/macbinary',
'doc' => 'application/msword',
'word' => 'application/msword',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'class' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'psd' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'so' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => 'application/pdf',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'php3' => 'application/x-httpd-php',
'php4' => 'application/x-httpd-php',
'php' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => 'application/x-tar',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'zip' => 'application/zip',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mpga' => 'audio/mpeg',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'wav' => 'audio/x-wav',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'jpeg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'eml' => 'message/rfc822',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'shtml' => 'text/html',
'log' => 'text/plain',
'text' => 'text/plain',
'txt' => 'text/plain',
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'vcf' => 'text/vcard',
'vcard' => 'text/vcard',
'xml' => 'text/xml',
'xsl' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mov' => 'video/quicktime',
'qt' => 'video/quicktime',
'rv' => 'video/vnd.rn-realvideo',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie'
);
if (array_key_exists(strtolower($ext), $mimes)) {
return $mimes[strtolower($ext)];
}
return 'application/octet-stream';
}
/**
* Map a file name to a MIME type.
* Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
* @param string $filename A file name or full path, does not need to exist as a file
* @return string
* @static
*/
public static function filenameToType($filename)
{
// In case the path is a URL, strip any query string before getting extension
$qpos = strpos($filename, '?');
if (false !== $qpos) {
$filename = substr($filename, 0, $qpos);
}
$pathinfo = self::mb_pathinfo($filename);
return self::_mime_types($pathinfo['extension']);
}
/**
* Multi-byte-safe pathinfo replacement.
* Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
* Works similarly to the one in PHP >= 5.2.0
* @link http://www.php.net/manual/en/function.pathinfo.php#107461
* @param string $path A filename or path, does not need to exist as a file
* @param integer|string $options Either a PATHINFO_* constant,
* or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
* @return string|array
* @static
*/
public static function mb_pathinfo($path, $options = null)
{
$ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
$pathinfo = array();
if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
if (array_key_exists(1, $pathinfo)) {
$ret['dirname'] = $pathinfo[1];
}
if (array_key_exists(2, $pathinfo)) {
$ret['basename'] = $pathinfo[2];
}
if (array_key_exists(5, $pathinfo)) {
$ret['extension'] = $pathinfo[5];
}
if (array_key_exists(3, $pathinfo)) {
$ret['filename'] = $pathinfo[3];
}
}
switch ($options) {
case PATHINFO_DIRNAME:
case 'dirname':
return $ret['dirname'];
case PATHINFO_BASENAME:
case 'basename':
return $ret['basename'];
case PATHINFO_EXTENSION:
case 'extension':
return $ret['extension'];
case PATHINFO_FILENAME:
case 'filename':
return $ret['filename'];
default:
return $ret;
}
}
/**
* Set or reset instance properties.
* You should avoid this function - it's more verbose, less efficient, more error-prone and
* harder to debug than setting properties directly.
* Usage Example:
* `$mail->set('SMTPSecure', 'tls');`
* is the same as:
* `$mail->SMTPSecure = 'tls';`
* @access public
* @param string $name The property name to set
* @param mixed $value The value to set the property to
* @return boolean
* @TODO Should this not be using the __set() magic function?
*/
public function set($name, $value = '')
{
if (property_exists($this, $name)) {
$this->$name = $value;
return true;
} else {
$this->setError($this->lang('variable_set') . $name);
return false;
}
}
/**
* Strip newlines to prevent header injection.
* @access public
* @param string $str
* @return string
*/
public function secureHeader($str)
{
return trim(str_replace(array("\r", "\n"), '', $str));
}
/**
* Normalize line breaks in a string.
* Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
* Defaults to CRLF (for message bodies) and preserves consecutive breaks.
* @param string $text
* @param string $breaktype What kind of line break to use, defaults to CRLF
* @return string
* @access public
* @static
*/
public static function normalizeBreaks($text, $breaktype = "\r\n")
{
return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
}
/**
* Set the public and private key files and password for S/MIME signing.
* @access public
* @param string $cert_filename
* @param string $key_filename
* @param string $key_pass Password for private key
* @param string $extracerts_filename Optional path to chain certificate
*/
public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
{
$this->sign_cert_file = $cert_filename;
$this->sign_key_file = $key_filename;
$this->sign_key_pass = $key_pass;
$this->sign_extracerts_file = $extracerts_filename;
}
/**
* Quoted-Printable-encode a DKIM header.
* @access public
* @param string $txt
* @return string
*/
public function DKIM_QP($txt)
{
$line = '';
for ($i = 0; $i < strlen($txt); $i++) {
$ord = ord($txt[$i]);
if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
$line .= $txt[$i];
} else {
$line .= '=' . sprintf('%02X', $ord);
}
}
return $line;
}
/**
* Generate a DKIM signature.
* @access public
* @param string $signHeader
* @throws phpmailerException
* @return string The DKIM signature value
*/
public function DKIM_Sign($signHeader)
{
if (!defined('PKCS7_TEXT')) {
if ($this->exceptions) {
throw new phpmailerException($this->lang('extension_missing') . 'openssl');
}
return '';
}
$privKeyStr = !empty($this->DKIM_private_string) ? $this->DKIM_private_string : file_get_contents($this->DKIM_private);
if ('' != $this->DKIM_passphrase) {
$privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
} else {
$privKey = openssl_pkey_get_private($privKeyStr);
}
//Workaround for missing digest algorithms in old PHP & OpenSSL versions
//@link http://stackoverflow.com/a/11117338/333340
if (version_compare(PHP_VERSION, '5.3.0') >= 0 and
in_array('sha256WithRSAEncryption', openssl_get_md_methods(true))) {
if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
openssl_pkey_free($privKey);
return base64_encode($signature);
}
} else {
$pinfo = openssl_pkey_get_details($privKey);
$hash = hash('sha256', $signHeader);
//'Magic' constant for SHA256 from RFC3447
//@link https://tools.ietf.org/html/rfc3447#page-43
$t = '3031300d060960864801650304020105000420' . $hash;
$pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3);
$eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t);
if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) {
openssl_pkey_free($privKey);
return base64_encode($signature);
}
}
openssl_pkey_free($privKey);
return '';
}
/**
* Generate a DKIM canonicalization header.
* @access public
* @param string $signHeader Header
* @return string
*/
public function DKIM_HeaderC($signHeader)
{
$signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
$lines = explode("\r\n", $signHeader);
foreach ($lines as $key => $line) {
list($heading, $value) = explode(':', $line, 2);
$heading = strtolower($heading);
$value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces
$lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
}
$signHeader = implode("\r\n", $lines);
return $signHeader;
}
/**
* Generate a DKIM canonicalization body.
* @access public
* @param string $body Message Body
* @return string
*/
public function DKIM_BodyC($body)
{
if ($body == '') {
return "\r\n";
}
// stabilize line endings
$body = str_replace("\r\n", "\n", $body);
$body = str_replace("\n", "\r\n", $body);
// END stabilize line endings
while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
$body = substr($body, 0, strlen($body) - 2);
}
return $body;
}
/**
* Create the DKIM header and body in a new message header.
* @access public
* @param string $headers_line Header lines
* @param string $subject Subject
* @param string $body Body
* @return string
*/
public function DKIM_Add($headers_line, $subject, $body)
{
$DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
$DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
$DKIMquery = 'dns/txt'; // Query method
$DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
$subject_header = "Subject: $subject";
$headers = explode($this->LE, $headers_line);
$from_header = '';
$to_header = '';
$date_header = '';
$current = '';
foreach ($headers as $header) {
if (strpos($header, 'From:') === 0) {
$from_header = $header;
$current = 'from_header';
} elseif (strpos($header, 'To:') === 0) {
$to_header = $header;
$current = 'to_header';
} elseif (strpos($header, 'Date:') === 0) {
$date_header = $header;
$current = 'date_header';
} else {
if (!empty($$current) && strpos($header, ' =?') === 0) {
$$current .= $header;
} else {
$current = '';
}
}
}
$from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
$to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
$date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
$subject = str_replace(
'|',
'=7C',
$this->DKIM_QP($subject_header)
); // Copied header fields (dkim-quoted-printable)
$body = $this->DKIM_BodyC($body);
$DKIMlen = strlen($body); // Length of body
$DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
if ('' == $this->DKIM_identity) {
$ident = '';
} else {
$ident = ' i=' . $this->DKIM_identity . ';';
}
$dkimhdrs = 'DKIM-Signature: v=1; a=' .
$DKIMsignatureType . '; q=' .
$DKIMquery . '; l=' .
$DKIMlen . '; s=' .
$this->DKIM_selector .
";\r\n" .
"\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
"\th=From:To:Date:Subject;\r\n" .
"\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
"\tz=$from\r\n" .
"\t|$to\r\n" .
"\t|$date\r\n" .
"\t|$subject;\r\n" .
"\tbh=" . $DKIMb64 . ";\r\n" .
"\tb=";
$toSign = $this->DKIM_HeaderC(
$from_header . "\r\n" .
$to_header . "\r\n" .
$date_header . "\r\n" .
$subject_header . "\r\n" .
$dkimhdrs
);
$signed = $this->DKIM_Sign($toSign);
return $dkimhdrs . $signed . "\r\n";
}
/**
* Detect if a string contains a line longer than the maximum line length allowed.
* @param string $str
* @return boolean
* @static
*/
public static function hasLineLongerThanMax($str)
{
//+2 to include CRLF line break for a 1000 total
return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
}
/**
* Allows for public read access to 'to' property.
* @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
* @access public
* @return array
*/
public function getToAddresses()
{
return $this->to;
}
/**
* Allows for public read access to 'cc' property.
* @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
* @access public
* @return array
*/
public function getCcAddresses()
{
return $this->cc;
}
/**
* Allows for public read access to 'bcc' property.
* @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
* @access public
* @return array
*/
public function getBccAddresses()
{
return $this->bcc;
}
/**
* Allows for public read access to 'ReplyTo' property.
* @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
* @access public
* @return array
*/
public function getReplyToAddresses()
{
return $this->ReplyTo;
}
/**
* Allows for public read access to 'all_recipients' property.
* @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
* @access public
* @return array
*/
public function getAllRecipientAddresses()
{
return $this->all_recipients;
}
/**
* Perform a callback.
* @param boolean $isSent
* @param array $to
* @param array $cc
* @param array $bcc
* @param string $subject
* @param string $body
* @param string $from
*/
protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
{
if (!empty($this->action_function) && is_callable($this->action_function)) {
$params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
call_user_func_array($this->action_function, $params);
}
}
}
/**
* PHPMailer exception handler
* @package PHPMailer
*/
class phpmailerException extends Exception
{
/**
* Prettify error message output
* @return string
*/
public function errorMessage()
{
$errorMsg = '<strong>' . htmlspecialchars($this->getMessage()) . "</strong><br />\n";
return $errorMsg;
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.phpmaileroauth.php'
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.4
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailerOAuth - PHPMailer subclass adding OAuth support.
* @package PHPMailer
* @author @sherryl4george
* @author Marcus Bointon (@Synchro) <phpmailer@synchromedia.co.uk>
*/
class PHPMailerOAuth extends PHPMailer
{
/**
* The OAuth user's email address
* @var string
*/
public $oauthUserEmail = '';
/**
* The OAuth refresh token
* @var string
*/
public $oauthRefreshToken = '';
/**
* The OAuth client ID
* @var string
*/
public $oauthClientId = '';
/**
* The OAuth client secret
* @var string
*/
public $oauthClientSecret = '';
/**
* An instance of the PHPMailerOAuthGoogle class.
* @var PHPMailerOAuthGoogle
* @access protected
*/
protected $oauth = null;
/**
* Get a PHPMailerOAuthGoogle instance to use.
* @return PHPMailerOAuthGoogle
*/
public function getOAUTHInstance()
{
if (!is_object($this->oauth)) {
$this->oauth = new PHPMailerOAuthGoogle(
$this->oauthUserEmail,
$this->oauthClientSecret,
$this->oauthClientId,
$this->oauthRefreshToken
);
}
return $this->oauth;
}
/**
* Initiate a connection to an SMTP server.
* Overrides the original smtpConnect method to add support for OAuth.
* @param array $options An array of options compatible with stream_context_create()
* @uses SMTP
* @access public
* @return bool
* @throws phpmailerException
*/
public function smtpConnect($options = array())
{
if (is_null($this->smtp)) {
$this->smtp = $this->getSMTPInstance();
}
if (is_null($this->oauth)) {
$this->oauth = $this->getOAUTHInstance();
}
// Already connected?
if ($this->smtp->connected()) {
return true;
}
$this->smtp->setTimeout($this->Timeout);
$this->smtp->setDebugLevel($this->SMTPDebug);
$this->smtp->setDebugOutput($this->Debugoutput);
$this->smtp->setVerp($this->do_verp);
$hosts = explode(';', $this->Host);
$lastexception = null;
foreach ($hosts as $hostentry) {
$hostinfo = array();
if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
// Not a valid host entry
continue;
}
// $hostinfo[2]: optional ssl or tls prefix
// $hostinfo[3]: the hostname
// $hostinfo[4]: optional port number
// The host string prefix can temporarily override the current setting for SMTPSecure
// If it's not specified, the default value is used
$prefix = '';
$secure = $this->SMTPSecure;
$tls = ($this->SMTPSecure == 'tls');
if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
$prefix = 'ssl://';
$tls = false; // Can't have SSL and TLS at the same time
$secure = 'ssl';
} elseif ($hostinfo[2] == 'tls') {
$tls = true;
// tls doesn't use a prefix
$secure = 'tls';
}
//Do we need the OpenSSL extension?
$sslext = defined('OPENSSL_ALGO_SHA1');
if ('tls' === $secure or 'ssl' === $secure) {
//Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
if (!$sslext) {
throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
}
}
$host = $hostinfo[3];
$port = $this->Port;
$tport = (integer)$hostinfo[4];
if ($tport > 0 and $tport < 65536) {
$port = $tport;
}
if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
try {
if ($this->Helo) {
$hello = $this->Helo;
} else {
$hello = $this->serverHostname();
}
$this->smtp->hello($hello);
//Automatically enable TLS encryption if:
// * it's not disabled
// * we have openssl extension
// * we are not already using SSL
// * the server offers STARTTLS
if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
$tls = true;
}
if ($tls) {
if (!$this->smtp->startTLS()) {
throw new phpmailerException($this->lang('connect_host'));
}
// We must resend HELO after tls negotiation
$this->smtp->hello($hello);
}
if ($this->SMTPAuth) {
if (!$this->smtp->authenticate(
$this->Username,
$this->Password,
$this->AuthType,
$this->Realm,
$this->Workstation,
$this->oauth
)
) {
throw new phpmailerException($this->lang('authenticate'));
}
}
return true;
} catch (phpmailerException $exc) {
$lastexception = $exc;
$this->edebug($exc->getMessage());
// We must have connected, but then failed TLS or Auth, so close connection nicely
$this->smtp->quit();
}
}
}
// If we get here, all connection attempts have failed, so close connection hard
$this->smtp->close();
// As we've caught all exceptions, just report whatever the last one was
if ($this->exceptions and !is_null($lastexception)) {
throw $lastexception;
}
return false;
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.phpmaileroauthgoogle.php'
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.4
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailerOAuthGoogle - Wrapper for League OAuth2 Google provider.
* @package PHPMailer
* @author @sherryl4george
* @author Marcus Bointon (@Synchro) <phpmailer@synchromedia.co.uk>
* @link https://github.com/thephpleague/oauth2-client
*/
class PHPMailerOAuthGoogle
{
private $oauthUserEmail = '';
private $oauthRefreshToken = '';
private $oauthClientId = '';
private $oauthClientSecret = '';
/**
* @param string $UserEmail
* @param string $ClientSecret
* @param string $ClientId
* @param string $RefreshToken
*/
public function __construct(
$UserEmail,
$ClientSecret,
$ClientId,
$RefreshToken
) {
$this->oauthClientId = $ClientId;
$this->oauthClientSecret = $ClientSecret;
$this->oauthRefreshToken = $RefreshToken;
$this->oauthUserEmail = $UserEmail;
}
private function getProvider()
{
return new League\OAuth2\Client\Provider\Google([
'clientId' => $this->oauthClientId,
'clientSecret' => $this->oauthClientSecret
]);
}
private function getGrant()
{
return new \League\OAuth2\Client\Grant\RefreshToken();
}
private function getToken()
{
$provider = $this->getProvider();
$grant = $this->getGrant();
return $provider->getAccessToken($grant, ['refresh_token' => $this->oauthRefreshToken]);
}
public function getOauth64()
{
$token = $this->getToken();
return base64_encode("user=" . $this->oauthUserEmail . "\001auth=Bearer " . $token . "\001\001");
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.pop3.php'
<?php
/**
* PHPMailer POP-Before-SMTP Authentication Class.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer POP-Before-SMTP Authentication Class.
* Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication.
* Does not support APOP.
* @package PHPMailer
* @author Richard Davey (original author) <rich@corephp.co.uk>
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
*/
class POP3
{
/**
* The POP3 PHPMailer Version number.
* @var string
* @access public
*/
public $Version = '5.2.26';
/**
* Default POP3 port number.
* @var integer
* @access public
*/
public $POP3_PORT = 110;
/**
* Default timeout in seconds.
* @var integer
* @access public
*/
public $POP3_TIMEOUT = 30;
/**
* POP3 Carriage Return + Line Feed.
* @var string
* @access public
* @deprecated Use the constant instead
*/
public $CRLF = "\r\n";
/**
* Debug display level.
* Options: 0 = no, 1+ = yes
* @var integer
* @access public
*/
public $do_debug = 0;
/**
* POP3 mail server hostname.
* @var string
* @access public
*/
public $host;
/**
* POP3 port number.
* @var integer
* @access public
*/
public $port;
/**
* POP3 Timeout Value in seconds.
* @var integer
* @access public
*/
public $tval;
/**
* POP3 username
* @var string
* @access public
*/
public $username;
/**
* POP3 password.
* @var string
* @access public
*/
public $password;
/**
* Resource handle for the POP3 connection socket.
* @var resource
* @access protected
*/
protected $pop_conn;
/**
* Are we connected?
* @var boolean
* @access protected
*/
protected $connected = false;
/**
* Error container.
* @var array
* @access protected
*/
protected $errors = array();
/**
* Line break constant
*/
const CRLF = "\r\n";
/**
* Simple static wrapper for all-in-one POP before SMTP
* @param $host
* @param integer|boolean $port The port number to connect to
* @param integer|boolean $timeout The timeout value
* @param string $username
* @param string $password
* @param integer $debug_level
* @return boolean
*/
public static function popBeforeSmtp(
$host,
$port = false,
$timeout = false,
$username = '',
$password = '',
$debug_level = 0
) {
$pop = new POP3;
return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level);
}
/**
* Authenticate with a POP3 server.
* A connect, login, disconnect sequence
* appropriate for POP-before SMTP authorisation.
* @access public
* @param string $host The hostname to connect to
* @param integer|boolean $port The port number to connect to
* @param integer|boolean $timeout The timeout value
* @param string $username
* @param string $password
* @param integer $debug_level
* @return boolean
*/
public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0)
{
$this->host = $host;
// If no port value provided, use default
if (false === $port) {
$this->port = $this->POP3_PORT;
} else {
$this->port = (integer)$port;
}
// If no timeout value provided, use default
if (false === $timeout) {
$this->tval = $this->POP3_TIMEOUT;
} else {
$this->tval = (integer)$timeout;
}
$this->do_debug = $debug_level;
$this->username = $username;
$this->password = $password;
// Reset the error log
$this->errors = array();
// connect
$result = $this->connect($this->host, $this->port, $this->tval);
if ($result) {
$login_result = $this->login($this->username, $this->password);
if ($login_result) {
$this->disconnect();
return true;
}
}
// We need to disconnect regardless of whether the login succeeded
$this->disconnect();
return false;
}
/**
* Connect to a POP3 server.
* @access public
* @param string $host
* @param integer|boolean $port
* @param integer $tval
* @return boolean
*/
public function connect($host, $port = false, $tval = 30)
{
// Are we already connected?
if ($this->connected) {
return true;
}
//On Windows this will raise a PHP Warning error if the hostname doesn't exist.
//Rather than suppress it with @fsockopen, capture it cleanly instead
set_error_handler(array($this, 'catchWarning'));
if (false === $port) {
$port = $this->POP3_PORT;
}
// connect to the POP3 server
$this->pop_conn = fsockopen(
$host, // POP3 Host
$port, // Port #
$errno, // Error Number
$errstr, // Error Message
$tval
); // Timeout (seconds)
// Restore the error handler
restore_error_handler();
// Did we connect?
if (false === $this->pop_conn) {
// It would appear not...
$this->setError(array(
'error' => "Failed to connect to server $host on port $port",
'errno' => $errno,
'errstr' => $errstr
));
return false;
}
// Increase the stream time-out
stream_set_timeout($this->pop_conn, $tval, 0);
// Get the POP3 server response
$pop3_response = $this->getResponse();
// Check for the +OK
if ($this->checkResponse($pop3_response)) {
// The connection is established and the POP3 server is talking
$this->connected = true;
return true;
}
return false;
}
/**
* Log in to the POP3 server.
* Does not support APOP (RFC 2828, 4949).
* @access public
* @param string $username
* @param string $password
* @return boolean
*/
public function login($username = '', $password = '')
{
if (!$this->connected) {
$this->setError('Not connected to POP3 server');
}
if (empty($username)) {
$username = $this->username;
}
if (empty($password)) {
$password = $this->password;
}
// Send the Username
$this->sendString("USER $username" . self::CRLF);
$pop3_response = $this->getResponse();
if ($this->checkResponse($pop3_response)) {
// Send the Password
$this->sendString("PASS $password" . self::CRLF);
$pop3_response = $this->getResponse();
if ($this->checkResponse($pop3_response)) {
return true;
}
}
return false;
}
/**
* Disconnect from the POP3 server.
* @access public
*/
public function disconnect()
{
$this->sendString('QUIT');
//The QUIT command may cause the daemon to exit, which will kill our connection
//So ignore errors here
try {
@fclose($this->pop_conn);
} catch (Exception $e) {
//Do nothing
};
}
/**
* Get a response from the POP3 server.
* $size is the maximum number of bytes to retrieve
* @param integer $size
* @return string
* @access protected
*/
protected function getResponse($size = 128)
{
$response = fgets($this->pop_conn, $size);
if ($this->do_debug >= 1) {
echo "Server -> Client: $response";
}
return $response;
}
/**
* Send raw data to the POP3 server.
* @param string $string
* @return integer
* @access protected
*/
protected function sendString($string)
{
if ($this->pop_conn) {
if ($this->do_debug >= 2) { //Show client messages when debug >= 2
echo "Client -> Server: $string";
}
return fwrite($this->pop_conn, $string, strlen($string));
}
return 0;
}
/**
* Checks the POP3 server response.
* Looks for for +OK or -ERR.
* @param string $string
* @return boolean
* @access protected
*/
protected function checkResponse($string)
{
if (substr($string, 0, 3) !== '+OK') {
$this->setError(array(
'error' => "Server reported an error: $string",
'errno' => 0,
'errstr' => ''
));
return false;
} else {
return true;
}
}
/**
* Add an error to the internal error store.
* Also display debug output if it's enabled.
* @param $error
* @access protected
*/
protected function setError($error)
{
$this->errors[] = $error;
if ($this->do_debug >= 1) {
echo '<pre>';
foreach ($this->errors as $error) {
print_r($error);
}
echo '</pre>';
}
}
/**
* Get an array of error messages, if any.
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* POP3 connection error handler.
* @param integer $errno
* @param string $errstr
* @param string $errfile
* @param integer $errline
* @access protected
*/
protected function catchWarning($errno, $errstr, $errfile, $errline)
{
$this->setError(array(
'error' => "Connecting to the POP3 server raised a PHP warning: ",
'errno' => $errno,
'errstr' => $errstr,
'errfile' => $errfile,
'errline' => $errline
));
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/class.smtp.php'
<?php
/**
* PHPMailer RFC821 SMTP email transport class.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer RFC821 SMTP email transport class.
* Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
* @package PHPMailer
* @author Chris Ryan
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/
class SMTP
{
/**
* The PHPMailer SMTP version number.
* @var string
*/
const VERSION = '5.2.26';
/**
* SMTP line break constant.
* @var string
*/
const CRLF = "\r\n";
/**
* The SMTP port to use if one is not specified.
* @var integer
*/
const DEFAULT_SMTP_PORT = 25;
/**
* The maximum line length allowed by RFC 2822 section 2.1.1
* @var integer
*/
const MAX_LINE_LENGTH = 998;
/**
* Debug level for no output
*/
const DEBUG_OFF = 0;
/**
* Debug level to show client -> server messages
*/
const DEBUG_CLIENT = 1;
/**
* Debug level to show client -> server and server -> client messages
*/
const DEBUG_SERVER = 2;
/**
* Debug level to show connection status, client -> server and server -> client messages
*/
const DEBUG_CONNECTION = 3;
/**
* Debug level to show all messages
*/
const DEBUG_LOWLEVEL = 4;
/**
* The PHPMailer SMTP Version number.
* @var string
* @deprecated Use the `VERSION` constant instead
* @see SMTP::VERSION
*/
public $Version = '5.2.26';
/**
* SMTP server port number.
* @var integer
* @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead
* @see SMTP::DEFAULT_SMTP_PORT
*/
public $SMTP_PORT = 25;
/**
* SMTP reply line ending.
* @var string
* @deprecated Use the `CRLF` constant instead
* @see SMTP::CRLF
*/
public $CRLF = "\r\n";
/**
* Debug output level.
* Options:
* * self::DEBUG_OFF (`0`) No debug output, default
* * self::DEBUG_CLIENT (`1`) Client commands
* * self::DEBUG_SERVER (`2`) Client commands and server responses
* * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
* * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages
* @var integer
*/
public $do_debug = self::DEBUG_OFF;
/**
* How to handle debug output.
* Options:
* * `echo` Output plain-text as-is, appropriate for CLI
* * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
* * `error_log` Output to error log as configured in php.ini
*
* Alternatively, you can provide a callable expecting two params: a message string and the debug level:
* <code>
* $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
* </code>
* @var string|callable
*/
public $Debugoutput = 'echo';
/**
* Whether to use VERP.
* @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
* @link http://www.postfix.org/VERP_README.html Info on VERP
* @var boolean
*/
public $do_verp = false;
/**
* The timeout value for connection, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
* @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
* @var integer
*/
public $Timeout = 300;
/**
* How long to wait for commands to complete, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* @var integer
*/
public $Timelimit = 300;
/**
* @var array Patterns to extract an SMTP transaction id from reply to a DATA command.
* The first capture group in each regex will be used as the ID.
*/
protected $smtp_transaction_id_patterns = array(
'exim' => '/[0-9]{3} OK id=(.*)/',
'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/'
);
/**
* @var string The last transaction ID issued in response to a DATA command,
* if one was detected
*/
protected $last_smtp_transaction_id;
/**
* The socket for the server connection.
* @var resource
*/
protected $smtp_conn;
/**
* Error information, if any, for the last SMTP command.
* @var array
*/
protected $error = array(
'error' => '',
'detail' => '',
'smtp_code' => '',
'smtp_code_ex' => ''
);
/**
* The reply the server sent to us for HELO.
* If null, no HELO string has yet been received.
* @var string|null
*/
protected $helo_rply = null;
/**
* The set of SMTP extensions sent in reply to EHLO command.
* Indexes of the array are extension names.
* Value at index 'HELO' or 'EHLO' (according to command that was sent)
* represents the server name. In case of HELO it is the only element of the array.
* Other values can be boolean TRUE or an array containing extension options.
* If null, no HELO/EHLO string has yet been received.
* @var array|null
*/
protected $server_caps = null;
/**
* The most recent reply received from the server.
* @var string
*/
protected $last_reply = '';
/**
* Output debugging info via a user-selected method.
* @see SMTP::$Debugoutput
* @see SMTP::$do_debug
* @param string $str Debug string to output
* @param integer $level The debug level of this message; see DEBUG_* constants
* @return void
*/
protected function edebug($str, $level = 0)
{
if ($level > $this->do_debug) {
return;
}
//Avoid clash with built-in function names
if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
call_user_func($this->Debugoutput, $str, $level);
return;
}
switch ($this->Debugoutput) {
case 'error_log':
//Don't output, just log
error_log($str);
break;
case 'html':
//Cleans up output a bit for a better looking, HTML-safe output
echo gmdate('Y-m-d H:i:s') . ' ' . htmlentities(
preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES,
'UTF-8'
) . "<br>\n";
break;
case 'echo':
default:
//Normalize line breaks
$str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
"\n",
"\n \t ",
trim($str)
) . "\n";
}
}
/**
* Connect to an SMTP server.
* @param string $host SMTP server IP or host name
* @param integer $port The port number to connect to
* @param integer $timeout How long to wait for the connection to open
* @param array $options An array of options for stream_context_create()
* @access public
* @return boolean
*/
public function connect($host, $port = null, $timeout = 30, $options = array())
{
static $streamok;
//This is enabled by default since 5.0.0 but some providers disable it
//Check this once and cache the result
if (is_null($streamok)) {
$streamok = function_exists('stream_socket_client');
}
// Clear errors to avoid confusion
$this->setError('');
// Make sure we are __not__ connected
if ($this->connected()) {
// Already connected, generate error
$this->setError('Already connected to a server');
return false;
}
if (empty($port)) {
$port = self::DEFAULT_SMTP_PORT;
}
// Connect to the SMTP server
$this->edebug(
"Connection: opening to $host:$port, timeout=$timeout, options=" .
var_export($options, true),
self::DEBUG_CONNECTION
);
$errno = 0;
$errstr = '';
if ($streamok) {
$socket_context = stream_context_create($options);
set_error_handler(array($this, 'errorHandler'));
$this->smtp_conn = stream_socket_client(
$host . ":" . $port,
$errno,
$errstr,
$timeout,
STREAM_CLIENT_CONNECT,
$socket_context
);
restore_error_handler();
} else {
//Fall back to fsockopen which should work in more places, but is missing some features
$this->edebug(
"Connection: stream_socket_client not available, falling back to fsockopen",
self::DEBUG_CONNECTION
);
set_error_handler(array($this, 'errorHandler'));
$this->smtp_conn = fsockopen(
$host,
$port,
$errno,
$errstr,
$timeout
);
restore_error_handler();
}
// Verify we connected properly
if (!is_resource($this->smtp_conn)) {
$this->setError(
'Failed to connect to server',
$errno,
$errstr
);
$this->edebug(
'SMTP ERROR: ' . $this->error['error']
. ": $errstr ($errno)",
self::DEBUG_CLIENT
);
return false;
}
$this->edebug('Connection: opened', self::DEBUG_CONNECTION);
// SMTP server can take longer to respond, give longer timeout for first read
// Windows does not have support for this timeout function
if (substr(PHP_OS, 0, 3) != 'WIN') {
$max = ini_get('max_execution_time');
// Don't bother if unlimited
if ($max != 0 && $timeout > $max) {
@set_time_limit($timeout);
}
stream_set_timeout($this->smtp_conn, $timeout, 0);
}
// Get any announcement
$announce = $this->get_lines();
$this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
return true;
}
/**
* Initiate a TLS (encrypted) session.
* @access public
* @return boolean
*/
public function startTLS()
{
if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
return false;
}
//Allow the best TLS version(s) we can
$crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
//PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
//so add them back in manually if we can
if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
}
// Begin encrypted connection
set_error_handler(array($this, 'errorHandler'));
$crypto_ok = stream_socket_enable_crypto(
$this->smtp_conn,
true,
$crypto_method
);
restore_error_handler();
return $crypto_ok;
}
/**
* Perform SMTP authentication.
* Must be run after hello().
* @see hello()
* @param string $username The user name
* @param string $password The password
* @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2)
* @param string $realm The auth realm for NTLM
* @param string $workstation The auth workstation for NTLM
* @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth)
* @return bool True if successfully authenticated.* @access public
*/
public function authenticate(
$username,
$password,
$authtype = null,
$realm = '',
$workstation = '',
$OAuth = null
) {
if (!$this->server_caps) {
$this->setError('Authentication is not allowed before HELO/EHLO');
return false;
}
if (array_key_exists('EHLO', $this->server_caps)) {
// SMTP extensions are available; try to find a proper authentication method
if (!array_key_exists('AUTH', $this->server_caps)) {
$this->setError('Authentication is not allowed at this stage');
// 'at this stage' means that auth may be allowed after the stage changes
// e.g. after STARTTLS
return false;
}
self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
self::edebug(
'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
self::DEBUG_LOWLEVEL
);
if (empty($authtype)) {
foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN', 'NTLM', 'XOAUTH2') as $method) {
if (in_array($method, $this->server_caps['AUTH'])) {
$authtype = $method;
break;
}
}
if (empty($authtype)) {
$this->setError('No supported authentication methods found');
return false;
}
self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
}
if (!in_array($authtype, $this->server_caps['AUTH'])) {
$this->setError("The requested authentication method \"$authtype\" is not supported by the server");
return false;
}
} elseif (empty($authtype)) {
$authtype = 'LOGIN';
}
switch ($authtype) {
case 'PLAIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
return false;
}
// Send encoded username and password
if (!$this->sendCommand(
'User & Password',
base64_encode("\0" . $username . "\0" . $password),
235
)
) {
return false;
}
break;
case 'LOGIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
return false;
}
if (!$this->sendCommand("Username", base64_encode($username), 334)) {
return false;
}
if (!$this->sendCommand("Password", base64_encode($password), 235)) {
return false;
}
break;
case 'XOAUTH2':
//If the OAuth Instance is not set. Can be a case when PHPMailer is used
//instead of PHPMailerOAuth
if (is_null($OAuth)) {
return false;
}
$oauth = $OAuth->getOauth64();
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
return false;
}
break;
case 'NTLM':
/*
* ntlm_sasl_client.php
* Bundled with Permission
*
* How to telnet in windows:
* http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
* PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
*/
require_once 'extras/ntlm_sasl_client.php';
$temp = new stdClass;
$ntlm_client = new ntlm_sasl_client_class;
//Check that functions are available
if (!$ntlm_client->initialize($temp)) {
$this->setError($temp->error);
$this->edebug(
'You need to enable some modules in your php.ini file: '
. $this->error['error'],
self::DEBUG_CLIENT
);
return false;
}
//msg1
$msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1
if (!$this->sendCommand(
'AUTH NTLM',
'AUTH NTLM ' . base64_encode($msg1),
334
)
) {
return false;
}
//Though 0 based, there is a white space after the 3 digit number
//msg2
$challenge = substr($this->last_reply, 3);
$challenge = base64_decode($challenge);
$ntlm_res = $ntlm_client->NTLMResponse(
substr($challenge, 24, 8),
$password
);
//msg3
$msg3 = $ntlm_client->typeMsg3(
$ntlm_res,
$username,
$realm,
$workstation
);
// send encoded username
return $this->sendCommand('Username', base64_encode($msg3), 235);
case 'CRAM-MD5':
// Start authentication
if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
return false;
}
// Get the challenge
$challenge = base64_decode(substr($this->last_reply, 4));
// Build the response
$response = $username . ' ' . $this->hmac($challenge, $password);
// send encoded credentials
return $this->sendCommand('Username', base64_encode($response), 235);
default:
$this->setError("Authentication method \"$authtype\" is not supported");
return false;
}
return true;
}
/**
* Calculate an MD5 HMAC hash.
* Works like hash_hmac('md5', $data, $key)
* in case that function is not available
* @param string $data The data to hash
* @param string $key The key to hash with
* @access protected
* @return string
*/
protected function hmac($data, $key)
{
if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key);
}
// The following borrowed from
// http://php.net/manual/en/function.mhash.php#27225
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC
// by Lance Rushing
$bytelen = 64; // byte length for md5
if (strlen($key) > $bytelen) {
$key = pack('H*', md5($key));
}
$key = str_pad($key, $bytelen, chr(0x00));
$ipad = str_pad('', $bytelen, chr(0x36));
$opad = str_pad('', $bytelen, chr(0x5c));
$k_ipad = $key ^ $ipad;
$k_opad = $key ^ $opad;
return md5($k_opad . pack('H*', md5($k_ipad . $data)));
}
/**
* Check connection state.
* @access public
* @return boolean True if connected.
*/
public function connected()
{
if (is_resource($this->smtp_conn)) {
$sock_status = stream_get_meta_data($this->smtp_conn);
if ($sock_status['eof']) {
// The socket is valid but we are not connected
$this->edebug(
'SMTP NOTICE: EOF caught while checking if connected',
self::DEBUG_CLIENT
);
$this->close();
return false;
}
return true; // everything looks good
}
return false;
}
/**
* Close the socket and clean up the state of the class.
* Don't use this function without first trying to use QUIT.
* @see quit()
* @access public
* @return void
*/
public function close()
{
$this->setError('');
$this->server_caps = null;
$this->helo_rply = null;
if (is_resource($this->smtp_conn)) {
// close the connection and cleanup
fclose($this->smtp_conn);
$this->smtp_conn = null; //Makes for cleaner serialization
$this->edebug('Connection: closed', self::DEBUG_CONNECTION);
}
}
/**
* Send an SMTP DATA command.
* Issues a data command and sends the msg_data to the server,
* finializing the mail transaction. $msg_data is the message
* that is to be send with the headers. Each header needs to be
* on a single line followed by a <CRLF> with the message headers
* and the message body being separated by and additional <CRLF>.
* Implements rfc 821: DATA <CRLF>
* @param string $msg_data Message data to send
* @access public
* @return boolean
*/
public function data($msg_data)
{
//This will use the standard timelimit
if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false;
}
/* The server is ready to accept data!
* According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
* so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
* smaller lines to fit within the limit.
* We will also look for lines that start with a '.' and prepend an additional '.'.
* NOTE: this does not count towards line-length limit.
*/
// Normalize line breaks before exploding
$lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
/* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
* of the first line (':' separated) does not contain a space then it _should_ be a header and we will
* process all lines before a blank line as headers.
*/
$field = substr($lines[0], 0, strpos($lines[0], ':'));
$in_headers = false;
if (!empty($field) && strpos($field, ' ') === false) {
$in_headers = true;
}
foreach ($lines as $line) {
$lines_out = array();
if ($in_headers and $line == '') {
$in_headers = false;
}
//Break this line up into several smaller lines if it's too long
//Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
while (isset($line[self::MAX_LINE_LENGTH])) {
//Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
//so as to avoid breaking in the middle of a word
$pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
//Deliberately matches both false and 0
if (!$pos) {
//No nice break found, add a hard break
$pos = self::MAX_LINE_LENGTH - 1;
$lines_out[] = substr($line, 0, $pos);
$line = substr($line, $pos);
} else {
//Break at the found point
$lines_out[] = substr($line, 0, $pos);
//Move along by the amount we dealt with
$line = substr($line, $pos + 1);
}
//If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
if ($in_headers) {
$line = "\t" . $line;
}
}
$lines_out[] = $line;
//Send the lines to the server
foreach ($lines_out as $line_out) {
//RFC2821 section 4.5.2
if (!empty($line_out) and $line_out[0] == '.') {
$line_out = '.' . $line_out;
}
$this->client_send($line_out . self::CRLF);
}
}
//Message data has been sent, complete the command
//Increase timelimit for end of DATA command
$savetimelimit = $this->Timelimit;
$this->Timelimit = $this->Timelimit * 2;
$result = $this->sendCommand('DATA END', '.', 250);
$this->recordLastTransactionID();
//Restore timelimit
$this->Timelimit = $savetimelimit;
return $result;
}
/**
* Send an SMTP HELO or EHLO command.
* Used to identify the sending server to the receiving server.
* This makes sure that client and server are in a known state.
* Implements RFC 821: HELO <SP> <domain> <CRLF>
* and RFC 2821 EHLO.
* @param string $host The host name or IP to connect to
* @access public
* @return boolean
*/
public function hello($host = '')
{
//Try extended hello first (RFC 2821)
return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
}
/**
* Send an SMTP HELO or EHLO command.
* Low-level implementation used by hello()
* @see hello()
* @param string $hello The HELO string
* @param string $host The hostname to say we are
* @access protected
* @return boolean
*/
protected function sendHello($hello, $host)
{
$noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
$this->helo_rply = $this->last_reply;
if ($noerror) {
$this->parseHelloFields($hello);
} else {
$this->server_caps = null;
}
return $noerror;
}
/**
* Parse a reply to HELO/EHLO command to discover server extensions.
* In case of HELO, the only parameter that can be discovered is a server name.
* @access protected
* @param string $type - 'HELO' or 'EHLO'
*/
protected function parseHelloFields($type)
{
$this->server_caps = array();
$lines = explode("\n", $this->helo_rply);
foreach ($lines as $n => $s) {
//First 4 chars contain response code followed by - or space
$s = trim(substr($s, 4));
if (empty($s)) {
continue;
}
$fields = explode(' ', $s);
if (!empty($fields)) {
if (!$n) {
$name = $type;
$fields = $fields[0];
} else {
$name = array_shift($fields);
switch ($name) {
case 'SIZE':
$fields = ($fields ? $fields[0] : 0);
break;
case 'AUTH':
if (!is_array($fields)) {
$fields = array();
}
break;
default:
$fields = true;
}
}
$this->server_caps[$name] = $fields;
}
}
}
/**
* Send an SMTP MAIL command.
* Starts a mail transaction from the email address specified in
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command.
* Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
* @param string $from Source address of this message
* @access public
* @return boolean
*/
public function mail($from)
{
$useVerp = ($this->do_verp ? ' XVERP' : '');
return $this->sendCommand(
'MAIL FROM',
'MAIL FROM:<' . $from . '>' . $useVerp,
250
);
}
/**
* Send an SMTP QUIT command.
* Closes the socket if there is no error or the $close_on_error argument is true.
* Implements from rfc 821: QUIT <CRLF>
* @param boolean $close_on_error Should the connection close if an error occurs?
* @access public
* @return boolean
*/
public function quit($close_on_error = true)
{
$noerror = $this->sendCommand('QUIT', 'QUIT', 221);
$err = $this->error; //Save any error
if ($noerror or $close_on_error) {
$this->close();
$this->error = $err; //Restore any error from the quit command
}
return $noerror;
}
/**
* Send an SMTP RCPT command.
* Sets the TO argument to $toaddr.
* Returns true if the recipient was accepted false if it was rejected.
* Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
* @param string $address The address the message is being sent to
* @access public
* @return boolean
*/
public function recipient($address)
{
return $this->sendCommand(
'RCPT TO',
'RCPT TO:<' . $address . '>',
array(250, 251)
);
}
/**
* Send an SMTP RSET command.
* Abort any transaction that is currently in progress.
* Implements rfc 821: RSET <CRLF>
* @access public
* @return boolean True on success.
*/
public function reset()
{
return $this->sendCommand('RSET', 'RSET', 250);
}
/**
* Send a command to an SMTP server and check its return code.
* @param string $command The command name - not sent to the server
* @param string $commandstring The actual command to send
* @param integer|array $expect One or more expected integer success codes
* @access protected
* @return boolean True on success.
*/
protected function sendCommand($command, $commandstring, $expect)
{
if (!$this->connected()) {
$this->setError("Called $command without being connected");
return false;
}
//Reject line breaks in all commands
if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
$this->setError("Command '$command' contained line breaks");
return false;
}
$this->client_send($commandstring . self::CRLF);
$this->last_reply = $this->get_lines();
// Fetch SMTP code and possible error code explanation
$matches = array();
if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
$code = $matches[1];
$code_ex = (count($matches) > 2 ? $matches[2] : null);
// Cut off error code from each response line
$detail = preg_replace(
"/{$code}[ -]" .
($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m",
'',
$this->last_reply
);
} else {
// Fall back to simple parsing if regex fails
$code = substr($this->last_reply, 0, 3);
$code_ex = null;
$detail = substr($this->last_reply, 4);
}
$this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
if (!in_array($code, (array)$expect)) {
$this->setError(
"$command command failed",
$detail,
$code,
$code_ex
);
$this->edebug(
'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
self::DEBUG_CLIENT
);
return false;
}
$this->setError('');
return true;
}
/**
* Send an SMTP SAML command.
* Starts a mail transaction from the email address specified in $from.
* Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command. This command
* will send the message to the users terminal if they are logged
* in and send them an email.
* Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
* @param string $from The address the message is from
* @access public
* @return boolean
*/
public function sendAndMail($from)
{
return $this->sendCommand('SAML', "SAML FROM:$from", 250);
}
/**
* Send an SMTP VRFY command.
* @param string $name The name to verify
* @access public
* @return boolean
*/
public function verify($name)
{
return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
}
/**
* Send an SMTP NOOP command.
* Used to keep keep-alives alive, doesn't actually do anything
* @access public
* @return boolean
*/
public function noop()
{
return $this->sendCommand('NOOP', 'NOOP', 250);
}
/**
* Send an SMTP TURN command.
* This is an optional command for SMTP that this class does not support.
* This method is here to make the RFC821 Definition complete for this class
* and _may_ be implemented in future
* Implements from rfc 821: TURN <CRLF>
* @access public
* @return boolean
*/
public function turn()
{
$this->setError('The SMTP TURN command is not implemented');
$this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
return false;
}
/**
* Send raw data to the server.
* @param string $data The data to send
* @access public
* @return integer|boolean The number of bytes sent to the server or false on error
*/
public function client_send($data)
{
$this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
set_error_handler(array($this, 'errorHandler'));
$result = fwrite($this->smtp_conn, $data);
restore_error_handler();
return $result;
}
/**
* Get the latest error.
* @access public
* @return array
*/
public function getError()
{
return $this->error;
}
/**
* Get SMTP extensions available on the server
* @access public
* @return array|null
*/
public function getServerExtList()
{
return $this->server_caps;
}
/**
* A multipurpose method
* The method works in three ways, dependent on argument value and current state
* 1. HELO/EHLO was not sent - returns null and set up $this->error
* 2. HELO was sent
* $name = 'HELO': returns server name
* $name = 'EHLO': returns boolean false
* $name = any string: returns null and set up $this->error
* 3. EHLO was sent
* $name = 'HELO'|'EHLO': returns server name
* $name = any string: if extension $name exists, returns boolean True
* or its options. Otherwise returns boolean False
* In other words, one can use this method to detect 3 conditions:
* - null returned: handshake was not or we don't know about ext (refer to $this->error)
* - false returned: the requested feature exactly not exists
* - positive value returned: the requested feature exists
* @param string $name Name of SMTP extension or 'HELO'|'EHLO'
* @return mixed
*/
public function getServerExt($name)
{
if (!$this->server_caps) {
$this->setError('No HELO/EHLO was sent');
return null;
}
// the tight logic knot ;)
if (!array_key_exists($name, $this->server_caps)) {
if ($name == 'HELO') {
return $this->server_caps['EHLO'];
}
if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
return false;
}
$this->setError('HELO handshake was used. Client knows nothing about server extensions');
return null;
}
return $this->server_caps[$name];
}
/**
* Get the last reply from the server.
* @access public
* @return string
*/
public function getLastReply()
{
return $this->last_reply;
}
/**
* Read the SMTP server's response.
* Either before eof or socket timeout occurs on the operation.
* With SMTP we can tell if we have more lines to read if the
* 4th character is '-' symbol. If it is a space then we don't
* need to read anything else.
* @access protected
* @return string
*/
protected function get_lines()
{
// If the connection is bad, give up straight away
if (!is_resource($this->smtp_conn)) {
return '';
}
$data = '';
$endtime = 0;
stream_set_timeout($this->smtp_conn, $this->Timeout);
if ($this->Timelimit > 0) {
$endtime = time() + $this->Timelimit;
}
while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
$str = @fgets($this->smtp_conn, 515);
$this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
$this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
$data .= $str;
// If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
// or 4th character is a space, we are done reading, break the loop,
// string array access is a micro-optimisation over strlen
if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) {
break;
}
// Timed-out? Log and break
$info = stream_get_meta_data($this->smtp_conn);
if ($info['timed_out']) {
$this->edebug(
'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
self::DEBUG_LOWLEVEL
);
break;
}
// Now check if reads took too long
if ($endtime and time() > $endtime) {
$this->edebug(
'SMTP -> get_lines(): timelimit reached (' .
$this->Timelimit . ' sec)',
self::DEBUG_LOWLEVEL
);
break;
}
}
return $data;
}
/**
* Enable or disable VERP address generation.
* @param boolean $enabled
*/
public function setVerp($enabled = false)
{
$this->do_verp = $enabled;
}
/**
* Get VERP address generation mode.
* @return boolean
*/
public function getVerp()
{
return $this->do_verp;
}
/**
* Set error messages and codes.
* @param string $message The error message
* @param string $detail Further detail on the error
* @param string $smtp_code An associated SMTP error code
* @param string $smtp_code_ex Extended SMTP code
*/
protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
{
$this->error = array(
'error' => $message,
'detail' => $detail,
'smtp_code' => $smtp_code,
'smtp_code_ex' => $smtp_code_ex
);
}
/**
* Set debug output method.
* @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
*/
public function setDebugOutput($method = 'echo')
{
$this->Debugoutput = $method;
}
/**
* Get debug output method.
* @return string
*/
public function getDebugOutput()
{
return $this->Debugoutput;
}
/**
* Set debug output level.
* @param integer $level
*/
public function setDebugLevel($level = 0)
{
$this->do_debug = $level;
}
/**
* Get debug output level.
* @return integer
*/
public function getDebugLevel()
{
return $this->do_debug;
}
/**
* Set SMTP timeout.
* @param integer $timeout
*/
public function setTimeout($timeout = 0)
{
$this->Timeout = $timeout;
}
/**
* Get SMTP timeout.
* @return integer
*/
public function getTimeout()
{
return $this->Timeout;
}
/**
* Reports an error number and string.
* @param integer $errno The error number returned by PHP.
* @param string $errmsg The error message returned by PHP.
* @param string $errfile The file the error occurred in
* @param integer $errline The line number the error occurred on
*/
protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
{
$notice = 'Connection failed.';
$this->setError(
$notice,
$errno,
$errmsg
);
$this->edebug(
$notice . ' Error #' . $errno . ': ' . $errmsg . " [$errfile line $errline]",
self::DEBUG_CONNECTION
);
}
/**
* Extract and return the ID of the last SMTP transaction based on
* a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
* Relies on the host providing the ID in response to a DATA command.
* If no reply has been received yet, it will return null.
* If no pattern was matched, it will return false.
* @return bool|null|string
*/
protected function recordLastTransactionID()
{
$reply = $this->getLastReply();
if (empty($reply)) {
$this->last_smtp_transaction_id = null;
} else {
$this->last_smtp_transaction_id = false;
foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
$this->last_smtp_transaction_id = $matches[1];
}
}
}
return $this->last_smtp_transaction_id;
}
/**
* Get the queue/transaction ID of the last SMTP transaction
* If no reply has been received yet, it will return null.
* If no pattern was matched, it will return false.
* @return bool|null|string
* @see recordLastTransactionID()
*/
public function getLastTransactionID()
{
return $this->last_smtp_transaction_id;
}
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/constantes.php'
<?php
$locals = array(
"utf-8",
"cp037",
"cp850",
"cp863",
"iso-8859-1",
"iso-8859-3",
"koi8-u",
"windows-1250",
"windows-1258",
"cp1006",
"cp852",
"cp864",
"iso-8859-10",
"iso-8859-4",
"mazovia",
"windows-1251",
"x-mac-ce",
"cp1026",
"cp855",
"cp865",
"iso-8859-11",
"iso-8859-5",
"nextstep",
"windows-1252",
"x-mac-cyrillic",
"cp424",
"cp856",
"cp866",
"iso-8859-13",
"iso-8859-6",
"windows-1253",
"x-mac-greek",
"cp437",
"cp857",
"cp869",
"iso-8859-14",
"iso-8859-7",
"windows-1254",
"x-mac-icelandic",
"cp500",
"cp860",
"cp874",
"iso-8859-15",
"iso-8859-8",
"turkish",
"windows-1255",
"x-mac-roman",
"cp737",
"cp861",
"cp875",
"iso-8859-16",
"iso-8859-9",
"us-ascii",
"windows-1256",
"zdingbat",
"cp775",
"cp862",
"gsm0338",
"iso-8859-2",
"koi8-r",
"us-ascii-quotes",
"windows-1257"
);
$PAYS_WITH_OPTION = "<option value='Africa/Abidjan' ".($timezone=='Africa/Abidjan'?'selected':'').">Africa/Abidjan</option>
<option value='Africa/Accra' ".($timezone=='Africa/Accra'?'selected':'').">Africa/Accra</option>
<option value='Africa/Addis_Ababa' ".($timezone=='Africa/Addis_Ababa'?'selected':'').">Africa/Addis_Ababa</option>
<option value='Africa/Algiers' ".($timezone=='Africa/Algiers'?'selected':'').">Africa/Algiers</option>
<option value='Africa/Asmara' ".($timezone=='Africa/Asmara'?'selected':'').">Africa/Asmara</option>
<option value='Africa/Asmera' ".($timezone=='Africa/Asmera'?'selected':'').">Africa/Asmera</option>
<option value='Africa/Bamako' ".($timezone=='Africa/Bamako'?'selected':'').">Africa/Bamako</option>
<option value='Africa/Bangui' ".($timezone=='Africa/Bangui'?'selected':'').">Africa/Bangui</option>
<option value='Africa/Banjul' ".($timezone=='Africa/Banjul'?'selected':'').">Africa/Banjul</option>
<option value='Africa/Bissau' ".($timezone=='Africa/Bissau'?'selected':'').">Africa/Bissau</option>
<option value='Africa/Blantyre' ".($timezone=='Africa/Blantyre'?'selected':'').">Africa/Blantyre</option>
<option value='Africa/Brazzaville' ".($timezone=='Africa/Brazzaville'?'selected':'').">Africa/Brazzaville</option>
<option value='Africa/Bujumbura' ".($timezone=='Africa/Bujumbura'?'selected':'').">Africa/Bujumbura</option>
<option value='Africa/Cairo' ".($timezone=='Africa/Cairo'?'selected':'').">Africa/Cairo</option>
<option value='Africa/Casablanca' ".($timezone=='Africa/Casablanca'?'selected':'').">Africa/Casablanca</option>
<option value='Africa/Ceuta' ".($timezone=='Africa/Ceuta'?'selected':'').">Africa/Ceuta</option>
<option value='Africa/Conakry' ".($timezone=='Africa/Conakry'?'selected':'').">Africa/Conakry</option>
<option value='Africa/Dakar' ".($timezone=='Africa/Dakar'?'selected':'').">Africa/Dakar</option>
<option value='Africa/Dar_es_Salaam' ".($timezone=='Africa/Dar_es_Salaam'?'selected':'').">Africa/Dar_es_Salaam</option>
<option value='Africa/Djibouti' ".($timezone=='Africa/Djibouti'?'selected':'').">Africa/Djibouti</option>
<option value='Africa/Douala' ".($timezone=='Africa/Douala'?'selected':'').">Africa/Douala</option>
<option value='Africa/El_Aaiun' ".($timezone=='Africa/El_Aaiun'?'selected':'').">Africa/El_Aaiun</option>
<option value='Africa/Freetown' ".($timezone=='Africa/Freetown'?'selected':'').">Africa/Freetown</option>
<option value='Africa/Gaborone' ".($timezone=='Africa/Gaborone'?'selected':'').">Africa/Gaborone</option>
<option value='Africa/Harare' ".($timezone=='Africa/Harare'?'selected':'').">Africa/Harare</option>
<option value='Africa/Johannesburg' ".($timezone=='Africa/Johannesburg'?'selected':'').">Africa/Johannesburg</option>
<option value='Africa/Juba' ".($timezone=='Africa/Juba'?'selected':'').">Africa/Juba</option>
<option value='Africa/Kampala' ".($timezone=='Africa/Kampala'?'selected':'').">Africa/Kampala</option>
<option value='Africa/Khartoum' ".($timezone=='Africa/Khartoum'?'selected':'').">Africa/Khartoum</option>
<option value='Africa/Kigali' ".($timezone=='Africa/Kigali'?'selected':'').">Africa/Kigali</option>
<option value='Africa/Kinshasa' ".($timezone=='Africa/Kinshasa'?'selected':'').">Africa/Kinshasa</option>
<option value='Africa/Lagos' ".($timezone=='Africa/Lagos'?'selected':'').">Africa/Lagos</option>
<option value='Africa/Libreville' ".($timezone=='Africa/Libreville'?'selected':'').">Africa/Libreville</option>
<option value='Africa/Lome' ".($timezone=='Africa/Lome'?'selected':'').">Africa/Lome</option>
<option value='Africa/Luanda' ".($timezone=='Africa/Luanda'?'selected':'').">Africa/Luanda</option>
<option value='Africa/Lubumbashi' ".($timezone=='Africa/Lubumbashi'?'selected':'').">Africa/Lubumbashi</option>
<option value='Africa/Lusaka' ".($timezone=='Africa/Lusaka'?'selected':'').">Africa/Lusaka</option>
<option value='Africa/Malabo' ".($timezone=='Africa/Malabo'?'selected':'').">Africa/Malabo</option>
<option value='Africa/Maputo' ".($timezone=='Africa/Maputo'?'selected':'').">Africa/Maputo</option>
<option value='Africa/Maseru' ".($timezone=='Africa/Maseru'?'selected':'').">Africa/Maseru</option>
<option value='Africa/Mbabane' ".($timezone=='Africa/Mbabane'?'selected':'').">Africa/Mbabane</option>
<option value='Africa/Mogadishu' ".($timezone=='Africa/Mogadishu'?'selected':'').">Africa/Mogadishu</option>
<option value='Africa/Monrovia' ".($timezone=='Africa/Monrovia'?'selected':'').">Africa/Monrovia</option>
<option value='Africa/Nairobi' ".($timezone=='Africa/Nairobi'?'selected':'').">Africa/Nairobi</option>
<option value='Africa/Ndjamena' ".($timezone=='Africa/Ndjamena'?'selected':'').">Africa/Ndjamena</option>
<option value='Africa/Niamey' ".($timezone=='Africa/Niamey'?'selected':'').">Africa/Niamey</option>
<option value='Africa/Nouakchott' ".($timezone=='Africa/Nouakchott'?'selected':'').">Africa/Nouakchott</option>
<option value='Africa/Ouagadougou' ".($timezone=='Africa/Ouagadougou'?'selected':'').">Africa/Ouagadougou</option>
<option value='Africa/Porto-Novo' ".($timezone=='Africa/Porto-Novo'?'selected':'').">Africa/Porto-Novo</option>
<option value='Africa/Sao_Tome' ".($timezone=='Africa/Sao_Tome'?'selected':'').">Africa/Sao_Tome</option>
<option value='Africa/Timbuktu' ".($timezone=='Africa/Timbuktu'?'selected':'').">Africa/Timbuktu</option>
<option value='Africa/Tripoli' ".($timezone=='Africa/Tripoli'?'selected':'').">Africa/Tripoli</option>
<option value='Africa/Tunis' ".($timezone=='Africa/Tunis'?'selected':'').">Africa/Tunis</option>
<option value='Africa/Windhoek' ".($timezone=='Africa/Windhoek'?'selected':'').">Africa/Windhoek</option>
<option value='America/Adak' ".($timezone=='America/Adak'?'selected':'').">America/Adak</option>
<option value='America/Anchorage' ".($timezone=='America/Anchorage'?'selected':'').">America/Anchorage</option>
<option value='America/Anguilla' ".($timezone=='America/Anguilla'?'selected':'').">America/Anguilla</option>
<option value='America/Antigua' ".($timezone=='America/Antigua'?'selected':'').">America/Antigua</option>
<option value='America/Araguaina' ".($timezone=='America/Araguaina'?'selected':'').">America/Araguaina</option>
<option value='America/Argentina/Buenos_Aires' ".($timezone=='America/Argentina/Buenos_Aires'?'selected':'').">America/Argentina/Buenos_Aires</option>
<option value='America/Argentina/Catamarca' ".($timezone=='America/Argentina/Catamarca'?'selected':'').">America/Argentina/Catamarca</option>
<option value='America/Argentina/ComodRivadavia' ".($timezone=='America/Argentina/ComodRivadavia'?'selected':'').">America/Argentina/ComodRivadavia</option>
<option value='America/Argentina/Cordoba' ".($timezone=='America/Argentina/Cordoba'?'selected':'').">America/Argentina/Cordoba</option>
<option value='America/Argentina/Jujuy' ".($timezone=='America/Argentina/Jujuy'?'selected':'').">America/Argentina/Jujuy</option>
<option value='America/Argentina/La_Rioja' ".($timezone=='America/Argentina/La_Rioja'?'selected':'').">America/Argentina/La_Rioja</option>
<option value='America/Argentina/Mendoza' ".($timezone=='America/Argentina/Mendoza'?'selected':'').">America/Argentina/Mendoza</option>
<option value='America/Argentina/Rio_Gallegos' ".($timezone=='America/Argentina/Rio_Gallegos'?'selected':'').">America/Argentina/Rio_Gallegos</option>
<option value='America/Argentina/Salta' ".($timezone=='America/Argentina/Salta'?'selected':'').">America/Argentina/Salta</option>
<option value='America/Argentina/San_Juan' ".($timezone=='America/Argentina/San_Juan'?'selected':'').">America/Argentina/San_Juan</option>
<option value='America/Argentina/San_Luis' ".($timezone=='America/Argentina/San_Luis'?'selected':'').">America/Argentina/San_Luis</option>
<option value='America/Argentina/Tucuman' ".($timezone=='America/Argentina/Tucuman'?'selected':'').">America/Argentina/Tucuman</option>
<option value='America/Argentina/Ushuaia' ".($timezone=='America/Argentina/Ushuaia'?'selected':'').">America/Argentina/Ushuaia</option>
<option value='America/Aruba' ".($timezone=='America/Aruba'?'selected':'').">America/Aruba</option>
<option value='America/Asuncion' ".($timezone=='America/Asuncion'?'selected':'').">America/Asuncion</option>
<option value='America/Atikokan' ".($timezone=='America/Atikokan'?'selected':'').">America/Atikokan</option>
<option value='America/Atka' ".($timezone=='America/Atka'?'selected':'').">America/Atka</option>
<option value='America/Bahia' ".($timezone=='America/Bahia'?'selected':'').">America/Bahia</option>
<option value='America/Bahia_Banderas' ".($timezone=='America/Bahia_Banderas'?'selected':'').">America/Bahia_Banderas</option>
<option value='America/Barbados' ".($timezone=='America/Barbados'?'selected':'').">America/Barbados</option>
<option value='America/Belem' ".($timezone=='America/Belem'?'selected':'').">America/Belem</option>
<option value='America/Belize' ".($timezone=='America/Belize'?'selected':'').">America/Belize</option>
<option value='America/Blanc-Sablon' ".($timezone=='America/Blanc-Sablon'?'selected':'').">America/Blanc-Sablon</option>
<option value='America/Boa_Vista' ".($timezone=='America/Boa_Vista'?'selected':'').">America/Boa_Vista</option>
<option value='America/Bogota' ".($timezone=='America/Bogota'?'selected':'').">America/Bogota</option>
<option value='America/Boise' ".($timezone=='America/Boise'?'selected':'').">America/Boise</option>
<option value='America/Buenos_Aires' ".($timezone=='America/Buenos_Aires'?'selected':'').">America/Buenos_Aires</option>
<option value='America/Cambridge_Bay' ".($timezone=='America/Cambridge_Bay'?'selected':'').">America/Cambridge_Bay</option>
<option value='America/Campo_Grande' ".($timezone=='America/Campo_Grande'?'selected':'').">America/Campo_Grande</option>
<option value='America/Cancun' ".($timezone=='America/Cancun'?'selected':'').">America/Cancun</option>
<option value='America/Caracas' ".($timezone=='America/Caracas'?'selected':'').">America/Caracas</option>
<option value='America/Catamarca' ".($timezone=='America/Catamarca'?'selected':'').">America/Catamarca</option>
<option value='America/Cayenne' ".($timezone=='America/Cayenne'?'selected':'').">America/Cayenne</option>
<option value='America/Cayman' ".($timezone=='America/Cayman'?'selected':'').">America/Cayman</option>
<option value='America/Chicago' ".($timezone=='America/Chicago'?'selected':'').">America/Chicago</option>
<option value='America/Chihuahua' ".($timezone=='America/Chihuahua'?'selected':'').">America/Chihuahua</option>
<option value='America/Coral_Harbour' ".($timezone=='America/Coral_Harbour'?'selected':'').">America/Coral_Harbour</option>
<option value='America/Cordoba' ".($timezone=='America/Cordoba'?'selected':'').">America/Cordoba</option>
<option value='America/Costa_Rica' ".($timezone=='America/Costa_Rica'?'selected':'').">America/Costa_Rica</option>
<option value='America/Creston' ".($timezone=='America/Creston'?'selected':'').">America/Creston</option>
<option value='America/Cuiaba' ".($timezone=='America/Cuiaba'?'selected':'').">America/Cuiaba</option>
<option value='America/Curacao' ".($timezone=='America/Curacao'?'selected':'').">America/Curacao</option>
<option value='America/Danmarkshavn' ".($timezone=='America/Danmarkshavn'?'selected':'').">America/Danmarkshavn</option>
<option value='America/Dawson' ".($timezone=='America/Dawson'?'selected':'').">America/Dawson</option>
<option value='America/Dawson_Creek' ".($timezone=='America/Dawson_Creek'?'selected':'').">America/Dawson_Creek</option>
<option value='America/Denver' ".($timezone=='America/Denver'?'selected':'').">America/Denver</option>
<option value='America/Detroit' ".($timezone=='America/Detroit'?'selected':'').">America/Detroit</option>
<option value='America/Dominica' ".($timezone=='America/Dominica'?'selected':'').">America/Dominica</option>
<option value='America/Edmonton' ".($timezone=='America/Edmonton'?'selected':'').">America/Edmonton</option>
<option value='America/Eirunepe' ".($timezone=='America/Eirunepe'?'selected':'').">America/Eirunepe</option>
<option value='America/El_Salvador' ".($timezone=='America/El_Salvador'?'selected':'').">America/El_Salvador</option>
<option value='America/Ensenada' ".($timezone=='America/Ensenada'?'selected':'').">America/Ensenada</option>
<option value='America/Fort_Wayne' ".($timezone=='America/Fort_Wayne'?'selected':'').">America/Fort_Wayne</option>
<option value='America/Fortaleza' ".($timezone=='America/Fortaleza'?'selected':'').">America/Fortaleza</option>
<option value='America/Glace_Bay' ".($timezone=='America/Glace_Bay'?'selected':'').">America/Glace_Bay</option>
<option value='America/Godthab' ".($timezone=='America/Godthab'?'selected':'').">America/Godthab</option>
<option value='America/Goose_Bay' ".($timezone=='America/Goose_Bay'?'selected':'').">America/Goose_Bay</option>
<option value='America/Grand_Turk' ".($timezone=='America/Grand_Turk'?'selected':'').">America/Grand_Turk</option>
<option value='America/Grenada' ".($timezone=='America/Grenada'?'selected':'').">America/Grenada</option>
<option value='America/Guadeloupe' ".($timezone=='America/Guadeloupe'?'selected':'').">America/Guadeloupe</option>
<option value='America/Guatemala' ".($timezone=='America/Guatemala'?'selected':'').">America/Guatemala</option>
<option value='America/Guayaquil' ".($timezone=='America/Guayaquil'?'selected':'').">America/Guayaquil</option>
<option value='America/Guyana' ".($timezone=='America/Guyana'?'selected':'').">America/Guyana</option>
<option value='America/Halifax' ".($timezone=='America/Halifax'?'selected':'').">America/Halifax</option>
<option value='America/Havana' ".($timezone=='America/Havana'?'selected':'').">America/Havana</option>
<option value='America/Hermosillo' ".($timezone=='America/Hermosillo'?'selected':'').">America/Hermosillo</option>
<option value='America/Indiana/Indianapolis' ".($timezone=='America/Indiana/Indianapolis'?'selected':'').">America/Indiana/Indianapolis</option>
<option value='America/Indiana/Knox' ".($timezone=='America/Indiana/Knox'?'selected':'').">America/Indiana/Knox</option>
<option value='America/Indiana/Marengo' ".($timezone=='America/Indiana/Marengo'?'selected':'').">America/Indiana/Marengo</option>
<option value='America/Indiana/Petersburg' ".($timezone=='America/Indiana/Petersburg'?'selected':'').">America/Indiana/Petersburg</option>
<option value='America/Indiana/Tell_City' ".($timezone=='America/Indiana/Tell_City'?'selected':'').">America/Indiana/Tell_City</option>
<option value='America/Indiana/Vevay' ".($timezone=='America/Indiana/Vevay'?'selected':'').">America/Indiana/Vevay</option>
<option value='America/Indiana/Vincennes' ".($timezone=='America/Indiana/Vincennes'?'selected':'').">America/Indiana/Vincennes</option>
<option value='America/Indiana/Winamac' ".($timezone=='America/Indiana/Winamac'?'selected':'').">America/Indiana/Winamac</option>
<option value='America/Indianapolis' ".($timezone=='America/Indianapolis'?'selected':'').">America/Indianapolis</option>
<option value='America/Inuvik' ".($timezone=='America/Inuvik'?'selected':'').">America/Inuvik</option>
<option value='America/Iqaluit' ".($timezone=='America/Iqaluit'?'selected':'').">America/Iqaluit</option>
<option value='America/Jamaica' ".($timezone=='America/Jamaica'?'selected':'').">America/Jamaica</option>
<option value='America/Jujuy' ".($timezone=='America/Jujuy'?'selected':'').">America/Jujuy</option>
<option value='America/Juneau' ".($timezone=='America/Juneau'?'selected':'').">America/Juneau</option>
<option value='America/Kentucky/Louisville' ".($timezone=='America/Kentucky/Louisville'?'selected':'').">America/Kentucky/Louisville</option>
<option value='America/Kentucky/Monticello' ".($timezone=='America/Kentucky/Monticello'?'selected':'').">America/Kentucky/Monticello</option>
<option value='America/Knox_IN' ".($timezone=='America/Knox_IN'?'selected':'').">America/Knox_IN</option>
<option value='America/Kralendijk' ".($timezone=='America/Kralendijk'?'selected':'').">America/Kralendijk</option>
<option value='America/La_Paz' ".($timezone=='America/La_Paz'?'selected':'').">America/La_Paz</option>
<option value='America/Lima' ".($timezone=='America/Lima'?'selected':'').">America/Lima</option>
<option value='America/Los_Angeles' ".($timezone=='America/Los_Angeles'?'selected':'').">America/Los_Angeles</option>
<option value='America/Louisville' ".($timezone=='America/Louisville'?'selected':'').">America/Louisville</option>
<option value='America/Lower_Princes' ".($timezone=='America/Lower_Princes'?'selected':'').">America/Lower_Princes</option>
<option value='America/Maceio' ".($timezone=='America/Maceio'?'selected':'').">America/Maceio</option>
<option value='America/Managua' ".($timezone=='America/Managua'?'selected':'').">America/Managua</option>
<option value='America/Manaus' ".($timezone=='America/Manaus'?'selected':'').">America/Manaus</option>
<option value='America/Marigot' ".($timezone=='America/Marigot'?'selected':'').">America/Marigot</option>
<option value='America/Martinique' ".($timezone=='America/Martinique'?'selected':'').">America/Martinique</option>
<option value='America/Matamoros' ".($timezone=='America/Matamoros'?'selected':'').">America/Matamoros</option>
<option value='America/Mazatlan' ".($timezone=='America/Mazatlan'?'selected':'').">America/Mazatlan</option>
<option value='America/Mendoza' ".($timezone=='America/Mendoza'?'selected':'').">America/Mendoza</option>
<option value='America/Menominee' ".($timezone=='America/Menominee'?'selected':'').">America/Menominee</option>
<option value='America/Merida' ".($timezone=='America/Merida'?'selected':'').">America/Merida</option>
<option value='America/Metlakatla' ".($timezone=='America/Metlakatla'?'selected':'').">America/Metlakatla</option>
<option value='America/Mexico_City' ".($timezone=='America/Mexico_City'?'selected':'').">America/Mexico_City</option>
<option value='America/Miquelon' ".($timezone=='America/Miquelon'?'selected':'').">America/Miquelon</option>
<option value='America/Moncton' ".($timezone=='America/Moncton'?'selected':'').">America/Moncton</option>
<option value='America/Monterrey' ".($timezone=='America/Monterrey'?'selected':'').">America/Monterrey</option>
<option value='America/Montevideo' ".($timezone=='America/Montevideo'?'selected':'').">America/Montevideo</option>
<option value='America/Montreal' ".($timezone=='America/Montreal'?'selected':'').">America/Montreal</option>
<option value='America/Montserrat' ".($timezone=='America/Montserrat'?'selected':'').">America/Montserrat</option>
<option value='America/Nassau' ".($timezone=='America/Nassau'?'selected':'').">America/Nassau</option>
<option value='America/New_York' ".($timezone=='America/New_York'?'selected':'').">America/New_York</option>
<option value='America/Nipigon' ".($timezone=='America/Nipigon'?'selected':'').">America/Nipigon</option>
<option value='America/Nome' ".($timezone=='America/Nome'?'selected':'').">America/Nome</option>
<option value='America/Noronha' ".($timezone=='America/Noronha'?'selected':'').">America/Noronha</option>
<option value='America/North_Dakota/Beulah' ".($timezone=='America/North_Dakota/Beulah'?'selected':'').">America/North_Dakota/Beulah</option>
<option value='America/North_Dakota/Center' ".($timezone=='America/North_Dakota/Center'?'selected':'').">America/North_Dakota/Center</option>
<option value='America/North_Dakota/New_Salem' ".($timezone=='America/North_Dakota/New_Salem'?'selected':'').">America/North_Dakota/New_Salem</option>
<option value='America/Ojinaga' ".($timezone=='America/Ojinaga'?'selected':'').">America/Ojinaga</option>
<option value='America/Panama' ".($timezone=='America/Panama'?'selected':'').">America/Panama</option>
<option value='America/Pangnirtung' ".($timezone=='America/Pangnirtung'?'selected':'').">America/Pangnirtung</option>
<option value='America/Paramaribo' ".($timezone=='America/Paramaribo'?'selected':'').">America/Paramaribo</option>
<option value='America/Phoenix' ".($timezone=='America/Phoenix'?'selected':'').">America/Phoenix</option>
<option value='America/Port-au-Prince' ".($timezone=='America/Port-au-Prince'?'selected':'').">America/Port-au-Prince</option>
<option value='America/Port_of_Spain' ".($timezone=='America/Port_of_Spain'?'selected':'').">America/Port_of_Spain</option>
<option value='America/Porto_Acre' ".($timezone=='America/Porto_Acre'?'selected':'').">America/Porto_Acre</option>
<option value='America/Porto_Velho' ".($timezone=='America/Porto_Velho'?'selected':'').">America/Porto_Velho</option>
<option value='America/Puerto_Rico' ".($timezone=='America/Puerto_Rico'?'selected':'').">America/Puerto_Rico</option>
<option value='America/Rainy_River' ".($timezone=='America/Rainy_River'?'selected':'').">America/Rainy_River</option>
<option value='America/Rankin_Inlet' ".($timezone=='America/Rankin_Inlet'?'selected':'').">America/Rankin_Inlet</option>
<option value='America/Recife' ".($timezone=='America/Recife'?'selected':'').">America/Recife</option>
<option value='America/Regina' ".($timezone=='America/Regina'?'selected':'').">America/Regina</option>
<option value='America/Resolute' ".($timezone=='America/Resolute'?'selected':'').">America/Resolute</option>
<option value='America/Rio_Branco' ".($timezone=='America/Rio_Branco'?'selected':'').">America/Rio_Branco</option>
<option value='America/Rosario' ".($timezone=='America/Rosario'?'selected':'').">America/Rosario</option>
<option value='America/Santa_Isabel' ".($timezone=='America/Santa_Isabel'?'selected':'').">America/Santa_Isabel</option>
<option value='America/Santarem' ".($timezone=='America/Santarem'?'selected':'').">America/Santarem</option>
<option value='America/Santiago' ".($timezone=='America/Santiago'?'selected':'').">America/Santiago</option>
<option value='America/Santo_Domingo' ".($timezone=='America/Santo_Domingo'?'selected':'').">America/Santo_Domingo</option>
<option value='America/Sao_Paulo' ".($timezone=='America/Sao_Paulo'?'selected':'').">America/Sao_Paulo</option>
<option value='America/Scoresbysund' ".($timezone=='America/Scoresbysund'?'selected':'').">America/Scoresbysund</option>
<option value='America/Shiprock' ".($timezone=='America/Shiprock'?'selected':'').">America/Shiprock</option>
<option value='America/Sitka' ".($timezone=='America/Sitka'?'selected':'').">America/Sitka</option>
<option value='America/St_Barthelemy' ".($timezone=='America/St_Barthelemy'?'selected':'').">America/St_Barthelemy</option>
<option value='America/St_Johns' ".($timezone=='America/St_Johns'?'selected':'').">America/St_Johns</option>
<option value='America/St_Kitts' ".($timezone=='America/St_Kitts'?'selected':'').">America/St_Kitts</option>
<option value='America/St_Lucia' ".($timezone=='America/St_Lucia'?'selected':'').">America/St_Lucia</option>
<option value='America/St_Thomas' ".($timezone=='America/St_Thomas'?'selected':'').">America/St_Thomas</option>
<option value='America/St_Vincent' ".($timezone=='America/St_Vincent'?'selected':'').">America/St_Vincent</option>
<option value='America/Swift_Current' ".($timezone=='America/Swift_Current'?'selected':'').">America/Swift_Current</option>
<option value='America/Tegucigalpa' ".($timezone=='America/Tegucigalpa'?'selected':'').">America/Tegucigalpa</option>
<option value='America/Thule' ".($timezone=='America/Thule'?'selected':'').">America/Thule</option>
<option value='America/Thunder_Bay' ".($timezone=='America/Thunder_Bay'?'selected':'').">America/Thunder_Bay</option>
<option value='America/Tijuana' ".($timezone=='America/Tijuana'?'selected':'').">America/Tijuana</option>
<option value='America/Toronto' ".($timezone=='America/Toronto'?'selected':'').">America/Toronto</option>
<option value='America/Tortola' ".($timezone=='America/Tortola'?'selected':'').">America/Tortola</option>
<option value='America/Vancouver' ".($timezone=='America/Vancouver'?'selected':'').">America/Vancouver</option>
<option value='America/Virgin' ".($timezone=='America/Virgin'?'selected':'').">America/Virgin</option>
<option value='America/Whitehorse' ".($timezone=='America/Whitehorse'?'selected':'').">America/Whitehorse</option>
<option value='America/Winnipeg' ".($timezone=='America/Winnipeg'?'selected':'').">America/Winnipeg</option>
<option value='America/Yakutat' ".($timezone=='America/Yakutat'?'selected':'').">America/Yakutat</option>
<option value='America/Yellowknife' ".($timezone=='America/Yellowknife'?'selected':'').">America/Yellowknife</option>
<option value='Antarctica/Casey' ".($timezone=='Antarctica/Casey'?'selected':'').">Antarctica/Casey</option>
<option value='Antarctica/Davis' ".($timezone=='Antarctica/Davis'?'selected':'').">Antarctica/Davis</option>
<option value='Antarctica/DumontDUrville' ".($timezone=='Antarctica/DumontDUrville'?'selected':'').">Antarctica/DumontDUrville</option>
<option value='Antarctica/Macquarie' ".($timezone=='Antarctica/Macquarie'?'selected':'').">Antarctica/Macquarie</option>
<option value='Antarctica/Mawson' ".($timezone=='Antarctica/Mawson'?'selected':'').">Antarctica/Mawson</option>
<option value='Antarctica/McMurdo' ".($timezone=='Antarctica/McMurdo'?'selected':'').">Antarctica/McMurdo</option>
<option value='Antarctica/Palmer' ".($timezone=='Antarctica/Palmer'?'selected':'').">Antarctica/Palmer</option>
<option value='Antarctica/Rothera' ".($timezone=='Antarctica/Rothera'?'selected':'').">Antarctica/Rothera</option>
<option value='Antarctica/South_Pole' ".($timezone=='Antarctica/South_Pole'?'selected':'').">Antarctica/South_Pole</option>
<option value='Antarctica/Syowa' ".($timezone=='Antarctica/Syowa'?'selected':'').">Antarctica/Syowa</option>
<option value='Antarctica/Troll' ".($timezone=='Antarctica/Troll'?'selected':'').">Antarctica/Troll</option>
<option value='Antarctica/Vostok' ".($timezone=='Antarctica/Vostok'?'selected':'').">Antarctica/Vostok</option>
<option value='Arctic/Longyearbyen' ".($timezone=='Arctic/Longyearbyen'?'selected':'').">Arctic/Longyearbyen</option>
<option value='Asia/Aden' ".($timezone=='Asia/Aden'?'selected':'').">Asia/Aden</option>
<option value='Asia/Almaty' ".($timezone=='Asia/Almaty'?'selected':'').">Asia/Almaty</option>
<option value='Asia/Amman' ".($timezone=='Asia/Amman'?'selected':'').">Asia/Amman</option>
<option value='Asia/Anadyr' ".($timezone=='Asia/Anadyr'?'selected':'').">Asia/Anadyr</option>
<option value='Asia/Aqtau' ".($timezone=='Asia/Aqtau'?'selected':'').">Asia/Aqtau</option>
<option value='Asia/Aqtobe' ".($timezone=='Asia/Aqtobe'?'selected':'').">Asia/Aqtobe</option>
<option value='Asia/Ashgabat' ".($timezone=='Asia/Ashgabat'?'selected':'').">Asia/Ashgabat</option>
<option value='Asia/Ashkhabad' ".($timezone=='Asia/Ashkhabad'?'selected':'').">Asia/Ashkhabad</option>
<option value='Asia/Baghdad' ".($timezone=='Asia/Baghdad'?'selected':'').">Asia/Baghdad</option>
<option value='Asia/Bahrain' ".($timezone=='Asia/Bahrain'?'selected':'').">Asia/Bahrain</option>
<option value='Asia/Baku' ".($timezone=='Asia/Baku'?'selected':'').">Asia/Baku</option>
<option value='Asia/Bangkok' ".($timezone=='Asia/Bangkok'?'selected':'').">Asia/Bangkok</option>
<option value='Asia/Beirut' ".($timezone=='Asia/Beirut'?'selected':'').">Asia/Beirut</option>
<option value='Asia/Bishkek' ".($timezone=='Asia/Bishkek'?'selected':'').">Asia/Bishkek</option>
<option value='Asia/Brunei' ".($timezone=='Asia/Brunei'?'selected':'').">Asia/Brunei</option>
<option value='Asia/Calcutta' ".($timezone=='Asia/Calcutta'?'selected':'').">Asia/Calcutta</option>
<option value='Asia/Choibalsan' ".($timezone=='Asia/Choibalsan'?'selected':'').">Asia/Choibalsan</option>
<option value='Asia/Chongqing' ".($timezone=='Asia/Chongqing'?'selected':'').">Asia/Chongqing</option>
<option value='Asia/Chungking' ".($timezone=='Asia/Chungking'?'selected':'').">Asia/Chungking</option>
<option value='Asia/Colombo' ".($timezone=='Asia/Colombo'?'selected':'').">Asia/Colombo</option>
<option value='Asia/Dacca' ".($timezone=='Asia/Dacca'?'selected':'').">Asia/Dacca</option>
<option value='Asia/Damascus' ".($timezone=='Asia/Damascus'?'selected':'').">Asia/Damascus</option>
<option value='Asia/Dhaka' ".($timezone=='Asia/Dhaka'?'selected':'').">Asia/Dhaka</option>
<option value='Asia/Dili' ".($timezone=='Asia/Dili'?'selected':'').">Asia/Dili</option>
<option value='Asia/Dubai' ".($timezone=='Asia/Dubai'?'selected':'').">Asia/Dubai</option>
<option value='Asia/Dushanbe' ".($timezone=='Asia/Dushanbe'?'selected':'').">Asia/Dushanbe</option>
<option value='Asia/Gaza' ".($timezone=='Asia/Gaza'?'selected':'').">Asia/Gaza</option>
<option value='Asia/Harbin' ".($timezone=='Asia/Harbin'?'selected':'').">Asia/Harbin</option>
<option value='Asia/Hebron' ".($timezone=='Asia/Hebron'?'selected':'').">Asia/Hebron</option>
<option value='Asia/Ho_Chi_Minh' ".($timezone=='Asia/Ho_Chi_Minh'?'selected':'').">Asia/Ho_Chi_Minh</option>
<option value='Asia/Hong_Kong' ".($timezone=='Asia/Hong_Kong'?'selected':'').">Asia/Hong_Kong</option>
<option value='Asia/Hovd' ".($timezone=='Asia/Hovd'?'selected':'').">Asia/Hovd</option>
<option value='Asia/Irkutsk' ".($timezone=='Asia/Irkutsk'?'selected':'').">Asia/Irkutsk</option>
<option value='Asia/Istanbul' ".($timezone=='Asia/Istanbul'?'selected':'').">Asia/Istanbul</option>
<option value='Asia/Jakarta' ".($timezone=='Asia/Jakarta'?'selected':'').">Asia/Jakarta</option>
<option value='Asia/Jayapura' ".($timezone=='Asia/Jayapura'?'selected':'').">Asia/Jayapura</option>
<option value='Asia/Jerusalem' ".($timezone=='Asia/Jerusalem'?'selected':'').">Asia/Jerusalem</option>
<option value='Asia/Kabul' ".($timezone=='Asia/Kabul'?'selected':'').">Asia/Kabul</option>
<option value='Asia/Kamchatka' ".($timezone=='Asia/Kamchatka'?'selected':'').">Asia/Kamchatka</option>
<option value='Asia/Karachi' ".($timezone=='Asia/Karachi'?'selected':'').">Asia/Karachi</option>
<option value='Asia/Kashgar' ".($timezone=='Asia/Kashgar'?'selected':'').">Asia/Kashgar</option>
<option value='Asia/Kathmandu' ".($timezone=='Asia/Kathmandu'?'selected':'').">Asia/Kathmandu</option>
<option value='Asia/Katmandu' ".($timezone=='Asia/Katmandu'?'selected':'').">Asia/Katmandu</option>
<option value='Asia/Khandyga' ".($timezone=='Asia/Khandyga'?'selected':'').">Asia/Khandyga</option>
<option value='Asia/Kolkata' ".($timezone=='Asia/Kolkata'?'selected':'').">Asia/Kolkata</option>
<option value='Asia/Krasnoyarsk' ".($timezone=='Asia/Krasnoyarsk'?'selected':'').">Asia/Krasnoyarsk</option>
<option value='Asia/Kuala_Lumpur' ".($timezone=='Asia/Kuala_Lumpur'?'selected':'').">Asia/Kuala_Lumpur</option>
<option value='Asia/Kuching' ".($timezone=='Asia/Kuching'?'selected':'').">Asia/Kuching</option>
<option value='Asia/Kuwait' ".($timezone=='Asia/Kuwait'?'selected':'').">Asia/Kuwait</option>
<option value='Asia/Macao' ".($timezone=='Asia/Macao'?'selected':'').">Asia/Macao</option>
<option value='Asia/Macau' ".($timezone=='Asia/Macau'?'selected':'').">Asia/Macau</option>
<option value='Asia/Magadan' ".($timezone=='Asia/Magadan'?'selected':'').">Asia/Magadan</option>
<option value='Asia/Makassar' ".($timezone=='Asia/Makassar'?'selected':'').">Asia/Makassar</option>
<option value='Asia/Manila' ".($timezone=='Asia/Manila'?'selected':'').">Asia/Manila</option>
<option value='Asia/Muscat' ".($timezone=='Asia/Muscat'?'selected':'').">Asia/Muscat</option>
<option value='Asia/Nicosia' ".($timezone=='Asia/Nicosia'?'selected':'').">Asia/Nicosia</option>
<option value='Asia/Novokuznetsk' ".($timezone=='Asia/Novokuznetsk'?'selected':'').">Asia/Novokuznetsk</option>
<option value='Asia/Novosibirsk' ".($timezone=='Asia/Novosibirsk'?'selected':'').">Asia/Novosibirsk</option>
<option value='Asia/Omsk' ".($timezone=='Asia/Omsk'?'selected':'').">Asia/Omsk</option>
<option value='Asia/Oral' ".($timezone=='Asia/Oral'?'selected':'').">Asia/Oral</option>
<option value='Asia/Phnom_Penh' ".($timezone=='Asia/Phnom_Penh'?'selected':'').">Asia/Phnom_Penh</option>
<option value='Asia/Pontianak' ".($timezone=='Asia/Pontianak'?'selected':'').">Asia/Pontianak</option>
<option value='Asia/Pyongyang' ".($timezone=='Asia/Pyongyang'?'selected':'').">Asia/Pyongyang</option>
<option value='Asia/Qatar' ".($timezone=='Asia/Qatar'?'selected':'').">Asia/Qatar</option>
<option value='Asia/Qyzylorda' ".($timezone=='Asia/Qyzylorda'?'selected':'').">Asia/Qyzylorda</option>
<option value='Asia/Rangoon' ".($timezone=='Asia/Rangoon'?'selected':'').">Asia/Rangoon</option>
<option value='Asia/Riyadh' ".($timezone=='Asia/Riyadh'?'selected':'').">Asia/Riyadh</option>
<option value='Asia/Saigon' ".($timezone=='Asia/Saigon'?'selected':'').">Asia/Saigon</option>
<option value='Asia/Sakhalin' ".($timezone=='Asia/Sakhalin'?'selected':'').">Asia/Sakhalin</option>
<option value='Asia/Samarkand' ".($timezone=='Asia/Samarkand'?'selected':'').">Asia/Samarkand</option>
<option value='Asia/Seoul' ".($timezone=='Asia/Seoul'?'selected':'').">Asia/Seoul</option>
<option value='Asia/Shanghai' ".($timezone=='Asia/Shanghai'?'selected':'').">Asia/Shanghai</option>
<option value='Asia/Singapore' ".($timezone=='Asia/Singapore'?'selected':'').">Asia/Singapore</option>
<option value='Asia/Taipei' ".($timezone=='Asia/Taipei'?'selected':'').">Asia/Taipei</option>
<option value='Asia/Tashkent' ".($timezone=='Asia/Tashkent'?'selected':'').">Asia/Tashkent</option>
<option value='Asia/Tbilisi' ".($timezone=='Asia/Tbilisi'?'selected':'').">Asia/Tbilisi</option>
<option value='Asia/Tehran' ".($timezone=='Asia/Tehran'?'selected':'').">Asia/Tehran</option>
<option value='Asia/Tel_Aviv' ".($timezone=='Asia/Tel_Aviv'?'selected':'').">Asia/Tel_Aviv</option>
<option value='Asia/Thimbu' ".($timezone=='Asia/Thimbu'?'selected':'').">Asia/Thimbu</option>
<option value='Asia/Thimphu' ".($timezone=='Asia/Thimphu'?'selected':'').">Asia/Thimphu</option>
<option value='Asia/Tokyo' ".($timezone=='Asia/Tokyo'?'selected':'').">Asia/Tokyo</option>
<option value='Asia/Ujung_Pandang' ".($timezone=='Asia/Ujung_Pandang'?'selected':'').">Asia/Ujung_Pandang</option>
<option value='Asia/Ulaanbaatar' ".($timezone=='Asia/Ulaanbaatar'?'selected':'').">Asia/Ulaanbaatar</option>
<option value='Asia/Ulan_Bator' ".($timezone=='Asia/Ulan_Bator'?'selected':'').">Asia/Ulan_Bator</option>
<option value='Asia/Urumqi' ".($timezone=='Asia/Urumqi'?'selected':'').">Asia/Urumqi</option>
<option value='Asia/Ust-Nera' ".($timezone=='Asia/Ust-Nera'?'selected':'').">Asia/Ust-Nera</option>
<option value='Asia/Vientiane' ".($timezone=='Asia/Vientiane'?'selected':'').">Asia/Vientiane</option>
<option value='Asia/Vladivostok' ".($timezone=='Asia/Vladivostok'?'selected':'').">Asia/Vladivostok</option>
<option value='Asia/Yakutsk' ".($timezone=='Asia/Yakutsk'?'selected':'').">Asia/Yakutsk</option>
<option value='Asia/Yekaterinburg' ".($timezone=='Asia/Yekaterinburg'?'selected':'').">Asia/Yekaterinburg</option>
<option value='Asia/Yerevan' ".($timezone=='Asia/Yerevan'?'selected':'').">Asia/Yerevan</option>
<option value='Atlantic/Azores' ".($timezone=='Atlantic/Azores'?'selected':'').">Atlantic/Azores</option>
<option value='Atlantic/Bermuda' ".($timezone=='Atlantic/Bermuda'?'selected':'').">Atlantic/Bermuda</option>
<option value='Atlantic/Canary' ".($timezone=='Atlantic/Canary'?'selected':'').">Atlantic/Canary</option>
<option value='Atlantic/Cape_Verde' ".($timezone=='Atlantic/Cape_Verde'?'selected':'').">Atlantic/Cape_Verde</option>
<option value='Atlantic/Faeroe' ".($timezone=='Atlantic/Faeroe'?'selected':'').">Atlantic/Faeroe</option>
<option value='Atlantic/Faroe' ".($timezone=='Atlantic/Faroe'?'selected':'').">Atlantic/Faroe</option>
<option value='Atlantic/Jan_Mayen' ".($timezone=='Atlantic/Jan_Mayen'?'selected':'').">Atlantic/Jan_Mayen</option>
<option value='Atlantic/Madeira' ".($timezone=='Atlantic/Madeira'?'selected':'').">Atlantic/Madeira</option>
<option value='Atlantic/Reykjavik' ".($timezone=='Atlantic/Reykjavik'?'selected':'').">Atlantic/Reykjavik</option>
<option value='Atlantic/South_Georgia' ".($timezone=='Atlantic/South_Georgia'?'selected':'').">Atlantic/South_Georgia</option>
<option value='Atlantic/St_Helena' ".($timezone=='Atlantic/St_Helena'?'selected':'').">Atlantic/St_Helena</option>
<option value='Atlantic/Stanley' ".($timezone=='Atlantic/Stanley'?'selected':'').">Atlantic/Stanley</option>
<option value='Australia/ACT' ".($timezone=='Australia/ACT'?'selected':'').">Australia/ACT</option>
<option value='Australia/Adelaide' ".($timezone=='Australia/Adelaide'?'selected':'').">Australia/Adelaide</option>
<option value='Australia/Brisbane' ".($timezone=='Australia/Brisbane'?'selected':'').">Australia/Brisbane</option>
<option value='Australia/Broken_Hill' ".($timezone=='Australia/Broken_Hill'?'selected':'').">Australia/Broken_Hill</option>
<option value='Australia/Canberra' ".($timezone=='Australia/Canberra'?'selected':'').">Australia/Canberra</option>
<option value='Australia/Currie' ".($timezone=='Australia/Currie'?'selected':'').">Australia/Currie</option>
<option value='Australia/Darwin' ".($timezone=='Australia/Darwin'?'selected':'').">Australia/Darwin</option>
<option value='Australia/Eucla' ".($timezone=='Australia/Eucla'?'selected':'').">Australia/Eucla</option>
<option value='Australia/Hobart' ".($timezone=='Australia/Hobart'?'selected':'').">Australia/Hobart</option>
<option value='Australia/LHI' ".($timezone=='Australia/LHI'?'selected':'').">Australia/LHI</option>
<option value='Australia/Lindeman' ".($timezone=='Australia/Lindeman'?'selected':'').">Australia/Lindeman</option>
<option value='Australia/Lord_Howe' ".($timezone=='Australia/Lord_Howe'?'selected':'').">Australia/Lord_Howe</option>
<option value='Australia/Melbourne' ".($timezone=='Australia/Melbourne'?'selected':'').">Australia/Melbourne</option>
<option value='Australia/North' ".($timezone=='Australia/North'?'selected':'').">Australia/North</option>
<option value='Australia/NSW' ".($timezone=='Australia/NSW'?'selected':'').">Australia/NSW</option>
<option value='Australia/Perth' ".($timezone=='Australia/Perth'?'selected':'').">Australia/Perth</option>
<option value='Australia/Queensland' ".($timezone=='Australia/Queensland'?'selected':'').">Australia/Queensland</option>
<option value='Australia/South' ".($timezone=='Australia/South'?'selected':'').">Australia/South</option>
<option value='Australia/Sydney' ".($timezone=='Australia/Sydney'?'selected':'').">Australia/Sydney</option>
<option value='Australia/Tasmania' ".($timezone=='Australia/Tasmania'?'selected':'').">Australia/Tasmania</option>
<option value='Australia/Victoria' ".($timezone=='Australia/Victoria'?'selected':'').">Australia/Victoria</option>
<option value='Australia/West' ".($timezone=='Australia/West'?'selected':'').">Australia/West</option>
<option value='Australia/Yancowinna' ".($timezone=='Australia/Yancowinna'?'selected':'').">Australia/Yancowinna</option>
<option value='Europe/Amsterdam' ".($timezone=='Europe/Amsterdam'?'selected':'').">Europe/Amsterdam</option>
<option value='Europe/Andorra' ".($timezone=='Europe/Andorra'?'selected':'').">Europe/Andorra</option>
<option value='Europe/Athens' ".($timezone=='Europe/Athens'?'selected':'').">Europe/Athens</option>
<option value='Europe/Belfast' ".($timezone=='Europe/Belfast'?'selected':'').">Europe/Belfast</option>
<option value='Europe/Belgrade' ".($timezone=='Europe/Belgrade'?'selected':'').">Europe/Belgrade</option>
<option value='Europe/Berlin' ".($timezone=='Europe/Berlin'?'selected':'').">Europe/Berlin</option>
<option value='Europe/Bratislava' ".($timezone=='Europe/Bratislava'?'selected':'').">Europe/Bratislava</option>
<option value='Europe/Brussels' ".($timezone=='Europe/Brussels'?'selected':'').">Europe/Brussels</option>
<option value='Europe/Bucharest' ".($timezone=='Europe/Bucharest'?'selected':'').">Europe/Bucharest</option>
<option value='Europe/Budapest' ".($timezone=='Europe/Budapest'?'selected':'').">Europe/Budapest</option>
<option value='Europe/Busingen' ".($timezone=='Europe/Busingen'?'selected':'').">Europe/Busingen</option>
<option value='Europe/Chisinau' ".($timezone=='Europe/Chisinau'?'selected':'').">Europe/Chisinau</option>
<option value='Europe/Copenhagen' ".($timezone=='Europe/Copenhagen'?'selected':'').">Europe/Copenhagen</option>
<option value='Europe/Dublin' ".($timezone=='Europe/Dublin'?'selected':'').">Europe/Dublin</option>
<option value='Europe/Gibraltar' ".($timezone=='Europe/Gibraltar'?'selected':'').">Europe/Gibraltar</option>
<option value='Europe/Guernsey' ".($timezone=='Europe/Guernsey'?'selected':'').">Europe/Guernsey</option>
<option value='Europe/Helsinki' ".($timezone=='Europe/Helsinki'?'selected':'').">Europe/Helsinki</option>
<option value='Europe/Isle_of_Man' ".($timezone=='Europe/Isle_of_Man'?'selected':'').">Europe/Isle_of_Man</option>
<option value='Europe/Istanbul' ".($timezone=='Europe/Istanbul'?'selected':'').">Europe/Istanbul</option>
<option value='Europe/Jersey' ".($timezone=='Europe/Jersey'?'selected':'').">Europe/Jersey</option>
<option value='Europe/Kaliningrad' ".($timezone=='Europe/Kaliningrad'?'selected':'').">Europe/Kaliningrad</option>
<option value='Europe/Kiev' ".($timezone=='Europe/Kiev'?'selected':'').">Europe/Kiev</option>
<option value='Europe/Lisbon' ".($timezone=='Europe/Lisbon'?'selected':'').">Europe/Lisbon</option>
<option value='Europe/Ljubljana' ".($timezone=='Europe/Ljubljana'?'selected':'').">Europe/Ljubljana</option>
<option value='Europe/London' ".($timezone=='Europe/London'?'selected':'').">Europe/London</option>
<option value='Europe/Luxembourg' ".($timezone=='Europe/Luxembourg'?'selected':'').">Europe/Luxembourg</option>
<option value='Europe/Madrid' ".($timezone=='Europe/Madrid'?'selected':'').">Europe/Madrid</option>
<option value='Europe/Malta' ".($timezone=='Europe/Malta'?'selected':'').">Europe/Malta</option>
<option value='Europe/Mariehamn' ".($timezone=='Europe/Mariehamn'?'selected':'').">Europe/Mariehamn</option>
<option value='Europe/Minsk' ".($timezone=='Europe/Minsk'?'selected':'').">Europe/Minsk</option>
<option value='Europe/Monaco' ".($timezone=='Europe/Monaco'?'selected':'').">Europe/Monaco</option>
<option value='Europe/Moscow' ".($timezone=='Europe/Moscow'?'selected':'').">Europe/Moscow</option>
<option value='Europe/Nicosia' ".($timezone=='Europe/Nicosia'?'selected':'').">Europe/Nicosia</option>
<option value='Europe/Oslo' ".($timezone=='Europe/Oslo'?'selected':'').">Europe/Oslo</option>
<option value='Europe/Paris' ".($timezone=='Europe/Paris'?'selected':'').">Europe/Paris</option>
<option value='Europe/Podgorica' ".($timezone=='Europe/Podgorica'?'selected':'').">Europe/Podgorica</option>
<option value='Europe/Prague' ".($timezone=='Europe/Prague'?'selected':'').">Europe/Prague</option>
<option value='Europe/Riga' ".($timezone=='Europe/Riga'?'selected':'').">Europe/Riga</option>
<option value='Europe/Rome' ".($timezone=='Europe/Rome'?'selected':'').">Europe/Rome</option>
<option value='Europe/Samara' ".($timezone=='Europe/Samara'?'selected':'').">Europe/Samara</option>
<option value='Europe/San_Marino' ".($timezone=='Europe/San_Marino'?'selected':'').">Europe/San_Marino</option>
<option value='Europe/Sarajevo' ".($timezone=='Europe/Sarajevo'?'selected':'').">Europe/Sarajevo</option>
<option value='Europe/Simferopol' ".($timezone=='Europe/Simferopol'?'selected':'').">Europe/Simferopol</option>
<option value='Europe/Skopje' ".($timezone=='Europe/Skopje'?'selected':'').">Europe/Skopje</option>
<option value='Europe/Sofia' ".($timezone=='Europe/Sofia'?'selected':'').">Europe/Sofia</option>
<option value='Europe/Stockholm' ".($timezone=='Europe/Stockholm'?'selected':'').">Europe/Stockholm</option>
<option value='Europe/Tallinn' ".($timezone=='Europe/Tallinn'?'selected':'').">Europe/Tallinn</option>
<option value='Europe/Tirane' ".($timezone=='Europe/Tirane'?'selected':'').">Europe/Tirane</option>
<option value='Europe/Tiraspol' ".($timezone=='Europe/Tiraspol'?'selected':'').">Europe/Tiraspol</option>
<option value='Europe/Uzhgorod' ".($timezone=='Europe/Uzhgorod'?'selected':'').">Europe/Uzhgorod</option>
<option value='Europe/Vaduz' ".($timezone=='Europe/Vaduz'?'selected':'').">Europe/Vaduz</option>
<option value='Europe/Vatican' ".($timezone=='Europe/Vatican'?'selected':'').">Europe/Vatican</option>
<option value='Europe/Vienna' ".($timezone=='Europe/Vienna'?'selected':'').">Europe/Vienna</option>
<option value='Europe/Vilnius' ".($timezone=='Europe/Vilnius'?'selected':'').">Europe/Vilnius</option>
<option value='Europe/Volgograd' ".($timezone=='Europe/Volgograd'?'selected':'').">Europe/Volgograd</option>
<option value='Europe/Warsaw' ".($timezone=='Europe/Warsaw'?'selected':'').">Europe/Warsaw</option>
<option value='Europe/Zagreb' ".($timezone=='Europe/Zagreb'?'selected':'').">Europe/Zagreb</option>
<option value='Europe/Zaporozhye' ".($timezone=='Europe/Zaporozhye'?'selected':'').">Europe/Zaporozhye</option>
<option value='Europe/Zurich' ".($timezone=='Europe/Zurich'?'selected':'').">Europe/Zurich</option>
<option value='Indian/Antananarivo' ".($timezone=='Indian/Antananarivo'?'selected':'').">Indian/Antananarivo</option>
<option value='Indian/Chagos' ".($timezone=='Indian/Chagos'?'selected':'').">Indian/Chagos</option>
<option value='Indian/Christmas' ".($timezone=='Indian/Christmas'?'selected':'').">Indian/Christmas</option>
<option value='Indian/Cocos' ".($timezone=='Indian/Cocos'?'selected':'').">Indian/Cocos</option>
<option value='Indian/Comoro' ".($timezone=='Indian/Comoro'?'selected':'').">Indian/Comoro</option>
<option value='Indian/Kerguelen' ".($timezone=='Indian/Kerguelen'?'selected':'').">Indian/Kerguelen</option>
<option value='Indian/Mahe' ".($timezone=='Indian/Mahe'?'selected':'').">Indian/Mahe</option>
<option value='Indian/Maldives' ".($timezone=='Indian/Maldives'?'selected':'').">Indian/Maldives</option>
<option value='Indian/Mauritius' ".($timezone=='Indian/Mauritius'?'selected':'').">Indian/Mauritius</option>
<option value='Indian/Mayotte' ".($timezone=='Indian/Mayotte'?'selected':'').">Indian/Mayotte</option>
<option value='Indian/Reunion' ".($timezone=='Indian/Reunion'?'selected':'').">Indian/Reunion</option>
<option value='Pacific/Apia' ".($timezone=='Pacific/Apia'?'selected':'').">Pacific/Apia</option>
<option value='Pacific/Auckland' ".($timezone=='Pacific/Auckland'?'selected':'').">Pacific/Auckland</option>
<option value='Pacific/Chatham' ".($timezone=='Pacific/Chatham'?'selected':'').">Pacific/Chatham</option>
<option value='Pacific/Chuuk' ".($timezone=='Pacific/Chuuk'?'selected':'').">Pacific/Chuuk</option>
<option value='Pacific/Easter' ".($timezone=='Pacific/Easter'?'selected':'').">Pacific/Easter</option>
<option value='Pacific/Efate' ".($timezone=='Pacific/Efate'?'selected':'').">Pacific/Efate</option>
<option value='Pacific/Enderbury' ".($timezone=='Pacific/Enderbury'?'selected':'').">Pacific/Enderbury</option>
<option value='Pacific/Fakaofo' ".($timezone=='Pacific/Fakaofo'?'selected':'').">Pacific/Fakaofo</option>
<option value='Pacific/Fiji' ".($timezone=='Pacific/Fiji'?'selected':'').">Pacific/Fiji</option>
<option value='Pacific/Funafuti' ".($timezone=='Pacific/Funafuti'?'selected':'').">Pacific/Funafuti</option>
<option value='Pacific/Galapagos' ".($timezone=='Pacific/Galapagos'?'selected':'').">Pacific/Galapagos</option>
<option value='Pacific/Gambier' ".($timezone=='Pacific/Gambier'?'selected':'').">Pacific/Gambier</option>
<option value='Pacific/Guadalcanal' ".($timezone=='Pacific/Guadalcanal'?'selected':'').">Pacific/Guadalcanal</option>
<option value='Pacific/Guam' ".($timezone=='Pacific/Guam'?'selected':'').">Pacific/Guam</option>
<option value='Pacific/Honolulu' ".($timezone=='Pacific/Honolulu'?'selected':'').">Pacific/Honolulu</option>
<option value='Pacific/Johnston' ".($timezone=='Pacific/Johnston'?'selected':'').">Pacific/Johnston</option>
<option value='Pacific/Kiritimati' ".($timezone=='Pacific/Kiritimati'?'selected':'').">Pacific/Kiritimati</option>
<option value='Pacific/Kosrae' ".($timezone=='Pacific/Kosrae'?'selected':'').">Pacific/Kosrae</option>
<option value='Pacific/Kwajalein' ".($timezone=='Pacific/Kwajalein'?'selected':'').">Pacific/Kwajalein</option>
<option value='Pacific/Majuro' ".($timezone=='Pacific/Majuro'?'selected':'').">Pacific/Majuro</option>
<option value='Pacific/Marquesas' ".($timezone=='Pacific/Marquesas'?'selected':'').">Pacific/Marquesas</option>
<option value='Pacific/Midway' ".($timezone=='Pacific/Midway'?'selected':'').">Pacific/Midway</option>
<option value='Pacific/Nauru' ".($timezone=='Pacific/Nauru'?'selected':'').">Pacific/Nauru</option>
<option value='Pacific/Niue' ".($timezone=='Pacific/Niue'?'selected':'').">Pacific/Niue</option>
<option value='Pacific/Norfolk' ".($timezone=='Pacific/Norfolk'?'selected':'').">Pacific/Norfolk</option>
<option value='Pacific/Noumea' ".($timezone=='Pacific/Noumea'?'selected':'').">Pacific/Noumea</option>
<option value='Pacific/Pago_Pago' ".($timezone=='Pacific/Pago_Pago'?'selected':'').">Pacific/Pago_Pago</option>
<option value='Pacific/Palau' ".($timezone=='Pacific/Palau'?'selected':'').">Pacific/Palau</option>
<option value='Pacific/Pitcairn' ".($timezone=='Pacific/Pitcairn'?'selected':'').">Pacific/Pitcairn</option>
<option value='Pacific/Pohnpei' ".($timezone=='Pacific/Pohnpei'?'selected':'').">Pacific/Pohnpei</option>
<option value='Pacific/Ponape' ".($timezone=='Pacific/Ponape'?'selected':'').">Pacific/Ponape</option>
<option value='Pacific/Port_Moresby' ".($timezone=='Pacific/Port_Moresby'?'selected':'').">Pacific/Port_Moresby</option>
<option value='Pacific/Rarotonga' ".($timezone=='Pacific/Rarotonga'?'selected':'').">Pacific/Rarotonga</option>
<option value='Pacific/Saipan' ".($timezone=='Pacific/Saipan'?'selected':'').">Pacific/Saipan</option>
<option value='Pacific/Samoa' ".($timezone=='Pacific/Samoa'?'selected':'').">Pacific/Samoa</option>
<option value='Pacific/Tahiti' ".($timezone=='Pacific/Tahiti'?'selected':'').">Pacific/Tahiti</option>
<option value='Pacific/Tarawa' ".($timezone=='Pacific/Tarawa'?'selected':'').">Pacific/Tarawa</option>
<option value='Pacific/Tongatapu' ".($timezone=='Pacific/Tongatapu'?'selected':'').">Pacific/Tongatapu</option>
<option value='Pacific/Truk' ".($timezone=='Pacific/Truk'?'selected':'').">Pacific/Truk</option>
<option value='Pacific/Wake' ".($timezone=='Pacific/Wake'?'selected':'').">Pacific/Wake</option>
<option value='Pacific/Wallis' ".($timezone=='Pacific/Wallis'?'selected':'').">Pacific/Wallis</option>
<option value='Pacific/Yap' ".($timezone=='Pacific/Yap'?'selected':'').">Pacific/Yap</option>";
$LISTE_PAYS_SIMPLE = "<option value='Africa/Abidjan'>Africa/Abidjan</option>
<option value='Africa/Accra'>Africa/Accra</option>
<option value='Africa/Addis_Ababa'>Africa/Addis_Ababa</option>
<option value='Africa/Algiers'>Africa/Algiers</option>
<option value='Africa/Asmara'>Africa/Asmara</option>
<option value='Africa/Asmera'>Africa/Asmera</option>
<option value='Africa/Bamako'>Africa/Bamako</option>
<option value='Africa/Bangui'>Africa/Bangui</option>
<option value='Africa/Banjul'>Africa/Banjul</option>
<option value='Africa/Bissau'>Africa/Bissau</option>
<option value='Africa/Blantyre'>Africa/Blantyre</option>
<option value='Africa/Brazzaville'>Africa/Brazzaville</option>
<option value='Africa/Bujumbura'>Africa/Bujumbura</option>
<option value='Africa/Cairo'>Africa/Cairo</option>
<option value='Africa/Casablanca'>Africa/Casablanca</option>
<option value='Africa/Ceuta'>Africa/Ceuta</option>
<option value='Africa/Conakry'>Africa/Conakry</option>
<option value='Africa/Dakar'>Africa/Dakar</option>
<option value='Africa/Dar_es_Salaam'>Africa/Dar_es_Salaam</option>
<option value='Africa/Djibouti'>Africa/Djibouti</option>
<option value='Africa/Douala'>Africa/Douala</option>
<option value='Africa/El_Aaiun'>Africa/El_Aaiun</option>
<option value='Africa/Freetown'>Africa/Freetown</option>
<option value='Africa/Gaborone'>Africa/Gaborone</option>
<option value='Africa/Harare'>Africa/Harare</option>
<option value='Africa/Johannesburg'>Africa/Johannesburg</option>
<option value='Africa/Juba'>Africa/Juba</option>
<option value='Africa/Kampala'>Africa/Kampala</option>
<option value='Africa/Khartoum'>Africa/Khartoum</option>
<option value='Africa/Kigali'>Africa/Kigali</option>
<option value='Africa/Kinshasa'>Africa/Kinshasa</option>
<option value='Africa/Lagos'>Africa/Lagos</option>
<option value='Africa/Libreville'>Africa/Libreville</option>
<option value='Africa/Lome'>Africa/Lome</option>
<option value='Africa/Luanda'>Africa/Luanda</option>
<option value='Africa/Lubumbashi'>Africa/Lubumbashi</option>
<option value='Africa/Lusaka'>Africa/Lusaka</option>
<option value='Africa/Malabo'>Africa/Malabo</option>
<option value='Africa/Maputo'>Africa/Maputo</option>
<option value='Africa/Maseru'>Africa/Maseru</option>
<option value='Africa/Mbabane'>Africa/Mbabane</option>
<option value='Africa/Mogadishu'>Africa/Mogadishu</option>
<option value='Africa/Monrovia'>Africa/Monrovia</option>
<option value='Africa/Nairobi'>Africa/Nairobi</option>
<option value='Africa/Ndjamena'>Africa/Ndjamena</option>
<option value='Africa/Niamey'>Africa/Niamey</option>
<option value='Africa/Nouakchott'>Africa/Nouakchott</option>
<option value='Africa/Ouagadougou'>Africa/Ouagadougou</option>
<option value='Africa/Porto-Novo'>Africa/Porto-Novo</option>
<option value='Africa/Sao_Tome'>Africa/Sao_Tome</option>
<option value='Africa/Timbuktu'>Africa/Timbuktu</option>
<option value='Africa/Tripoli'>Africa/Tripoli</option>
<option value='Africa/Tunis'>Africa/Tunis</option>
<option value='Africa/Windhoek'>Africa/Windhoek</option>
<option value='America/Adak'>America/Adak</option>
<option value='America/Anchorage'>America/Anchorage</option>
<option value='America/Anguilla'>America/Anguilla</option>
<option value='America/Antigua'>America/Antigua</option>
<option value='America/Araguaina'>America/Araguaina</option>
<option value='America/Argentina/Buenos_Aires'>America/Argentina/Buenos_Aires</option>
<option value='America/Argentina/Catamarca'>America/Argentina/Catamarca</option>
<option value='America/Argentina/ComodRivadavia'>America/Argentina/ComodRivadavia</option>
<option value='America/Argentina/Cordoba'>America/Argentina/Cordoba</option>
<option value='America/Argentina/Jujuy'>America/Argentina/Jujuy</option>
<option value='America/Argentina/La_Rioja'>America/Argentina/La_Rioja</option>
<option value='America/Argentina/Mendoza'>America/Argentina/Mendoza</option>
<option value='America/Argentina/Rio_Gallegos'>America/Argentina/Rio_Gallegos</option>
<option value='America/Argentina/Salta'>America/Argentina/Salta</option>
<option value='America/Argentina/San_Juan'>America/Argentina/San_Juan</option>
<option value='America/Argentina/San_Luis'>America/Argentina/San_Luis</option>
<option value='America/Argentina/Tucuman'>America/Argentina/Tucuman</option>
<option value='America/Argentina/Ushuaia'>America/Argentina/Ushuaia</option>
<option value='America/Aruba'>America/Aruba</option>
<option value='America/Asuncion'>America/Asuncion</option>
<option value='America/Atikokan'>America/Atikokan</option>
<option value='America/Atka'>America/Atka</option>
<option value='America/Bahia'>America/Bahia</option>
<option value='America/Bahia_Banderas'>America/Bahia_Banderas</option>
<option value='America/Barbados'>America/Barbados</option>
<option value='America/Belem'>America/Belem</option>
<option value='America/Belize'>America/Belize</option>
<option value='America/Blanc-Sablon'>America/Blanc-Sablon</option>
<option value='America/Boa_Vista'>America/Boa_Vista</option>
<option value='America/Bogota'>America/Bogota</option>
<option value='America/Boise'>America/Boise</option>
<option value='America/Buenos_Aires'>America/Buenos_Aires</option>
<option value='America/Cambridge_Bay'>America/Cambridge_Bay</option>
<option value='America/Campo_Grande'>America/Campo_Grande</option>
<option value='America/Cancun'>America/Cancun</option>
<option value='America/Caracas'>America/Caracas</option>
<option value='America/Catamarca'>America/Catamarca</option>
<option value='America/Cayenne'>America/Cayenne</option>
<option value='America/Cayman'>America/Cayman</option>
<option value='America/Chicago'>America/Chicago</option>
<option value='America/Chihuahua'>America/Chihuahua</option>
<option value='America/Coral_Harbour'>America/Coral_Harbour</option>
<option value='America/Cordoba'>America/Cordoba</option>
<option value='America/Costa_Rica'>America/Costa_Rica</option>
<option value='America/Creston'>America/Creston</option>
<option value='America/Cuiaba'>America/Cuiaba</option>
<option value='America/Curacao'>America/Curacao</option>
<option value='America/Danmarkshavn'>America/Danmarkshavn</option>
<option value='America/Dawson'>America/Dawson</option>
<option value='America/Dawson_Creek'>America/Dawson_Creek</option>
<option value='America/Denver'>America/Denver</option>
<option value='America/Detroit'>America/Detroit</option>
<option value='America/Dominica'>America/Dominica</option>
<option value='America/Edmonton'>America/Edmonton</option>
<option value='America/Eirunepe'>America/Eirunepe</option>
<option value='America/El_Salvador'>America/El_Salvador</option>
<option value='America/Ensenada'>America/Ensenada</option>
<option value='America/Fort_Wayne'>America/Fort_Wayne</option>
<option value='America/Fortaleza'>America/Fortaleza</option>
<option value='America/Glace_Bay'>America/Glace_Bay</option>
<option value='America/Godthab'>America/Godthab</option>
<option value='America/Goose_Bay'>America/Goose_Bay</option>
<option value='America/Grand_Turk'>America/Grand_Turk</option>
<option value='America/Grenada'>America/Grenada</option>
<option value='America/Guadeloupe'>America/Guadeloupe</option>
<option value='America/Guatemala'>America/Guatemala</option>
<option value='America/Guayaquil'>America/Guayaquil</option>
<option value='America/Guyana'>America/Guyana</option>
<option value='America/Halifax'>America/Halifax</option>
<option value='America/Havana'>America/Havana</option>
<option value='America/Hermosillo'>America/Hermosillo</option>
<option value='America/Indiana/Indianapolis'>America/Indiana/Indianapolis</option>
<option value='America/Indiana/Knox'>America/Indiana/Knox</option>
<option value='America/Indiana/Marengo'>America/Indiana/Marengo</option>
<option value='America/Indiana/Petersburg'>America/Indiana/Petersburg</option>
<option value='America/Indiana/Tell_City'>America/Indiana/Tell_City</option>
<option value='America/Indiana/Vevay'>America/Indiana/Vevay</option>
<option value='America/Indiana/Vincennes'>America/Indiana/Vincennes</option>
<option value='America/Indiana/Winamac'>America/Indiana/Winamac</option>
<option value='America/Indianapolis'>America/Indianapolis</option>
<option value='America/Inuvik'>America/Inuvik</option>
<option value='America/Iqaluit'>America/Iqaluit</option>
<option value='America/Jamaica'>America/Jamaica</option>
<option value='America/Jujuy'>America/Jujuy</option>
<option value='America/Juneau'>America/Juneau</option>
<option value='America/Kentucky/Louisville'>America/Kentucky/Louisville</option>
<option value='America/Kentucky/Monticello'>America/Kentucky/Monticello</option>
<option value='America/Knox_IN'>America/Knox_IN</option>
<option value='America/Kralendijk'>America/Kralendijk</option>
<option value='America/La_Paz'>America/La_Paz</option>
<option value='America/Lima'>America/Lima</option>
<option value='America/Los_Angeles'>America/Los_Angeles</option>
<option value='America/Louisville'>America/Louisville</option>
<option value='America/Lower_Princes'>America/Lower_Princes</option>
<option value='America/Maceio'>America/Maceio</option>
<option value='America/Managua'>America/Managua</option>
<option value='America/Manaus'>America/Manaus</option>
<option value='America/Marigot'>America/Marigot</option>
<option value='America/Martinique'>America/Martinique</option>
<option value='America/Matamoros'>America/Matamoros</option>
<option value='America/Mazatlan'>America/Mazatlan</option>
<option value='America/Mendoza'>America/Mendoza</option>
<option value='America/Menominee'>America/Menominee</option>
<option value='America/Merida'>America/Merida</option>
<option value='America/Metlakatla'>America/Metlakatla</option>
<option value='America/Mexico_City'>America/Mexico_City</option>
<option value='America/Miquelon'>America/Miquelon</option>
<option value='America/Moncton'>America/Moncton</option>
<option value='America/Monterrey'>America/Monterrey</option>
<option value='America/Montevideo'>America/Montevideo</option>
<option value='America/Montreal'>America/Montreal</option>
<option value='America/Montserrat'>America/Montserrat</option>
<option value='America/Nassau'>America/Nassau</option>
<option value='America/New_York'>America/New_York</option>
<option value='America/Nipigon'>America/Nipigon</option>
<option value='America/Nome'>America/Nome</option>
<option value='America/Noronha'>America/Noronha</option>
<option value='America/North_Dakota/Beulah'>America/North_Dakota/Beulah</option>
<option value='America/North_Dakota/Center'>America/North_Dakota/Center</option>
<option value='America/North_Dakota/New_Salem'>America/North_Dakota/New_Salem</option>
<option value='America/Ojinaga'>America/Ojinaga</option>
<option value='America/Panama'>America/Panama</option>
<option value='America/Pangnirtung'>America/Pangnirtung</option>
<option value='America/Paramaribo'>America/Paramaribo</option>
<option value='America/Phoenix'>America/Phoenix</option>
<option value='America/Port-au-Prince'>America/Port-au-Prince</option>
<option value='America/Port_of_Spain'>America/Port_of_Spain</option>
<option value='America/Porto_Acre'>America/Porto_Acre</option>
<option value='America/Porto_Velho'>America/Porto_Velho</option>
<option value='America/Puerto_Rico'>America/Puerto_Rico</option>
<option value='America/Rainy_River'>America/Rainy_River</option>
<option value='America/Rankin_Inlet'>America/Rankin_Inlet</option>
<option value='America/Recife'>America/Recife</option>
<option value='America/Regina'>America/Regina</option>
<option value='America/Resolute'>America/Resolute</option>
<option value='America/Rio_Branco'>America/Rio_Branco</option>
<option value='America/Rosario'>America/Rosario</option>
<option value='America/Santa_Isabel'>America/Santa_Isabel</option>
<option value='America/Santarem'>America/Santarem</option>
<option value='America/Santiago'>America/Santiago</option>
<option value='America/Santo_Domingo'>America/Santo_Domingo</option>
<option value='America/Sao_Paulo'>America/Sao_Paulo</option>
<option value='America/Scoresbysund'>America/Scoresbysund</option>
<option value='America/Shiprock'>America/Shiprock</option>
<option value='America/Sitka'>America/Sitka</option>
<option value='America/St_Barthelemy'>America/St_Barthelemy</option>
<option value='America/St_Johns'>America/St_Johns</option>
<option value='America/St_Kitts'>America/St_Kitts</option>
<option value='America/St_Lucia'>America/St_Lucia</option>
<option value='America/St_Thomas'>America/St_Thomas</option>
<option value='America/St_Vincent'>America/St_Vincent</option>
<option value='America/Swift_Current'>America/Swift_Current</option>
<option value='America/Tegucigalpa'>America/Tegucigalpa</option>
<option value='America/Thule'>America/Thule</option>
<option value='America/Thunder_Bay'>America/Thunder_Bay</option>
<option value='America/Tijuana'>America/Tijuana</option>
<option value='America/Toronto'>America/Toronto</option>
<option value='America/Tortola'>America/Tortola</option>
<option value='America/Vancouver'>America/Vancouver</option>
<option value='America/Virgin'>America/Virgin</option>
<option value='America/Whitehorse'>America/Whitehorse</option>
<option value='America/Winnipeg'>America/Winnipeg</option>
<option value='America/Yakutat'>America/Yakutat</option>
<option value='America/Yellowknife'>America/Yellowknife</option>
<option value='Antarctica/Casey'>Antarctica/Casey</option>
<option value='Antarctica/Davis'>Antarctica/Davis</option>
<option value='Antarctica/DumontDUrville'>Antarctica/DumontDUrville</option>
<option value='Antarctica/Macquarie'>Antarctica/Macquarie</option>
<option value='Antarctica/Mawson'>Antarctica/Mawson</option>
<option value='Antarctica/McMurdo'>Antarctica/McMurdo</option>
<option value='Antarctica/Palmer'>Antarctica/Palmer</option>
<option value='Antarctica/Rothera'>Antarctica/Rothera</option>
<option value='Antarctica/South_Pole'>Antarctica/South_Pole</option>
<option value='Antarctica/Syowa'>Antarctica/Syowa</option>
<option value='Antarctica/Troll'>Antarctica/Troll</option>
<option value='Antarctica/Vostok'>Antarctica/Vostok</option>
<option value='Arctic/Longyearbyen'>Arctic/Longyearbyen</option>
<option value='Asia/Aden'>Asia/Aden</option>
<option value='Asia/Almaty'>Asia/Almaty</option>
<option value='Asia/Amman'>Asia/Amman</option>
<option value='Asia/Anadyr'>Asia/Anadyr</option>
<option value='Asia/Aqtau'>Asia/Aqtau</option>
<option value='Asia/Aqtobe'>Asia/Aqtobe</option>
<option value='Asia/Ashgabat'>Asia/Ashgabat</option>
<option value='Asia/Ashkhabad'>Asia/Ashkhabad</option>
<option value='Asia/Baghdad'>Asia/Baghdad</option>
<option value='Asia/Bahrain'>Asia/Bahrain</option>
<option value='Asia/Baku'>Asia/Baku</option>
<option value='Asia/Bangkok'>Asia/Bangkok</option>
<option value='Asia/Beirut'>Asia/Beirut</option>
<option value='Asia/Bishkek'>Asia/Bishkek</option>
<option value='Asia/Brunei'>Asia/Brunei</option>
<option value='Asia/Calcutta'>Asia/Calcutta</option>
<option value='Asia/Choibalsan'>Asia/Choibalsan</option>
<option value='Asia/Chongqing'>Asia/Chongqing</option>
<option value='Asia/Chungking'>Asia/Chungking</option>
<option value='Asia/Colombo'>Asia/Colombo</option>
<option value='Asia/Dacca'>Asia/Dacca</option>
<option value='Asia/Damascus'>Asia/Damascus</option>
<option value='Asia/Dhaka'>Asia/Dhaka</option>
<option value='Asia/Dili'>Asia/Dili</option>
<option value='Asia/Dubai'>Asia/Dubai</option>
<option value='Asia/Dushanbe'>Asia/Dushanbe</option>
<option value='Asia/Gaza'>Asia/Gaza</option>
<option value='Asia/Harbin'>Asia/Harbin</option>
<option value='Asia/Hebron'>Asia/Hebron</option>
<option value='Asia/Ho_Chi_Minh'>Asia/Ho_Chi_Minh</option>
<option value='Asia/Hong_Kong'>Asia/Hong_Kong</option>
<option value='Asia/Hovd'>Asia/Hovd</option>
<option value='Asia/Irkutsk'>Asia/Irkutsk</option>
<option value='Asia/Istanbul'>Asia/Istanbul</option>
<option value='Asia/Jakarta'>Asia/Jakarta</option>
<option value='Asia/Jayapura'>Asia/Jayapura</option>
<option value='Asia/Jerusalem'>Asia/Jerusalem</option>
<option value='Asia/Kabul'>Asia/Kabul</option>
<option value='Asia/Kamchatka'>Asia/Kamchatka</option>
<option value='Asia/Karachi'>Asia/Karachi</option>
<option value='Asia/Kashgar'>Asia/Kashgar</option>
<option value='Asia/Kathmandu'>Asia/Kathmandu</option>
<option value='Asia/Katmandu'>Asia/Katmandu</option>
<option value='Asia/Khandyga'>Asia/Khandyga</option>
<option value='Asia/Kolkata'>Asia/Kolkata</option>
<option value='Asia/Krasnoyarsk'>Asia/Krasnoyarsk</option>
<option value='Asia/Kuala_Lumpur'>Asia/Kuala_Lumpur</option>
<option value='Asia/Kuching'>Asia/Kuching</option>
<option value='Asia/Kuwait'>Asia/Kuwait</option>
<option value='Asia/Macao'>Asia/Macao</option>
<option value='Asia/Macau'>Asia/Macau</option>
<option value='Asia/Magadan'>Asia/Magadan</option>
<option value='Asia/Makassar'>Asia/Makassar</option>
<option value='Asia/Manila'>Asia/Manila</option>
<option value='Asia/Muscat'>Asia/Muscat</option>
<option value='Asia/Nicosia'>Asia/Nicosia</option>
<option value='Asia/Novokuznetsk'>Asia/Novokuznetsk</option>
<option value='Asia/Novosibirsk'>Asia/Novosibirsk</option>
<option value='Asia/Omsk'>Asia/Omsk</option>
<option value='Asia/Oral'>Asia/Oral</option>
<option value='Asia/Phnom_Penh'>Asia/Phnom_Penh</option>
<option value='Asia/Pontianak'>Asia/Pontianak</option>
<option value='Asia/Pyongyang'>Asia/Pyongyang</option>
<option value='Asia/Qatar'>Asia/Qatar</option>
<option value='Asia/Qyzylorda'>Asia/Qyzylorda</option>
<option value='Asia/Rangoon'>Asia/Rangoon</option>
<option value='Asia/Riyadh'>Asia/Riyadh</option>
<option value='Asia/Saigon'>Asia/Saigon</option>
<option value='Asia/Sakhalin'>Asia/Sakhalin</option>
<option value='Asia/Samarkand'>Asia/Samarkand</option>
<option value='Asia/Seoul'>Asia/Seoul</option>
<option value='Asia/Shanghai'>Asia/Shanghai</option>
<option value='Asia/Singapore'>Asia/Singapore</option>
<option value='Asia/Taipei'>Asia/Taipei</option>
<option value='Asia/Tashkent'>Asia/Tashkent</option>
<option value='Asia/Tbilisi'>Asia/Tbilisi</option>
<option value='Asia/Tehran'>Asia/Tehran</option>
<option value='Asia/Tel_Aviv'>Asia/Tel_Aviv</option>
<option value='Asia/Thimbu'>Asia/Thimbu</option>
<option value='Asia/Thimphu'>Asia/Thimphu</option>
<option value='Asia/Tokyo'>Asia/Tokyo</option>
<option value='Asia/Ujung_Pandang'>Asia/Ujung_Pandang</option>
<option value='Asia/Ulaanbaatar'>Asia/Ulaanbaatar</option>
<option value='Asia/Ulan_Bator'>Asia/Ulan_Bator</option>
<option value='Asia/Urumqi'>Asia/Urumqi</option>
<option value='Asia/Ust-Nera'>Asia/Ust-Nera</option>
<option value='Asia/Vientiane'>Asia/Vientiane</option>
<option value='Asia/Vladivostok'>Asia/Vladivostok</option>
<option value='Asia/Yakutsk'>Asia/Yakutsk</option>
<option value='Asia/Yekaterinburg'>Asia/Yekaterinburg</option>
<option value='Asia/Yerevan'>Asia/Yerevan</option>
<option value='Atlantic/Azores'>Atlantic/Azores</option>
<option value='Atlantic/Bermuda'>Atlantic/Bermuda</option>
<option value='Atlantic/Canary'>Atlantic/Canary</option>
<option value='Atlantic/Cape_Verde'>Atlantic/Cape_Verde</option>
<option value='Atlantic/Faeroe'>Atlantic/Faeroe</option>
<option value='Atlantic/Faroe'>Atlantic/Faroe</option>
<option value='Atlantic/Jan_Mayen'>Atlantic/Jan_Mayen</option>
<option value='Atlantic/Madeira'>Atlantic/Madeira</option>
<option value='Atlantic/Reykjavik'>Atlantic/Reykjavik</option>
<option value='Atlantic/South_Georgia'>Atlantic/South_Georgia</option>
<option value='Atlantic/St_Helena'>Atlantic/St_Helena</option>
<option value='Atlantic/Stanley'>Atlantic/Stanley</option>
<option value='Australia/ACT'>Australia/ACT</option>
<option value='Australia/Adelaide'>Australia/Adelaide</option>
<option value='Australia/Brisbane'>Australia/Brisbane</option>
<option value='Australia/Broken_Hill'>Australia/Broken_Hill</option>
<option value='Australia/Canberra'>Australia/Canberra</option>
<option value='Australia/Currie'>Australia/Currie</option>
<option value='Australia/Darwin'>Australia/Darwin</option>
<option value='Australia/Eucla'>Australia/Eucla</option>
<option value='Australia/Hobart'>Australia/Hobart</option>
<option value='Australia/LHI'>Australia/LHI</option>
<option value='Australia/Lindeman'>Australia/Lindeman</option>
<option value='Australia/Lord_Howe'>Australia/Lord_Howe</option>
<option value='Australia/Melbourne'>Australia/Melbourne</option>
<option value='Australia/North'>Australia/North</option>
<option value='Australia/NSW'>Australia/NSW</option>
<option value='Australia/Perth'>Australia/Perth</option>
<option value='Australia/Queensland'>Australia/Queensland</option>
<option value='Australia/South'>Australia/South</option>
<option value='Australia/Sydney'>Australia/Sydney</option>
<option value='Australia/Tasmania'>Australia/Tasmania</option>
<option value='Australia/Victoria'>Australia/Victoria</option>
<option value='Australia/West'>Australia/West</option>
<option value='Australia/Yancowinna'>Australia/Yancowinna</option>
<option value='Europe/Amsterdam'>Europe/Amsterdam</option>
<option value='Europe/Andorra'>Europe/Andorra</option>
<option value='Europe/Athens'>Europe/Athens</option>
<option value='Europe/Belfast'>Europe/Belfast</option>
<option value='Europe/Belgrade'>Europe/Belgrade</option>
<option value='Europe/Berlin'>Europe/Berlin</option>
<option value='Europe/Bratislava'>Europe/Bratislava</option>
<option value='Europe/Brussels'>Europe/Brussels</option>
<option value='Europe/Bucharest'>Europe/Bucharest</option>
<option value='Europe/Budapest'>Europe/Budapest</option>
<option value='Europe/Busingen'>Europe/Busingen</option>
<option value='Europe/Chisinau'>Europe/Chisinau</option>
<option value='Europe/Copenhagen'>Europe/Copenhagen</option>
<option value='Europe/Dublin'>Europe/Dublin</option>
<option value='Europe/Gibraltar'>Europe/Gibraltar</option>
<option value='Europe/Guernsey'>Europe/Guernsey</option>
<option value='Europe/Helsinki'>Europe/Helsinki</option>
<option value='Europe/Isle_of_Man'>Europe/Isle_of_Man</option>
<option value='Europe/Istanbul'>Europe/Istanbul</option>
<option value='Europe/Jersey'>Europe/Jersey</option>
<option value='Europe/Kaliningrad'>Europe/Kaliningrad</option>
<option value='Europe/Kiev'>Europe/Kiev</option>
<option value='Europe/Lisbon'>Europe/Lisbon</option>
<option value='Europe/Ljubljana'>Europe/Ljubljana</option>
<option value='Europe/London'>Europe/London</option>
<option value='Europe/Luxembourg'>Europe/Luxembourg</option>
<option value='Europe/Madrid'>Europe/Madrid</option>
<option value='Europe/Malta'>Europe/Malta</option>
<option value='Europe/Mariehamn'>Europe/Mariehamn</option>
<option value='Europe/Minsk'>Europe/Minsk</option>
<option value='Europe/Monaco'>Europe/Monaco</option>
<option value='Europe/Moscow'>Europe/Moscow</option>
<option value='Europe/Nicosia'>Europe/Nicosia</option>
<option value='Europe/Oslo'>Europe/Oslo</option>
<option value='Europe/Paris' selected>Europe/Paris</option>
<option value='Europe/Podgorica'>Europe/Podgorica</option>
<option value='Europe/Prague'>Europe/Prague</option>
<option value='Europe/Riga'>Europe/Riga</option>
<option value='Europe/Rome'>Europe/Rome</option>
<option value='Europe/Samara'>Europe/Samara</option>
<option value='Europe/San_Marino'>Europe/San_Marino</option>
<option value='Europe/Sarajevo'>Europe/Sarajevo</option>
<option value='Europe/Simferopol'>Europe/Simferopol</option>
<option value='Europe/Skopje'>Europe/Skopje</option>
<option value='Europe/Sofia'>Europe/Sofia</option>
<option value='Europe/Stockholm'>Europe/Stockholm</option>
<option value='Europe/Tallinn'>Europe/Tallinn</option>
<option value='Europe/Tirane'>Europe/Tirane</option>
<option value='Europe/Tiraspol'>Europe/Tiraspol</option>
<option value='Europe/Uzhgorod'>Europe/Uzhgorod</option>
<option value='Europe/Vaduz'>Europe/Vaduz</option>
<option value='Europe/Vatican'>Europe/Vatican</option>
<option value='Europe/Vienna'>Europe/Vienna</option>
<option value='Europe/Vilnius'>Europe/Vilnius</option>
<option value='Europe/Volgograd'>Europe/Volgograd</option>
<option value='Europe/Warsaw'>Europe/Warsaw</option>
<option value='Europe/Zagreb'>Europe/Zagreb</option>
<option value='Europe/Zaporozhye'>Europe/Zaporozhye</option>
<option value='Europe/Zurich'>Europe/Zurich</option>
<option value='Indian/Antananarivo'>Indian/Antananarivo</option>
<option value='Indian/Chagos'>Indian/Chagos</option>
<option value='Indian/Christmas'>Indian/Christmas</option>
<option value='Indian/Cocos'>Indian/Cocos</option>
<option value='Indian/Comoro'>Indian/Comoro</option>
<option value='Indian/Kerguelen'>Indian/Kerguelen</option>
<option value='Indian/Mahe'>Indian/Mahe</option>
<option value='Indian/Maldives'>Indian/Maldives</option>
<option value='Indian/Mauritius'>Indian/Mauritius</option>
<option value='Indian/Mayotte'>Indian/Mayotte</option>
<option value='Indian/Reunion'>Indian/Reunion</option>
<option value='Pacific/Apia'>Pacific/Apia</option>
<option value='Pacific/Auckland'>Pacific/Auckland</option>
<option value='Pacific/Chatham'>Pacific/Chatham</option>
<option value='Pacific/Chuuk'>Pacific/Chuuk</option>
<option value='Pacific/Easter'>Pacific/Easter</option>
<option value='Pacific/Efate'>Pacific/Efate</option>
<option value='Pacific/Enderbury'>Pacific/Enderbury</option>
<option value='Pacific/Fakaofo'>Pacific/Fakaofo</option>
<option value='Pacific/Fiji'>Pacific/Fiji</option>
<option value='Pacific/Funafuti'>Pacific/Funafuti</option>
<option value='Pacific/Galapagos'>Pacific/Galapagos</option>
<option value='Pacific/Gambier'>Pacific/Gambier</option>
<option value='Pacific/Guadalcanal'>Pacific/Guadalcanal</option>
<option value='Pacific/Guam'>Pacific/Guam</option>
<option value='Pacific/Honolulu'>Pacific/Honolulu</option>
<option value='Pacific/Johnston'>Pacific/Johnston</option>
<option value='Pacific/Kiritimati'>Pacific/Kiritimati</option>
<option value='Pacific/Kosrae'>Pacific/Kosrae</option>
<option value='Pacific/Kwajalein'>Pacific/Kwajalein</option>
<option value='Pacific/Majuro'>Pacific/Majuro</option>
<option value='Pacific/Marquesas'>Pacific/Marquesas</option>
<option value='Pacific/Midway'>Pacific/Midway</option>
<option value='Pacific/Nauru'>Pacific/Nauru</option>
<option value='Pacific/Niue'>Pacific/Niue</option>
<option value='Pacific/Norfolk'>Pacific/Norfolk</option>
<option value='Pacific/Noumea'>Pacific/Noumea</option>
<option value='Pacific/Pago_Pago'>Pacific/Pago_Pago</option>
<option value='Pacific/Palau'>Pacific/Palau</option>
<option value='Pacific/Pitcairn'>Pacific/Pitcairn</option>
<option value='Pacific/Pohnpei'>Pacific/Pohnpei</option>
<option value='Pacific/Ponape'>Pacific/Ponape</option>
<option value='Pacific/Port_Moresby'>Pacific/Port_Moresby</option>
<option value='Pacific/Rarotonga'>Pacific/Rarotonga</option>
<option value='Pacific/Saipan'>Pacific/Saipan</option>
<option value='Pacific/Samoa'>Pacific/Samoa</option>
<option value='Pacific/Tahiti'>Pacific/Tahiti</option>
<option value='Pacific/Tarawa'>Pacific/Tarawa</option>
<option value='Pacific/Tongatapu'>Pacific/Tongatapu</option>
<option value='Pacific/Truk'>Pacific/Truk</option>
<option value='Pacific/Wake'>Pacific/Wake</option>
<option value='Pacific/Wallis'>Pacific/Wallis</option>
<option value='Pacific/Yap'>Pacific/Yap</option>";
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/pmn_fonctions.php'
<?php
$PMNL_VERSION = "2.0.5";
if (!function_exists('iconv') && function_exists('libiconv')) {
function iconv($input_encoding, $output_encoding, $string) {
return libiconv($input_encoding, $output_encoding, $string);
}
}
if (!function_exists('iconv') && !function_exists('libiconv')) {
include_once("include/lib/ConvertCharset.class.php");
function iconv($input_encoding, $output_encoding, $string) {
$converter = new ConvertCharset();
return $converter->Convert($string, $input_encoding, $output_encoding);
}
}
function add_subscriber($cnx, $table_email, $list_id, $add_addr, $table_email_deleted) {
$add_addr = trim(strtolower($add_addr));
$hash = @current($cnx->query("SELECT hash
FROM ".$table_email."
WHERE list_id='".($cnx->CleanInput($list_id))."'
AND email='".($cnx->CleanInput($add_addr))."'")->fetch());
if($hash==''){
$black_listed = @current($cnx->query("SELECT email
FROM ".$table_email_deleted."
WHERE list_id='".($cnx->CleanInput($list_id))."'
AND email='".($cnx->CleanInput($add_addr))."'")->fetch());
if($black_listed==''){
$hash = unique_id($add_addr);
if($cnx->query("INSERT INTO ".$table_email." (`email`, `list_id`, `hash`)
VALUES ('".($cnx->CleanInput($add_addr))."', '".($cnx->CleanInput($list_id))."', '".($cnx->CleanInput($hash))."')")){
return 2;
} else {
return true;
}
} else {
return 3;
}
} else {
return -1;
}
}
function addSubscriber($cnx, $table_email, $table_temp, $list_id, $addr, $hash, $table_email_deleted) {
$addr = trim(strtolower(urldecode($addr)));
$email = @current($cnx->query("SELECT email FROM $table_temp WHERE list_id='$list_id' AND email='$addr' AND hash='$hash'")->fetch());
if ($email!='') {
$cnx->query("INSERT INTO $table_email (`email`, `list_id` , `hash`) VALUES ('$addr', '$list_id','$hash')");
$cnx->query("DELETE FROM $table_temp WHERE email='$addr' AND list_id='$list_id' AND hash='$hash'");
$cnx->query("DELETE FROM $table_email_deleted WHERE email='$addr' AND list_id='$list_id'");
return true;
} else {
return false;
}
}
function addSubscriberMod($cnx, $table_email, $ref_sub_table, $list_id, $addr) {
$addr = trim(strtolower($addr));
$this_mail = $cnx->query("SELECT email FROM $table_email WHERE list_id='$list_id' AND email='$addr'");
if ((!$this_mail)||count($this_mail)>0) {
return -1;
}
$this_mail = $cnx->query("SELECT email FROM $ref_sub_table WHERE list_id='$list_id' AND email='$addr'");
if ((!$this_mail)||count($this_mail)>0) {
return -1;
}
if (!$cnx->query("INSERT INTO $ref_sub_table (`email`, `list_id`) VALUES ('$addr', '$list_id')")) {
return -1;
}
return true;
}
function addSubscriberDirect($cnx, $table_email, $list_id, $addr) {
$addr = trim(strtolower($addr));
$x = $cnx->query("SELECT email FROM $table_email WHERE list_id='$list_id' AND email='$addr'")->fetchAll();
if (count($x)>0) {
return false;
} else {
$hash = unique_id($addr);
if ($cnx->query("INSERT INTO ".$table_email." (`email`, `list_id` , `hash`) VALUES ('$addr', '$list_id','$hash')")) {
$cnx->query("DELETE FROM ".$table_email."_deleted WHERE email='$addr' AND list_id='$list_id'");
return $hash;
} else
return false;
}
}
function addSubscriberTemp($cnx, $table_email, $table_temp, $list_id, $addr) {
$addr = trim(strtolower($addr));
$x = $cnx->query("SELECT email FROM $table_email WHERE list_id='$list_id' AND email='$addr'")->fetchAll();
if (count($x)>0) {
return false;
}
$x = $cnx->query("SELECT email FROM $table_temp WHERE list_id='$list_id' AND email='$addr'")->fetchAll();
if (count($x)>0) {
return false;
}
$hash = unique_id($addr);
if($_SESSION['timezone']!=''){
date_default_timezone_set($_SESSION['timezone']);
}elseif(file_exists('include/config.php')) {
date_default_timezone_set('Europe/Paris');
}
$date = date("Ymd");
if (!$cnx->query("INSERT INTO $table_temp (`email`, `list_id` , `hash` , `date`) VALUES ('$addr', '$list_id','$hash' , '$date')")) {
return false;
}
return $hash;
}
function append_cronjob($command){
if(is_string($command)&&!empty($command)){
exec("crontab -l | { cat; echo '$command'; } |crontab -",$output,$code_retour);
}
if( $code_retour !== 0 ) {
return false;
} else {
return true;
}
}
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
function checkAdminAccess($cnx, $conf_pass, $admin_pass, $admin_mail) {
if (!empty($_COOKIE['PMNLNG_admin_password']) && ($_COOKIE['PMNLNG_admin_password'] == $conf_pass)) {
return true;
} else {
if ($conf_pass == md5($admin_pass)) {
setcookie("PMNLNG_admin_password", md5($admin_pass));
return true;
} else {
return false;
}
}
}
function checkVersion(){
$VL=file_get_contents('VERSION');
if($VL===FALSE) {
echo '<span class="error">fichier version non détecté</span>';
} else {
$header=checkVersionCurl();
if(version_compare($header['content'],$VL,'>')) {
echo '<li class="icn_alert"><a href="http://www.phpmynewsletter.com/telechargement.html"
target="_blank">Version '.$header['content'].' disponible !</a></li>';
}
}
}
function checkVersionCurl() {
(function_exists('curl_init')) ? '' : die('cURL Must be installed for geturl function to work. Ask your host to enable it or uncomment extension=php_curl.dll in php.ini');
$h[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$h[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$h[] = "Cache-Control: max-age=0";
$h[] = "Connection: keep-alive";
$h[] = "Keep-Alive: 300";
$h[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$h[] = "Accept-Language: en-us,en;q=0.5";
$h[] = "Pragma: ";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.phpmynewsletter.com/versions/current_version');
curl_setopt($curl, CURLOPT_USERAGENT, 'Check Version PhpMyNewsLetter');
curl_setopt($curl, CURLOPT_HTTPHEADER, $h);
curl_setopt($curl, CURLOPT_REFERER, 'https://www.phpmynewsletter.com/versions/current_version');
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
$header['errno'] = curl_errno($curl);
$header['errmsg'] = curl_error($curl);
$header['content'] = curl_exec($curl);
curl_close($curl);
return $header;
}
function clean_old_tmp_files(){
foreach (glob(PREFIX_DIR.'/'.PREFIX."*") as $filename){
$age = time() - filemtime($filename);
if ($age > TIME_LIMIT) {
unlink($filename);
}
}
}
function createNewsletter($cnx,$table_listsconfig,$newsletter_name,$from,
$from_name,$subject,$header,$footer,
$subscription_subject,$subscription_body,
$welcome_subject,$welcome_body,$quit_subject,$quit_body,$preview_addr) {
$sql = "SELECT list_id FROM $table_listsconfig ORDER BY list_id DESC";
$newidTab = $cnx->SqlRow($sql);
$newid = $newidTab['list_id'] + 1;
$newsletter_name = escape_string($cnx,$newsletter_name);
$from = escape_string($cnx,$from);
$from_name = escape_string($cnx,$from_name);
$subject = escape_string($cnx,$subject);
$header = escape_string($cnx,$header);
$footer = escape_string($cnx,$footer);
$subscription_subject = escape_string($cnx,$subscription_subject);
$subscription_body = escape_string($cnx,$subscription_body);
$welcome_subject = escape_string($cnx,$welcome_subject);
$welcome_body = escape_string($cnx,$welcome_body);
$quit_subject = escape_string($cnx,$quit_subject);
$quit_body = escape_string($cnx,$quit_body);
$preview_addr = escape_string($cnx,$preview_addr);
if (!$cnx->query("INSERT INTO $table_listsconfig (`list_id` , `newsletter_name` , `from_addr` ,
`from_name` , `subject` , `header` , `footer` ,
`subscription_subject` , `subscription_body`, `welcome_subject` ,
`welcome_body` , `quit_subject` ,`quit_body`,`preview_addr`)
VALUES ($newid,$newsletter_name, $from,
$from_name, $subject, $header, $footer,
$subscription_subject, $subscription_body,$welcome_subject,
$welcome_body, $quit_subject, $quit_body, $preview_addr)")) {
return false;
} else {
return $cnx->lastInsertId();
}
}
function CronID() {
$len = 5;
$base='ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz';
$max=strlen($base)-1;
$activatecode='';
mt_srand((double)microtime()*1000000);
while (strlen($activatecode)<$len+1){
$activatecode.=$base{mt_rand(0,$max)};
}
return 'pmnl2_'.$activatecode;
}
function delete_subscriber($cnx, $table_email, $list_id, $del_addr, $table_email_deleted, $motif) {
$CPTID = $cnx->query("SELECT count(id) AS CPTID
FROM $table_email
WHERE list_id = ".$list_id."
AND email = ".escape_string($cnx,$del_addr))->fetch();
if ( $CPTID['CPTID'] > 0 ) {
if (!$cnx->query("INSERT IGNORE INTO $table_email_deleted
SELECT *
FROM $table_email
WHERE email=".escape_string($cnx,$del_addr)."
AND list_id=".$list_id)){
return false;
} else {
$cnx->query("UPDATE $table_email_deleted
SET error='Y', type='".($motif!=''?$motif:'unsub')."'
WHERE email=".escape_string($cnx,$del_addr)."
AND list_id=".$list_id);
if (!$cnx->query("DELETE FROM $table_email
WHERE list_id = ".$list_id."
AND email=".escape_string($cnx,$del_addr))) {
return false;
} else {
return true;
}
}
} else {
return 5;
}
}
function delete_subscriber_tmp($cnx, $table_email, $list_id, $del_addr, $table_email_deleted, $motif) {
$CPTID = $cnx->query("SELECT count(*) AS CPTID
FROM $table_email
WHERE list_id = ".$list_id."
AND email = ".escape_string($cnx,$del_addr))->fetch();
if ( $CPTID['CPTID'] > 0 ) {
if (!$cnx->query("INSERT IGNORE INTO $table_email_deleted (email, list_id, hash)
SELECT email, list_id, hash
FROM $table_email
WHERE email=".escape_string($cnx,$del_addr)."
AND list_id=".$list_id)){
return false;
} else {
$cnx->query("UPDATE $table_email_deleted
SET error='Y', type='".($motif!=''?$motif:'unsub')."'
WHERE email=".escape_string($cnx,$del_addr)."
AND list_id=".$list_id);
if (!$cnx->query("DELETE FROM $table_email
WHERE list_id = ".$list_id."
AND email=".escape_string($cnx,$del_addr))) {
return false;
} else {
return true;
}
}
} else {
return 5;
}
}
function force_subscriber($cnx, $table_email_tmp, $list_id, $del_addr, $table_email, $hash) {
$CPTID = $cnx->query("SELECT count(*) AS CPTID
FROM $table_email_tmp
WHERE list_id = '".$list_id."'
AND email = ".escape_string($cnx,$del_addr)."")->fetch();
if ( $CPTID['CPTID'] > 0 ) {
if (!$cnx->query("INSERT IGNORE INTO $table_email (list_id,email,hash)
VALUES (".escape_string($cnx,$list_id).",".escape_string($cnx,$del_addr).",".escape_string($cnx,$hash).")")) {
return false;
} else {
if (!$cnx->query("DELETE FROM $table_email_tmp
WHERE list_id = '$list_id'
AND email='$del_addr'")) {
return false;
} else {
return true;
}
}
} else {
return 5;
}
}
function deleteArchive($cnx,$table_archives, $msg_id) {
if (!$cnx->query("DELETE FROM $table_archives WHERE id='$msg_id'")) {
return false;
} else {
return true;
}
}
function deleteModMsg($cnx, $table_mod, $msg_id) {
if ($cnx->query("DELETE FROM $table_mod WHERE id='$msg_id'")) {
return true;
} else {
return -1;
}
}
function deleteNewsletter($cnx, $table_list, $table_archives, $table_email, $table_temp, $table_send, $table_tracking, $table_autosave, $list_id) {
if (!$cnx->query("DELETE FROM $table_list WHERE list_id='$list_id'")) {
return false;
}
if (!$cnx->query("DELETE FROM $table_email WHERE list_id='$list_id'")) {
return false;
}
if (!$cnx->query("DELETE FROM $table_temp WHERE list_id='$list_id'")) {
return false;
}
if (!$cnx->query("DELETE FROM $table_archives WHERE list_id='$list_id'")) {
return false;
}
if (!$cnx->query("DELETE $table_tracking,$table_send
FROM $table_tracking
INNER JOIN $table_send
WHERE $table_tracking.subject = $table_send.id_mail
AND $table_send.id_list = '$list_id'")) {
return false;
}
if (!$cnx->query("DELETE FROM $table_send WHERE id_list = '$list_id'")) {
return false;
}
if (!$cnx->query("DELETE FROM $table_autosave WHERE list_id = '$list_id'")) {
return false;
}
return true;
}
function DelMsgTemp($cnx, $list_id, $table){
if (!$cnx->query("DELETE FROM $table WHERE list_id='$list_id'")) {
return false;
}
}
function export_subscribers($cnx, $table_email, $list_id) {
$x = $cnx->query("SELECT email FROM $table_email WHERE list_id='$list_id' AND error='N'")->fetchAll(PDO::FETCH_ASSOC);
if (!$x){
die('export error');
} else {
header("Content-disposition: filename=listing_export_liste_".sprintf("%'.03d", $list_id)."_".date('Y-m-d-H-i-s').".txt");
header("Content-type: application/octetstream");
header("Pragma: no-cache");
header("Expires: 0");
if (strpos($_SERVER["HTTP_USER_AGENT"],"MSIE")){
$crlf = "\r\n";
} else {
$crlf = "\n";
}
foreach ($x as $item) {
print $item['email'].$crlf;
}
exit();
}
}
function escape_string($cnx, $string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
if (!is_numeric($string)) {
$string = $cnx->quote($string);
}
return $string;
}
function flushTempTable($cnx, $temp_table, $limit) {
if($_SESSION['timezone']!=''){
date_default_timezone_set($_SESSION['timezone']);
}elseif(file_exists('include/config.php')) {
date_default_timezone_set('Europe/Paris');
}
$date = date("Y/m/d");
$elts = explode("/", $date);
$y = $elts[0];
$m = $elts[1];
$d = $elts[2];
$before = mktime(0, 0, 0, $m, $d - $limit, $y);
$before = date("Ymd", $before);
if($cnx->query("DELETE FROM $temp_table where date < '$before'")){
return true;
} else {
return false;
}
}
function get_cpt_send($cnx, $row_config_globale, $list_id) {
$rowCpt = $cnx->SqlRow("SELECT cpt
FROM ".$row_config_globale['table_send'] ."
WHERE id_list = '$list_id' ORDER BY id_mail DESC LIMIT 1");
$cpt_send = $rowCpt['cpt'];
$rowCpt = $cnx->SqlRow("SELECT count(*) AS CPTMAIL
FROM ".$row_config_globale['table_email']."
WHERE list_id = '$list_id' AND campaign_id>0");
$cpt_mail = $rowCpt['CPTMAIL'];
return (int)$cpt_mail-(int)$cpt_send;
}
function get_first_newsletter_id($cnx,$lists_table) {
$x = $cnx->query("SELECT list_id FROM $lists_table LIMIT 1")->fetch();
if (count($x) == 0){
return '';
} else {
return $x['list_id'];
}
}
function get_id_send($cnx,$list_id,$table_send){
return $cnx->query("SELECT count(id) AS CPTID FROM $table_send WHERE id_list = '".$list_id."'")->fetch();
}
function get_message($cnx, $table_archive, $msg_id) {
$x = $cnx->query("SELECT type, subject, message, sender_email, preheader
FROM $table_archive
WHERE id='$msg_id'")->fetch(PDO::FETCH_ASSOC);
if(!$x){
return -1;
} else {
return $x;
}
}
function get_message_preview($cnx, $table_autosave, $list_id) {
$x = $cnx->query("SELECT type, subject, textarea
FROM $table_autosave
WHERE list_id='$list_id'")->fetch(PDO::FETCH_ASSOC);
if(!$x){
return -1;
} else {
return $x;
}
}
function get_newsletter_name($cnx, $lists_table, $list_id) {
$this_name = $cnx->query("SELECT newsletter_name
FROM $lists_table
WHERE list_id = '$list_id'")->fetch();
if (count($this_name) == 0){
return -1;
} else {
return $name = $this_name['newsletter_name'];
}
}
function get_newsletter_total_subscribers($cnx, $email_table, $list_id, $msg_id) {
$row = $cnx->query("SELECT COUNT( email ) AS CPT
FROM $email_table
WHERE list_id ='$list_id'
AND ERROR ='N'
AND (
campaign_id != '$msg_id'
OR
campaign_id IS NULL)"
)->fetch();
return $row['CPT'];
}
function get_relative_path($filename) {
return preg_replace("/^.*\/(".PREFIX_DIR."\/.*)/", "$1", $filename);
}
function get_stats_send($cnx,$list_id,$param_global){
return $cnx->query("SELECT a.id, DATE_FORMAT(a.date,'%Y-%m-%d') as dt, a.subject, s.cpt, s.error, s.`leave`,s.id_mail,
(
SELECT COUNT(DISTINCT(hash),subject)
FROM ".$param_global['table_tracking']."
WHERE subject = a.id
) AS TID,
(
SELECT COUNT(distinct(tr.hash))
FROM ".$param_global['table_tracking']." tr, ".$param_global['table_email_deleted']." em
WHERE subject = a.id
AND tr.hash = em.hash
) AS TIDUNSUB,
(
SELECT SUM(open_count) FROM ".$param_global['table_send']."
WHERE id_mail = a.id AND id_list = '".$list_id."'
) AS TOPEN,
(
SELECT SUM(cpt) FROM ".$param_global['table_track_links']."
WHERE list_id = '".$list_id."' AND msg_id=a.id
) AS CPT_CLICKED
FROM ".$param_global['table_send']." s
LEFT JOIN ".$param_global['table_archives']." a
ON a.id = s.id_mail
LEFT JOIN ".$param_global['table_tracking']." t
ON a.id = t.subject
WHERE a.list_id = '".$list_id."'
GROUP BY a.id
ORDER BY a.id DESC LIMIT 30")->fetchAll(PDO::FETCH_ASSOC);
}
function get_stats_send_global($cnx,$param_global){
return $cnx->query("SELECT
(
SELECT COUNT(id) FROM ".$param_global['table_send']."
) AS TSEND,
(
SELECT SUM(cpt) FROM ".$param_global['table_send']."
) AS TMAILS,
(
SELECT COUNT(id) FROM ".$param_global['table_tracking']."
) AS TID,
(
SELECT SUM(error) FROM ".$param_global['table_send']."
) AS TERROR,
(
SELECT SUM(`leave`) FROM ".$param_global['table_send']."
) AS TLEAVE,
(
SELECT SUM(open_count) FROM ".$param_global['table_tracking']."
) AS TOPEN,
(
SELECT SUM(cpt) FROM ".$param_global['table_track_links']."
) AS CPT_CLICKED
FROM ".$param_global['table_send']." LIMIT 1")->fetchAll(PDO::FETCH_ASSOC);
}
function get_stats_send_global_by_list($cnx,$param_global,$list_id){
return $cnx->query("SELECT
(
SELECT COUNT(id) FROM ".$param_global['table_send']." WHERE id_list=$list_id
) AS TSEND,
(
SELECT SUM(cpt) FROM ".$param_global['table_send']." WHERE id_list=$list_id
) AS TMAILS,
(
SELECT COUNT(DISTINCT(hash),subject) FROM ".$param_global['table_tracking']." WHERE subject IN
(SELECT id FROM ".$param_global['table_archives']." WHERE list_id=$list_id)
) AS TID,
(
SELECT SUM(error) FROM ".$param_global['table_send']." WHERE id_list=$list_id
) AS TERROR,
(
SELECT SUM(`leave`) FROM ".$param_global['table_send']." WHERE id_list=$list_id
) AS TLEAVE,
(
SELECT SUM(open_count) FROM ".$param_global['table_tracking']." WHERE subject IN
(SELECT id FROM ".$param_global['table_archives']." WHERE list_id=$list_id)
) AS TOPEN,
(
SELECT SUM(cpt) FROM ".$param_global['table_track_links']." WHERE list_id=$list_id
) AS CPT_CLICKED
FROM ".$param_global['table_send']." LIMIT 1")->fetchAll(PDO::FETCH_ASSOC);
}
function get_subscribers($cnx, $table_email, $list_id) {
return $subscribers = $cnx->query("SELECT email
FROM $table_email
WHERE list_id = '$list_id'
ORDER BY email ASC")->fetchAll(PDO::FETCH_ASSOC);
}
function getAddress($cnx,$table_email,$list_id,$begin='',$limit='',$msg_id) {
$limite=(isset($limit))?" LIMIT 0,$limit":"";
return $Addr = $cnx->query("SELECT id,email,hash
FROM $table_email
WHERE list_id = '$list_id'
AND error='N'
AND (
campaign_id != '$msg_id'
OR
campaign_id IS NULL)
ORDER BY id ASC
$limite")->fetchAll(PDO::FETCH_ASSOC);
}
function getArchiveMsg($cnx, $table_archives, $msg_id,$token,$list,$type_user=false,$droit_liste=0) {
if (empty($offset)) $offset = 0;
$row = $cnx->query("SELECT id, date, type, subject, message, list_id
FROM $table_archives
WHERE id='$msg_id'")->fetch(PDO::FETCH_ASSOC);
if (count($row) == 0){
return -1;
} else {
$subject = htmlspecialchars($row['subject']);
$subject = stripslashes($subject);
echo "<h5>Sujet : <b>\"" . $subject . "\"</b>, envoyé le : <i>" . $row['date'] . "</i></h5><br>";
echo "<div class='iframePreview' style='width:100%'><iframe src='preview.php?list_id=". $row['list_id']
."&token=$token&id=". $row['id'] ."' width='100%' height='300px' frameborder='0' style='border:0;' scrolling='no' id='_preview' scrolling='no' onload='rszifr(this)'><p>Oups ! Your browser does not support iframes.</p></iframe></div>";
echo "<br>";
echo "<div class='archmsg' style='padding-bottom:15px;text-align:center;'><form action='".$_SERVER['PHP_SELF']."' method='post' name='selected_newsletter'>";
echo "<br>Utiliser ce message comme modèle pour nouvelle rédaction avec la liste : <select name='list_id' class='selectpicker' data-width='auto'>";
foreach ($list as $item) {
if($droit_liste==0||$type_user) {
echo "<option value='" . $item['list_id'] . "' ";
if($row['list_id']== $item['list_id']){
echo "selected='selected' ";
}
echo ">" . $item['newsletter_name'] . "</option>";
} elseif(($droit_liste>0&&!$type_user)&&$droit_liste==$item['list_id']) {
echo "<option value='" . $item['list_id'] . "' ";
if($row['list_id']== $item['list_id']){
echo "selected='selected' ";
}
echo ">" . $item['newsletter_name'] . "</option>";
}
}
echo "</select>";
echo "<input type='hidden' name='import_id' value='".$row['id']."' />";
echo "<input type='hidden' name='page' value='compose' />";
echo "<input type='hidden' name='op' value='init' />";
echo "<input type='hidden' name='token' value='$token' />";
echo " <input type='submit' value=' O K ' class='btn btn-primary' />";
echo "</form></div>";
}
}
function getArchivesSelectList($cnx, $table_archives, $msg_id = '', $form_name = 'archive_form2',$list_id) {
$row = $cnx->query("SELECT id, date, subject FROM $table_archives WHERE list_id='$list_id' ORDER BY date DESC")->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 0){
return -1;
} else {
$archive = "<select name='msg_id' onchange='document.$form_name.submit()' class='selectpicker' data-width='auto'>";
foreach($row as $x) {
$archive .= "<option value='".$x['id']."'";
if ($msg_id == $x['id']){
$archive .= " selected='selected'";
}
$archive .= ">" . stripslashes($x['subject'])." du " . $x['date'] . " </option>\n";
}
$archive .= "</select>";
echo $archive;
}
}
function getConfig($cnx, $list_id, $list_table) {
$x = $cnx->query("SELECT * FROM $list_table WHERE list_id='$list_id'")->fetch(PDO::FETCH_ASSOC);
if(!$x){
return -1;
} else {
return $x;
}
}
function getConfigSender($cnx, $list_table, $email) {
$x = $cnx->query("SELECT * FROM $list_table WHERE email='".($cnx->CleanInput($email))."'")->fetch(PDO::FETCH_ASSOC);
if(!$x){
return -1;
} else {
return $x;
}
}
function getEmail($cnx, $mail, $table_email) {
$x = $cnx->query("SELECT email FROM $table_email WHERE email like '%$mail%' LIMIT 0,5")->fetchAll(PDO::FETCH_ASSOC);
if(count($x)>0){
return $x;
}
}
function getLanguageList($selected) {
$ret = "";
$langfiles = array();
if ($handle = opendir("include/lang/")) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && preg_match("/([a-z_]+)\.php$/i", $file, $match)) {
array_push($langfiles, str_replace("_", " ", $match[1]));
}
}
closedir($handle);
}
asort($langfiles);
foreach ($langfiles as $value) {
$ret .= "\t<option value='$value' " . ($selected == $value ? 'selected' : '') . ">" . ucfirst($value) . "</option>\n";
}
return $ret;
}
function getlocale($category) {
return setlocale($category, NULL);
}
function getMsgById($cnx,$id,$table) {
$x = $cnx->query("SELECT * FROM $table WHERE id='$id'")->fetch(PDO::FETCH_ASSOC);
if(!$x){
return -1;
} else {
return $x;
}
}
function getMsgDraft($cnx, $list_id, $table_draft) {
$NB = $cnx->query("SELECT COUNT(*) AS NB FROM $table_draft WHERE list_id = '$list_id'")->fetch(PDO::FETCH_ASSOC);
if(!$NB){
return -1;
} else {
return $NB;
}
}
function getSenders($cnx, $table_senders, $sender='') {
$row = $cnx->query("SELECT name_organisation,email FROM $table_senders ORDER BY 1 ASC")->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 0){
return -1;
} else {
$liste_senders = "<select name='sender_id' id='sender_id' class='selectpicker' data-width='auto'><option value=''></option>";
foreach($row as $x) {
$liste_senders .= "<option value='".$x['email']."'";
if ($x['email']==$sender && $sender!='') $liste_senders .= ' selected';
$liste_senders .= ">" . stripslashes($x['email']) . ($x['name_organisation']!=''?" (".stripslashes($x['name_organisation']).")":"" ) . " </option>";
}
$liste_senders .= "</select>";
return $liste_senders;
}
}
function getSendersFull($cnx, $table_senders, $table_archives) {
$row = $cnx->query("SELECT A.subject,A.id,S.id_sender,S.name_organisation,S.email,S.smtp FROM $table_senders S
LEFT JOIN $table_archives A
ON S.last_send=A.id ORDER BY 1 ASC")->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 0){
return false;
} else {
return $row;
}
}
function getUsersFull($cnx, $table_users, $table_listes) {
$row = $cnx->query("SELECT U.*, L.newsletter_name FROM $table_users U
LEFT JOIN $table_listes L
ON U.liste=L.list_id ORDER BY id_user ASC")->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 0){
return false;
} else {
return $row;
}
}
function getOneSenderFull($cnx, $table_senders, $account) {
$row = $cnx->query("SELECT * FROM $table_senders WHERE email = '$account'")->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 0){
return false;
} else {
return $row;
}
}
function getOneUserFull($cnx, $table_users, $account) {
$row = $cnx->query("SELECT * FROM $table_users WHERE email = '$account'")->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 0){
return false;
} else {
return $row;
}
}
function getSubscribersEmail($cnx, $table_config, $email, $from, $from_name, $list_id = '') {
$conf = new config();
$conf->getConfig($db_host, $db_login, $db_pass, $db_name, $table_config);
$db = new Db();
$db->DbConnect($db_host, $db_login, $db_pass, $db_name);
$sql = "SELECT DISTINCT email FROM $conf->table_email ";
if (!empty($list_id))
$sql .= "WHERE list_id='$list_id'";
$cnx->SqlRow($sql);
if ($db->DbError()) {
echo $db->DbError();
return -1;
}
$body = "adresse email des abonnés:\n";
$body .= "-------------------------\n";
while ($a = $db->DbNextRow()) {
$body .= $a[0] . "\n";
}
return sendEmail($conf->sending_method, $email, $from, $from_name, "Liste des adresses", $body,
$conf->smtp_auth, $conf->smtp_host = '', $conf->smtp_login = '', $conf->smtp_pass);
}
function getSubscribersNumbers($cnx,$table_email,$list_id,$type='') {
switch($type){
case 'unsub':
$row = $cnx->SqlRow("SELECT COUNT( email ) AS CPT FROM $table_email WHERE list_id ='$list_id' and type='unsub'");
break;
case 'bounce':
$row = $cnx->SqlRow("SELECT COUNT( email ) AS CPT FROM $table_email WHERE list_id ='$list_id' and type!='unsub'");
break;
default:
$row = $cnx->SqlRow("SELECT COUNT( email ) AS CPT FROM $table_email WHERE list_id ='$list_id'");
break;
}
return $row['CPT'];
}
function getSubscribersTotal($cnx,$table_email) {
$row = $cnx->SqlRow("SELECT COUNT( distinct(email) ) AS CPT FROM $table_email");
return $row['CPT'];
}
function getWaitingMsg($hostname, $login, $pass, $database, $table_mod, $msg_id) {
$sql = "SELECT date, type, email_from, subject, message, list_id FROM $table_mod WHERE id='$msg_id'";
$cnx->SqlRow($sql);
if ($cnx->DbNumRows())
return $cnx->DbNextRow();
else
return false;
}
function getWaitingMsgList($hostname, $login, $pass, $database, $table_mod, $list_id, $msg_id = '') {
$sql = "SELECT id, date, email_from, subject FROM $table_mod WHERE list_id='$list_id'";
$cnx->SqlRow($sql);
if ($cnx->DbNumRows()) {
while ($r = $cnx->DbNextRow()) {
$form .= "<option value=\"" . $r[0] . "\"";
if ($msg_id == $r[0])
$form .= " selected ";
$form .= ">$r[1] | $r[2] | $r[3] </option> ";
}
return $form;
} else
return false;
}
function is_exec_available() {
// SOURCE : http://stackoverflow.com/a/12980534
static $available;
if (!isset($available)) {
$available = true;
if (ini_get('safe_mode')) {
$available = false;
} else {
$d = ini_get('disable_functions');
$s = ini_get('suhosin.executor.func.blacklist');
if ("$d$s") {
$array = preg_split('/,\s*/', "$d,$s");
if (in_array('exec', $array)) {
$available = false;
}
}
}
}
return $available;
}
function isSSL() {
if (!empty($_SERVER['https']) && $_SERVER['HTTPS'] != 'off') {
return true;
}
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
return true;
}
return false;
}
function isValidNewsletter($cnx, $table_list, $list_id) {
$x = $cnx->query("SELECT list_id FROM $table_list WHERE list_id='$list_id'");
if (!$x) {
return false;
}
return count($x);
}
function isValidSubscriber($cnx, $table_email, $list_id, $email_addr) {
$email_addr = strtolower($email_addr);
$x = $cnx->query("SELECT hash FROM $table_email WHERE list_id='$list_id' AND email='$email_addr'")->fetch();
if(!$x) {
return false;
}elseif(count($x)==0){
return false;
}else{
return $x['hash'];
}
}
function leaveAdmin() {
if (setcookie("PMNLNG_admin_password"))
return true;
return false;
}
function list_bounce_error($cnx, $table_email,$list_id) {
$x = $cnx->query("SELECT *
FROM $table_email
WHERE list_id=$list_id
AND error='Y'
AND status IS NOT NULL
ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
return $x;
}
function list_bounce_error_chart_data($cnx, $table_email,$list_id) {
$x = $cnx->query("SELECT count(*) AS NB_ERROR, status
FROM $table_email
WHERE list_id=$list_id AND error='Y'
AND status IS NOT NULL
GROUP BY status")->fetchAll(PDO::FETCH_ASSOC);
return $x;
}
function list_bounce_error_chart_data_by_type($cnx, $table_email,$list_id) {
$x = $cnx->query("SELECT
(COUNT(CASE WHEN substr(status,1,1)=5 THEN 1 END)) as hard,
(COUNT(CASE WHEN substr(status,1,1)=4 THEN 1 END)) as soft
FROM $table_email
WHERE list_id=$list_id AND error='Y'")->fetchAll(PDO::FETCH_ASSOC);
return $x;
}
function list_newsletter($cnx, $lists_table) {
$x = $cnx->query("SELECT list_id,newsletter_name FROM $lists_table ORDER BY list_id ASC")->fetchAll(PDO::FETCH_ASSOC);
if (count($x) == 0){
return false;
} else {
return $x;
}
}
function list_newsletter_last_id_send($cnx, $table_send, $list_id, $table_archives) {
$x = $cnx->query("SELECT s.id_mail, a.subject
FROM $table_send s
LEFT JOIN $table_archives a ON s.id_mail=a.id
WHERE s.id_list='$list_id'
ORDER BY id_mail DESC
LIMIT 0,1")->fetchAll(PDO::FETCH_ASSOC);
return $x;
}
function loggit($file,$msg) {
$file_to_write = dirname(dirname(__DIR__)).'/logs/'.str_replace(' ','_',$file);
$rs_log = @fopen($file_to_write, 'a+');
$tolog = date("d/m/Y H:i:s"). " : " . $msg . "\n";
fwrite($rs_log, $tolog, strlen($tolog));
fclose($rs_log);
}
function moderate_subscriber($cnx, $table_email, $table_sub, $list_id, $mod_addr) {
$cnx->SqlRow("DELETE FROM $table_moderation WHERE list_id = '$list_id' AND email='$mod_addr'");
if ($cnx->DbError()) {
echo $cnx->DbError();
return false;
}
$hash = unique_id($mod_addr);
$cnx->SqlRow("INSERT INTO $table_email (`email`, `list_id`, `hash`) VALUES ('$mod_addr', '$list_id','$hash')");
if ($cnx->DbError()) {
echo $cnx->DbError();
return false;
} else
return $hash;
}
function optimize_tables($cnx){
$x = $cnx->query("SHOW TABLE STATUS WHERE Data_free / Data_length > 0.1 AND Data_free > 10240")->fetchAll(PDO::FETCH_ASSOC);
if (count($x)>0){
foreach($x as $row){
$cnx->query('OPTIMIZE TABLE ' . $row['Name']);
}
}
}
function quick_Exit(){
@session_start();
$_SESSION=array();
if(ini_get("session.use_cookies")){
$params=session_get_cookie_params();
setcookie(session_name(),'',time()-42000,
$params["path"],$params["domain"],
$params["secure"],$params["httponly"]
);
}
session_destroy();
header('Content-type: text/html; charset=utf-8');
header("Location:login.php",true,307);
echo "<html></html>";
@flush();
@ob_flush();
exit;
}
function readfile_chunked($filename) {
$chunksize = 1*(1024*1024);
$buffer = '';
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
print $buffer;
}
return fclose($handle);
}
function removeSubscriber($cnx, $table_email, $table_send, $list_id, $addr, $hash, $id_mail, $table_email_deleted) {
$x = $cnx->query("SELECT email FROM $table_email WHERE list_id='$list_id' AND email='$addr' AND hash='$hash'")->fetch();
if(!$x) {
return -1;
}elseif(count($x)==0){
return -1;
}else{
$y = $cnx->query("DELETE FROM $table_email WHERE email='$addr' AND list_id='$list_id' AND hash='$hash'");
if(!$y){
return -2;
} else {
$cnx->query("UPDATE $table_send SET `leave`=`leave`+1 WHERE id_list='$list_id' AND id_mail='$id_mail'");
$cnx->query("INSERT INTO $table_email_deleted (list_id,email,hash,type,campaign_id)
VALUES (".escape_string($cnx,$list_id).",".escape_string($cnx,$addr).",".escape_string($cnx,$hash).",'unsub',".escape_string($cnx,$id_mail).")");
return true;
}
}
}
function removeSubscriberDirect($cnx, $table_email, $table_send, $list_id, $addr, $hash, $id_mail, $table_email_deleted) {
$addr = strtolower($addr);
$rm=$cnx->query("SELECT email FROM $table_email WHERE list_id='$list_id' AND email='$addr'")->fetch(PDO::FETCH_ASSOC);
if ($rm == 0) return -1;
if($cnx->query("DELETE FROM $table_email WHERE email='$addr' AND list_id='$list_id'")){
$cnx->query("UPDATE $table_send SET `leave`=`leave`+1 WHERE id_list='$list_id' AND id_mail='$id_mail'");
$cnx->query("INSERT INTO $table_email_deleted (list_id,email,hash,type,campaign_id)
VALUES (".escape_string($cnx,$list_id).",".escape_string($cnx,$addr).",".escape_string($cnx,$hash).",'unsub',".escape_string($cnx,$id_mail).")");
return true;
} else return -2;
}
function sanitize_output($buffer) {
$search = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
$replace = array('>','<','\\1');
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
function save_message($cnx, $table_archive, $subject, $format, $body, $date, $list_id, $sender_email, $draft, $preheader) {
$id = $cnx->query("SELECT MAX(id) AS MAXID FROM $table_archive ORDER BY id DESC")->fetch(PDO::FETCH_ASSOC);
$newid = $id['MAXID'] + 1;
$sql = "INSERT into ".$table_archive."
(`id`, `date`,`type`, `subject` , `message`, `list_id`, `sender_email`, `draft`, `preheader`)
VALUES ('".($cnx->CleanInput($newid))."',
'".($cnx->CleanInput($date))."',
'".($cnx->CleanInput($format))."',
'".addslashes($cnx->CleanInput($subject))."',
'".addslashes($cnx->CleanInput($body, true, false, false))."',
'".($cnx->CleanInput($list_id))."',
'".($cnx->CleanInput($sender_email))."',
'".addslashes($cnx->CleanInput($draft, true, false, false))."',
'".addslashes($cnx->CleanInput($preheader))."')";
if ($cnx->query($sql)) {
return $newid;
} else {
return -1;
}
}
function save_mod_message($hostname, $login, $pass, $database, $table_mod, $subject, $format, $body, $date, $list_id, $from) {
$this_id = $cnx->SqlRow("SELECT id FROM $table_mod ORDER BY id DESC");
$id = $this_id['id'];
$newid = $id[0] + 1;
$sql = "INSERT into $table_mod (`id`, `date`,`type`, `subject` , `message`, `list_id` , `email_from`)
VALUES ('$newid', '$date','$format','$subject','$body', '$list_id', '$from')";
if ($cnx->query($sql)) {
return -1;
}
return $newid;
}
function saveBounceFile($bounce_host,$bounce_user,$bounce_pass,$bounce_port,$bounce_service,$bounce_option,$bounce_mail='') {
$configfile = "<?php\n";
if($bounce_mail!=''){
$configfile .= "\n\t$" . "bounce_mail = \"$bounce_mail\";";
}
$configfile .= "\n\t$" . "bounce_host = \"$bounce_host\";";
$configfile .= "\n\t$" . "bounce_user = \"$bounce_user\";";
$configfile .= "\n\t$" . "bounce_pass = \"$bounce_pass\";";
$configfile .= "\n\t$" . "bounce_port = \"$bounce_port\";";
$configfile .= "\n\t$" . "bounce_service = \"$bounce_service\";";
$configfile .= "\n\t$" . "bounce_option = \"$bounce_option\";";
$configfile .= "\n?>";
if(file_exists("include/config_bounce.php")) {
if (is_writable("include/config_bounce.php")) {
$fc = fopen("include/config_bounce.php", "w");
$w = fwrite($fc, $configfile);
}
} elseif (is_writable("include/")) {
$fc = fopen("include/config_bounce.php", "w");
$w = fwrite($fc, $configfile);
} else {
return -1;
}
}
function saveConfig($cnx,$config_table,$admin_pass,$archive_limit,$base_url,$path,$language,
$table_email,$table_temp,$table_listsconfig,$table_archives,$sending_method,
$smtp_host,$smtp_port,$smtp_auth,$smtp_login,$smtp_pass,$sending_limit,
$validation_period,$sub_validation,$unsub_validation,$admin_email,
$admin_name,$mod_sub,$table_sub,$charset,$table_track,$table_send,
$table_sauvegarde,$table_upload,$table_email_deleted,$table_senders,
$alert_sub,$active_tracking) {
$base_url = escape_string($cnx,$base_url);
$path = escape_string($cnx,$path);
$smtp_host = escape_string($cnx,$smtp_host);
$smtp_port = escape_string($cnx,$smtp_port);
$smtp_login = escape_string($cnx,$smtp_login);
$smtp_pass = escape_string($cnx,$smtp_pass);
$sending_limit = escape_string($cnx,$sending_limit);
$sending_method = escape_string($cnx,$sending_method);
$validation_period = escape_string($cnx,$validation_period);
$admin_email = escape_string($cnx,$admin_email);
$admin_name = escape_string($cnx,$admin_name);
$mod_sub = escape_string($cnx,$mod_sub);
$language = escape_string($cnx,$language);
$charset = escape_string($cnx,$charset);
$table_email = escape_string($cnx,$table_email);
$table_listsconfig = escape_string($cnx,$table_listsconfig);
$table_temp = escape_string($cnx,$table_temp);
$table_archives = escape_string($cnx,$table_archives);
$table_track = escape_string($cnx,$table_track);
$table_send = escape_string($cnx,$table_send);
$table_sauvegarde = escape_string($cnx,$table_sauvegarde);
$table_upload = escape_string($cnx,$table_upload);
$table_email_deleted=escape_string($cnx,$table_email_deleted);
$table_senders=escape_string($cnx,$table_senders);
$alert_sub = escape_string($cnx,$alert_sub);
$active_tracking = escape_string($cnx,$active_tracking);
$sql = "UPDATE $config_table SET ";
if (!empty($admin_pass)) {
$sql .= "admin_pass='" . md5($admin_pass) . "', ";
setcookie("PMNLNG_admin_password", md5($admin_pass));
}
$sql .= "archive_limit=$archive_limit, base_url=$base_url, path=$path,
language=$language, table_email=$table_email, table_temp=$table_temp,
table_listsconfig=$table_listsconfig, table_archives=$table_archives,
sending_limit=$sending_limit, sending_method=$sending_method,
sub_validation='$sub_validation', unsub_validation='$unsub_validation',
admin_email=$admin_email, admin_name=$admin_name, mod_sub='$mod_sub' ,
charset=$charset, mod_sub_table='$table_sub', validation_period=$validation_period,
table_tracking=$table_track, table_send=$table_send, table_sauvegarde=$table_sauvegarde,
table_upload=$table_upload, alert_sub='$alert_sub', active_tracking='$active_tracking',
table_email_deleted=$table_email_deleted, table_senders=$table_senders";
if($sending_method == 'mail') {
$sql .= ", smtp_host='', ";
$sql .= "smtp_auth='0' ";
$sql .= ", smtp_login='', ";
$sql .= "smtp_pass=''";
} else {
$sql .= ", smtp_host=$smtp_host, ";
$sql .= "smtp_port=$smtp_port, ";
$sql .= "smtp_auth='$smtp_auth' ";
if ($smtp_auth == 1) {
$sql .= ", smtp_login=$smtp_login, ";
$sql .= "smtp_pass=$smtp_pass";
} else {
$sql .= ", smtp_login='', ";
$sql .= "smtp_pass=''";
}
}
if ($cnx->query($sql)) {
return true;
} else {
return false;
}
}
function saveConfigFile($version,$db_host, $db_login, $db_pass, $db_name, $db_config_table,
$db_type = 'mysql', $serveur='shared', $environnement='dev', $timezone,
$code_mailtester, $timer_ajax, $timer_cron, $free_id, $free_pass,
$end_task,$end_task_sms,$sub_validation_sms,$unsub_validation_sms,
$alert_unsub,$nb_backup,$key_dkim,$loader,$menu) {
$prefix = str_replace ( 'config','',$db_config_table);
$configfile = "<?php\nif ( !defined( '_CONFIG' ) ) {\n\tdefine('_CONFIG', 1);";
$configfile .= "\n\t$" . "db_type = '$db_type';";
$configfile .= "\n\t$" . "hostname = '$db_host';";
$configfile .= "\n\t$" . "login = '$db_login';";
$configfile .= "\n\t$" . "pass = '$db_pass';";
$configfile .= "\n\t$" . "database = '$db_name';";
$configfile .= "\n\t$" . "nb_backup = $nb_backup;";
$configfile .= "\n\t$" . "prefix = '$prefix';";
$configfile .= "\n\t$" . "type_serveur = '$serveur';";
$configfile .= "\n\t$" . "code_mailtester = '$code_mailtester';";
$configfile .= "\n\t$" . "key_dkim = '$key_dkim';";
$configfile .= "\n\t$" . "type_env = '$environnement';";
$configfile .= "\n\t$" . "timezone = '$timezone';";
$configfile .= "\n\t$" . "table_global_config= '$db_config_table';";
$configfile .= "\n\t$" . "timer_ajax = $timer_ajax;";
$configfile .= "\n\t$" . "timer_cron = $timer_cron;";
$configfile .= "\n\t$" . "end_task = $end_task;";
$configfile .= "\n\t$" . "loader = $loader;";
$configfile .= "\n\t$" . "menu = '$menu';";
if($free_id!='' && $free_pass!='') {
$configfile .= "\n\t$" . "free_id = '$free_id';";
$configfile .= "\n\t$" . "free_pass = '$free_pass';";
$configfile .= "\n\t$" . "end_task_sms = $end_task_sms;";
$configfile .= "\n\t$" . "sub_validation_sms = $sub_validation_sms;";
$configfile .= "\n\t$" . "unsub_validation_sms = $unsub_validation_sms;";
}
$configfile .= "\n\t$" . "alert_unsub = $alert_unsub;";
if(is_exec_available()){
$configfile .= "\n\t$" . "exec_available = true;";
}else{
$configfile .= "\n\t$" . "exec_available = false;";
}
$configfile .= "\n\t$" . "pmnl_version = '$version';\n}";
if (is_writable("include/config.php")) {
$fc = fopen("include/config.php", "w");
$w = fwrite($fc, $configfile);
return true;
} else {
return -1;
}
}
function saveDKIMFiles($dkim_htkeypublic,$dkim_htkeyprivate,$DKIM_domain,$DKIM_passphrase,$DKIM_record,$DKIM_selector,$DKIM_identity) {
if($dkim_htkeyprivate['name']!=''){
move_uploaded_file($dkim_htkeyprivate['tmp_name'],'DKIM/'.$dkim_htkeyprivate['name']);
$DKIM_private = 'DKIM/'.$dkim_htkeyprivate['name'];
}
if($dkim_htkeypublic['name']!=''){
move_uploaded_file($dkim_htkeypublic['tmp_name'],'DKIM/'.$dkim_htkeypublic['name']);
$DKIM_public = 'DKIM/'.$dkim_htkeypublic['name'];
}
$DKIM_param = "<?php\n";
$DKIM_param .= "\n\t$" . "DKIM_domain = '$DKIM_domain';";
$DKIM_param .= "\n\t$" . "DKIM_private = '$DKIM_private';";
$DKIM_param .= "\n\t$" . "DKIM_public = '$DKIM_public';";
$DKIM_param .= "\n\t$" . "DKIM_selector = '$DKIM_selector';";
$DKIM_param .= "\n\t$" . "DKIM_passphrase = '$DKIM_passphrase';";
$DKIM_param .= "\n\t$" . "DKIM_identity = '$DKIM_identity';";
$DKIM_param .= "\n\t$" . "DKIM_record = '$DKIM_record';";
$DKIM_param .= "\n?>";
if (file_exists("DKIM/DKIM_config.php")) {
if (is_writable("DKIM/DKIM_config.php")) {
$fc = fopen("DKIM/DKIM_config.php", "w");
$w = fwrite($fc, $DKIM_param);
}
} elseif (is_writable("DKIM/")) {
$fc = fopen("DKIM/DKIM_config.php", "w");
$w = fwrite($fc, $DKIM_param);
} else {
return -1;
}
}
function saveModele($cnx,$list_id,$table_listsconfig,$newsletter_name,$from,$from_name,$subject,$header,$footer,
$subscription_subject,$subscription_body,$welcome_subject,$welcome_body,$quit_subject,$quit_body,$preview_addr) {
$newsletter_name = escape_string($cnx,$newsletter_name);
$from = escape_string($cnx,$from);
$from_name = escape_string($cnx,$from_name);
$subject = escape_string($cnx,$subject);
$header = escape_string($cnx,$header);
$footer = escape_string($cnx,$footer);
$subscription_subject = escape_string($cnx,$subscription_subject);
$subscription_body = escape_string($cnx,$subscription_body);
$welcome_subject = escape_string($cnx,$welcome_subject);
$welcome_body = escape_string($cnx,$welcome_body);
$quit_subject = escape_string($cnx,$quit_subject);
$quit_body = escape_string($cnx,$quit_body);
$preview_addr = escape_string($cnx,$preview_addr);
$sql = "UPDATE $table_listsconfig SET newsletter_name=$newsletter_name, from_addr=$from, from_name=$from_name,
subject=$subject, header=$header , footer=$footer ,
subscription_subject=$subscription_subject, subscription_body=$subscription_body,
welcome_subject=$welcome_subject, welcome_body=$welcome_body,
quit_subject=$quit_subject, quit_body=$quit_body, preview_addr=$preview_addr
WHERE list_id=$list_id";
if ($cnx->query($sql)){
return true;
} else {
return false;
}
}
function sendEmail($send_method, $to, $from, $from_name, $subject, $body, $auth = 0,
$smtp_host = '', $smtp_login = '', $smtp_pass = '', $charset = 'UTF-8',
$secure = '', $port ='') {
$mail = new phpmailer();
$mail->CharSet = $charset;
$mail->PluginDir = "include/lib/";
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
switch ($send_method) {
case 'lbsmtp':
case "smtp":
$mail->IsSMTP();
$mail->Host = $smtp_host;
if ($auth) {
$mail->SMTPAuth = true;
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
}
if ($secure != '') {
$mail->SMTPSecure = $secure;
}
if ($port != '') {
$mail->Port = (int)$port;
} else {
$mail->Port = 25;
}
break;
case "smtp_gmail":
case "smtp_gmail_tls":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
break;
case "smtp_gmail_ssl":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
break;
case "php_mail":
case "php_mail_infomaniak":
$mail->IsMail();
break;
case "smtp_mutu_ovh":
$mail->IsSMTP();
$mail->Port = 587;
$mail->Host = 'ssl0.ovh.net';
if ($auth) {
$mail->SMTPAuth = true;
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
}
break;
case "smtp_mutu_1and1":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 465;
$mail->Host = 'auth.smtp.1and1.fr';
if ($auth) {
$mail->SMTPAuth = true;
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
}
break;
case "smtp_mutu_gandi":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Host = 'mail.gandi.net';
if ($auth) {
$mail->SMTPAuth = true;
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
}
break;
case "smtp_mutu_online":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Port = 587;
$mail->Host = 'smtpauth.online.net';
if ($auth) {
$mail->SMTPAuth = true;
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
}
break;
case "smtp_mutu_infomaniak":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Port = 587;
$mail->Host = 'mail.infomaniak.ch';
if ($auth) {
$mail->SMTPAuth = true;
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
}
break;
case "smtp_one_com":
$mail->IsSMTP();
$mail->SMTPAuth = false;
$mail->Port = 25;
$mail->Host = 'mailout.one.com';
break;
case "smtp_one_com_ssl":
require_once(__DIR__.'/class.pop3.php');
$pop = new POP3();
$pop->Authorise("send.one.com", 465, 30, $smtp_login, $smtp_pass, 1);
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'send.one.com';
$mail->Username = $smtp_login;
$mail->Password = $smtp_pass;
break;
default:
die(tr("NO_SEND_DEFINITION"));
break;
}
if (file_exists("DKIM/DKIM_config.php")) {
include("DKIM/DKIM_config.php");
$mail->DKIM_domain = $DKIM_domain;
$mail->DKIM_private = $DKIM_private;
$mail->DKIM_selector = $DKIM_selector;
$mail->DKIM_passphrase = $DKIM_passphrase;
$mail->DKIM_identity = $DKIM_identity;
}
$mail->ClearAllRecipients();
$mail->ClearCustomHeaders();
$mail->IsHTML(true);
$mail->From = $from;
$mail->FromName = $from_name;
$mail->AddAddress($to);
$mail->XMailer = ' ';
$mail->Subject = $subject;
$mail->Body = $body;
if (!$mail->Send()) {
echo $mail->ErrorInfo;
return -2;
}
return true;
}
function send_sms($free_id,$free_pass,$msg) {
$opts = array('http' =>
array(
'method' => 'POST'
)
);
$context = stream_context_create($opts);
$url = "https://smsapi.free-mobile.fr/sendmsg?user=$free_id&pass=$free_pass&msg=$msg";
$result = file_get_contents($url, false, $context);
return $result;
}
function tok_gen($name = ''){
@session_start();
if (function_exists("hash_algos") and in_array("sha512",hash_algos())){
$token=hash("sha512",mt_rand(0,mt_getrandmax()));
}else{
$token=' ';
for ($i=0;$i<128;++$i){
$r=mt_rand(0,35);
if ($r<26){
$c=chr(ord('a')+$r);
}else{
$c=chr(ord('0')+$r-26);
}
$token.=$c;
}
}
$_SESSION['_token'] = $token;
$_SESSION['_token_time'] = time();
return $token;
}
function tok_val($token){
@session_start();
$temps_de_connexion = 9999;
$tok = false;
$trimToken = trim($token);
if(isset($_SESSION['_token'])&&isset($_SESSION['_token_time'])&&isset($token)&&!empty($trimToken)){
if($_SESSION['_token'] == $token){
if($_SESSION['_token_time'] >= (time() - $temps_de_connexion)){
$_SESSION['_token_time'] = time();
$tok = true;
} else {
$tok = false;
}
} else {
$tok = false;
}
}
return $tok;
}
function tr($s, $i="") {
global $lang_array;
if (!isset($lang_array[$s])){
return ("[Translation required] : $s");
}
if ($lang_array[$s] != "") {
if($i == ""){
return $lang_array[$s];
}
$sprint = $lang_array[$s];
return sprintf("$sprint" , $i);
} else {
return ("[Translation required] : $s");
}
}
function unique_id($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
$clen = strlen($x);
$randomString = '';
for ($i = 0; $i < $clen; $i++) {
$randomString .= $x[rand(0, $clen - 1)];
}
mt_srand((double) microtime() * 1000000);
return md5(mt_rand(0, 9999999).$randomString);
}
function UpdateEmailError($cnx , $table_email , $list_id , $email , $status , $type , $categorie ,
$short_desc , $long_desc , $campaign_id , $table_email_deleted , $table_send , $hash){
$hash = @current($cnx->query("SELECT hash
FROM ".$table_email."
WHERE list_id='".($cnx->CleanInput($list_id))."'
AND email='".($cnx->CleanInput($email))."'
AND hash='".($cnx->CleanInput($hash))."'
")->fetch());
if($hash!=''){
if ($cnx->query("INSERT IGNORE INTO ".$table_email_deleted." (id,email,list_id,hash,error,status,type,categorie,short_desc,long_desc,campaign_id)
SELECT id,email,list_id,hash,'Y','".($cnx->CleanInput($status))."','".($cnx->CleanInput($type))."',
'".($cnx->CleanInput($categorie))."','".($cnx->CleanInput($short_desc))."',
'".($cnx->CleanInput($long_desc))."','".($cnx->CleanInput($campaign_id))."'
FROM ".$table_email."
WHERE email = '" . ($cnx->CleanInput($email)) . "'
AND hash = '" . ($cnx->CleanInput($hash)) . "'")){
if ($cnx->query("DELETE FROM ".$table_email."
WHERE email='" . ($cnx->CleanInput($email)) . "'
AND hash = '" . ($cnx->CleanInput($hash)) . "'")) {
if ($cnx->query("UPDATE ".$table_send ."
SET error=error+1
WHERE id_mail='".($cnx->CleanInput($campaign_id))."'")){
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
}
function validEmailAddress($email) {
$email = trim($email);
$exp = "/^(.*)@(.*)$/";
preg_match($exp, $email, $matches);
$domains_to_kick_off=array('voila.fr','bocps.biz','yahoogroupes.fr','yahoogroupes.com');
if (is_string($email) && !empty($matches[1]) && filter_var($email, FILTER_VALIDATE_EMAIL) && !in_array($matches[2],$domains_to_kick_off)) {
return (checkdnsrr($matches[2],'MX'));
} else {
return false;
}
}
function msleep($time){
usleep($time * 1000000);
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/switch_smtp.php'
<?php
/*------------------------------------------------------------------------
For a new smtp service, please ask it on www.phpmynewsletter.com/forum/
--------------------------------------------------------------------------
Please, don't touch after this line, or phpmynewsletter won't work anymore.
------------------------------------------------------------------------*/
if(!isset($send_method)){
$send_method = $row_config_globale['sending_method'];
}
if($row_config_globale['sending_method']=='lbsmtp'){
$cnx->query("UPDATE ".$row_config_globale['table_smtp']."
SET smtp_date_update=NOW(),smtp_used=0
WHERE smtp_date_update < DATE_SUB(CURDATE(), INTERVAL 1 DAY)");
$daylog = @fopen('logs/daylog-' . date("Y-m-d") . '.txt', 'a+');
$date = date("Y-m-d H:i:s");
$daylogmsg=$date. " : RAZ compteurs load_balancing SMTP\n";
fwrite($daylog, $daylogmsg, strlen($daylogmsg));
fclose($daylog);
}
switch ($send_method) {
case "smtp":
$mail->IsSMTP();
$mail->Host = $row_config_globale['smtp_host'];
if ($row_config_globale['smtp_auth']) {
$mail->SMTPAuth = true;
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
}
break;
case 'lbsmtp':
$CURRENT_ID = @current($cnx->query("SELECT MAX( id_use ) AS CURRENT_ID
FROM ".$row_config_globale['table_smtp'])->fetch());
$info_smtp_lb = $cnx->SqlRow("SELECT *
FROM ".$row_config_globale['table_smtp']."
WHERE smtp_used < smtp_limite
AND smtp_date_update > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
ORDER BY id_use ASC LIMIT 1");
$mail->IsSMTP();
$mail->SMTPDebug = false;
if($info_smtp_lb['smtp_user']!=''){
$mail->SMTPAuth = true;
$mail->Username = $info_smtp_lb['smtp_user'];
$mail->Password = $info_smtp_lb['smtp_pass'];
}
if($info_smtp_lb['smtp_secure']!=''){
$mail->SMTPSecure = $info_smtp_lb['smtp_secure'];
}
$mail->Host = $info_smtp_lb['smtp_url'];
if($info_smtp_lb['smtp_url']=='smtp.gmail.com'){
$mail->IsHTML(true);
}
if($info_smtp_lb['smtp_port']!=''){
$mail->Port = $info_smtp_lb['smtp_port'];
}else{
$mail->Port = 25;
}
$cnx->query('UPDATE '.$row_config_globale['table_smtp'].'
SET smtp_used=smtp_used+1,
id_use=' . (intval($CURRENT_ID)+1) . ',
smtp_date_update=NOW()
WHERE smtp_id='.$info_smtp_lb['smtp_id']);
$daylog = @fopen('logs/daylog-' . date("Y-m-d") . '.txt', 'a+');
$daylogmsg= date("Y-m-d H:i:s") . " : envoi à " . $addr[$i]['email'] . " sur serveur " . $info_smtp_lb['smtp_name'] . "\n";
fwrite($daylog, $daylogmsg, strlen($daylogmsg));
fclose($daylog);
$handler = @fopen('logs/list' . $list_id . '-msg' . $msg_id . '.txt', 'a+');
$daylogmsg= date("Y-m-d H:i:s") . " : envoi à " . $addr[$i]['email'] . " sur serveur " . $info_smtp_lb['smtp_name'] . "\n";
fwrite($handler, $daylogmsg, strlen($daylogmsg));
fclose($handler);
break;
case "smtp_over_tls":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = $row_config_globale['smtp_host'];
$mail->Port = 587;
$mail->IsHTML(true);
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
break;
case "smtp_over_ssl":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = $row_config_globale['smtp_host'];
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
break;
case "smtp_gmail_tls":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->IsHTML(true);
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
break;
case "smtp_gmail_ssl":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
break;
case "php_mail":
case "php_mail_infomaniak":
$mail->IsMail();
break;
case "smtp_mutu_ovh":
$mail->IsSMTP();
$mail->Port = 587;
$mail->Host = 'ssl0.ovh.net';
if ($row_config_globale['smtp_auth']) {
$mail->SMTPAuth = true;
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
}
break;
case "smtp_mutu_1and1":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->Host = 'auth.smtp.1and1.fr';
if ($row_config_globale['smtp_auth']) {
$mail->SMTPAuth = true;
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
}
break;
case "smtp_mutu_gandi":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Host = 'mail.gandi.net';
if ($row_config_globale['smtp_auth']) {
$mail->SMTPAuth = true;
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
}
break;
case "smtp_mutu_online":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Port = 587;
$mail->Host = 'smtpauth.online.net';
if ($row_config_globale['smtp_auth']) {
$mail->SMTPAuth = true;
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
}
break;
case "smtp_mutu_infomaniak":
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Port = 587;
$mail->Host = 'mail.infomaniak.ch';
if ($row_config_globale['smtp_auth']) {
$mail->SMTPAuth = true;
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
}
break;
case "smtp_one_com":
$mail->IsSMTP();
$mail->SMTPAuth = false;
$mail->Port = 25;
$mail->Host = 'mailout.one.com';
break;
case "smtp_one_com_ssl":
require_once(__DIR__.'/class.pop3.php');
$pop = new POP3();
$pop->Authorise("send.one.com", 465, 30, $row_config_globale['smtp_login'], $row_config_globale['smtp_pass'], 1);
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'send.one.com';
$mail->Username = $row_config_globale['smtp_login'];
$mail->Password = $row_config_globale['smtp_pass'];
break;
default:
die(tr("NO_SEND_DEFINITION"));
break;
}
wget 'https://sme10.lists2.roe3.org/pmnl3/include/lib/switch_ua.php'
<?php
/*
* https://svn.apache.org/repos/asf/spamassassin/branches/b2_4_0/rules/20_anti_ratware.cf
* https://mail.python.org/pipermail/mailman-developers/2011-November/021593.html
* http://www.greenend.org.uk/rjk/spoolstats/agents.html
* http://www.l0d.org/user_agent
*/
$user_agent = array(
//User-Agent =~ /^Mozilla\/5\.\d+ \(.*\) Gecko\/\d{8}(?: |$)/
'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.5.1',
'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.5.0',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.5.1',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.5.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.5.1',
'Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Thunderbird/38.4.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.5.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:38.0) Gecko/20100101 Thunderbird/38.5.1',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0 SeaMonkey/2.39',
'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0 SeaMonkey/2.39',
'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.5.1',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:38.0) Gecko/20100101 Thunderbird/38.5.0',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070728 Thunderbird/2.0.0.6 Mnenhy/0.7.6.666',
'Mozilla/5.0 (X11; Linux i686 on x86_64; rv:42.0) Gecko/20100101 Firefox/42.0 SeaMonkey/2.39',
//user-Agent =~ /^Mutt\/\d(?:\.\d+){1,4}/
'Mutt/1.2.5.1i',
'Mutt/1.2.5i',
'Mutt/1.3.25i',
'Mutt/1.3.28i',
'Mutt/1.4.1i',
'Mutt/1.4.2.1i',
'Mutt/1.4i',
'Mutt/1.5.24 (2015-08-30)',
'Mutt/1.5.3i',
'Mutt/1.5.4i',
'Mutt/1.5.5.1+cvs20040105i',
'Mutt/1.5.5.1i',
'Mutt/1.5.6i',
//X-Mailer =~ /^Mozilla 4\.\d{2} \[[a-z]{2}\]/
'Mozilla 4.8 [en] (Windows NT 5.0; U)',
'Mozilla 4.73 [en]C-CCK-MCD VERIZON473 (Win98; U)',
'Mozilla 4.75 [de] (Win98; U)',
'Mozilla 4.79 [en] (Win98; U)',
'Mozilla 4.08 [en] (Win16; U)',
//User-Agent =~ /^Microsoft[ -]Outlook[ -]Express[ -]Macintosh[ -]Edition/
'Microsoft-Outlook-Express-Macintosh-Edition/5.02.2022',
//X-Mailer =~ /^Microsoft Outlook [A-Z]{3}, Build [89]\.0\.[1-3]\d{3} \([89]\.0\.[1-3]\d{3}\.0\)$/
'Microsoft Outlook Express 6.00.3790.3959',
'Microsoft Outlook Express 6.00.2900.5931',
'Microsoft Outlook Express 6.00.2900.5843',
'Microsoft Outlook Express 6.00.2900.5512',
'Microsoft Outlook Express 6.00.2900.2180',
'Microsoft Outlook Express 6.00.2900.3664',
'Microsoft Outlook Express 5.00.2615.200',
'Microsoft Outlook 14.0',
'Microsoft Outlook 15.0',
// X-Mailer =~ /^Microsoft Windows Live Mail 16.4.3522.110
'Microsoft Windows Live Mail 16.4.3522.110',
'Microsoft Windows Live Mail 16.4.3505.912',
// X-Mailer=~ /^Microsoft Office Outlook
'X-Mailer: Microsoft Office Outlook 12.0',
//User-Agent =~ /^Microsoft-Entourage\/\d{1,2}(?:\.\d){1,2}\.\d{4}$/
'Microsoft-Entourage/11.4.0.080122',
'Microsoft-Entourage/12.30.0.110427',
//User-Agent =~ /^KMail\/1\.\d\.\d+$/
'KMail/1.4.1',
'KMail/1.4.3',
'KMail/1.5',
'KMail/1.5.1',
'KMail/1.5.2',
'KMail/1.5.3',
'KMail/1.5.4',
'KMail/1.5.93',
'KMail/1.6',
'KMail/1.6.1',
'KMail/1.6.2',
'KMail/1.9.10 (enterprise35 0.20100827.1168748)',
//User-Agent =~ /^Internet Messaging Program \(IMP\) [34]\.\d/
'Internet Messaging Program (IMP) 3.0',
'Internet Messaging Program (IMP) 3.1',
'Internet Messaging Program (IMP) 3.1 / FreeBSD-4.6',
'Internet Messaging Program (IMP) 3.2',
'Internet Messaging Program (IMP) 3.2.1',
'Internet Messaging Program (IMP) 3.2.1 / FreeBSD-5.0 ',
'Internet Messaging Program (IMP) 3.2.2',
'Internet Messaging Program (IMP) 3.2.2-cvs',
'Internet Messaging Program (IMP) 3.2.3',
'Internet Messaging Program (IMP) 3.2.3-cvs',
'Internet Messaging Program (IMP) 4.0-cvs',
//X-Mailer =~ /^T-Online (?:e|Web)Mail \d\.\d+$/
//X-Mailer =~ /^Apple Mail \(\d\.\d+\)$/
'Apple Mail (2.3112)',
'Apple Mail (2.1510)',
'Apple Mail (2.1283)',
'Apple Mail (2.1085)',
//User-Agent =~ /^Gnus\/\d\.\d+ /
'Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)',
'Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux)',
'Gnus/5.13 (Gnus v5.13) Emacs/23.4 (gnu/linux)',
'Gnus/5.13 (Gnus v5.13) Emacs/24.4 (gnu/linux)',
'Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux)',
'Gnus/5.13 (Gnus v5.13) Emacs/24.5 (darwin)',
'Gnus/5.13 (Gnus v5.13) Emacs/24.4 (darwin)',
'Gnus/5.130014 (Ma Gnus v0.14) Emacs/24.5 (x86_64-pc-linux-gnu)',
'Gnus/5.13 (Gnus v5.13) Emacs/23.2 (gnu/linux)',
'Gnus/5.13 (Gnus v5.13) Emacs/24.3 (windows-nt)',
'Gnus/5.09 (Gnus v5.9.0) Emacs/21.2',
'Gnus/5.1002 (Gnus v5.10.2) Emacs/21.2 (gnu/linux)',
'Gnus/5.1002 (Gnus v5.10.2) Emacs/21.3 (berkeley-unix)',
'Gnus/5.1003 (Gnus v5.10.3) Emacs/21.3 (gnu/linux)',
'Gnus/5.1008 (Gnus v5.10.8) Emacs/21.3 (irix)',
'Gnus/5.1008 (Gnus v5.10.8) XEmacs/21.4.22 (darwin)',
//X-Mailer =~ /^Gnus v\d(?:\.\d+){1,2}\/X?Emacs \d+\.\d+/
'Gnus v5.7/Emacs 20.7',
);