'; foreach($supported_languages as $lang => $lang_name) { if ($lang == $current_lang) { $selected = ' selected="selected"'; } else { $selected = ''; } $selector .= ""; } $selector .= ""; return $selector; } // // check_string // Action: checks if a string is valid and returns TRUE if this is the case. // Call: check_string (string var) // function check_string ($var) { if (preg_match ('/^([A-Za-z0-9 ]+)+$/', $var)) { return true; } else { return false; } } // // check_domain // Action: Checks if domain is valid and returns TRUE if this is the case. // Call: check_domain (string domain) // // TODO: make check_domain able to handle as example .local domains function check_domain ($domain) { global $CONF; global $PALANG; if (!preg_match ('/^([-0-9A-Z]+\.)+' . '([0-9A-Z]){2,6}$/i', ($domain))) { flash_error(sprintf($PALANG['pInvalidDomainRegex'], htmlentities($domain))); return false; } if (isset($CONF['emailcheck_resolve_domain']) && 'YES' == $CONF['emailcheck_resolve_domain'] && 'WINDOWS'!=(strtoupper(substr(php_uname('s'), 0, 7)))) { // Look for an AAAA, A, or MX record for the domain if(function_exists('checkdnsrr')) { // AAAA (IPv6) is only available in PHP v. >= 5 if (version_compare(phpversion(), "5.0.0", ">=")) { if (checkdnsrr($domain,'AAAA')) return true; } if (checkdnsrr($domain,'A')) return true; if (checkdnsrr($domain,'MX')) return true; flash_error(sprintf($PALANG['pInvalidDomainDNS'], htmlentities($domain))); return false; } else { flash_error("emailcheck_resolve_domain is enabled, but function (checkdnsrr) missing!"); } } return true; } /** * check_email * Checks if an email is valid - if it is, return true, else false. * @param String $email - a string that may be an email address. * @return boolean true if it's an email address, else false. * TODO: make check_email able to handle already added domains * TODO: don't use flash_error, use return value instead */ function check_email ($email) { global $CONF; global $PALANG; $ce_email=$email; //strip the vacation domain out if we are using it //and change from blah#foo.com@autoreply.foo.com to blah@foo.com if ($CONF['vacation'] == 'YES') { $vacation_domain = $CONF['vacation_domain']; $ce_email = preg_replace("/@$vacation_domain\$/", '', $ce_email); $ce_email = preg_replace("/#/", '@', $ce_email); } // Perform non-domain-part sanity checks if (!preg_match ('/^[-!#$%&\'*+\\.\/0-9=?A-Z^_{|}~]+' . '@' . '[^@]+$/i', $ce_email)) { flash_error($PALANG['pInvalidMailRegex']); return false; } // Determine domain name $matches=array(); if (!preg_match('|@(.+)$|',$ce_email,$matches)) { flash_error($PALANG['pInvalidMailRegex']); return false; } $domain=$matches[1]; # check domain name return check_domain($domain); } /** * Clean a string, escaping any meta characters that could be * used to disrupt an SQL string. i.e. "'" => "\'" etc. * * @param String (or Array) * @return String (or Array) of cleaned data, suitable for use within an SQL * statement. */ function escape_string ($string) { global $CONF; // if the string is actually an array, do a recursive cleaning. // Note, the array keys are not cleaned. if(is_array($string)) { $clean = array(); foreach(array_keys($string) as $row) { $clean[$row] = escape_string($string[$row]); } return $clean; } if (get_magic_quotes_gpc ()) { $string = stripslashes($string); } if (!is_numeric($string)) { $link = db_connect(); if ($CONF['database_type'] == "mysql") { $escaped_string = mysql_real_escape_string($string, $link); } if ($CONF['database_type'] == "mysqli") { $escaped_string = mysqli_real_escape_string($link, $string); } if ($CONF['database_type'] == "pgsql") { // php 5.2+ allows for $link to be specified. if (version_compare(phpversion(), "5.2.0", ">=")) { $escaped_string = pg_escape_string($link, $string); } else { $escaped_string = pg_escape_string($string); } } } else { $escaped_string = $string; } return $escaped_string; } /** * safeget * Action: get value from $_GET[$param], or $default if $_GET[$param] is not set * Call: $param = safeget('param') # replaces $param = $_GET['param'] * - or - * $param = safeget('param', 'default') * * @param String parameter name. * @param String (optional) - default value if key is not set. * @return String */ function safeget ($param, $default="") { $retval=$default; if (isset($_GET[$param])) $retval=$_GET[$param]; return $retval; } /** * safepost - similar to safeget() * @see safeget() * @param String parameter name * @param String (optional) default value (defaults to "") * @return String - value in $_POST[$param] or $default * same as safeget, but for $_POST */ function safepost ($param, $default="") { $retval=$default; if (isset($_POST[$param])) $retval=$_POST[$param]; return $retval; } /** * safeserver * @see safeget() * @param String $param * @param String $default (optional) * @return String value from $_SERVER[$param] or $default */ function safeserver ($param, $default="") { $retval=$default; if (isset($_SERVER[$param])) $retval=$_SERVER[$param]; return $retval; } /** * safecookie * @see safeget() * @param String $param * @param String $default (optional) * @return String value from $_COOKIE[$param] or $default */ function safecookie ($param, $default="") { $retval=$default; if (isset($_COOKIE[$param])) $retval=$_COOKIE[$param]; return $retval; } /** * pacol * @param int $allow_editing * @param int $display_in_form * @param int display_in_list * @param String $type * @param String PALANG_label * @param String PALANG_desc * @param any optional $default * @param array optional $options * @param int $not_in_db * @return array for $struct */ function pacol($allow_editing, $display_in_form, $display_in_list, $type, $PALANG_label, $PALANG_desc, $default = "", $options = array(), $not_in_db=0, $dont_write_to_db=0, $select="", $extrafrom="") { if ($PALANG_label != '') $PALANG_label = Lang::Read($PALANG_label); if ($PALANG_desc != '') $PALANG_desc = Lang::Read($PALANG_desc ); return array( 'editable' => $allow_editing, 'display_in_form' => $display_in_form, 'display_in_list' => $display_in_list, 'type' => $type, 'label' => $PALANG_label, # $PALANG field label 'desc' => $PALANG_desc, # $PALANG field description 'default' => $default, 'options' => $options, 'not_in_db' => $not_in_db, 'dont_write_to_db' => $dont_write_to_db, 'select' => $select, # replaces the field name after SELECT 'extrafrom' => $extrafrom, # added after FROM xy - useful for JOINs etc. ); } // // get_domain_properties // Action: Get all the properties of a domain. // Call: get_domain_properties (string domain) // function get_domain_properties ($domain) { $handler = new DomainHandler(); if (!$handler->init($domain)) { die("Error: " . join("\n", $handler->errormsg)); } if (!$handler->view()) { die("Error: " . join("\n", $handler->errormsg)); } $result = $handler->return; return $result; } /** * create_page_browser * Action: Get page browser for a long list of mailboxes, aliases etc. * Call: $pagebrowser = create_page_browser('table.field', 'query', 50) # replaces $param = $_GET['param'] * * @param String idxfield - database field name to use as title * @param String query - core part of the query (starting at "FROM") * @return String */ function create_page_browser($idxfield, $querypart) { global $CONF; $page_size = (int) $CONF['page_size']; $label_len = 2; $pagebrowser = array(); if ($page_size < 2) { # will break the page browser die('$CONF[\'page_size\'] must be 2 or more!'); } # get number of rows $query = "SELECT count(*) as counter FROM (SELECT $idxfield $querypart) AS tmp"; $result = db_query ($query); if ($result['rows'] > 0) { $row = db_array ($result['result']); $count_results = $row['counter'] -1; # we start counting at 0, not 1 } # echo "
rows: " . ($count_results +1) . " --- $query"; if ($count_results < $page_size) { return array(); # only one page - no pagebrowser required } # init row counter $initcount = "SET @row=-1"; if ('pgsql'==$CONF['database_type']) { $initcount = "CREATE TEMPORARY SEQUENCE rowcount MINVALUE 0"; } $result = db_query($initcount); # get labels for relevant rows (first and last of each page) $page_size_zerobase = $page_size - 1; $query = " SELECT * FROM ( SELECT $idxfield AS label, @row := @row + 1 AS row $querypart ) idx WHERE MOD(idx.row, $page_size) IN (0,$page_size_zerobase) OR idx.row = $count_results "; if ('pgsql'==$CONF['database_type']) { $query = " SELECT * FROM ( SELECT $idxfield AS label, nextval('rowcount') AS row $querypart ) idx WHERE MOD(idx.row, $page_size) IN (0,$page_size_zerobase) OR idx.row = $count_results "; } # echo "
$query"; # TODO: $query is MySQL-specific # PostgreSQL: # http://www.postgresql.org/docs/8.1/static/sql-createsequence.html # http://www.postgresonline.com/journal/archives/79-Simulating-Row-Number-in-PostgreSQL-Pre-8.4.html # http://www.pg-forum.de/sql/1518-nummerierung-der-abfrageergebnisse.html # CREATE TEMPORARY SEQUENCE foo MINVALUE 0 MAXVALUE $page_size_zerobase CYCLE # afterwards: DROP SEQUENCE foo $result = db_query ($query); if ($result['rows'] > 0) { while ($row = db_array ($result['result'])) { if ($row2 = db_array ($result['result'])) { $label = substr($row['label'],0,$label_len) . '-' . substr($row2['label'],0,$label_len); $pagebrowser[] = $label; } else { # only one row remaining $label = substr($row['label'],0,$label_len); $pagebrowser[] = $label; } } } if ('pgsql'==$CONF['database_type']) { db_query ("DROP SEQUENCE rowcount"); } return $pagebrowser; } // // get_mailbox_properties // Action: Get all the properties of a mailbox. // Call: get_mailbox_properties (string mailbox) // function get_mailbox_properties ($username) { global $CONF; global $table_mailbox; $query="SELECT * FROM $table_mailbox WHERE username='$username'"; if ('pgsql'==$CONF['database_type']) { $query=" SELECT *, EXTRACT(epoch FROM created) AS uts_created, EXTRACT(epoch FROM modified) AS uts_modified FROM $table_mailbox WHERE username='$username' "; } $result = db_query ($query); $row = db_array ($result['result']); $list['name'] = $row['name']; $list['maildir'] = $row['maildir']; $list['quota'] = $row['quota']; $list['domain'] = $row['domain']; $list['created'] = $row['created']; $list['modified'] = $row['modified']; $list['active'] = $row['active']; if ($CONF['database_type'] == "pgsql") { $list['active']=('t'==$row['active']) ? 1 : 0; $list['created']= gmstrftime('%c %Z',$row['uts_created']); $list['modified']= gmstrftime('%c %Z',$row['uts_modified']); } else { $list['active'] = $row['active']; } return $list; } // // check_quota // Action: Checks if the user is creating a mailbox with the correct quota // Call: check_quota (string domain) // # TODO: move to MailboxHandler # TODO: merge with allowed_quota? function check_quota ($quota, $domain, $username="") { global $CONF; $rval = false; if ($CONF['quota'] == "NO") { return true; # enforcing quotas is disabled - just allow it } $limit = get_domain_properties ($domain); if ($limit['maxquota'] == 0) { $rval = true; # maxquota unlimited -> OK, but domain level quota could still be hit } if (($limit['maxquota'] < 0) and ($quota < 0)) { return true; # maxquota and $quota are both disabled -> OK, no need for more checks } if (($limit['maxquota'] > 0) and ($quota == 0)) { return false; # mailbox with unlimited quota on a domain with maxquota restriction -> not allowed, no more checks needed } if ($limit['maxquota'] != 0 && $quota > $limit['maxquota']) { return false; # mailbox bigger than maxquota restriction (and maxquota != unlimited) -> not allowed, no more checks needed } else { $rval = true; # mailbox size looks OK, but domain level quota could still be hit } # TODO: detailed error message ("domain quota exceeded", "mailbox quota too big" etc.) via flash_error? Or "available quota: xxx MB"? if (!$rval || $CONF['domain_quota'] != 'YES') { return $rval; } elseif ($limit['quota'] <= 0) { # TODO: CHECK - 0 (unlimited) is fine, not sure about <= -1 (disabled)... $rval = true; } else { $table_mailbox = table_by_key('mailbox'); $query = "SELECT SUM(quota) FROM $table_mailbox WHERE domain = '" . escape_string($domain) . "'"; if ($username != "") { $query .= " AND username != '" . escape_string($username) . "'"; } $result = db_query ($query); $row = db_row ($result['result']); $cur_quota_total = divide_quota($row[0]); # convert to MB if ( ($quota + $cur_quota_total) > $limit['quota'] ) { $rval = false; } else { $rval = true; } } return $rval; } /** * Get allowed maximum quota for a mailbox * @param String $domain * @param Integer $current_user_quota (in bytes) * @return Integer allowed maximum quota (in MB) */ function allowed_quota($domain, $current_user_quota) { $domain_properties = get_domain_properties($domain); $tMaxquota = $domain_properties['maxquota']; if (boolconf('domain_quota') && $domain_properties['quota']) { $dquota = $domain_properties['quota'] - $domain_properties['total_quota'] + divide_quota($current_user_quota); if ($dquota < $tMaxquota) { $tMaxquota = $dquota; } if ($tMaxquota == 0) { $tMaxquota = $dquota; } } return $tMaxquota; } // // divide_quota // Action: Recalculates the quota from MBs to bytes (divide, /) // Call: divide_quota (string $quota) // function divide_quota ($quota) { global $CONF; if ($quota == -1) return $quota; $value = round($quota / $CONF['quota_multiplier'],2); return $value; } // // check_owner // Action: Checks if the admin is the owner of the domain (or global-admin) // Call: check_owner (string admin, string domain) // function check_owner ($username, $domain) { global $table_domain_admins; $E_username = escape_string($username); $E_domain = escape_string($domain); $result = db_query ("SELECT 1 FROM $table_domain_admins WHERE username='$E_username' AND (domain='$E_domain' OR domain='ALL') AND active='1'"); if ($result['rows'] == 1 || $result['rows'] == 2) { # "ALL" + specific domain permissions is possible # TODO: if superadmin, check if given domain exists in the database return true; } else { if ($result['rows'] > 2) { # more than 2 results means something really strange happened... flash_error("Permission check returned multiple results. Please go to 'edit admin' for your username and press the save " . "button once to fix the database. If this doesn't help, open a bugreport."); } return false; } } // // check_alias_owner // Action: Checks if the admin is the owner of the alias. // Call: check_alias_owner (string admin, string alias) // function check_alias_owner ($username, $alias) { global $CONF; if (authentication_has_role('global-admin')) return true; $tmp = preg_split('/\@/', $alias); if (($CONF['special_alias_control'] == 'NO') && array_key_exists($tmp[0], $CONF['default_aliases'])) { return false; } else { return true; } } /** * List domains for an admin user. * @param String $username * @return array of domain names. */ function list_domains_for_admin ($username) { global $CONF; global $table_domain, $table_domain_admins; $E_username = escape_string($username); $query = "SELECT $table_domain.domain FROM $table_domain "; $condition[] = "$table_domain.domain != 'ALL'"; $result = db_query ("SELECT username FROM $table_domain_admins WHERE username='$E_username' AND domain='ALL'"); if ($result['rows'] < 1) { # not a superadmin $query .= " LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain "; $condition[] = "$table_domain_admins.username='$E_username' "; $condition[] = "$table_domain.active='" . db_get_boolean(true) . "'"; # TODO: does it really make sense to exclude inactive... $condition[] = "$table_domain.backupmx='" . db_get_boolean(False) . "'"; # TODO: ... and backupmx domains for non-superadmins? } $query .= " WHERE " . join(' AND ', $condition); $query .= " ORDER BY $table_domain.domain"; $list = array (); $result = db_query ($query); if ($result['rows'] > 0) { $i = 0; while ($row = db_array ($result['result'])) { $list[$i] = $row['domain']; $i++; } } return $list; } // // list_domains // Action: List all available domains. // Call: list_domains () // function list_domains () { global $table_domain; $list = array(); $result = db_query ("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain"); if ($result['rows'] > 0) { $i = 0; while ($row = db_array ($result['result'])) { $list[$i] = $row['domain']; $i++; } } return $list; } // // admin_exist // Action: Checks if the admin already exists. // Call: admin_exist (string admin) // function admin_exist ($username) { $result = db_query ("SELECT 1 FROM " . table_by_key ('admin') . " WHERE username='$username'"); if ($result['rows'] != 1) { return false; } else { return true; } } // // domain_exist // Action: Checks if the domain already exists. // Call: domain_exist (string domain) // function domain_exist ($domain) { global $table_domain; $result = db_query("SELECT 1 FROM $table_domain WHERE domain='$domain'"); if ($result['rows'] != 1) { return false; } else { return true; } } // // list_admins // Action: Lists all the admins // Call: list_admins () // // was admin_list_admins // function list_admins () { $handler = new AdminHandler(); if ($handler->getList('1=1')) { $list = $handler->result(); } else { $list = array(); # TODO: check if there was an error or simply no admins (which shouldn't happen because nobody could login then...) } return $list; } // // encode_header // Action: Encode a string according to RFC 1522 for use in headers if it contains 8-bit characters. // Call: encode_header (string header, string charset) // function encode_header ($string, $default_charset = "utf-8") { if (strtolower ($default_charset) == 'iso-8859-1') { $string = str_replace ("\240",' ',$string); } $j = strlen ($string); $max_l = 75 - strlen ($default_charset) - 7; $aRet = array (); $ret = ''; $iEncStart = $enc_init = false; $cur_l = $iOffset = 0; for ($i = 0; $i < $j; ++$i) { switch ($string{$i}) { case '=': case '<': case '>': case ',': case '?': case '_': if ($iEncStart === false) { $iEncStart = $i; } $cur_l+=3; if ($cur_l > ($max_l-2)) { $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset); $aRet[] = "=?$default_charset?Q?$ret?="; $iOffset = $i; $cur_l = 0; $ret = ''; $iEncStart = false; } else { $ret .= sprintf ("=%02X",ord($string{$i})); } break; case '(': case ')': if ($iEncStart !== false) { $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset); $aRet[] = "=?$default_charset?Q?$ret?="; $iOffset = $i; $cur_l = 0; $ret = ''; $iEncStart = false; } break; case ' ': if ($iEncStart !== false) { $cur_l++; if ($cur_l > $max_l) { $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset); $aRet[] = "=?$default_charset?Q?$ret?="; $iOffset = $i; $cur_l = 0; $ret = ''; $iEncStart = false; } else { $ret .= '_'; } } break; default: $k = ord ($string{$i}); if ($k > 126) { if ($iEncStart === false) { // do not start encoding in the middle of a string, also take the rest of the word. $sLeadString = substr ($string,0,$i); $aLeadString = explode (' ',$sLeadString); $sToBeEncoded = array_pop ($aLeadString); $iEncStart = $i - strlen ($sToBeEncoded); $ret .= $sToBeEncoded; $cur_l += strlen ($sToBeEncoded); } $cur_l += 3; // first we add the encoded string that reached it's max size if ($cur_l > ($max_l-2)) { $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset); $aRet[] = "=?$default_charset?Q?$ret?= "; $cur_l = 3; $ret = ''; $iOffset = $i; $iEncStart = $i; } $enc_init = true; $ret .= sprintf ("=%02X", $k); } else { if ($iEncStart !== false) { $cur_l++; if ($cur_l > $max_l) { $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset); $aRet[] = "=?$default_charset?Q?$ret?="; $iEncStart = false; $iOffset = $i; $cur_l = 0; $ret = ''; } else { $ret .= $string{$i}; } } } break; # end switch } } if ($enc_init) { if ($iEncStart !== false) { $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset); $aRet[] = "=?$default_charset?Q?$ret?="; } else { $aRet[] = substr ($string,$iOffset); } $string = implode ('',$aRet); } return $string; } // // generate_password // Action: Generates a random password // Call: generate_password () // function generate_password () { global $CONF; // length of the generated password $length = 8; // define possible characters $possible = "2345678923456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; # skip 0 and 1 to avoid confusion with O and l // add random characters to $password until $length is reached $password = ""; while (strlen($password) < $length) { // pick a random character from the possible ones $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); // we don't want this character if it's already in the password if (!strstr($password, $char)) { $password .= $char; } } return $password; } /** * Check if a password is strong enough based on the conditions in $CONF['password_validation'] * @param String $password * @return array of error messages, or empty array if the password is ok */ function validate_password($password) { global $CONF; global $PALANG; $result = array(); if (isset($CONF['min_password_length'])) { # used up to 2.3.x - check it for backward compatibility $minlen = (int) $CONF['min_password_length']; $CONF['password_validation']['/.{' . $minlen . '}/'] = "password_too_short $minlen"; } foreach ($CONF['password_validation'] as $regex => $message) { if (!preg_match($regex, $password)) { $msgparts = preg_split("/ /", $message, 2); if (count($msgparts) == 1) { $result[] = $PALANG[$msgparts[0]]; } else { $result[] = sprintf($PALANG[$msgparts[0]], $msgparts[1]); } } } return $result; } /** * Encrypt a password, using the apparopriate hashing mechanism as defined in * config.inc.php ($CONF['encrypt']). * When wanting to compare one pw to another, it's necessary to provide the salt used - hence * the second parameter ($pw_db), which is the existing hash from the DB. * * @param string $pw * @param string $encrypted password * @return string encrypted password. */ function pacrypt ($pw, $pw_db="") { global $CONF; $pw = stripslashes($pw); $password = ""; $salt = ""; if ($CONF['encrypt'] == 'md5crypt') { $split_salt = preg_split ('/\$/', $pw_db); if (isset ($split_salt[2])) { $salt = $split_salt[2]; } $password = md5crypt ($pw, $salt); } elseif ($CONF['encrypt'] == 'md5') { $password = md5($pw); } elseif ($CONF['encrypt'] == 'system') { if (preg_match("/\\$1\\$/", $pw_db)) { $split_salt = preg_split ('/\$/', $pw_db); $salt = "\$1\$${split_salt[2]}\$"; } else { if (strlen($pw_db) == 0) { $salt = substr (md5 (mt_rand ()), 0, 2); } else { $salt = substr ($pw_db, 0, 2); } } $password = crypt ($pw, $salt); } elseif ($CONF['encrypt'] == 'cleartext') { $password = $pw; } // See https://sourceforge.net/tracker/?func=detail&atid=937966&aid=1793352&group_id=191583 // this is apparently useful for pam_mysql etc. elseif ($CONF['encrypt'] == 'mysql_encrypt') { $pw = escape_string($pw); if ($pw_db!="") { $salt=escape_string(substr($pw_db,0,2)); $res=db_query("SELECT ENCRYPT('".$pw."','".$salt."');"); } else { $res=db_query("SELECT ENCRYPT('".$pw."');"); } $l = db_row($res["result"]); $password = $l[0]; } elseif ($CONF['encrypt'] == 'authlib') { $flavor = $CONF['authlib_default_flavor']; $salt = substr(create_salt(), 0, 2); # courier-authlib supports only two-character salts if(preg_match('/^{.*}/', $pw_db)) { // we have a flavor in the db -> use it instead of default flavor $result = preg_split('/[{}]/', $pw_db, 3); # split at { and/or } $flavor = $result[1]; $salt = substr($result[2], 0, 2); } if(stripos($flavor, 'md5raw') === 0) { $password = '{' . $flavor . '}' . md5($pw); } elseif(stripos($flavor, 'md5') === 0) { $password = '{' . $flavor . '}' . base64_encode(md5($pw, TRUE)); } elseif(stripos($flavor, 'crypt') === 0) { $password = '{' . $flavor . '}' . crypt($pw, $salt); } elseif(stripos($flavor, 'SHA') === 0) { $password = '{' . $flavor . '}' . base64_encode(sha1($pw, TRUE)); } else { die("authlib_default_flavor '" . $flavor . "' unknown. Valid flavors are 'md5raw', 'md5', 'SHA' and 'crypt'"); } } elseif (preg_match("/^dovecot:/", $CONF['encrypt'])) { $split_method = preg_split ('/:/', $CONF['encrypt']); $method = strtoupper($split_method[1]); if (! preg_match("/^[A-Z0-9-]+$/", $method)) { die("invalid dovecot encryption method"); } # TODO: check against a fixed list? if (strtolower($method) == 'md5-crypt') die("\$CONF['encrypt'] = 'dovecot:md5-crypt' will not work because dovecotpw generates a random salt each time. Please use \$CONF['encrypt'] = 'md5crypt' instead."); $dovecotpw = "dovecotpw"; if (!empty($CONF['dovecotpw'])) $dovecotpw = $CONF['dovecotpw']; # Use proc_open call to avoid safe_mode problems and to prevent showing plain password in process table $spec = array( 0 => array("pipe", "r"), // stdin 1 => array("pipe", "w"), // stdout 2 => array("pipe", "w"), // stderr ); $pipe = proc_open("$dovecotpw '-s' $method", $spec, $pipes); if (!$pipe) { die("can't proc_open $dovecotpw"); } else { // use dovecot's stdin, it uses getpass() twice // Write pass in pipe stdin fwrite($pipes[0], $pw . "\n", 1+strlen($pw)); usleep(1000); fwrite($pipes[0], $pw . "\n", 1+strlen($pw)); fclose($pipes[0]); // Read hash from pipe stdout $password = fread($pipes[1], "200"); if ( !preg_match('/^\{' . $method . '\}/', $password)) { $stderr_output = stream_get_contents($pipes[2]); error_log('dovecotpw password encryption failed.'); error_log('STDERR output: ' . $stderr_output); die("can't encrypt password with dovecotpw, see error log for details"); } fclose($pipes[1]); fclose($pipes[2]); proc_close($pipe); $password = trim(str_replace('{' . $method . '}', '', $password)); } } else { die ('unknown/invalid $CONF["encrypt"] setting: ' . $CONF['encrypt']); } return $password; } // // md5crypt // Action: Creates MD5 encrypted password // Call: md5crypt (string cleartextpassword) // function md5crypt ($pw, $salt="", $magic="") { $MAGIC = "$1$"; if ($magic == "") $magic = $MAGIC; if ($salt == "") $salt = create_salt (); $slist = explode ("$", $salt); if ($slist[0] == "1") $salt = $slist[1]; $salt = substr ($salt, 0, 8); $ctx = $pw . $magic . $salt; $final = hex2bin (md5 ($pw . $salt . $pw)); for ($i=strlen ($pw); $i>0; $i-=16) { if ($i > 16) { $ctx .= substr ($final,0,16); } else { $ctx .= substr ($final,0,$i); } } $i = strlen ($pw); while ($i > 0) { if ($i & 1) $ctx .= chr (0); else $ctx .= $pw[0]; $i = $i >> 1; } $final = hex2bin (md5 ($ctx)); for ($i=0;$i<1000;$i++) { $ctx1 = ""; if ($i & 1) { $ctx1 .= $pw; } else { $ctx1 .= substr ($final,0,16); } if ($i % 3) $ctx1 .= $salt; if ($i % 7) $ctx1 .= $pw; if ($i & 1) { $ctx1 .= substr ($final,0,16); } else { $ctx1 .= $pw; } $final = hex2bin (md5 ($ctx1)); } $passwd = ""; $passwd .= to64 (((ord ($final[0]) << 16) | (ord ($final[6]) << 8) | (ord ($final[12]))), 4); $passwd .= to64 (((ord ($final[1]) << 16) | (ord ($final[7]) << 8) | (ord ($final[13]))), 4); $passwd .= to64 (((ord ($final[2]) << 16) | (ord ($final[8]) << 8) | (ord ($final[14]))), 4); $passwd .= to64 (((ord ($final[3]) << 16) | (ord ($final[9]) << 8) | (ord ($final[15]))), 4); $passwd .= to64 (((ord ($final[4]) << 16) | (ord ($final[10]) << 8) | (ord ($final[5]))), 4); $passwd .= to64 (ord ($final[11]), 2); return "$magic$salt\$$passwd"; } function create_salt () { srand ((double) microtime ()*1000000); $salt = substr (md5 (rand (0,9999999)), 0, 8); return $salt; } /**/ if (!function_exists('hex2bin')) { # PHP around 5.3.8 includes hex2bin as native function - http://php.net/hex2bin function hex2bin ($str) { $len = strlen ($str); $nstr = ""; for ($i=0;$i<$len;$i+=2) { $num = sscanf (substr ($str,$i,2), "%x"); $nstr.=chr ($num[0]); } return $nstr; } /**/ } /* * remove item $item from array $array */ function remove_from_array($array, $item) { # array_diff might be faster, but doesn't provide an easy way to know if the value was found or not # return array_diff($array, array($item)); $ret = array_search($item, $array); if ($ret === false) { $found = 0; } else { $found = 1; unset ($array[$ret]); } return array($found, $array); } function to64 ($v, $n) { $ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; $ret = ""; while (($n - 1) >= 0) { $n--; $ret .= $ITOA64[$v & 0x3f]; $v = $v >> 6; } return $ret; } /** * smtp_mail * Action: Send email * Call: smtp_mail (string to, string from, string subject, string body]) - or - * Call: smtp_mail (string to, string from, string data) - DEPRECATED * @param String - To: * @param String - From: * @param String - Subject: (if called with 4 parameters) or full mail body (if called with 3 parameters) * @param String (optional, but recommended) - mail body * @return bool - true on success, otherwise false * TODO: Replace this with something decent like PEAR::Mail or Zend_Mail. */ function smtp_mail ($to, $from, $data, $body = "") { global $CONF; $smtpd_server = $CONF['smtp_server']; $smtpd_port = $CONF['smtp_port']; //$smtp_server = $_SERVER["SERVER_NAME"]; $smtp_server = php_uname("n"); $errno = "0"; $errstr = "0"; $timeout = "30"; if ($body != "") { $maildata = "To: " . $to . "\n" . "From: " . $from . "\n" . "Subject: " . encode_header ($data) . "\n" . "MIME-Version: 1.0\n" . "Content-Type: text/plain; charset=utf-8\n" . "Content-Transfer-Encoding: 8bit\n" . "\n" . $body ; } else { $maildata = $data; } $fh = @fsockopen ($smtpd_server, $smtpd_port, $errno, $errstr, $timeout); if (!$fh) { error_log("fsockopen failed - errno: $errno - errstr: $errstr"); return false; } else { $res = smtp_get_response($fh); fputs ($fh, "EHLO $smtp_server\r\n"); $res = smtp_get_response($fh); fputs ($fh, "MAIL FROM:<$from>\r\n"); $res = smtp_get_response($fh); fputs ($fh, "RCPT TO:<$to>\r\n"); $res = smtp_get_response($fh); fputs ($fh, "DATA\r\n"); $res = smtp_get_response($fh); fputs ($fh, "$maildata\r\n.\r\n"); $res = smtp_get_response($fh); fputs ($fh, "QUIT\r\n"); $res = smtp_get_response($fh); fclose ($fh); } return true; } /** * smtp_get_admin_email * Action: Get configured email address or current user if nothing configured * Call: smtp_get_admin_email * @return String - username/mail address */ function smtp_get_admin_email() { global $CONF; if(isset($CONF['admin_email']) && !empty($CONF['admin_email'])) return $CONF['admin_email']; else return authentication_get_username(); } // // smtp_get_response // Action: Get response from mail server // Call: smtp_get_response (string FileHandle) // function smtp_get_response ($fh) { $res =''; do { $line = fgets($fh, 256); $res .= $line; } while (preg_match("/^\d\d\d\-/", $line)); return $res; } $DEBUG_TEXT = "\n
\n Please check the documentation and website for more information.\n \n Postfix AdminWARNING: Problems running mailbox postcreation script!
'; return FALSE; } return TRUE; } /* Called after a mailbox has been altered in the DBMS. Returns: boolean. */ function mailbox_postedit($username,$domain,$maildir,$quota) { if (empty($username) || empty($domain) || empty($maildir)) { trigger_error('In '.__FUNCTION__.': empty username, domain and/or maildir parameter',E_USER_ERROR); return FALSE; } global $CONF; $confpar='mailbox_postedit_script'; if (!isset($CONF[$confpar]) || empty($CONF[$confpar])) return TRUE; $cmdarg1=escapeshellarg($username); $cmdarg2=escapeshellarg($domain); $cmdarg3=escapeshellarg($maildir); if ($quota <= 0) $quota = 0; $cmdarg4=escapeshellarg($quota); $command=$CONF[$confpar]." $cmdarg1 $cmdarg2 $cmdarg3 $cmdarg4"; $retval=0; $output=array(); $firstline=''; $firstline=exec($command,$output,$retval); if (0!=$retval) { error_log("Running $command yielded return value=$retval, first line of output=$firstline"); print 'WARNING: Problems running mailbox postedit script!
'; return FALSE; } return TRUE; } /* Called after a mailbox has been deleted in the DBMS. Returns: boolean. */ function mailbox_postdeletion($username,$domain) { global $CONF; $confpar='mailbox_postdeletion_script'; if (!isset($CONF[$confpar]) || empty($CONF[$confpar])) { return true; } if (empty($username) || empty($domain)) { print 'Warning: empty username and/or domain parameter.
'; return false; } $cmdarg1=escapeshellarg($username); $cmdarg2=escapeshellarg($domain); $command=$CONF[$confpar]." $cmdarg1 $cmdarg2"; $retval=0; $output=array(); $firstline=''; $firstline=exec($command,$output,$retval); if (0!=$retval) { error_log("Running $command yielded return value=$retval, first line of output=$firstline"); print 'WARNING: Problems running mailbox postdeletion script!
'; return FALSE; } return TRUE; } /* Called after a domain has been added in the DBMS. Returns: boolean. */ function domain_postcreation($domain) { global $CONF; $confpar='domain_postcreation_script'; if (!isset($CONF[$confpar]) || empty($CONF[$confpar])) { return true; } if (empty($domain)) { print 'Warning: empty domain parameter.
'; return false; } $cmdarg1=escapeshellarg($domain); $command=$CONF[$confpar]." $cmdarg1"; $retval=0; $output=array(); $firstline=''; $firstline=exec($command,$output,$retval); if (0!=$retval) { error_log("Running $command yielded return value=$retval, first line of output=$firstline"); print 'WARNING: Problems running domain postcreation script!
'; return FALSE; } return TRUE; } /* Called after a domain has been deleted in the DBMS. Returns: boolean. */ function domain_postdeletion($domain) { global $CONF; $confpar='domain_postdeletion_script'; if (!isset($CONF[$confpar]) || empty($CONF[$confpar])) { return true; } if (empty($domain)) { print 'Warning: empty domain parameter.
'; return false; } $cmdarg1=escapeshellarg($domain); $command=$CONF[$confpar]." $cmdarg1"; $retval=0; $output=array(); $firstline=''; $firstline=exec($command,$output,$retval); if (0!=$retval) { error_log("Running $command yielded return value=$retval, first line of output=$firstline"); print 'WARNING: Problems running domain postdeletion script!
'; return FALSE; } return TRUE; } /* Called after an alias_domain has been deleted in the DBMS. Returns: boolean. */ function alias_domain_postdeletion($alias_domain) { global $CONF; $confpar='alias_domain_postdeletion_script'; if (!isset($CONF[$confpar]) || empty($CONF[$confpar])) { return true; } if (empty($alias_domain)) { print 'Warning: empty alias_domain parameter.
'; return false; } $cmdarg1=escapeshellarg($alias_domain); $command=$CONF[$confpar]." $cmdarg1"; $retval=0; $output=array(); $firstline=''; $firstline=exec($command,$output,$retval); if (0!=$retval) { error_log("Running $command yielded return value=$retval, first line of output=$firstline"); print 'WARNING: Problems running alias_domain postdeletion script!
'; return FALSE; } return TRUE; } /* Called by mailbox_postcreation() after a mailbox has been created. Immediately returns, unless configuration indicates that one or more sub-folders should be created. Triggers E_USER_ERROR if configuration error is detected. If IMAP login fails, the problem is logged to the system log (such as /var/log/httpd/error_log), and the function returns FALSE. Returns FALSE on all other errors, or TRUE if everything succeeds. Doesn't clean up, if only some of the folders could be created. */ function create_mailbox_subfolders($login,$cleartext_password) { global $CONF; if (empty($login)) { trigger_error('In '.__FUNCTION__.': empty $login',E_USER_ERROR); return FALSE; } if (!isset($CONF['create_mailbox_subdirs']) || empty($CONF['create_mailbox_subdirs'])) return TRUE; if (!is_array($CONF['create_mailbox_subdirs'])) { trigger_error('create_mailbox_subdirs must be an array',E_USER_ERROR); return FALSE; } if (!isset($CONF['create_mailbox_subdirs_host']) || empty($CONF['create_mailbox_subdirs_host'])) { trigger_error('An IMAP/POP server host ($CONF["create_mailbox_subdirs_host"]) must be configured, if sub-folders are to be created',E_USER_ERROR); return FALSE; } $s_host=$CONF['create_mailbox_subdirs_host']; $s_prefix=$CONF['create_mailbox_subdirs_prefix']; $s_options=''; $s_port=''; if ( isset($CONF['create_mailbox_subdirs_hostoptions']) && !empty($CONF['create_mailbox_subdirs_hostoptions']) ) { if (!is_array($CONF['create_mailbox_subdirs_hostoptions'])) { trigger_error('The $CONF["create_mailbox_subdirs_hostoptions"] parameter must be an array',E_USER_ERROR); return FALSE; } foreach ($CONF['create_mailbox_subdirs_hostoptions'] as $o) { $s_options.='/'.$o; } } if (isset($CONF['create_mailbox_subdirs_hostport']) && !empty($CONF['create_mailbox_subdirs_hostport'])) { $s_port=$CONF['create_mailbox_subdirs_hostport']; if (intval($s_port)!=$s_port) { trigger_error('The $CONF["create_mailbox_subdirs_hostport"] parameter must be an integer',E_USER_ERROR); return FALSE; } $s_port=':'.$s_port; } $s='{'.$s_host.$s_port.$s_options.'}'; sleep(1); # give the mail triggering the mailbox creation a chance to do its job $i=@imap_open($s,$login,$cleartext_password); if (FALSE==$i) { error_log('Could not log into IMAP/POP server: '.imap_last_error()); return FALSE; } foreach($CONF['create_mailbox_subdirs'] as $f) { $f='{'.$s_host.'}'.$s_prefix.$f; $res=imap_createmailbox($i,$f); if (!$res) { error_log('Could not create IMAP folder $f: '.imap_last_error()); @imap_close($i); return FALSE; } @imap_subscribe($i,$f); } @imap_close($i); return TRUE; } // // gen_show_status // Action: Return a string of colored 's that indicate // the if an alias goto has an error or is sent to // addresses list in show_custom_domains // Call: gen_show_status (string alias_address) // function gen_show_status ($show_alias) { global $CONF, $table_alias; $stat_string = ""; $stat_goto = ""; $stat_result = db_query ("SELECT goto FROM $table_alias WHERE address='$show_alias'"); if ($stat_result['rows'] > 0) { $row = db_row ($stat_result['result']); $stat_goto = $row[0]; } if (!empty($CONF['recipient_delimiter'])) { $delimiter = preg_quote($CONF['recipient_delimiter'], "/"); $delimiter_regex = '/' .$delimiter. '[^' .$delimiter. '@]*@/'; } // UNDELIVERABLE CHECK if ( $CONF['show_undeliverable'] == 'YES' ) { $gotos=array(); $gotos=explode(',',$stat_goto); $undel_string=""; //make sure this alias goes somewhere known $stat_ok = 1; while ( ($g=array_pop($gotos)) && $stat_ok ) { list(/*NULL*/,$stat_domain) = explode('@',$g); $stat_delimiter = ""; if (!empty($CONF['recipient_delimiter'])) { $stat_delimiter = "OR address = '" . preg_replace($delimiter_regex, "@", $g) . "'"; } $stat_result = db_query ("SELECT address FROM $table_alias WHERE address = '$g' OR address = '@$stat_domain' $stat_delimiter"); if ($stat_result['rows'] == 0) { $stat_ok = 0; } if ( $stat_ok == 0 ) { if ( $stat_domain == $CONF['vacation_domain'] || in_array($stat_domain, $CONF['show_undeliverable_exceptions']) ) { $stat_ok = 1; } } } // while if ( $stat_ok == 0 ) { $stat_string .= "" . $CONF['show_status_text'] . " "; } else { $stat_string .= $CONF['show_status_text'] . " "; } } // POP/IMAP CHECK if ( $CONF['show_popimap'] == 'YES' ) { $stat_delimiter = ""; if (!empty($CONF['recipient_delimiter'])) { $stat_delimiter = ',' . preg_replace($delimiter_regex, "@", $stat_goto); } //if the address passed in appears in its own goto field, its POP/IMAP # TODO: or not (might also be an alias loop) -> check mailbox table! if ( preg_match ('/,' . $show_alias . ',/', ',' . $stat_goto . $stat_delimiter . ',') ) { $stat_string .= "" . $CONF['show_status_text'] . " "; } else { $stat_string .= $CONF['show_status_text'] . " "; } } // CUSTOM DESTINATION CHECK if ( count($CONF['show_custom_domains']) > 0 ) { for ($i = 0; $i < sizeof ($CONF['show_custom_domains']); $i++) { if (preg_match ('/^.*' . $CONF['show_custom_domains'][$i] . '.*$/', $stat_goto)) { $stat_string .= "" . $CONF['show_status_text'] . " "; } else { $stat_string .= $CONF['show_status_text'] . " "; } } } else { $stat_string .= "; "; } // $stat_string .= " " . // " "; return $stat_string; } function getRemoteAddr() { $REMOTE_ADDR = 'localhost'; if (isset($_SERVER['REMOTE_ADDR'])) $REMOTE_ADDR = $_SERVER['REMOTE_ADDR']; return $REMOTE_ADDR; } /* Convert $CONF['whatever'] to boolean (obviously only useful for settings that can be YES or NO) Returns: TRUE (on YES/yes) or FALSE (on NO/no/not set/unknown value) */ function boolconf($setting) { global $CONF; if (!isset($CONF[$setting])) { # not set # TODO: show/log error message on unknown settings? return false; } elseif (strtoupper($CONF[$setting]) == 'YES') { # YES return true; } else { # NO, unknown value # TODO: show/log error message on unknown value? return false; } } $table_admin = table_by_key ('admin'); $table_alias = table_by_key ('alias'); $table_alias_domain = table_by_key ('alias_domain'); $table_domain = table_by_key ('domain'); $table_domain_admins = table_by_key ('domain_admins'); $table_log = table_by_key ('log'); $table_mailbox = table_by_key ('mailbox'); $table_vacation = table_by_key ('vacation'); $table_vacation_notification = table_by_key('vacation_notification'); $table_quota = table_by_key ('quota'); $table_quota2 = table_by_key ('quota2'); /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */