/** * Define onde os arquivos de cache serão salvos * * Irá verificar se a pasta existe e pode ser escrita, caso contrário * uma mensagem de erro será exibida * * @param string $folder Local para salvar os arquivos de cache (opcional) * * @return void */ protected function setFolder($folder = null) { $folder = ROOT . 'src' . DS . 'tmp' . DS . 'cache' . DS . trim($folder, DS); try { if (!is_dir($folder)) { mkdir($folder, 0777, true); } if (file_exists($folder) && is_dir($folder) && is_writable($folder)) { $this->folder = $folder; } else { throw new Exception('Não foi possível acessar a pasta de cache'); } } catch (Exception $exception) { $ex = new MyException(); $ex->show_exception($exception); } }
public function getSetting($filename) { try { if (!file_exists($filename)) { throw new Exception("Неверный путь к файлу конфигурации или его не существует"); } $ini_array = parse_ini_file($filename); return $ini_array; } catch (Exception $e) { MyException::ErrorLog($e->getMessage() . " " . $link->connect_error, $e->getFile(), $e->getLine()); } }
public function Download($file) { try { if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: image/*'); header('Content-Disposition: attachment; filename=' . basename($file)); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); if (!readfile($file)) { throw new Exception("Не удалось скачать файл"); } } else { throw new Exception("Файла для загрузки не существует"); } } catch (Exception $e) { $log = new MyException(); $log->ErrorLog($e->getMessage(), $e->getFile(), $e->getLine()); } }
/** * Exceptions *异常信息 * * @Param $Errmessage * @Param $trace * @Access public * @Return void */ public static function Exceptions($Errmessage = NULL, $trace = NULL) { if (empty($trace)) { $e = new Exception(); $trace = $e->getTrace(); if (empty($Errmessage)) { $Errmessage = $e->getMessage(); } } self::$trace = $trace; self::$Errmessage = $Errmessage; self::$type = __CLASS__; if (DEBUG && DEBUG === TRUE) { //本地测试环境 self::showDebug(); } else { //线上环境,短信通知 exit; //直接退出不显示任何内容 } }
/** * getConn * * @Access public * @Return void */ private static function getConn() { global $memServers; if (empty($memServers)) { return FALSE; } if (!extension_loaded('memcache')) { MyException::Exception('请先安装PHP中Memcache模块'); } if (empty(self::$m)) { $m = new Memcache(); //系统默认对象 foreach ($memServers as $key => $value) { $m->addServer($key, $value); } self::$m = $m; } if (empty(self::$prefix)) { self::$prefix = $_SERVER['SINASRV_MEMCACHED_KEY_PREFIX'] ? $_SERVER['SINASRV_MEMCACHED_KEY_PREFIX'] : 'Reluc-'; } return self::$m; }
/** * start * * @Param $MemcacheObject * @Access public * @Return void */ public static function start($MemcacheObject) { //将 session.save_handler 设置为 user(自定义),而不是默认的 files ini_set('session.save_handler', 'user'); //不使用 GET/POST 变量方式,如果有需要请手动去掉注释 //ini_set('session.use_trans_sid', 0); //设置垃圾回收最大生存时间,如果有需要请手动去掉注释 //ini_set('session.gc_maxlifetime', 3600); //使用 COOKIE 保存 SESSION ID 的方式,如果有需要请手动去掉注释 //ini_set('session.use_cookies', 1); //ini_set('session.cookie_path', '/'); //多主机共享保存 SESSION ID 的 COOKIE,如果有需要请手动去掉注释 //ini_set('session.cookie_domain','.youDomain.com'); if (!$MemcacheObject) { MyException::Exception('请确认Memcache开启'); } self::$m = $MemcacheObject; self::$lifeTime = ini_get('session.gc_maxlifetime'); self::$time = time(); session_set_save_handler(array(__CLASS__, 'open'), array(__CLASS__, 'close'), array(__CLASS__, 'read'), array(__CLASS__, 'write'), array(__CLASS__, 'destroy'), array(__CLASS__, 'gc')); session_start(); return TRUE; }
/** * コンストラクタ。 * * @param string $mes エラーメッセージ * @param string $pagename ページ名 */ public function __construct($mes = '', $pagename) { parent::__construct($mes . "({$pagename})"); }
/** * ArgumentOutOfRangeException constructor. * * @uses MyException::__construct * * @param string $message The exception message. * @param mixed $userArgument The user supplied argument. Default: Empty String. * @param Exception $previous A previously thrown exception to be included in this exception to preserve the * trace. Default: NULL. * @param int $code An associated error code. Default: 0. */ public function __construct($message, $userArgument = NULL, Exception $previous = NULL, $code = 0) { parent::__construct($message, $previous, $code); $this->userArgument = $userArgument; }
/** * Pode ser chamado diretamente por um throw ou quando o PHP dispara um erro (WARNING, PARSE ou FATAL). * No segundo caso um próprio método erro() dessa clase dispara a exceção. * * @param String $message Texto descritivo sobre o que pode ter acontecido na rotina que disparou o erro. * @param int $gravidade Valor inteiro para indicar a gravidade (0 a 3) da exceção. No caso de ser disparada por um * erro do PHP esse campo é um valor constante que indica qual tipo de erro. * @param array $contexto Array com valores do debug_backtrace() (nativo do PHP), pode não ser enviado ou ignorado * com valor false. No caso de erros no PHP tráz informações sobre linha, arquivo e contexto (veja doc * set_error_handler) * @param bool $erro_php É usado apenas pelo método erro() da classe para indicar que não é uma exceção do sistema, * mas sim um erro no PHP. O método erro() está sendo usado como handle dos erros no PHP para que os * usuários não vejam mensagens de erros. * @return void */ public function __construct($message, $gravidade = __CLASS__, $contexto = false, $erro_php = false) { if (!self::$identificador_execucao) { self::$identificador_execucao = str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT); } $this->message = $message; $this->erro_nome = self::$identificador_execucao . '-' . ++self::$cont_erros . '-' . $gravidade . "-" . date('Y-m-d-H-i-s') . ".json"; $this->erros['level'] = $gravidade; $this->erros['datetime'] = date("H:i:s Y-m-d", time()); $this->erros['mensagem'] = $message; $this->erros['db_error'] = DB::error(); if ($erro_php) { $erro_linha = $contexto['linha']; $erro_arquivo = $contexto['arquivo']; $message = strip_tags($message); /* * Não sei porque diabos esta chave as vezes vem com valores recursivos infinitos que causam erro no * sistema. */ $contexto['contexto']["GLOBALS"] = " "; // muitas vezes o erro do php não traz o debug_backtrace $contexto['Backtrace'] = debug_backtrace(); } else { $erro_linha = self::getLine(); $erro_arquivo = self::getFile(); if (SYS_MODO_DEVEL) { echo "<pre><br /><b>{$gravidade}</b> {$message}\n\nno arquivo {$erro_arquivo} Linha: {$erro_linha}<br /><br /></pre>"; } } $this->id_unico = basename($erro_arquivo, '.php') . '.' . $erro_linha; $this->erros['PHP']['Arquivo'] = $erro_arquivo; $this->erros['PHP']['Linha'] = $erro_linha; $this->erros['PHP']['Codigo'] = $this->id_unico; /* * Caso tenha sido passado um array com o contexto do erro/exceção. */ if ($contexto) { $this->erros['Contexto'] = $contexto; } else { $this->erros['Backtrace'] = debug_backtrace(); } $this->erros["GET"] = $_GET; $this->erros["POST"] = $_POST; $this->erros["REQUEST"] = $_REQUEST; if (isset($_SESSION)) { $this->erros["Sessao"] = $_SESSION; } $this->erros["Cookies"] = $_COOKIE; $this->erros["Arquivos"] = $_FILES; $this->erros["Servidor"] = $_SERVER; $this->erros["APPS"] = (array) System::getInstance(); foreach (SysDebug::getErros() as $err) { $this->erros['user_erros'][] = ['Label' => $err['Label'], 'VAR' => $err['VAR'], 'file' => $err['file'], 'line' => $err['line'], 'stringy' => $err['stringy']]; } $json = utf8_decode(json_encode($this->erros, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); $tam_file = file_put_contents(PATH_LOG_ERRO . $this->erro_nome, $json); if (SYS_MODO_DEVEL) { echo "<br/>Erro: " . $this->erro_nome; echo "<br/><pre>{$json}</pre>"; } /* * Verifica se o sistema está configurado para enviar um e-mail para o administrador com o json. */ if (ERROS_ENVIAR_EMAIL && !self::$erro_pai_enviado) { $largura_coluna = 20; $msg = '<code><pre>' . SYS_NAME . " Disse:\n" . $message; $msg .= "\n\n" . str_pad('Arquivo: ', $largura_coluna) . $erro_arquivo; $msg .= "\n" . str_pad('Codigo: ', $largura_coluna) . $this->id_unico; $msg .= "\n" . str_pad('Linha: ', $largura_coluna) . $erro_linha; $msg .= "\n" . str_pad('Erro banco: ', $largura_coluna) . DB::error(); $msg .= "\n----------------------------------------------------------------------------------\n"; $msg .= "\n" . str_pad("Horario:", $largura_coluna) . date('H:i:s d/m/Y'); if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) { $msg .= "\n" . str_pad("IP:", $largura_coluna) . $_SERVER['HTTP_X_FORWARDED_FOR']; $msg .= "\n" . str_pad("Proxy:", $largura_coluna) . '<a href="http://www.geoiptool.com/?IP=' . $_SERVER['REMOTE_ADDR'] . '" target="_blank">' . $_SERVER['REMOTE_ADDR'] . '</a>'; } else { $msg .= "\n" . str_pad("IP:", $largura_coluna) . '<a href="http://www.geoiptool.com/?IP=' . $_SERVER['REMOTE_ADDR'] . '" target="_blank">' . $_SERVER['REMOTE_ADDR'] . '</a>'; } $msg .= "\n" . str_pad("Navegador:", $largura_coluna) . $_SERVER['HTTP_USER_AGENT']; $msg .= "\n" . str_pad("URL requisitada:", $largura_coluna) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $msg .= "\n" . str_pad("POST:", $largura_coluna) . count($_POST); $msg .= "\n" . str_pad("GET:", $largura_coluna) . count($_GET); $msg .= "\n" . str_pad("FILES:", $largura_coluna) . count($_FILES); $msg .= "\n" . str_pad("URL raiz:", $largura_coluna) . URL_ROOT; $msg .= "\n\n\n" . str_pad("JSON", $largura_coluna) . $json; if ($tam_file) { $msg .= "\n----------------------------------------------------------------------------------\n"; $msg .= "\n" . str_pad("Arquivo em:", $largura_coluna) . PATH_LOG_ERRO . $this->erro_nome; } else { $msg .= "\n\nNÃO FOI POSSÍVEL ESCREVER O ARQUIVO EM DISCO!"; } $msg .= "</pre></code>"; if (ERROS_ANEXAR) { $anexo_codificado = chunk_split(base64_encode($json)); $mailheaders = "\nMIME-version: 1.0\n"; $mailheaders .= "Content-type: multipart/mixed; "; $mailheaders .= "boundary=\"Message-Boundary\"\n"; $mailheaders .= "Content-transfer-encoding: 7BIT\n"; $mailheaders .= "X-attachments: {$this->erro_nome}"; $body_top = "--Message-Boundary\n"; $body_top .= "Content-type: text/html; charset=utf8\n"; $body_top .= "Content-transfer-encoding: 7BIT\n"; $body_top .= "Content-description: Mail message body\n\n"; $msg = $body_top . $msg; $msg .= "\n\n--Message-Boundary\n"; $msg .= "Content-type: application/json; name=\"{$this->erro_nome}\"\n"; $msg .= "Content-Transfer-Encoding: BASE64\n"; $msg .= "Content-disposition: attachment; filename=\"{$this->erro_nome}\"\n\n"; $msg .= "{$anexo_codificado}\n"; $msg .= "--Message-Boundary--\n"; } $mailheaders .= "\nReferences: <" . $this->id_unico . "@" . parse_url(URL_ROOT, PHP_URL_HOST) . ">\n"; $msg .= "\n\nAtt, " . SYS_NAME . " (" . SIS_EMAIL . ")"; $assunto = "[" . $gravidade . "][" . str_replace("http://", '', URL_ROOT) . '] ' . utf8_decode(substr($this->id_unico, 0, 30)); if (mail(ERROS_EMAIL, $assunto, $msg, "From: " . SYS_NAME . " <" . SIS_EMAIL . ">" . $mailheaders)) { self::$erro_pai_enviado = true; } else { file_put_contents(PATH_LOG_ERRO . "EMAIL_{$this->erro_nome}", "Erro ao enviar e-mail do erro {$this->erro_nome}"); } } }
public static function synchronizeFolioAltitude(IConnection $connect, $campaignID, $folioID, $syncID, $userID) { global $database, $servers_altitude; $response = ""; $path_data = PATHDATA_SOCKET_EASYLOAD; $path_file = "{$path_data}/{$userID}_{$syncID}"; $output = ""; try { $objCampaign = Campaign::getCampaignByID($connect, $campaignID); $shortname = $objCampaign->getShortName(); $objSync = new SynchronizeFolio($syncID, 0, 0, "", "", ""); $without_easycode = FolioImport::getRegistersWithoutEasycode($connect, $objCampaign->getShortName(), $folioID, 'S'); $action = 1; try { $objSocket = new Socket(IP_SOCKET_EASYLOAD, PORT_SOCKET_EASYLOAD, TIMEOUT_SOCKET_EASYLOAD); $objSocket->connect(); // 1. Comprobando enlace con socket $objSocket->send("ACTION=TEST"); $response = $objSocket->receive(); if (dir(PATHDATA_SOCKET_EASYLOAD)) { $objSync->updateSynchronizeAction($connect, $action, "OK"); } else { $objSync->updateSynchronizeAction($connect, $action, "Error: compartida no disponible"); throw new MyException("Compartida para importaciones no disponible"); } // 2. Generando archivo .TYP $action = 2; sleep(1); $filename = Util::generateFilesImport($connect, $objCampaign, $folioID, $path_file, "TYP", true); $objSync->updateSynchronizeAction($connect, $action, "OK"); // 3. Generando archivo .dat $action = 3; sleep(1); Util::generateFilesImport($connect, $objCampaign, $folioID, $path_file, "DAT", true); $objSync->updateSynchronizeAction($connect, $action, "OK"); // 4. Delegar a socket importar data en altitude $action = 4; sleep(1); $serverAtt = trim($objCampaign->getServerAltitude()) == "" ? SERVER_NORMAL : trim($objCampaign->getServerAltitude()); $connectSQL = Util::createConnection(ENGINE_SQLSERVER, $database[$servers_altitude["{$serverAtt}"]['altitude']]); $connectSQL->connect(); $rsDataAltitude = Altitude::getCampaignsByContactTable($connectSQL, $shortname); $data = $connectSQL->getRows($rsDataAltitude); $campaignATT = trim($data['shortname']); $accessInstance = $database[$servers_altitude["{$serverAtt}"]['altitude']]; $instance = $accessInstance['serverIA'] . ":" . $accessInstance['portIA']; $objSocket->send("ACTION=IMPORT;CAMPAIGN={$campaignATT};FILE={$filename};INSTANCE={$instance};USER={$userID};SYNCID={$syncID}"); $response = $objSocket->receive(); if ($response == "ERROR" || $response == "WARN") { $msg = Util::getContentFile("{$path_file}/{$campaignATT}_messages.txt"); $txt = "Ocurrio un problema en la importacion altitude"; $mex = new MyException("{$msg}", 0, $txt); $mex->publisherSqlException(false); $mex->setText("{$txt}. Error# {$mex->getExceptionID()}"); $output = "{$txt}. Error# {$mex->getExceptionID()}."; if ($response == "ERROR") { throw $mex; } } $objSync->updateSynchronizeAction($connect, $action, "{$response}"); // 5. Sincronizando easycodes entre altitude y altiva $action = 5; $rs = Altitude::getContactsCampaign($connectSQL, $shortname, $folioID); if ($connectSQL->numRows($rs) > 0) { while ($data = $connectSQL->getRows($rs)) { $easycode = $data['easycode'] == '' ? 0 : $data['easycode']; $nuic = $data['cta_nuic']; Campaign::updateCampaignContact($connect, $shortname, $nuic, $easycode, $folioID); Altitude::updateStatusReadyRegisterCampaign($connectSQL, $shortname, $folioID, $easycode); } Campaign::updateCampaignContactCustom($connect, $shortname, $folioID); } $objSync->updateSynchronizeAction($connect, $action, "OK"); // 6. Finalizando enlace con socket $action = 6; $objSocket->changeTimeout(15); $objSocket->send("ACTION=END"); $response = $objSocket->receive(); $objFolio = FolioImport::getFolioImport($connect, $folioID); $total_folio = $objFolio->getRegistersImported(); $without_easycode = FolioImport::getRegistersWithoutEasycode($connect, $shortname, $folioID, 'S'); $objSync->updateSynchronizeAction($connect, $action, $total_folio - $without_easycode); try { if ($objCampaign->getScript() != '') { $objScript = ConfigScripts::getScript($connect, $objCampaign->getScript()); if ($objScript->getName() == SCRIPT_MONITOREO_DTH) { Altitude::changeStatusContact($connectSQL, $shortname, $folioID, '3'); } } } catch (MyException $exs) { } } catch (MyException $ex) { $output = "ERROR: " . $ex->getText(); $objSync->updateSynchronizeAction($connect, $action, "ERROR: {$ex->getText()}"); } } catch (MyException $ex) { $output = "Error: " . $ex->getText(); } return $output; }
/** * コンストラクタ。 * * @param string $cmd コマンド名 */ public function __construct($cmd) { parent::__construct("コマンドがありません({$cmd})。"); }
public function group($keys, $initial, $reduce, $options = array()) { try { return $this->getCollection()->group($keys, $initial, $reduce, $options); } catch (MongoCursorException $e) { MyException::Exceptions($e->getMessage(), $e->getTrace()); } }
/** * InvalidOperationException constructor. * * @uses MyException::__construct * * @param string $message The exception message * @param Exception|NULL $previous A related previously thrown exception to preserve the trace. Default: NULL. * @param int $code An associated error code. Default: 0. */ public function __construct($message, Exception $previous = NULL, $code = 0) { parent::__construct($message, $previous, $code); }
protected static function getFields($tabName) { $CacheFieldPos = $_SERVER['SINASRV_CACHE_DIR'] . '/DbFieldCache/'; $conn = self::achieveConn(TRUE); $filedPath = $CacheFieldPos . md5('Reluctance' . $tabName) . '.php'; try { $stmt = $conn->query('DESC ' . $tabName); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { MyException::Exceptions('您传入的表名不正确,请确认!<br />' . $e->getMessage(), $e->getTrace()); } if (DEBUG) { //本地环境 $fields = self::getFieldArray($result); if (file_exists($filedPath)) { //当修改数据库中字段重新生成新的文件 $fieldArr = (include $filedPath); if ($fieldArr == $fields) { return $fieldArr; } else { unlink($filedPath); } } } else { //线上环境,可以少一个foreach循环 if (file_exists($filedPath)) { return include $filedPath; } $fields = self::getFieldArray($result); } $tabName = md5('Reluctance' . $tabName); $FieldString = "<?php \n return " . var_export($fields, true) . ";\n?" . ">"; file_put_contents($CacheFieldPos . $tabName . '.php', $FieldString); return $fields; }
public function update($link, $table, $rows, $where = null) { $query = "UPDATE " . $table . " SET "; foreach ($rows as $key => $row) { $query .= $key . "='" . $row . "', "; } $query = substr($query, 0, -2); if ($where != null) { $query .= " WHERE " . $where; } try { if (!$link->query("set character_set_client='utf8'")) { throw new Exception("Невозможно выполнить запрос"); } if (!$link->query("set character_set_results='utf8'")) { throw new Exception("Невозможно выполнить запрос"); } if (!$link->query("set collation_connection='utf8_general_ci'")) { throw new Exception("Невозможно выполнить запрос"); } $result = $link->query($query); if (!$result) { throw new Exception("Невозможно выполнить запрос"); } return $result; } catch (Exception $e) { MyException::ErrorLog($e->getMessage() . " " . $link->error, $e->getFile(), $e->getLine()); } }
function getReport() { mydump(parent::getMessage()); }
/** * コンストラクタ。 * * @param string $plugin プラグイン名 */ public function __construct($plugin) { parent::__construct("プラグインがありません({$plugin})。"); }
/** * 删除数据方法 * @param $table 表名 * @param array $where * @return int */ public function delete($table, array $where) { $sql = "delete from {$table} " . $this->whereStr; try { self::$_link->beginTransaction(); $stmt = self::$_link->prepare($sql); $stmt->execute($where); if ($stmt->rowCount() > 0) { self::$_link->commit(); return 1; } else { self::$_link->rollback(); $err = $stmt->errorInfo(); throw new PDOException($err[2]); } } catch (PDOException $e) { MyException::showError($e->getMessage()); } }
public function delete($link, $table, $where) { $query = "DELETE FROM " . $table . " WHERE " . $where; try { if (!$link->query($query)) { throw new Exception("Невозможно выполнить запрос"); } return true; } catch (Exception $e) { //$log = new MyException(); MyException::ErrorLog($e->getMessage() . " " . $link->error, $e->getFile(), $e->getLine()); } }