public function log($level, &$message) { switch ($level) { case LogHelper::LEVEL_DEBUG: log_debug($message); break; case LogHelper::LEVEL_INFO: log_info($message); break; case LogHelper::LEVEL_NOTICE: log_notice($message); break; case LogHelper::LEVEL_WARNING: log_warn($message); break; case LogHelper::LEVEL_ERROR: log_error($message); break; case LogHelper::LEVEL_CRITICAL: log_critical($message); break; case LogHelper::LEVEL_ALERT: log_alert($message); break; case LogHelper::LEVEL_EMERGENCY: log_emergency($message); break; } }
function cache_unset($cache_key) { $cache_key = _cache_prepare_cache_key($cache_key); log_notice("cache", "unset cache key {$cache_key}"); if (isset($GLOBALS['cache_local'][$cache_key])) { unset($GLOBALS['cache_local'][$cache_key]); } $remote_rsp = _cache_do_remote('unset', $cache_key); return array('ok' => 1); }
function cache_unset($key, $more = array()) { $key = _cache_prepare_key($key, $more); unset($GLOBALS['_cache_local'][$key]); if ($GLOBALS['_cache_hooks']['unset']) { return call_user_func($GLOBALS['_cache_hooks']['unset'], $key); } log_notice("cache", "unset {$key}"); return array('ok' => 1, 'local' => 1); }
function export_cache_path_for_sheet(&$sheet, &$more) { if (!isset($more['filename'])) { log_notice('export', 'missing filename for export path'); return null; } $root = export_cache_root_for_sheet($sheet); $parts = array($root, $more['filename']); return implode(DIRECTORY_SEPARATOR, $parts); }
function cache_memcache_set($cache_key, $data) { if (!$data) { log_notice("cache", "missing data to set key {$cache_key}"); return array('ok' => 0, 'error' => 'missing data'); } $memcache = cache_memcache_connect(); if (!$memcache) { return array('ok' => 0, 'error' => 'failed to connect to memcache'); } $ok = $memcache->set($cache_key, serialize($data)); return array('ok' => $ok); }
/** * Action * * Actions handled by this page: * logout * * @param string $action_name Action */ function action($action_name) { switch ($action_name) { case "logout": // Logout log_notice("Logout", "User: "******" logged out"); session_destroy(); $this->gotoPage("home"); break; default: // No matching action, refer to base class parent::action($action_name); } }
/** * Login Customer */ function login() { if ($this->post['user']->getPassword() == $this->post['password']) { // Only customers are allowed to login to the order form if ($this->post['user']->getType() != "Client") { $this->setError(array("type" => "[ONLY_CUSTOMERS_CAN_LOGIN]")); return; } // Login success $_SESSION['client']['userdbo'] = $this->post['user']; log_notice("CustomerLoginPage::login()", "User: "******" logged in."); $this->gotoPage("cart"); } else { // Login failure log_security("CustomerLoginPage::login()", "Password Incorrect."); $this->setError(array("type" => "[LOGIN_FAILED]")); } }
function Engine_ErrorHandler($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_ERROR: log_error($errstr, $errfile, $errline); break; case E_PARSE: log_error($errstr, $errfile, $errline); break; case E_WARNING: log_warning($errstr, $errfile, $errline); break; case E_NOTICE: log_notice($errstr, $errfile, $errline); break; default: log_notice($errstr, $errfile, $errline); } }
/** * Login * * Validate the login. Store the UserDBO in the session if OK, or display an error * if the login failed. */ function login() { try { $user_dbo = load_UserDBO($this->post['username']); if ($user_dbo->getPassword() == $this->post['password'] && ($user_dbo->getType() == "Administrator" || $user_dbo->getType() == "Account Manager")) { // Login success if (isset($this->post['theme'])) { $user_dbo->setTheme($this->post['theme']); } $_SESSION['client']['userdbo'] = $user_dbo; log_notice("Login", "User: "******" logged in"); $_SESSION['jsFunction'] = "reloadMenu()"; $this->gotoPage("home"); } } catch (DBNoRowsFoundException $e) { } // Login failure log_security("Login", "Login failed for " . $this->post['username']); throw new SWUserException("[LOGIN_FAILED]"); }
function cache_memcache_connect() { if (!isset($GLOBALS['remote_cache_conns']['memcache'])) { $host = $GLOBALS['cfg']['memcache_host']; $port = $GLOBALS['cfg']['memcache_port']; $start = microtime_ms(); $memcache = new Memcache(); if (!$memcache->connect($host, $port)) { $memcache = null; } if (!$memcache) { log_fatal("Connection to memcache {$host}:{$port} failed"); } $end = microtime_ms(); $time = $end - $start; log_notice("cache", "connect to memcache {$host}:{$port} ({$time}ms)"); $GLOBALS['remote_cache_conns']['memcache'] = $memcache; $GLOBALS['timings']['memcache_conns_count']++; $GLOBALS['timings']['memcache_conns_time'] += $time; } return $GLOBALS['remote_cache_conns']['memcache']; }
function db_ping($cluster, $shard = null) { $cluster_key = _db_cluster_key($cluster, $shard); if (is_resource($GLOBALS['db_conns'][$cluster_key])) { $start = microtime_ms(); $ret = @mysql_ping($GLOBALS['db_conns'][$cluster_key]); $end = microtime_ms(); log_notice('db', "DB-{$cluster_key}: Ping", $end - $start); return $ret; } return FALSE; }
function _hash($data, $controlType) { if (!$this->enabling) { return false; } switch ($controlType) { case 'md5': return md5($data); case 'crc32': return sprintf('% 32d', crc32($data)); case 'strlen': return sprintf('% 32d', strlen($data)); default: log_notice('Не определенн контроль записи "' . $controlType . '" кэша данных'); } }
/** * Notice logging * * @param string $message */ public static function notice($message) { log_notice($message); }
# * notice - Some action has happened that's useful for debugging # # By default, errors and fatals are always shown, but notices are only shown when # `debug=1` is passed in the querystring or `$cfg['admin_flags_show_notices']` is # set. Messages are only shown (on webpages) for callers with appropriate auth # (see lib_auth.php for more details). # # The 'html' and 'plain' handlers are smart and will only show output where appropriate - the # html version for web pages and the plain version for CLI scripts. # $GLOBALS['log_handlers'] = array('notice' => array('html', 'plain'), 'error' => array('html', 'plain', 'error_log'), 'fatal' => array('html', 'plain', 'error_log')); $GLOBALS['log_html_colors'] = array('db' => '#eef,#000', 'cache' => '#fdd,#000', 'smarty' => '#efe,#000', 'http' => '#ffe,#000', '_error' => '#fcc,#000', '_fatal' => '#800,#fff'); # # log a startup notice so we know what page this is and what env # log_notice('init', "this is {$_SERVER['SCRIPT_NAME']} on {$GLOBALS['cfg']['environment']}"); ################################################################################################################### # # public api # function log_fatal($msg) { _log_dispatch('fatal', $msg); error_500(); exit; } function log_error($msg) { _log_dispatch('error', $msg); } function log_notice($type, $msg, $time = -1)
function cache_memcache_unset($key) { $memcache = cache_memcache_connect(); if (!$memcache) { log_error('Failed to connect to memcache for unset'); return array('ok' => 0, 'local' => 1, 'remote' => 0, 'error' => 'memcache_cant_connect'); } $ok = $memcache->delete($key); if (!$ok) { log_error("Failed to unset memcache key {$key}"); return array('ok' => 0, 'local' => 1, 'remote' => 0, 'error' => 'memcache_unset_failed'); } log_notice("cache", "remote unset {$key}"); return array('ok' => 1, 'local' => 1, 'remote' => 1); }
function _db_query($sql, $cluster, $k=null){ $cluster_key = $k ? "{$cluster}-{$k}" : $cluster; if (!$GLOBALS['db_conns'][$cluster_key]){ _db_connect($cluster, $k); } $trace = _db_callstack(); $use_sql = _db_comment_query($sql, $trace); $start = microtime_ms(); $result = @mysql_query($use_sql, $GLOBALS['db_conns'][$cluster_key]); $end = microtime_ms(); $GLOBALS['timings']['db_queries_count']++; $GLOBALS['timings']['db_queries_time'] += $end-$start; log_notice('db', "DB-$cluster_key: $sql ($trace)", $end-$start); # # profiling? # $profile = null; if ($GLOBALS['cfg']['db_profiling']){ $profile = array(); $p_result = @mysql_query("SHOW PROFILE ALL", $GLOBALS['db_conns'][$cluster_key]); while ($p_row = mysql_fetch_array($p_result, MYSQL_ASSOC)){ $profile[] = $p_row; } } # # build result # if (!$result){ $error_msg = mysql_error($GLOBALS['db_conns'][$cluster_key]); $error_code = mysql_errno($GLOBALS['db_conns'][$cluster_key]); log_error("DB-$cluster_key: $error_code ".HtmlSpecialChars($error_msg)); $ret = array( 'ok' => 0, 'error' => $error_msg, 'error_code' => $error_code, 'sql' => $sql, 'cluster' => $cluster, 'shard' => $k, ); }else{ $ret = array( 'ok' => 1, 'result' => $result, 'sql' => $sql, 'cluster' => $cluster, 'shard' => $k, ); } if ($profile) $ret['profile'] = $profile; return $ret; }
/** * Set Message * * Set a message in the Page session * * @param array $message Message data */ function setMessage($message) { $_SESSION['messages'][] = $message; // Insert arguments into message // TODO: This probably results in running translate twice - needed a quick fix $text = Translator::getTranslator()->translateString($message['type']); if (isset($message['args'])) { foreach ($message['args'] as $i => $arg) { $text = str_replace("{" . $i . "}", $arg, $text); } } log_notice($this->getClassName(), $text); }
/** * Выдавать ли кеш или нет из-за GPC */ function IsCacheGPC() { //return true; // включался для тестирования // Если _GET или _POST - кеша не будет if ($_GET || $_POST) { return false; } // Если сессия - кеша не будет if (isset($_COOKIE[session_name()])) { if (DEV_MODE) { log_notice("cache rejected because of session"); } return false; } // Если в куках есть нужные переменные - кеша не будет (CACHE_COOKIE) if ($_COOKIE && defined('CACHE_COOKIE')) { $vars = explode(',', CACHE_COOKIE); if (!$vars) { foreach ($vars as $var) { if (isset($_COOKIE[trim($var)])) { return false; } } } } return true; // false - генерим страницу // true - берем из кеша }
function http_get($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); # Get around error 417 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, $GLOBALS['cfg']['http_timeout']); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_HEADER, true); # # execute request # $start = microtime_ms(); $raw = curl_exec($ch); $info = curl_getinfo($ch); $end = microtime_ms(); curl_close($ch); $GLOBALS['timings']['http_count']++; $GLOBALS['timings']['http_time'] += $end-$start; # # parse request & response # list($head, $body) = explode("\r\n\r\n", $raw, 2); list($head_out, $body_out) = explode("\r\n\r\n", $info['request_header'], 2); unset($info['request_header']); $headers_in = http_parse_headers($head, '_status'); $headers_out = http_parse_headers($head_out, '_request'); log_notice("http", "GET $url", $end-$start); # # return # if ($info['http_code'] != "200"){ return array( 'ok' => 0, 'error' => 'http_failed', 'code' => $info['http_code'], 'url' => $url, 'info' => $info, 'req_headers' => $headers_out, 'headers' => $headers_in, 'body' => $body, ); } return array( 'ok' => 1, 'url' => $url, 'info' => $info, 'req_headers' => $headers_out, 'headers' => $headers_in, 'body' => $body, ); }
/** * Verifies the signature of a signed OpenID request/response. * * @param array $request the OpenID request/response * @return bool true if the signature is verified * @since 0.8 */ function simpleid_verify_signatures($request) { global $version; log_info('simpleid_verify_signatures'); $is_valid = TRUE; $assoc = isset($request['openid.assoc_handle']) ? cache_get('association', $request['openid.assoc_handle']) : NULL; $stateless = isset($request['openid.response_nonce']) ? cache_get('stateless', $request['openid.response_nonce']) : NULL; if (!$assoc) { log_notice('simpleid_verify_signatures: Association not found.'); $is_valid = FALSE; } elseif (!$assoc['assoc_type']) { log_error('simpleid_verify_signatures: Association does not contain valid assoc_type.'); $is_valid = FALSE; } elseif (!isset($assoc['private']) || $assoc['private'] != 1) { log_warn('simpleid_verify_signatures: Attempting to verify an association with a shared key.'); $is_valid = FALSE; } elseif (!$stateless || $stateless['assoc_handle'] != $request['openid.assoc_handle']) { log_warn('simpleid_verify_signatures: Attempting to verify a response_nonce more than once, or private association expired.'); $is_valid = FALSE; } else { $mac_key = $assoc['mac_key']; $assoc_types = openid_association_types(); $hmac_func = $assoc_types[$assoc['assoc_type']]['hmac_func']; $signed_keys = explode(',', $request['openid.signed']); $signature = openid_sign($request, $signed_keys, $mac_key, $hmac_func, $version); log_debug('***** Signature: ' . $signature); if ($signature != $request['openid.sig']) { log_warn('simpleid_verify_signatures: Signature supplied in request does not match the signatured generated.'); $is_valid = FALSE; } cache_delete('stateless', $request['openid.response_nonce']); } return $is_valid; }
/** * Update Payment */ function updatePayment() { update_PaymentDBO($this->paymentDBO); log_notice("PSIPNPage::paymentCompleted()", sprintf("Updated Paypal payment. TXN=%s, Customer=%s", $_POST['txn_id'], $_POST['payer_email'])); }
function SQLAuthenticate() { global $db; global $password_encryption; global $session_key; if (isset($_SESSION["userlogin"]) && isset($_SESSION["userpwd"])) { //Username and password are set, lets try to authenticate. $session_pass = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($session_key), base64_decode($_SESSION["userpwd"]), MCRYPT_MODE_CBC, md5(md5($session_key))), ""); $rowObj = $db->queryRow("SELECT id, fullname, password FROM users WHERE username="******"userlogin"], 'text') . " AND active=1"); if ($rowObj) { if ($password_encryption == 'md5salt') { $session_password = mix_salt(extract_salt($rowObj["password"]), $session_pass); } else { $session_password = md5($session_pass); } if ($session_password == $rowObj["password"]) { $_SESSION["userid"] = $rowObj["id"]; $_SESSION["name"] = $rowObj["fullname"]; $_SESSION["auth_used"] = "internal"; if (isset($_POST["authenticate"])) { log_notice(sprintf('Successful authentication attempt from [%s] for user \'%s\'', $_SERVER['REMOTE_ADDR'], $_SESSION["userlogin"])); //If a user has just authenticated, redirect him to requested page session_write_close(); $redirect_url = $_POST["query_string"] ? $_SERVER['SCRIPT_NAME'] . "?" . $_POST["query_string"] : $_SERVER['SCRIPT_NAME']; clean_page($redirect_url); exit; } } else { if (isset($_POST['authenticate'])) { // auth( _('Authentication failed! - <a href="reset_password.php">(forgot password)</a>'),"error"); auth(_('Authentication failed!'), "error"); } else { auth(); } } } else { if (isset($_POST['authenticate'])) { log_warn(sprintf('Failed authentication attempt from [%s]', $_SERVER['REMOTE_ADDR'])); //Authentication failed, retry. // auth( _('Authentication failed! - <a href="reset_password.php">(forgot password)</a>'),"error"); auth(_('Authentication failed!'), "error"); } else { unset($_SESSION["userpwd"]); unset($_SESSION["userlogin"]); auth(); } } } else { //No username and password set, show auth form (again). auth(); } }
function find_dir($name) { //ищем директорию, везде где возможно:) //приоритет: // 1. ищем ее в папке вызвавшего файла // 2. ищем в корне сайта (1 и 2 пункт меняются в зависимости от режима работы) // 3. ищем в директории admin // 4. ищем по Include_path // 5. ищем на уровень выше, от вызвавшего файла:) // 1. $bt = backtrace(1, 'file'); $path = explode("/", path($bt)); array_pop($path); $dir = implode("/", $path) . "/" . $name; $rp = realpath($dir); if (is_dir($dir)) { return path($rp) . "/"; } // 2. $rp = realpath($name); if (is_dir($name)) { return path($rp) . "/"; } // 3. if (is_dir('admin')) { //мы на сайте $rp = realpath("admin/" . $name); if (is_dir("admin/" . $name)) { return path($rp) . "/"; } } else { //мы в админке $rp = realpath("../" . $name); if (is_dir("../" . $name)) { return path($rp) . "/"; } } // 4. $inc = getIncludePaths(); foreach ($inc as $pref) { if ($pref == "./") { continue; } if (is_dir($pref . $name)) { $rp = realpath($pref . $name); return path($rp) . "/"; } } // 5. array_pop($path); $dir = implode("/", $path) . "/" . $name; if (is_dir($dir)) { $rp = realpath($dir); return path($rp) . "/"; } log_notice('Директория "' . $name . '" не найдена', backtrace(1, 'file'), backtrace(1, 'line')); return false; }
/** * compile the template * * @param string $resource_name * @param string $compile_path * @return boolean */ function _compile_resource($resource_name, $compile_path) { $start = microtime_ms(); $ret = $this->_compile_resource_real($resource_name, $compile_path); $end = microtime_ms(); $GLOBALS['timings']['smarty_comp_count']++; $GLOBALS['timings']['smarty_comp_time'] += $end - $start; log_notice("smarty", "Compiling {$resource_name}", $end - $start); return $ret; }
function checkAnswer($answer, $inputarr_bs, $inputarr_pi) { $an_cnt = count($answer); if ($an_cnt != 0) { foreach (array_keys($answer) as $model_num) { echo "\ndebug checkAnswer: model_num =" . $model_num; if ($model_num < 10000) { log_notice("checkAnswer model_num wrong\n"); continue; } else { $type = intval($model_num / 10000); $area = intval($model_num % 10000 / 1000); $product_id = intval($model_num % 1000 / 100); $hour = $model_num % 100; $model_name = ""; echo " type = " . $type; switch ($type) { //如果有weight //type == 1 调价乘客模型 //type == 2 不调价乘客模型 //type == 3 调价司机模型 //type == 4 不调价司机模型 case 1: $model_name .= "passenger_dp_"; break; case 2: $model_name .= "passenger_"; break; case 3: $model_name .= "driver_dp_"; break; case 4: $model_name .= "driver_"; break; } $model_name .= "model_normlization"; $model_type = $model_name; $model_name = $model_name . "_" . $area . "_" . $product_id . "_" . $hour; echo "In function checkAnswer,model name is:" . $model_name; //第一个参数modeltype //todo test begin here //构造inputarr basic和passengerinfo $inputarr_bs['area'] = $area; $inputarr_bs['dynamic_price_id'] = '201505271902205_337671'; $inputarr_bs['passenger_id'] = '337672'; $inputarr_bs['product_id'] = $product_id; $now = time(); $weekday = intval(date('w', $now)); $inputarr_bs['weekday'] = $weekday; $inputarr_bs['hour'] = $hour; $inputarr_bs['flnglat'] = intval($inputarr_bs['flng'] * 100) * 10000 + intval($inputarr_bs['flat'] * 100); $inputarr_bs['tlnglat'] = intval($inputarr_bs['tlng'] * 100) * 10000 + intval($inputarr_bs['tlat'] * 100); $inputarr_bs['threshold'] = 0.55; //验证basicinputarr echo "\nbasic Array count = " . count($inputarr_bs); foreach (array_keys($inputarr_bs) as $key) { echo "\nkey = " . $key . ",value = " . $inputarr_bs[$key]; } echo "\npassinfo Array count " . count($inputarr_pi); foreach (array_keys($inputarr_pi) as $key) { echo "\nkey = " . $key . ",value = " . $inputarr_pi[$key]; } //调用线上的方法 // $return = getPredictRate($model_type, $inputarr_bs, $inputarr_pi, $test = 1); $return = array("v_date_total_last_call" => 0.23412561, "v_cnt_ord_bonus_w" => 0.5); $weight_m = $answer[$model_num]; foreach (array_keys($weight_m) as $weight_key) { if (!empty($weight_key) && !empty($weight_m[$weight_key])) { if (array_key_exists($weight_key, $return)) { if (abs($weight_m[$weight_key] - $return[$weight_key]) <= DEVIATION) { log_notice("Model:" . $model_name . " KeySuccess" . $weight_key . "\n"); continue; } else { log_notice("Model:" . $model_name . " ErrorKey:" . $weight_key . " answer=" . $weight_m[$weight_key] . " result=" . $return[$weight_key] . "\n"); return false; } } else { log_notice("Model:" . $model_name . " MissKey:" . $weight_key . "\n"); return false; } } } } } } return true; }
function run() { $info = get_info(); $result = process($info); log_notice(sprintf("hook triggered at repository[%s] ref[%s] by %s, svn[%s], result[%s]", $info['git_path'], $info['commit_info']['ref'], $info['commit_info']['user_name'], $info['svn_path'], $result ? 'succeed' : 'failed')); }
function emailSend($data) { $stime = array_sum(explode(' ', microtime())); require_once "getmxrr.php"; $smtp =& $this->params; $mail = new phpmailer(); $mail->Mailer = "smtp"; $mail->From = isset($data['from']) & !empty($data['from']) ? $data['from'] : '*****@*****.**'; $mail->FromName = isset($data['fromName']) & !empty($data['fromName']) ? $data['fromName'] : 'RuSoft'; $mail->Sender = isset($data['from']) & !empty($data['from']) ? $data['from'] : '*****@*****.**'; $mail->Host = $smtp['host']; $mail->CharSet = $smtp['charset']; $mail->Encoding = $smtp['encoding']; $mail->Port = $smtp['port']; $mail->SMTPAuth = $smtp['auth']; $mail->Subject = isset($data['subj']) & !empty($data['subj']) ? $data['subj'] : ''; if ($smtp['auth']) { $mail->Username = $smtp['user']; $mail->Password = $smtp['pass']; } // HTML body if (isset($data['mess']['html']) & !empty($data['mess']['html'])) { $body = $data['mess']['html']; $mail->isHTML(true); } // Plain text body (for mail clients that cannot read HTML) if (isset($data['mess']['text']) & !empty($data['mess']['text'])) { $text_body = $data['mess']['text']; $mail->isHTML(false); } $mail->AltBody = isset($text_body) ? $text_body : ''; $mail->Body = isset($body) ? $body : (isset($text_body) ? $text_body : ''); $i = 1; // порядковый номер файла //добавляем файлы прикрепленные файлы if (isset($data['attachment']) & !empty($data['attachment'])) { foreach ($data['attachment'] as $k => $item) { if (isset($item['binary']) & !empty($item['binary'])) { $mail->AddStringAttachment($item["binary"], isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } elseif (isset($item['path']) & !empty($item['path'])) { $mail->AddAttachment($item["path"], isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } } } // добавляем файлы, отображаемые на странице if (isset($data['embedded']) & !empty($data['embedded'])) { foreach ($data['embedded'] as $k => $item) { if (isset($item['path']) & !empty($item['path'])) { $mail->AddEmbeddedImage($item["path"], isset($item["cid"]) & !empty($item["cid"]) ? $item["cid"] : $i, isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } } } //pr($mail); //на данном этапе имеется уже собранное письмо и нам необходимо определить mx серверы для отправки...для каждого письма. //чтобы повторно не искать серверы в момент отправки для каждого... //сохраняем для каждого домена один и тот же сервер $mxsrvs = array(); $mxemails = array(); $debug['ctime'] = round((array_sum(explode(' ', microtime())) - $stime) * 1000, 2) . " ms"; foreach ($data['to'] as $email => $name) { //берем чисто host if (!$this->_is_valid_email($email)) { $debug['emails'][$email]['error'] = "неправильно указан email адрес."; continue; } $host = substr($email, strpos($email, "@") + 1); $domains = explode(".", $host); foreach ($domains as $level => $domain) { $address = implode(".", $domains); if (!key_exists($address, $mxsrvs)) { $time = array_sum(explode(' ', microtime())); if (getmxrr_portable($address, $mxhosts, $preference) == true) { array_multisort($preference, $mxhosts); } $debug['emails'][$email]['mxtime'] = round((array_sum(explode(' ', microtime())) - $time) * 1000, 2) . " ms"; if (!empty($mxhosts)) { $mxhosts[] = $smtp['host']; //потому что shadow тормознутый сервак if (in_array('shadow.rusoft.ru', $mxhosts)) { unset($mxhosts[0]); } //чтобы включить рассылку на smtp серверы получателей, необходимо закоментировать следующую строчку $mxhosts = array_reverse($mxhosts); $mxsrvs[$address] = $mxhosts; $mxemails[$email] =& $mxsrvs[$address]; $debug['emails'][$email]['mxsrvs'] =& $mxsrvs[$address]; break; } else { unset($domains[$level]); } } else { $debug['emails'][$email]['mxtime'] = 'cache(0 ms)'; $mxemails[$email] =& $mxsrvs[$address]; $debug['emails'][$email]['mxsrvs'] =& $mxsrvs[$address]; } } } //получены все mx северы и теперь начинаем отправку по списку foreach ($mxemails as $email => $mxs) { //проверяем email адрес на существование и работу mx сервера //можно включить проверку, но это 1) замедляет, 2) вероятность очень низкая //$this->checkEmail($email, $mxs, $debug); $mail->AddAddress($email, $name); foreach ($mxs as $k => $host) { $mail->Host = $host; $time = array_sum(explode(' ', microtime())); $status = $mail->Send(); $debug['emails'][$email]['sendtime'] = round((array_sum(explode(' ', microtime())) - $time) * 1000, 2) . " ms"; $debug['emails'][$email]['status'] = $status; if ($status) { $debug['emails'][$email]['host'] = $host; break; } } $mail->ClearAddresses(); } $debug['time'] = round((array_sum(explode(' ', microtime())) - $stime) * 1000, 2) . " ms"; if (function_exists('log_notice')) { //скидываем в лог информацию о отправленных сообщениях $str = "<b>Были отправлены следующие сообщения:</b><br>Время генерации шалона для отправки: " . $debug['ctime'] . "<br>Общее время: " . $debug['time'] . "<br><b>Адреса:</b><br>"; foreach ($debug['emails'] as $k => $v) { $str .= "<br> <b><font color='blue'>" . $k . "</font></b>"; $str .= "<br> Определение smtp серверов: " . $v['mxtime']; $str .= "<br> Отправлено через: " . $v['host']; $str .= "<br> Время отправления: " . $v['sendtime']; $str .= "<br> Статус: " . ($v['status'] ? '<font color="green">успешно</font>' : '<font color="red">неудачно</font>'); } log_notice('email', false, $str); } //$status = true; // Clear attachments for next loop $mail->ClearAttachments(); if ($status) { return true; } return false; }