public function testWrite() { $this->log->err('123'); $this->log->info('123'); $count = $this->rediska->getListLength('log'); $this->assertEquals(2, $count); }
/** * Performs order delivery for the provided orderId. * * @param int $orderId The unique identifier of the order. * @return void */ public function deliverOrder($orderId) { try { $order = $this->_repository->getById($orderId); // TODO: Do something useful with the order. $this->_notifier->notifyCustomerOfDelivery($order->getCustomer(), $order); } catch (\Exception $e) { $this->_logger->err('An error occurred while delivering the order: ' . $e->getMessage(), $e); } }
/** * Delivers the file via function "fpassthru()". * * @param string $file */ private function sendFileViaFpassthru($file) { $response = $this->getResponse(); $response->setHttpResponseCode(200); if (!is_null($this->logger)) { $content = ob_get_contents(); if (!empty($content)) { $this->logger->err($content); } } ob_end_clean(); set_time_limit(300); $modified = filemtime($file); $response->setHeader('Last-Modified', gmdate('r', $modified), true); $response->setHeader('Content-Length', filesize($file), true); $response->sendHeaders(); $fp = fopen($file, 'rb'); if ($fp === false) { throw new Exception('fopen failed.'); } $retval = fpassthru($fp); if ($retval === false) { throw new Exception('fpassthru failed.'); } fclose($fp); exit; }
public function errorAction() { $errors = $this->_getParam('error_handler'); switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); break; default: // application error $this->getResponse()->setHttpResponseCode(500); break; } // log exception to database $db = Zend_Registry::get('db'); $columnMapping = array('priority' => 'priority', 'type' => 'type', 'message' => 'message', 'user' => 'user', 'ip' => 'ip', 'agent' => 'agent', 'url' => 'url'); $user = Zend_Auth::getInstance()->hasIdentity() ? Zend_Auth::getInstance()->getIdentity()->getEmail() : 'anonymous'; $writer = new Zend_Log_Writer_Db($db, 'Logs', $columnMapping); $logger = new Zend_Log($writer); $logger->setEventItem('user', $user); $logger->setEventItem('ip', $_SERVER['REMOTE_ADDR']); $logger->setEventItem('agent', $_SERVER['HTTP_USER_AGENT']); $logger->setEventItem('url', $this->view->url()); $logger->setEventItem('type', $errors->type); $logger->err($errors->exception); }
/** * * @param Opus_SolrSearch_Query $query * @param bool $validateDocIds check document IDs coming from Solr index against database * @return Opus_SolrSearch_ResultList * @throws Opus_SolrSearch Exception If Solr server responds with an error or the response is empty. */ public function search($query, $validateDocIds = true) { /** * @var Apache_Solr_Response $solr_response */ $solr_response = null; try { $this->log->debug("query: " . $query->getQ()); $solr_response = $this->solr_server->search($query->getQ(), $query->getStart(), $query->getRows(), $this->getParams($query)); } catch (Exception $e) { $msg = 'Solr server responds with an error ' . $e->getMessage(); $this->log->err($msg); if ($e instanceof Apache_Solr_HttpTransportException) { if ($e->getResponse()->getHttpStatus() == '400') { // 400 seems to indicate org.apache.lucene.query.ParserParseException throw new Opus_SolrSearch_Exception($msg, Opus_SolrSearch_Exception::INVALID_QUERY, $e); } if ($e->getResponse()->getHttpStatus() == '404') { // 404 seems to indicate Solr server is unreachable throw new Opus_SolrSearch_Exception($msg, Opus_SolrSearch_Exception::SERVER_UNREACHABLE, $e); } } throw new Opus_SolrSearch_Exception($msg, null, $e); } if (is_null($solr_response)) { $msg = 'could not get an Apache_Solr_Response object'; $this->log->err($msg); throw new Opus_SolrSearch_Exception($msg); } $responseRenderer = new Opus_SolrSearch_ResponseRenderer($solr_response, $validateDocIds, $query->getSeriesId()); return $responseRenderer->getResultList(); }
/** * Execute a job and remove it from the jobs table on success. * * @param Opus_Job $job Job description model. * @return boolean Returns true if a job is consumend false if not */ protected function consume(Opus_Job $job) { $label = $job->getLabel(); if ($job->getState() !== null) { return false; } if (array_key_exists($label, $this->_workers)) { $worker = $this->_workers[$label]; if (null !== $this->_logger) { $this->_logger->info('Processing ' . $label); } $job->setState(Opus_Job::STATE_PROCESSING); $job->store(); try { $worker->setLogger($this->_logger); $worker->work($job); $job->delete(); sleep($this->_delay); } catch (Exception $ex) { if (null !== $this->_logger) { $msg = get_class($worker) . ': ' . $ex->getMessage(); $this->_logger->err($msg); } $job->setErrors(json_encode(array('exception' => get_class($ex), 'message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()))); $job->setState(Opus_Job::STATE_FAILED); $job->store(); return false; } return true; } return false; }
public function errorAction() { $http_accept = $_SERVER['HTTP_ACCEPT']; $this->_redirecUnknownImage($http_accept); $errors = $this->_getParam('error_handler'); $msg = $errors->exception->getMessage(); $backTrace = $errors->exception->getTraceAsString(); $this->_handleMessage($errors); $this->_helper->viewRenderer->setViewScriptPathSpec('error/' . $this->getResponse()->getHttpResponseCode() . '.:suffix'); $this->view->exception = $errors->exception; $this->view->request = $errors->request; $this->view->ui = 1; $logPath = realpath(APPLICATION_PATH . '/../log') . "/error"; if (!is_dir($logPath)) { mkdir($logPath, 755, TRUE); } $log = new Zend_Log(new Zend_Log_Writer_Stream($logPath . "/" . date("Ymd") . "_applicationException.log")); $params1 = $this->_request->getParams(); unset($params1["error_handler"]); $params = Zend_Json::encode($params1); $messages = array($msg, $backTrace, $params, "HTTP_ACCEPT: " . $http_accept, ""); $log->err(implode(self::LOG_EOL, $messages)); try { self::$_dispatcher->notify(new sfEvent($this, 'error.log', array('message' => array($msg, $backTrace), 'priority' => 3))); return; } catch (Exception $e) { echo $e->getMessage(); } }
public static function addItem($message, $error = false) { global $s1b; if (self::getConfig()->getTracesEnabled() || self::getConfig()->getLogsEnabled()) { if (!strlen(trim($message))) { throw new \Exception('Cannot insert empty trace.'); } // Ecriture du message dans le tableau des items en sessions si traces activées if (self::getConfig()->getTracesEnabled()) { self::initItems(); self::$items[] = $message; } // Ecriture du log si activé if (self::getConfig()->getLogsEnabled()) { // vérification de l'existence du fichier et création si non existant $now = new \DateTime(); $logFilePath = self::getContext()->getBaseDirectory() . sprintf("/var/log/%s-log.txt", $now->format("Ymd")); if (!file_exists($logFilePath)) { $file = fopen($logFilePath, "w"); fclose($file); } // ecriture du log dans le fichier $writer = new \Zend_Log_Writer_Stream($logFilePath); $logger = new \Zend_Log($writer); if ($error) { $logger->err($message); } else { $logger->info($message); } $logger = null; } } }
/** * Logs a message to the error log along with its trace. * The backtrace is automatically retrieved, even if the entry is a string, so NO backtrace * information should be provided in the message. However, if you need to save other context * data, as the URL, HTTP headers, or ENV variables, these should be part of the message. * * @param mixed $entry Can be of type string, ErrorException or Exception * @param int $priority One of the Cli_Service_Log class constants. * @param bool $addTrace Whether to add a trace to log message. */ public static function log($entry, $priority = self::ERR, $addTrace = true) { if (!self::$_logger) { self::$_logger = Zend_Registry::get('errorLog'); } $logData = array('message' => '', 'priority' => $priority); if ($entry instanceof ErrorException) { $severity = $entry->getSeverity(); switch ($severity) { case E_NOTICE: $logData['priority'] = self::NOTICE; break; case E_WARNING: $logData['priority'] = self::WARN; break; case E_ERROR: default: $logData['priority'] = self::ERR; break; } if ($addTrace) { $logData['message'] = ''; $traceString = str_replace("#", "\t#", $entry->getTraceAsString()); $logData['message'] .= $entry->getMessage() . PHP_EOL . $traceString . PHP_EOL; } else { $logData['message'] = $entry->getMessage(); } } elseif ($entry instanceof Exception) { // add a tab beofre each new line of the trace string $logData['priority'] = $entry->getCode(); if ($addTrace) { $logData['message'] = ''; $traceString = str_replace("#", "\t#", $entry->getTraceAsString()); $logData['message'] .= $entry->getMessage() . PHP_EOL . $traceString . PHP_EOL; } else { $logData['message'] = $entry->getMessage(); } } elseif (is_string($entry)) { if ($addTrace) { $rawBacktrace = debug_backtrace(); $formattedBacktrace = self::_getFormattedBacktrace($rawBacktrace); $logData['message'] = $entry . PHP_EOL . $formattedBacktrace; } else { $logData['message'] = $entry; } } else { throw new BadMethodCallException('Logging service called with unknown entry type: ' . gettype($entry)); } if ($logData['priority'] >= self::EMERG && $logData['priority'] <= self::DEBUG) { self::$_logger->log($logData['message'], $logData['priority']); } else { self::$_logger->err($logData['message']); } if (ini_get('display_errors')) { echo $logData['message'] . PHP_EOL; } }
/** * Optimizes the index * * @throws Opus_SolrSearch_Index_Exception If index optimization failed. * @return void */ public function optimize() { try { $this->getSolrServer('index')->optimize(); } catch (Apache_Solr_Exception $e) { $msg = 'Error while performing index optimization'; $this->log->err("{$msg} : " . $e->getMessage()); throw new Opus_SolrSearch_Index_Exception($msg, 0, $e); } }
public function errorAction() { /** * Check database connection */ try { $db = Zend_Registry::get('db'); $db->getConnection(); } catch (Zend_Db_Adapter_Exception $e) { // perhaps a failed login credential, or perhaps the RDBMS is not running $this->databaseError($e); } catch (Zend_Exception $e) { // perhaps factory() failed to load the specified Adapter class $this->databaseError($e); } /** * Normal error page */ $pageProxy = new SxCms_Page_Proxy(); $page = $pageProxy->getPageById(36); $this->view->page = $page; $this->view->lng = isset($_SESSION['System']['lng']) ? $_SESSION['System']['lng'] : $this->_getParam('lng', 'nl'); $this->_helper->layout->setLayout('full'); $this->view->errorpage = true; $this->view->glob_tmx = new Zend_Translate('tmx', APPLICATION_ROOT . '/application/var/locale/global.tmx', $this->_getParam('lng', 'nl')); $errors = $this->_getParam('error_handler'); switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $this->render('404'); break; default: // application error $this->getResponse()->setHttpResponseCode(500); break; } // log exception to database $db = Zend_Registry::get('db'); $columnMapping = array('priority' => 'priority', 'type' => 'type', 'message' => 'message', 'user' => 'user', 'ip' => 'ip', 'agent' => 'agent', 'url' => 'url'); $user = Zend_Auth::getInstance()->hasIdentity() ? Zend_Auth::getInstance()->getIdentity()->getEmail() : 'anonymous'; $writer = new Zend_Log_Writer_Db($db, 'Logs', $columnMapping); $logger = new Zend_Log($writer); $logger->setEventItem('user', $user); $logger->setEventItem('ip', $_SERVER['REMOTE_ADDR']); $logger->setEventItem('agent', $_SERVER['HTTP_USER_AGENT']); $logger->setEventItem('url', $this->view->url()); $logger->setEventItem('type', $errors->type); $logger->err($errors->exception); }
public function __construct($results = array(), $numberOfHits = 0, $queryTime = 0, $facets = array(), $validateDocIds = true, $log = null) { $this->log = $log; $this->numberOfHits = $numberOfHits; $this->queryTime = $queryTime; $this->facets = $facets; $this->results = array(); // make sure that documents returned from index exist in database if (!empty($results)) { if ($validateDocIds) { $docIds = array(); foreach ($results as $result) { array_push($docIds, $result->getId()); } $finder = new Opus_DocumentFinder(); $finder->setServerState('published'); $finder->setIdSubset($docIds); $docIdsDB = $finder->ids(); $notInDB = 0; foreach ($results as $result) { if (in_array($result->getId(), $docIdsDB)) { array_push($this->results, $result); } else { $notInDB++; } } $resultsSize = count($this->results); if ($notInDB > 0 && !is_null($this->log)) { $inDB = $resultsSize - $notInDB; $this->log->err("found inconsistency between database and solr index: index returns {$resultsSize} documents, but only " . $inDB . " found in database"); } } else { $this->results = $results; } } }
/** * Add readFile privilege to all files of this document. * * @param string $roleName * @return Matheon_Model_Document Fluent interface. */ public function addReadFilePrivilege($roleName = 'guest') { $role = Opus_UserRole::fetchByName($roleName); if (is_null($role)) { $this->_log->err("Cannot add readFile privilege for non-existent role '{$role->getName()}' to document " . $this->getId() . "."); return $this; } $this->_log->warn("Warning: Setting all files readable for role '{$role->getName()}' (document " . $this->getId() . ")"); $role->appendAccessDocument($this->getId()); foreach ($this->_document->getFile() as $file) { $role->appendAccessFile($file->getId()); } $role->store(); return $this; }
/** * Receive message * * @param AMQPMessage $rabbitMessage Rabbit message * @param Oggetto_Messenger_Model_Message_Interface $messagePrototype Message prototype * @param array|Closure $callback Callback * * @throws Exception * @throws Oggetto_Messenger_Exception_Critical * * @return void */ public function receiveMessage(AMQPMessage $rabbitMessage, Oggetto_Messenger_Model_Message_Interface $messagePrototype, $callback) { try { $this->_logger->info("Received new message: {$rabbitMessage->body}"); $message = clone $messagePrototype; $message->init($rabbitMessage->body); call_user_func_array($callback, array($message)); } catch (Oggetto_Messenger_Exception_Critical $e) { // Only critical exceptions are supposed to stop the receiver throw $e; } catch (Exception $e) { $this->_logger->err($e); } $channel = $rabbitMessage->{'delivery_info'}['channel']; $channel->basic_ack($rabbitMessage->{'delivery_info'}['delivery_tag']); }
private function _zendlog() { $write = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/log/log.txt'); $format = new Zend_Log_Formatter_Simple('%message%'); $write->setFormatter($format); $log = new Zend_Log($write); $log->info('thong bao', Zend_Log::INFO); $log->err('thong bao loi', Zend_Log::ERR); // $write= new Zend_Log_Writer_Stream(APPLICATION_PATH.'/log/log.txt'); // // $log->info('thong bao', Zend_Log::INFO); // $log->err('thong bao loi', Zend_Log::ERR); // // // // $log = new Zend_Log($write); }
public function run() { $this->init(); foreach ($this->config['plugins'] as $name => $config) { include_once $name . '.php'; $plugin = new $name($config); $this->frontController->registerPlugin($plugin); } try { $__start = getmicrotime(); $this->frontController->dispatch(); za()->recordStat('za::dispatch', getmicrotime() - $__start); } catch (Exception $e) { // record the current _GET and _POST variables $this->logger->err("Dispatch failed for " . current_url() . ": " . $e->getMessage() . ", get and post to follow"); $this->logger->err(print_r($_REQUEST, true)); throw $e; } }
/** * initGuiTexts * @author Thomas Schedler <*****@*****.**> * @version 1.0 */ public function initGuiTexts($blnGuiTextsClassSession = true) { /** * initialize the guiTexts object && the security object */ try { //$this->guiTexts = GuiTexts::getInstance($this->logger, $this->dbh); if (GUI_TEXTS_CLASS_SESSION == true && $blnGuiTextsClassSession == true) { if (isset($_SESSION['sesGuiTextsObject'])) { $this->logger->debug('load guiTexts object from session'); $this->guiTexts = unserialize($_SESSION['sesGuiTextsObject']); } else { $this->logger->debug('load guiTexts object from engine db and write to the session'); $this->guiTexts = GuiTexts::getInstance($this->logger); $_SESSION['sesGuiTextsObject'] = serialize($this->guiTexts); } } else { $this->logger->debug('load guiTexts object from engine db'); $this->guiTexts = GuiTexts::getInstance($this->logger); } } catch (Exception $exc) { $this->logger->err($exc); } }
$writer = new Zend_Log_Writer_Stream('php://output'); $writer->addFilter((int) $log_level); $logger = new Zend_Log($writer); $logger->debug('Running search shell utility'); global $unifiedsearchlib; require_once 'lib/search/searchlib-unified.php'; if ($_SERVER['argv'][1] === 'stopRebuild') { $logger->info('Stopping rebuild...'); ob_flush(); $unifiedsearchlib->stopRebuild(); $logger->info("Stopped rebuild\n"); ob_flush(); return; } if ($unifiedsearchlib->rebuildInProgress()) { $logger->err('Rebuild in progress - exiting.'); exit(1); } if ($_SERVER['argv'][1] === 'process') { $queueCount = $unifiedsearchlib->getQueueCount(); if ($queueCount > 0) { $toProcess = isset($_SERVER['argv'][2]) && is_numeric($_SERVER['argv'][2]) ? $_SERVER['argv'][2] : 10; $toProcess = min($queueCount, $toProcess); try { $logger->debug('Started processing queue...'); ob_flush(); $unifiedsearchlib->processUpdateQueue($toProcess); $logger->info('Processed queue'); ob_flush(); } catch (Zend_Search_Lucene_Exception $e) { $msg = tr('Search index could not be updated: %0', $e->getMessage());
include_once 'lib/core/Zend/Log/Writer/Syslog.php'; $log_level = Zend_Log::INFO; $writer = new Zend_Log_Writer_Stream('php://output'); $writer->addFilter((int) $log_level); $logger = new Zend_Log($writer); $logger->debug('Running search shell utility'); require_once 'lib/profilelib/profilelib.php'; require_once 'lib/profilelib/installlib.php'; if ($_SERVER['argv'][1] === 'install') { $args = $_SERVER['argv']; $script = array_shift($args); $command = array_shift($args); $profile = array_shift($args); $repository = array_shift($args); if (!$repository) { $repository = 'profiles.tiki.org'; } if (!$profile) { $logger->err('Profile not specified.'); exit(1); } $profile = Tiki_Profile::fromNames($repository, $profile); if (!$profile) { $logger->err('Profile not found'); exit(1); } $transaction = $tikilib->begin(); $installer = new Tiki_Profile_Installer(); $installer->install($profile); $transaction->commit(); }
/** * Constructor */ protected function __construct($blnWithDbh = true, Zend_Config_Xml &$sysConfig, Zend_Config_Xml &$zooConfig, Zend_Config_Xml &$config) { /** * set sys config object */ $this->sysConfig = $sysConfig; /** * set modules config object */ $this->zooConfig = $zooConfig; /** * set website config object */ $this->config = $config; /** * initialize Zend_Log */ $this->logger = new Zend_Log(); /** * initialize Zend_Session_Namespace */ $this->objCoreSession = new Zend_Session_Namespace('Core'); /** * create logfile extension for file writer */ $strLogFileExtension = ''; if ($this->sysConfig->logger->priority > Zend_Log::ERR) { if (isset($_SESSION["sesUserName"]) && isset($_SERVER['REMOTE_ADDR'])) { $strLogFileExtension = '_' . $_SESSION["sesUserName"] . '_' . $_SERVER['REMOTE_ADDR']; } else { if (isset($_SERVER['REMOTE_ADDR'])) { $strLogFileExtension = '_' . $_SERVER['REMOTE_ADDR']; } else { $strLogFileExtension = '_local'; } } } /** * create log file writer */ $writer = new Zend_Log_Writer_Stream(GLOBAL_ROOT_PATH . $this->sysConfig->logger->path . 'log_' . date('Ymd') . $strLogFileExtension . '.log'); $this->logger->addWriter($writer); /** * set log priority */ $filter = new Zend_Log_Filter_Priority((int) $this->sysConfig->logger->priority); $this->logger->addFilter($filter); /** * get language and set translate object */ $this->logger->info('get language from ... '); if (isset($_GET['language'])) { $this->logger->info('GET'); $this->strLanguageCode = trim($_GET['language'], '/'); foreach ($this->config->languages->language->toArray() as $arrLanguage) { if (array_key_exists('code', $arrLanguage) && $arrLanguage['code'] == strtolower($this->strLanguageCode)) { $this->intLanguageId = $arrLanguage['id']; break; } } if ($this->intLanguageId == null) { if (isset($this->objCoreSession->languageId)) { $this->logger->info('SESSION'); $this->intLanguageId = $this->objCoreSession->languageId; $this->strLanguageCode = $this->objCoreSession->languageCode; } else { $this->logger->info('DEFAULT'); $this->blnIsDefaultLanguage = true; $this->intLanguageId = $this->sysConfig->languages->default->id; $this->strLanguageCode = $this->sysConfig->languages->default->code; } } } else { if (isset($_SERVER['REQUEST_URI']) && preg_match('/^\\/[a-zA-Z\\-]{2,5}\\//', $_SERVER['REQUEST_URI'])) { $this->logger->info('URI'); preg_match('/^\\/[a-zA-Z\\-]{2,5}\\//', $_SERVER['REQUEST_URI'], $arrMatches); $this->strLanguageCode = trim($arrMatches[0], '/'); foreach ($this->config->languages->language->toArray() as $arrLanguage) { if (array_key_exists('code', $arrLanguage) && $arrLanguage['code'] == strtolower($this->strLanguageCode)) { $this->intLanguageId = $arrLanguage['id']; break; } } if ($this->intLanguageId == null) { if (isset($this->objCoreSession->languageId)) { $this->logger->info('SESSION'); $this->intLanguageId = $this->objCoreSession->languageId; $this->strLanguageCode = $this->objCoreSession->languageCode; } else { $this->logger->info('DEFAULT'); $this->blnIsDefaultLanguage = true; $this->intLanguageId = $this->sysConfig->languages->default->id; $this->strLanguageCode = $this->sysConfig->languages->default->code; } } } else { if (isset($this->objCoreSession->languageId)) { $this->logger->info('SESSION'); $this->intLanguageId = $this->objCoreSession->languageId; $this->strLanguageCode = $this->objCoreSession->languageCode; } else { $this->logger->info('DEFAULT'); $this->blnIsDefaultLanguage = true; $this->intLanguageId = $this->sysConfig->languages->default->id; $this->strLanguageCode = $this->sysConfig->languages->default->code; } } } /** * set up zoolu translate obj */ $this->intZooluLanguageId = Zend_Auth::getInstance()->hasIdentity() ? Zend_Auth::getInstance()->getIdentity()->languageId : $this->intLanguageId; $this->strZooluLanguageCode = Zend_Auth::getInstance()->hasIdentity() ? Zend_Auth::getInstance()->getIdentity()->languageCode : $this->strLanguageCode; if (file_exists(GLOBAL_ROOT_PATH . 'application/zoolu/language/zoolu-' . $this->strZooluLanguageCode . '.mo')) { $this->translate = new HtmlTranslate('gettext', GLOBAL_ROOT_PATH . 'application/zoolu/language/zoolu-' . $this->strZooluLanguageCode . '.mo'); } else { $this->translate = new HtmlTranslate('gettext', GLOBAL_ROOT_PATH . 'application/zoolu/language/zoolu-' . $this->zooConfig->languages->default->code . '.mo'); } // update session language $this->updateSessionLanguage(); if ($blnWithDbh == true) { /** * initialize the ZEND DB Connection * do lazy connection binding, so db connection will be established on first use with dbh->getConnection() */ try { $pdoParams = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true); $dbhParameters = array('host' => $this->sysConfig->database->params->host, 'username' => $this->sysConfig->database->params->username, 'password' => $this->sysConfig->database->params->password, 'dbname' => $this->sysConfig->database->params->dbname, 'driver_options' => $pdoParams); $this->dbh = Zend_Db::factory($this->sysConfig->database->adapter, $dbhParameters); if ($this->sysConfig->logger->priority == Zend_Log::DEBUG) { $this->dbh->getProfiler()->setEnabled(true); } $this->dbh->getConnection(); $this->dbh->exec('SET CHARACTER SET ' . $this->sysConfig->encoding->db); Zend_Db_Table::setDefaultAdapter($this->dbh); /** * using a default metadata cache for all table objects * * set up the cache */ $arrFrontendOptions = array('automatic_serialization' => true); /** * memcache server configuration */ $arrServer = array('host' => Zend_Cache_Backend_Memcached::DEFAULT_HOST, 'port' => Zend_Cache_Backend_Memcached::DEFAULT_PORT, 'persistent' => Zend_Cache_Backend_Memcached::DEFAULT_PERSISTENT); $arrBackendOptions = array('cache_dir' => GLOBAL_ROOT_PATH . $this->sysConfig->path->cache->tables); $objCache = Zend_Cache::factory('Core', 'File', $arrFrontendOptions, $arrBackendOptions); /** * set the cache to be used with all table objects */ Zend_Db_Table_Abstract::setDefaultMetadataCache($objCache); } catch (Zend_Db_Adapter_Exception $exc) { $this->logger->err($exc); header('Location: http://' . $this->sysConfig->hostname); die; } catch (Zend_Exception $exc) { $this->logger->err($exc); header('Location: http://' . $this->sysConfig->hostname); die; } } }
public function createAction() { // debugMessage($this->_getAllParams()); exit(); // $this->_setParam('id', NULL); // exit(); $session = SessionWrapper::getInstance(); // the name of the class to be instantiated $classname = $this->_getParam("entityname"); $new_object = new $classname(); // parameters for the response - default do not prepend the baseurl $response_params = array(); // add the createdby using the id of the user in session if (isEmptyString($this->_getParam('id'))) { // new entity $this->_setParam('createdby', $session->getVar('userid')); // merge the post data to enable loading of any relationships in process post // TODO: Verify if this breaks any other functionality $new_object->merge(array_remove_empty($this->_getAllParams()), false); } else { // id is already encoded during update so no need to encode it again $response_params['id'] = $this->_getParam('id'); // decode the id field and add it back to the array otherwise it will cause a type error during processPost $this->_setParam('id', decode($this->_getParam('id'))); // load the details for the current entity from the database $new_object->populate($this->_getParam('id')); $this->_setParam('lastupdatedby', $session->getVar('userid')); } // populate the object with data from the post and validate the object // to ensure that its wellformed $new_object->processPost($this->_getAllParams()); /* debugMessage($new_object->toArray()); debugMessage('errors are '.$new_object->getErrorStackAsString()); exit(); */ if ($new_object->hasError()) { // there were errors - add them to the session $this->_logger->info("Validation Error for " . $classname . " - " . $new_object->getErrorStackAsString()); $session->setVar(FORM_VALUES, $this->_getAllParams()); $session->setVar(ERROR_MESSAGE, $new_object->getErrorStackAsString()); $response_params['id'] = encode($this->_getParam('id')); // return to the create page if (isEmptyString($this->_getParam(URL_FAILURE))) { $this->_helper->redirector->gotoSimple('index', $this->getRequest()->getControllerName(), $this->getRequest()->getModuleName(), $response_params); return false; } else { $this->_helper->redirector->gotoUrl(decode($this->_getParam(URL_FAILURE)), $response_params); return false; } } // end check for whether errors occured during the population of the object instance from the submitted data // save the object to the database try { switch ($this->_getParam('action')) { case "": case ACTION_CREATE: if (in_array($new_object->getTableName(), array('useraccount'))) { $new_object->transactionSave(); } else { $new_object->beforeSave(); $new_object->save(); // there are no errors so call the afterSave() hook $new_object->afterSave(); } /* debugMessage($new_object->toArray()); debugMessage('errors are '.$new_object->getErrorStackAsString()); exit(); */ break; case ACTION_EDIT: // update the entity $new_object->beforeUpdate(); $new_object->save(); // there are no errors so call the afterSave() hook $new_object->afterUpdate(); // debugMessage('errors are '.$new_object->getErrorStackAsString()); exit(); break; case ACTION_DELETE: // update the entity $new_object->delete(); // there are no errors so call the afterSave() hook $new_object->afterDelete(); break; case ACTION_APPROVE: // update the entity $new_object->approve(); // there are no errors so call the afterSave() hook $new_object->afterApprove(); break; default: break; } # exit(); // add a success message, if any, to the session for display if (!isEmptyString($this->_getParam(SUCCESS_MESSAGE))) { $session->setVar(SUCCESS_MESSAGE, $this->_translate->translate($this->_getParam(SUCCESS_MESSAGE))); } if (isEmptyString($this->_getParam(URL_SUCCESS))) { // add the id of the new object created which is encoded $response_params['id'] = encode($new_object->getID()); $this->_helper->redirector->gotoSimple('view', $this->getRequest()->getControllerName(), $this->getRequest()->getModuleName(), $response_params); return false; } else { $url = decode($this->_getParam(URL_SUCCESS)); if (!isArrayKeyAnEmptyString('nosuccessid', $this->_getAllParams())) { $this->_helper->redirector->gotoUrl($url); } else { // check if the last character is a / then add it if (substr($url, -1) != "/") { // add the slash $url .= "/"; } // add the ID parameter $url .= "id/" . encode($new_object->getID()); $this->_helper->redirector->gotoUrl($url, $response_params); } return false; } } catch (Exception $e) { $session->setVar(FORM_VALUES, $this->_getAllParams()); $session->setVar(ERROR_MESSAGE, $e->getMessage()); $this->_logger->err("Saving Error " . $e->getMessage()); // debugMessage($e->getMessage()); exit(); // return to the create page if (isEmptyString($this->_getParam(URL_FAILURE))) { $this->_helper->redirector->gotoSimple('index', $this->getRequest()->getControllerName(), $this->getRequest()->getModuleName(), $response_params); return false; } else { $this->_helper->redirector->gotoUrl(decode($this->_getParam(URL_FAILURE)), $response_params); return false; } } // exit(); }
public function ordemDePagamentoAction() { $this->_pedido = new Application_Model_Pedidos(); $this->_itens = new Application_Model_Itens(); $dados = $this->getRequest()->getParams(); $request = $this->getRequest(); if ($request->isXmlHttpRequest() && $request->isPost()) { if (!is_null($dados["orderInName"])) { $orderInName = $dados["orderInName"]; } else { $orderInName = $this->_identity->usr_id; } $creditos = new Zend_Session_Namespace('Creditos'); if (!empty($creditos->usado) && isset($creditos->usado)) { $valorCredito = $creditos->usado; } else { $valorCredito = null; } $valorDoPedido = $dados["orderValue"]; $pedido = array("ped_valor" => $valorDoPedido, "ped_status" => "pedidio-realizado", "usr_id_fk" => $orderInName, "ped_creditos_usados" => $valorCredito); try { /** Inserir Pedido **/ $lastId = $this->_pedido->insert($pedido); $authNamespace = new Zend_Session_Namespace('Carrinho'); $carrinho = $authNamespace->carrinho; if (!empty($carrinho)) { foreach ($carrinho as $key => $value) { foreach ($value["numeros"] as $indice => $valor) { $item = array("iten_valor" => $value["valor"], "iten_numeracao" => $indice, "iten_qtd" => $valor, "ped_id_fk" => $lastId, "pro_id_fk" => $key); /** Inserir Item **/ $this->_itens->insert($item); } } } } catch (Zend_Db_Exception $e) { $message = $e->getMessage(); $stream = @fopen('../log/log.log', 'a', false); $writer = new Zend_Log_Writer_Stream($stream); $logger = new Zend_Log($writer); $logger->err("{$message}"); exit; } $pagamento = new Tokem_PagSeguro(); unset($dados["controller"]); unset($dados["action"]); unset($dados["module"]); $xml = $pagamento->processOrder($dados, $lastId); $aux = json_encode($xml); $xml = json_decode($aux); if (isset($xml->paymentLink)) { $link = $xml->paymentLink; } else { $link = null; } if (isset($xml->code)) { $this->_pagSeguro = new Application_Model_PagSeguro(); $pagseguro = array("lastEventDate" => $xml->lastEventDate, "code" => $xml->code, "reference" => $xml->reference, "type" => $xml->type, "status" => $xml->status, "paymentMethod_type" => $xml->paymentMethod->type, "paymentMethod_code" => $xml->paymentMethod->code, "paymentLink" => $link, "grossAmount" => $xml->grossAmount, "installmentCount" => $xml->installmentCount, "ped_id_fk" => $xml->reference); try { $lastId = $this->_pagSeguro->insert($pagseguro); $pagseguro = $this->_pagSeguro->fetchRow("pag_id='{$lastId}'"); $fk = $pagseguro->reference; $pedido = $this->_pedido->fetchRow("ped_id='{$fk}'"); $pedido->pag_seg_id_fk = $pagseguro->pag_id; $pedido->save(); } catch (Zend_Db_Exception $e) { $messenger = Zend_Controller_Action_HelperBroker::getStaticHelper('flashMessenger'); $messenger->addMessage('<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>ERRO</strong> - Ocorreu um erro inesperado! ao tentar processar seu pagamento emtre em contato conosco! </div>'); } } // $retorno = array("resultado"=>"1","url"=>"pedidos"); // echo $status = json_encode($retorno); exit; } }
/** * Prio 3: Error: error conditions * * Has an alias called 'error' * * @param string $msg * @param EngineBlock_Log_Message_AdditionalInfo $additionalInfo * @return void */ public function err($msg, $additionalInfo = null) { $this->_setAdditionalEventItems($additionalInfo); parent::err($msg); }
public function getNotificationStatus() { $notificationCode = "06D1FA77-DBDC-405B-8931-D398C90CAE53"; $url = 'https://ws.sandbox.pagseguro.uol.com.br/v2/transactions/notifications/' . $notificationCode; $client = new Zend_Http_Client($url, array('keepalive' => true)); $client->setParameterGet(array('token' => "*****@*****.**", 'email' => "24707C512FF041ED96B762FE807CA552")); $request = $client->request(); //var_dump($request); exit; $resposta = $client->getLastResponse()->getBody(); $stream = @fopen('../log/pagseguroNotification.log', 'a', false); $writer = new Zend_Log_Writer_Stream($stream); $logger = new Zend_Log($writer); $logger->err(sprintf('Retorno do Pagseguro para notificationCode %s: %s', $notificationCode, $resposta)); libxml_use_internal_errors(true); $xml = simplexml_load_string(trim($resposta)); if (false === $xml) { $stream = @fopen('../log/pagseguroNotification.log', 'a', false); $writer = new Zend_Log_Writer_Stream($stream); $logger = new Zend_Log($writer); $logger->err('Retorno de notificacao XML PagSeguro em formato não esperado. Retorno: ' . $resposta); } //return $xml; var_dump($xml); exit; }
public function sendAction($messages) { $logger = new Zend_Log(new Zend_Log_Writer_Stream(APPLICATION_PATH."/../tmp/sms.log")); try { $hour = date('G'); if ($hour < 10 || $hour >=18 ) exit; $SmsSoapClient = new Logic_Service_SmsSoapClient(); if ($SmsSoapClient->getIsError() === false) { // Bledy opisane w dokumenacji do uslugi POST_CODE_SOAP, blad 999 - mozliwosc ustawienia przez uzytkownika takiego bledu co bedzie skutkowalo proba ponownego wyslania // Blad 1000 - opis bledu znajduje sie w polu send_error_message $val = $messages[0] ; $val['text'] = htmlspecialchars_decode($val['text']); $val['text'] = strip_tags ($val['text']);; $val['text'] = preg_replace ("#\s{2,}#", " ", $val['text']); $val['text'] = preg_replace ("#^\s{1,}#", "", $val['text']); $val['text'] = preg_replace ("#\s{1,}$#", "", $val['text']); $val['text'] = str_replace("'", "'", $val['text']); $val['text'] = str_replace("&", "&", $val['text']); $val['text'] = str_replace(""", '"', $val['text']); $val['text'] = str_replace("<", '<', $val['text']); $val['text'] = str_replace(">", '>', $val['text']); $numbers[$val['phone']] = $val['text']; //tablica do rozsylki //tablice uzywane przy zapisie informacji do bazy o statusie rozsylki poszczegolnego sms'a $numbers_update[$val['phone']] = array ( 'is_sent' => 'TRUE', 'send_date' => 'now()' ); //nie pobieram id z bazy //$numbers_where[$val['phone']] = $val['id']; //wiec ustawie timestampa zamiast tego $numbers_where[$val['phone']] = time(); // w bazie znajduja sie oczekujace smsy if (!empty($numbers)) { $SmsSoapClient->registerNumbers($numbers); $SmsSoapClient->setStartDate(date('dmyHis')); $SmsSoapClient->registerContent('Wiadomosc indywidualna'); $response = $SmsSoapClient->send(); //$blad[] = array ('number' => 609804902, 'content' => 'tresc', 'reason'=>'info o bledzie'); //$response->report = $blad; //jezeli zwrocono odpowiedz if (!empty($response)) { // jezali znajduja sie nie rozeslane sms'y - numery wylaczone z rozeslania if (is_array($response->report) && count($response->report) > 0) { foreach ($response->report as $item) { //$item = array(number, content, reason) if (array_key_exists($item['number'], $numbers_update )) { //numer zwrocony przez usluge znajduje sie w numerach przekazanych do rozsylki $numbers_update[$item['number']]['is_sent'] = 'FALSE'; $numbers_update[$item['number']]['send_error'] = 1000; $numbers_update[$item['number']]['send_error_message'] = $item['reason']; $this->_listError .= '('.$numbers_where[$item['number']].','.$item['number'].','.$item['reason'].') '; $this->_tableError .= '<tr><td>'.$numbers_where[$item['number']].'</td><td>'.$item['number'].'</td><td>'.$item['reason'].'</td></tr>'; } } } if (!empty($this->_listError) || $this->_countError > 0) $logger->err('Wyslano:'.$this->_countSuccess.' nie wyslano:'.$this->_countError.' Lista numerow na ktore nie wyslano sms: (id, phone, reason) '.$this->_listError); else $logger->info('Wyslano:'.$this->_countSuccess); } elseif ($SmsSoapClient->getCodeError() != 0) { $codeError = $SmsSoapClient->getCodeError(); $messageError = $SmsSoapClient->getMessageError(); $logger->err($codeError.' :: '.$messageError); $this->sendErrorMail($codeError.' :: '.$messageError); } //debug($response); } else { $logger->info('Brak numerow oczekujacych na wyslanie'); } } else { //nie polaczono $codeError = $SmsSoapClient->getCodeError(); $messageError = $SmsSoapClient->getMessageError(); $logger->err($codeError.' :: '.$messageError); $this->sendErrorMail($codeError.' :: '.$messageError); } } catch (Exception $e) { $logger->err($e->getMessage()); $this->sendErrorMail($e->getMessage()); } return true; }
public function loadAction() { $this->_helper->layout->disableLayout(); $filters = $this->_getAllParams(); /* * Items count query */ $count_query = $this->_service->newItemQuery(); $count_query->setContent('stats'); $bq = ''; if (isset($filters['country']) && $filters['country'] != '') { $bq .= "[target country: {$filters['country']}]"; } if (isset($filters['site_id']) && $filters['site_id'] != '') { $bq .= "[site: {$filters['site_id']}]"; } if (isset($filters['product_type']) && $filters['product_type'] != '') { $bq .= "[product_type: {$filters['product_type']}]"; } if ($bq != '') { $count_query->setBq($bq); } $count_feed = $this->_service->getGbaseItemFeed($count_query); $total_count = $count_feed->getTotalResults(); /* * Items content query */ $query = $this->_service->newItemQuery(); $query->setContent('attributes,meta'); if ($bq != '') { $query->setBq($bq); } $query->setMaxResults(isset($filters['limit']) ? $filters['limit'] : 25); $query->setStartIndex(isset($filters['start']) ? $filters['start'] + 1 : 1); $orderBy = ''; switch ($filters['sort']) { case 'price': switch ($filters['country']) { case 'US': $orderBy = 'price(float usd)'; break; case 'DE': $orderBy = 'price(float eur)'; break; case 'GB': $orderBy = 'price(float gbp)'; break; default: $orderBy = ''; break; } break; case 'modification_time': $orderBy = "{$filters['sort']}"; break; default: $orderBy = "{$filters['sort']}({$filters['sortType']})"; break; } if ($orderBy != '') { $query->setOrderBy($orderBy); $query->setSortOrder($filters['dir'] == 'ASC' ? 'ascending' : 'descending'); } try { $feed = $this->_service->getGbaseItemFeed($query); } catch (Exception $e) { Axis::message()->addError($this->view->escape($e->getMessage())); try { $log = new Zend_Log(new Zend_Log_Writer_Stream(Axis::config()->system->path . '/var/logs/gbase.log')); $log->err($e->getMessage()); } catch (Exception $e) { Axis::message()->addError($e->getMessage()); } exit; } $result = array(); $i = 0; foreach ($feed->entries as $entry) { $result[$i]['title'] = $entry->title->getText(); $result[$i]['id'] = $entry->id->getText(); $result[$i]['modification_time'] = substr($entry->updated->getText(), 0, 10); /* * Base attributes */ $price = $entry->getGbaseAttribute('price'); $quantity = $entry->getGbaseAttribute('quantity'); $expiration_date = $entry->getGbaseAttribute('expiration_date'); $language = $entry->getGbaseAttribute('item_language'); $result[$i]['price'] = $price[0]->text; $result[$i]['currency'] = substr($price[0]->text, -3); $result[$i]['quantity'] = $quantity[0]->text; $result[$i]['expiration_date'] = substr($expiration_date[0]->text, 0, 10); $result[$i]['language'] = $language[0]->text; /* * Private attributes */ $localId = $entry->getGbaseAttribute('local_id'); $site = $entry->getGbaseAttribute('site'); $result[$i]['local_id'] = $localId[0]->text; $result[$i]['site_id'] = $site[0]->text; /* * Extension Attributes (getting clicks, imressions, page_views) */ $extensionElements = $entry->getExtensionElements(); foreach ($extensionElements as $extElement) { $innerElements = $extElement->getExtensionElements(); foreach ($innerElements as $innerElement) { $elName = $innerElement->rootElement; $attributes = $innerElement->getExtensionAttributes(); foreach ($attributes as $aName => $aValue) { $result[$i][$elName] = $aValue['value']; } } } /* * Control attributes (draft, dissaproved, published) */ $control = $entry->getControl(); $result[$i]['status'] = 'published'; if (isset($control)) { $draftElement = $control->draft; $elName = $draftElement->rootElement; $result[$i]['status'] = $elName; $extensionElements = $control->getExtensionElements(); foreach ($extensionElements as $extElement) { $elName = $extElement->rootElement; $result[$i]['status'] = $elName; } } $i++; } $this->_helper->json->sendJson(array('total_count' => $total_count->getText(), 'feed' => $result)); }
define("LOOMP_USER_URI_NS", LOOMP_BASE_PATH . "/users/"); if (!strstr($_SERVER['REQUEST_URI'], 'install') && !strstr($_SERVER['REQUEST_URI'], 'error')) { try { // set database connection and retrieve the rdf model $logger->debug("Initializing RDF store"); $rdfStore = ModelFactory::getDbStore($configuration->loomp->db->type, $configuration->loomp->db->host, $configuration->loomp->db->name, $configuration->loomp->db->user, $configuration->loomp->db->pass); //die(LOOMP_MODEL_URI); $registry->rdfModel = $rdfStore->getModel(LOOMP_MODEL_URI); if ($registry->rdfModel === false) { throw new Exception("Failed to initialize RDF store."); } $logger->debug("Initializing Loomp API"); $registry->loompApi = new LoompApi(); // Active Record stuff require_once RDFAPI_INCLUDE_DIR . 'util/adodb/adodb-active-record.inc.php'; require_once APPLICATION_PATH . '/model/User.php'; require_once APPLICATION_PATH . '/model/Access.php'; ADOdb_Active_Record::SetDatabaseAdapter($rdfStore->getDbConn()); } catch (Exception $e) { $logger->err("Init error: " . $e->getMessage()); $logger->err($e->getTraceAsString()); $loomp_path = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . "/error/nosetup"; header("Location: " . $loomp_path); die; } } // CLEANUP - remove items from global scope // This will clear all our local boostrap variables from the global scope of // this script (and any scripts that called bootstrap). This will enforce // object retrieval through the Applications's Registry unset($frontController, $view, $configuration, $arsConfig, $registry, $logger, $translate);
/** * Setup Logging * * @throws Exception If logging file couldn't be opened. * @return void * */ protected function _initLogging() { $this->bootstrap('Configuration'); $config = $this->getResource('Configuration'); // Detect if running in CGI environment. $logFilename = 'opus.log'; if (!array_key_exists('SERVER_PROTOCOL', $_SERVER) and !array_key_exists('REQUEST_METHOD', $_SERVER)) { $logFilename = "opus-console.log"; } $logfilePath = $config->workspacePath . '/log/' . $logFilename; $logfile = @fopen($logfilePath, 'a', false); if ($logfile === false) { // TODO use Opus exception throw new Exception('Failed to open logging file:' . $logfilePath); } $GLOBALS['id_string'] = uniqid(); // Write ID string to global variables, so we can identify/match individual runs. $format = '%timestamp% %priorityName% (%priority%, ID ' . $GLOBALS['id_string'] . '): %message%' . PHP_EOL; $formatter = new Zend_Log_Formatter_Simple($format); $writer = new Zend_Log_Writer_Stream($logfile); $writer->setFormatter($formatter); $logger = new Zend_Log($writer); $logLevelName = 'INFO'; $logLevelNotConfigured = false; if (isset($config->log->level)) { $logLevelName = strtoupper($config->log->level); } else { $logLevelNotConfigured = true; } $zendLogRefl = new ReflectionClass('Zend_Log'); $invalidLogLevel = false; $logLevel = $zendLogRefl->getConstant($logLevelName); if (empty($logLevel)) { $logLevel = Zend_Log::INFO; $invalidLogLevel = true; } // filter log output $priorityFilter = new Zend_Log_Filter_Priority($logLevel); Zend_Registry::set('LOG_LEVEL', $logLevel); $logger->addFilter($priorityFilter); if ($logLevelNotConfigured) { $logger->warn('Log level not configured, using default \'' . $logLevelName . '\'.'); } if ($invalidLogLevel) { $logger->err('Invalid log level \'' . $logLevelName . '\' configured.'); } Zend_Registry::set('Zend_Log', $logger); $logger->debug('Logging initialized'); return $logger; }
public static function err($message) { self::$_logger->err($message); }
try { $doc = new Opus_Document($docId); } catch (Opus_Model_NotFoundException $e) { continue; } $removeMscSubjects = array(); $removeDdcSubjects = array(); try { if (is_object($mscRole)) { $removeMscSubjects = migrateSubjectToCollection($doc, 'msc', $mscRole->getId(), 'MigrateSubjectMSC'); } if (is_object($ddcRole)) { $removeDdcSubjects = migrateSubjectToCollection($doc, 'ddc', $ddcRole->getId(), 'MigrateSubjectDDC'); } } catch (Exception $e) { $logger->err("fatal error while parsing document {$docId}: " . $e); continue; } if (count($removeMscSubjects) > 0 or count($removeDdcSubjects) > 0) { $changedDocumentIds[] = $docId; try { $doc->unregisterPlugin('Opus_Document_Plugin_Index'); $doc->store(); $logger->info("changed document {$docId}"); } catch (Exception $e) { $logger->err("fatal error while STORING document {$docId}: " . $e); } } } $logger->info("changed " . count($changedDocumentIds) . " documents: " . implode(",", $changedDocumentIds)); function checkDocumentHasCollectionId($doc, $collectionId)