示例#1
0
 /**
  * Show execution time
  */
 public function __destruct()
 {
     if (!$this->log) {
         return;
     }
     $this->log->debug('Complete in ' . round(microtime(true) - $this->_timeStart, 3) . ' seconds.  ' . $this->getMemoryUsageNow() . ' of memory used.');
     $this->log->debug('== Script execution completed ==');
 }
示例#2
0
 private function getFacets()
 {
     $config = Zend_Registry::get('Zend_Config');
     if (!isset($config->searchengine->solr->facets)) {
         $this->log->debug('config parameter searchengine.solr.facets is not defined -- no facets will be displayed');
         return array();
     }
     if (!array_key_exists('facet_counts', $this->jsonResponse) || !array_key_exists('facet_fields', $this->jsonResponse['facet_counts'])) {
         return array();
     }
     $facetsResult = $this->jsonResponse['facet_counts']['facet_fields'];
     $facets = explode(",", $config->searchengine->solr->facets);
     $result = array();
     foreach ($facets as $facet) {
         $facet = trim($facet);
         $facetItems = array();
         foreach ($this->getFacet($facetsResult, $facet) as $text => $count) {
             if ($facet == 'year_inverted') {
                 $valueParts = explode(':', $text, 2);
                 $text = $valueParts[1];
             }
             array_push($facetItems, new Opus_SolrSearch_FacetItem($text, $count));
         }
         if ($facet == 'year_inverted') {
             $facet = 'year';
         }
         $result[$facet] = $facetItems;
     }
     return $result;
 }
示例#3
0
 /**
  *
  * @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();
 }
示例#4
0
 public function testLogSimple()
 {
     $writer = new Zfb_Log_Writer_Rolling_File(dirname(__FILE__) . '/resources/application.log');
     $writer->setFileMaxSize("10KB");
     $writer->setMaxFiles(10);
     $this->zendLog->addWriter($writer);
     for ($i = 0; $i < 5; $i++) {
         $this->zendLog->debug('testLogSimple - test debug using rolling file : ' . $i);
     }
     $dir = dirname(__FILE__) . '/resources';
     $content = file_get_contents($dir . '/application.log');
     $this->assertFileExists($dir . '/application.log');
     $this->assertRegExp('~testLogSimple - test debug using rolling file : 0~', $content);
     $this->assertRegExp('~testLogSimple - test debug using rolling file : 1~', $content);
     $this->assertRegExp('~testLogSimple - test debug using rolling file : 2~', $content);
     $this->assertRegExp('~testLogSimple - test debug using rolling file : 3~', $content);
     $this->assertRegExp('~testLogSimple - test debug using rolling file : 4~', $content);
 }
示例#5
0
 /**
  * Posts the given xml document to the Solr server without using the solr php client library.
  *
  * @param DOMDocument $solrXml
  * @return void
  */
 private function sendSolrXmlToServer($solrXml)
 {
     $stream = stream_context_create();
     stream_context_set_option($stream, array('http' => array('method' => 'POST', 'header' => 'Content-Type: text/xml; charset=UTF-8', 'content' => $solrXml->saveXML(), 'timeout' => '3600')));
     $response = new Apache_Solr_Response(@file_get_contents($this->index_server_url . '/update', false, $stream));
     $this->log->debug('Solr Response Status: ' . $response->getHttpStatus());
     if (!$response->getRawResponse()) {
         throw new Opus_SolrSearch_Index_Exception("Solr Server {$this->index_server_url} not responding.");
     }
 }
示例#6
0
 /**
  * Performs the HTTP request and parses the result to return the Result Object
  *
  * @param string $httpMethod
  * @return Tid_Zend_REST_Json_Result
  */
 protected function _performRequest($httpMethod)
 {
     // For calculating the time spent in the request
     $initTime = microtime(true);
     // Perform the HTTP request
     $response = self::getHttpClient()->request($httpMethod);
     // Log the request and response
     if ($this->_logger) {
         $requestDuration = (microtime(true) - $initTime) * 1000;
         $this->_logger->debug("\nRESTClient request: " . self::getHttpClient()->getLastRequest() . "\n\nRESTClient response: " . round($requestDuration, 2) . "ms\n" . self::getHttpClient()->getLastResponse() . "\n");
     }
     if ($this->_throwExceptions && $response->isError()) {
         /**
          * If the client is configured to throw exceptions, parse the HTTP
          * response headers to throw the corresponding exception
          */
         switch ($response->getStatus()) {
             case 400:
                 require_once 'Tid/Zend/REST/Json/Exception/BadRequest.php';
                 throw new Tid_Zend_REST_Json_Exception_BadRequest(self::getHttpClient()->getLastResponse(), $response->getStatus());
             case 401:
                 require_once 'Tid/Zend/REST/Json/Exception/Unauthorized.php';
                 throw new Tid_Zend_REST_Json_Exception_Unauthorized(self::getHttpClient()->getLastResponse(), $response->getStatus());
             case 403:
                 require_once 'Tid/Zend/REST/Json/Exception/Forbidden.php';
                 throw new Tid_Zend_REST_Json_Exception_Forbidden(self::getHttpClient()->getLastResponse(), $response->getStatus());
             case 404:
                 require_once 'Tid/Zend/REST/Json/Exception/NotFound.php';
                 throw new Tid_Zend_REST_Json_Exception_NotFound(self::getHttpClient()->getLastResponse(), $response->getStatus());
             case 502:
                 require_once 'Tid/Zend/REST/Json/Exception/BadGateway.php';
                 throw new Tid_Zend_REST_Json_Exception_BadGateway(self::getHttpClient()->getLastResponse(), $response->getStatus());
             case 503:
                 require_once 'Tid/Zend/REST/Json/Exception/ServiceUnaivailable.php';
                 throw new Tid_Zend_REST_Json_Exception_ServiceUnavailable(self::getHttpClient()->getLastResponse(), $response->getStatus());
             default:
                 require_once 'Tid/Zend/REST/Json/Exception/InternalError.php';
                 throw new Tid_Zend_REST_Json_Exception_InternalError(self::getHttpClient()->getLastResponse(), $response->getStatus());
         }
     }
     // Hydrate an object with the result contents
     try {
         if (!$response->getBody()) {
             $result = null;
         } else {
             require_once 'Zend/Json.php';
             $result = Zend_Json::decode($response->getBody(), Zend_Json::TYPE_OBJECT);
         }
     } catch (Zend_Json_Exception $e) {
         require_once 'Tid/Zend/REST/Json/Exception/InvalidFormat.php';
         throw new Tid_Zend_REST_Json_Exception_InvalidFormat($response->getBody(), $response->getStatus());
     }
     require_once 'Tid/Zend/REST/Json/Result.php';
     return new Tid_Zend_REST_Json_Result($result, $response->getHeaders(), $response->getStatus(), $response->isSuccessful());
 }
 /**
  * log something to the logger
  * 
  * @param string $logMessage
  */
 protected function _log($logMessage)
 {
     if ($this->_logger === null) {
         return;
     }
     try {
         $this->_logger->debug($logMessage);
     } catch (Zend_Log_Exception $zle) {
         // the logger stream might have been closed already
     }
 }
示例#8
0
 protected function saveLog($errors)
 {
     $logger = new Zend_Log();
     $writer = new Zend_Log_Writer_Stream('application/tmp/erro/error.xml');
     $formatter = new Zend_Log_Formatter_Xml();
     $writer->setFormatter($formatter);
     $logger->addWriter($writer);
     $exception = $errors->exception;
     $exception->getTraceAsString();
     $logger->debug($exception->getMessage() . "\r\n");
 }
 /**
  * perform rollBack on all transactionables with open transactions
  * 
  * @return void
  */
 public function rollBack()
 {
     if ($this->_logger instanceof Zend_Log) {
         $this->_logger->debug(__METHOD__ . '::' . __LINE__ . "  rollBack request, rollBack all transactionables");
     }
     foreach ($this->_openTransactionables as $transactionable) {
         if ($transactionable instanceof Zend_Db_Adapter_Abstract) {
             $transactionable->rollBack();
             #Tinebase_Backend_Sql_Command::setAutocommit($transactionable,true);
         }
     }
     $this->_openTransactionables = array();
     $this->_openTransactions = array();
 }
示例#10
0
 public function errorAction()
 {
     $errors = $this->_getParam('error_handler');
     $exception = $errors->exception;
     try {
         $log = new Zend_Log(new Zend_Log_Writer_Stream(Axis::config()->system->path . Axis::config()->log->main->php));
         $log->debug($exception->getMessage() . "\n" . $exception->getTraceAsString());
     } catch (Zend_Log_Exception $e) {
         //who cares
     }
     $this->getResponse()->clearBody();
     if ($this->getRequest()->isXmlHttpRequest()) {
         Axis::message()->addError($exception->getMessage());
         $this->_helper->json->sendFailure();
     } else {
         $this->view->pageTitle = Axis::translate('admin')->__('Error');
         $this->view->error = str_replace("\n", "<br />\n", $exception->getMessage() . "\n" . $exception->getTraceAsString());
         $this->render();
     }
 }
示例#11
0
 public function errorAction()
 {
     $errors = $this->_getParam('error_handler');
     // Is this a Zend not found exception ?
     switch ($errors->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
             return $this->_forward('notfound', null, null, array('message' => 'No such controller'));
             break;
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             return $this->_forward('notfound', null, null, array('message' => 'No such action'));
             break;
     }
     // Application error
     $exception = $errors->exception;
     // Is this a stuffpress not found exception ?
     if (get_class($exception) == 'Stuffpress_NotFoundException') {
         return $this->_forward('notfound', null, null, array('message' => $exception->getMessage()));
     }
     // Is this a stuffpress access denied exception ?
     if (get_class($exception) == 'Stuffpress_AccessDeniedException') {
         return $this->_forward('denied', null, null, array('message' => $exception->getMessage()));
     }
     // Log the error
     $config = Zend_Registry::get("configuration");
     $path = isset($config->path->logs) ? $config->path->logs : Zend_Registry::get("root") . '/logs/';
     $root = Zend_Registry::get("root");
     $uri = Zend_Registry::isRegistered("uri") ? Zend_Registry::get("uri") : '';
     $host = Zend_Registry::isRegistered("host") ? Zend_Registry::get("host") : '';
     $log = new Zend_Log(new Zend_Log_Writer_Stream($path . '/applicationException.log'));
     $log->debug("Exception for request http://{$host}/{$uri}\n" . $exception->getMessage() . "\n" . $exception->getTraceAsString() . "\n----------------------------\n\n");
     // Are we in debug mode ?
     $config = Zend_Registry::get("configuration");
     $debug = $config->debug;
     // Don't forget to clear the response body, just in case
     $this->getResponse()->clearBody();
     if ($debug) {
         $this->view->message = $exception->getMessage();
         $this->view->trace = $exception->getTraceAsString();
         return $this->render('debug');
     }
 }
示例#12
0
 public function errorAction()
 {
     //error_log('errorAction');
     $this->setCanonicalUrl(false);
     $this->getResponse()->clearBody();
     $errors = $this->_getParam('error_handler');
     $exception = $errors->exception;
     // log all kind of errors
     try {
         $log = new Zend_Log(new Zend_Log_Writer_Stream(Axis::config()->system->path . Axis::config()->log->main->php));
         $log->debug($exception->getMessage() . "\n" . $exception->getTraceAsString());
     } catch (Zend_Log_Exception $e) {
         //who cares
     }
     switch ($errors->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             // 404 error -- controller or action not found
             return $this->_forward('not-found');
             //return $this->notFoundAction();
         //return $this->notFoundAction();
         default:
             // application error
             $this->_helper->layout->setLayout('layout_error');
             // hardcoded layout for application errors
             $this->getResponse()->setHttpResponseCode(500);
             $this->view->pageTitle = Axis::translate('core')->__('An error has occured processing your request');
             $this->view->meta()->setTitle($this->view->pageTitle);
             if (Axis::app()->getEnvironment() == 'development') {
                 //                    $traceAsString = preg_replace(
                 //                        '/(#\d+\s)(\/.*\/[^\/]+(?:\.php|\.phtml))/',
                 ////                        "<a onclick=\"window.open('file://$2');return false;\">$1$2</a>",
                 //                        "<a href=\"file://$2\">$1$2</a>",
                 //                        $exception->getTraceAsString()
                 //                    );
                 $this->view->error = str_replace(AXIS_ROOT . '/', '/', $exception->getMessage() . "\n<strong>" . Axis::translate('core')->__('Trace') . ":</strong>\n" . $this->view->escape($exception->getTraceAsString()));
             }
             break;
     }
 }
 public function errorAction()
 {
     $errors = $this->_getParam('error_handler');
     $exception = $errors->exception;
     $message = $exception->getMessage();
     $trace = $exception->getTraceAsString();
     $controller = trim($this->getRequest()->getParam('controller'));
     switch ($errors->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
         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()->setRawHeader('HTTP/1.1 404 Not Found');
             // ... get some output to display...
             break;
         default:
             if (!preg_match('/Invalid controller specified/', $exception->getMessage())) {
                 // application error; display error page, but don't change
                 // status code
                 // Log the exception:
                 $log = new Zend_Log(new Zend_Log_Writer_Stream(LOG_DIR . '/php-exceptions-' . date('m-d-Y') . '.log'));
                 $log->debug($exception->getMessage() . "\n" . $exception->getTraceAsString());
             }
     }
     // clear previous content
     $this->getResponse()->clearBody();
     if (is_array(@$_SESSION['site']['permissions']['admin'])) {
         if (in_array('can_view_debug_messages', $_SESSION['site']['permissions']['admin'])) {
             $this->view->message = $message;
             $this->view->trace = $trace;
         } else {
             $this->view->message = fetchTranslation('http_error_404_text');
             $this->view->trace = null;
         }
     } else {
         $this->view->message = fetchTranslation('http_error_404_text');
         $this->view->trace = null;
     }
 }
示例#14
0
文件: Action.php 项目: alexukua/opus4
 private function performRedirect($action, $message = null, $controller = null, $module = null, $params = array(), $exit = false)
 {
     if (!is_null($message)) {
         if (is_array($message) && count($message) !== 0) {
             $keys = array_keys($message);
             $key = $keys[0];
             if ($key === 'failure' || $key === 'notice') {
                 $this->__flashMessenger->addMessage(array('level' => $key, 'message' => $message[$key]));
             } else {
                 $this->__flashMessenger->addMessage(array('level' => 'notice', 'message' => $message[$key]));
             }
         } else {
             if (is_string($message) && $message != '') {
                 $this->__flashMessenger->addMessage(array('level' => 'notice', 'message' => $message));
             }
         }
     }
     $this->_logger->debug("redirect to module: {$module} controller: {$controller} action: {$action}");
     $this->__redirector->gotoSimple($action, $controller, $module, $params);
     $this->__redirector->setExit($exit);
     return;
 }
 public function errorAction()
 {
     $errors = $this->_getParam('error_handler');
     $exception = $errors->exception;
     $log = new Zend_Log(new Zend_Log_Writer_Stream('/tmp/applicationException.log'));
     $log->debug($exception->getMessage() . "\n" . $exception->getTraceAsString());
     if (!$errors || !$errors instanceof ArrayObject) {
         $this->view->message = 'You have reached the error page';
         return;
     }
     switch ($errors->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
         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);
             $priority = Zend_Log::NOTICE;
             $this->view->message = 'Page not found';
             break;
         default:
             // application error
             $this->getResponse()->setHttpResponseCode(500);
             $priority = Zend_Log::CRIT;
             $this->view->message = 'Application error';
             break;
     }
     // Log exception, if logger available
     if ($log = $this->getLog()) {
         $log->log($this->view->message, $priority, $errors->exception);
         $log->log('Request Parameters', $priority, $errors->request->getParams());
     }
     // conditionally display exceptions
     if ($this->getInvokeArg('displayExceptions') == true) {
         $this->view->exception = $errors->exception;
     }
     $this->view->request = $errors->request;
 }
示例#16
0
 /**
  * read ldap / get users and groups from tine an create mapping
  * 
  * @return array
  */
 protected function _getGroupMapping()
 {
     $this->_logger->info(__METHOD__ . '::' . __LINE__ . ' Fetching user mapping ...');
     $filter = Zend_Ldap_Filter::andFilter(Zend_Ldap_Filter::string($this->_groupBaseFilter));
     $mapping = array();
     $groupNameMapping = $this->_config->groupNameMapping ? $this->_config->groupNameMapping->toArray() : array();
     $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' Group name mapping: ' . print_r($groupNameMapping, TRUE));
     $ldapGroups = $this->_ldap->search($filter, $this->_config->ldap->baseDn, $this->_groupSearchScope, array('*', '+'));
     foreach ($ldapGroups as $group) {
         $groupname = isset($groupNameMapping[$group['cn'][0]]) ? $groupNameMapping[$group['cn'][0]] : $group['cn'][0];
         $ldapUuid = $group['entryuuid'][0];
         try {
             $tineGroup = $this->_tineGroupBackend->getGroupByName($groupname);
             $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' Group ' . $groupname . ' (' . $group['cn'][0] . '): ' . $tineGroup->getId() . ' -> ' . $ldapUuid);
             $mapping[$tineGroup->getId()] = $ldapUuid;
         } catch (Tinebase_Exception_Record_NotDefined $tenf) {
             // @todo should be: Tinebase_Exception_NotFound
             $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' Group ' . $groupname . ' (' . $group['cn'][0] . '): ' . $tenf->getMessage());
         }
     }
     $this->_logger->info(__METHOD__ . '::' . __LINE__ . ' Found ' . count($mapping) . ' groups for the mapping.');
     $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($mapping, TRUE));
     return $mapping;
 }
示例#17
0
 /**
  * Log Query Stats
  *
  * Prints out profiling information for queries executed.
  *
  * @param bool $showQueries If true, queries themselves are printed to screen
  * @return void
  */
 public function logQueryStats($showQueries = false)
 {
     $profiler = $this->zendDb()->getProfiler();
     $totalTime = $profiler->getTotalElapsedSecs();
     $queryCount = $profiler->getTotalNumQueries();
     $longestTime = 0;
     $longestQuery = null;
     $out = '';
     if ($showQueries) {
         $out .= '<table border="1" cellspacing="0" cellpadding="5">';
     }
     foreach ($profiler->getQueryProfiles() as $i => $query) {
         if ($showQueries) {
             $out .= '<tr><td>' . $i . '</td>';
             $out .= '<td>' . $query->getElapsedSecs() . '</td><td>' . $query->getQuery() . '</td>';
             $out .= '</tr>';
         }
         if ($query->getElapsedSecs() > $longestTime) {
             $longestTime = $query->getElapsedSecs();
             $longestQuery = $query->getQuery();
         }
     }
     if ($showQueries) {
         $out .= '</table>';
     }
     $out .= 'Executed ' . $queryCount . ' queries in ' . $totalTime . ' seconds' . "\n";
     $out .= 'Average query length: ' . $totalTime / $queryCount . ' seconds' . "\n";
     $out .= 'Queries per second: ' . $queryCount / $totalTime . "\n";
     $out .= 'Longest query length: ' . $longestTime . "\n";
     $out .= "Longest query: \n" . $longestQuery . "\n";
     if ($this->_logger) {
         $this->_logger->debug($out);
     } else {
         error_log($out);
     }
 }
示例#18
0
 /**
  * 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);
     }
 }
示例#19
0
 /**
  * Fetches all rows according to the where, order, count, offset rules.
  *
  * @param string|array $where  Where clause.
  * @param string|array $order  Order by.
  * @param string|array $count  Limit query.
  * @param string|array $offset Query offset.
  * @param string       $select The comma-separated columns of the joined tables.
  * @param string       $join   Join Statements.
  *
  * @return Zend_Db_Table_Rowset The rowset with the results.
  */
 public function fetchAll($where = null, $order = null, $count = null, $offset = null, $select = null, $join = null)
 {
     $wheres = array();
     if (array_key_exists('hasMany', $this->_relations)) {
         $keyName = $this->_translateKeyFormat($this->_relations['hasMany']['classname']);
         $wheres[] = sprintf('%s = %d', $this->getAdapter()->quoteIdentifier($keyName), (int) $this->_relations['hasMany']['id']);
     }
     if (null !== $where) {
         $wheres[] = $where;
     }
     $where = is_array($wheres) && count($wheres) > 0 ? implode(' AND ', $wheres) : null;
     if (null !== $this->_log) {
         $this->_log->debug($where);
     }
     if (null === $order) {
         $order = 'id';
     }
     // In case of join strings please note that the resultset is read only.
     if (null !== $join) {
         $rows = $this->_fetchWithJoin($where, $order, $count, $offset, $select, $join);
     } else {
         $rows = $this->_fetchWithOutJoin($where, $order, $count, $offset);
     }
     $result = array();
     foreach ($rows as $row) {
         $instance = clone $this;
         $instance->_data = array();
         if ($row instanceof Zend_Db_Table_Row) {
             $data = $row->toArray();
         } else {
             $data = $row;
         }
         foreach ($data as $k => $v) {
             $instance->_data[self::convertVarFromSql($k)] = $v;
         }
         $instance->_storedId = $instance->_data['id'];
         $instance->_originalData = $instance->_data;
         $result[] = $instance;
     }
     return $result;
 }
示例#20
0
<?php

// Quick example to test a local Node_log server using the defaults.
// Rob Morgan - 12-02-2010
require_once 'Zend/Log.php';
require_once 'library/ZendX/Log/Writer/Nodelog.php';
$writer = new ZendX_Log_Writer_Nodelog();
$logger = new Zend_Log($writer);
$logger->info('Informational message');
$logger->debug('Debug message');
 /**
  * Prio 7: Debug: debug messages
  *
  * @param string $msg
  * @param EngineBlock_Log_Message_AdditionalInfo $additionalInfo
  * @return void
  */
 public function debug($msg, $additionalInfo = null)
 {
     $this->_setAdditionalEventItems($additionalInfo);
     parent::debug($msg);
 }
示例#22
0
文件: Db.php 项目: lchen01/STEdwards
 /**
  * Log SQL query if logging is configured.
  * 
  * This logs the query before variable substitution from bind params.
  *
  * @param string|Zend_Db_Select $sql
  */
 protected function log($sql)
 {
     if ($this->_logger) {
         $this->_logger->debug((string) $sql);
     }
 }
示例#23
0
 /**
  * Waits for the server to send the specified tag back.
  *
  * @param string $tag Tag to wait for from the server.
  *
  * @return boolean|SimpleXMLElement
  */
 protected function waitForServer($tag)
 {
     $this->_logger->debug("Tag we're waiting for: " . $tag);
     $fromServer = false;
     // If there is nothing left in the buffer, wait for the stream to update
     if (count($this->_buffer) == 0 && $this->_stream->select() > 0) {
         $response = '';
         $done = false;
         // Read data from the connection.
         while (!$done) {
             $response .= $this->_stream->read(4096);
             if ($this->_stream->select() == 0) {
                 $done = true;
             }
         }
         $this->_logger->debug('Response (Xmpp_Connection): ' . $response);
         // If the response isn't empty, load it into a SimpleXML element
         if (trim($response) != '') {
             // If the response from the server starts (where "starts
             // with" means "appears after the xml prologue if one is
             // present") with "<stream:stream and it doesn't have a
             // closing "</stream:stream>" then we should append one so
             // that it can be easily loaded into a SimpleXMLElement,
             // otherwise it will cause an error to be thrown because of
             // malformed XML.
             // Check if response starts with XML Prologue:
             if (preg_match("/^<\\?xml version='1.0'( encoding='UTF-8')?\\?>/", $response, $matches) == 1) {
                 $offset = strlen($matches[0]);
                 $prologue = $matches[0];
             } else {
                 $offset = 0;
             }
             // Check if first part of the actual response starts with
             // <stream:stream
             if (strpos($response, '<stream:stream ') === $offset) {
                 // If so, append a closing tag
                 $response .= '</stream:stream>';
             }
             // For consistent handling and correct stream namespace
             // support, we should wrap all responses in the
             // stream:stream tags to make sure everything works as
             // expected. Unless the response already contains such tags.
             if (strpos($response, '<stream:stream') === false) {
                 $response = '<stream:stream ' . 'xmlns:stream="http://etherx.jabber.org/streams" ' . "xmlns:ack='http://www.xmpp.org/extensions/xep-0198.html#ns' " . 'xmlns="jabber:client" ' . 'from="' . $this->_realm . '" ' . 'xml:lang="en" version="1.0">' . $response . '</stream:stream>';
             }
             // If the xml prologue should be at the start, move it
             // because it will now be in the wrong place. We can assume
             // if $offset is not 0 that there was a prologue.
             if ($offset != 0) {
                 $response = $prologue . str_replace($prologue, '', $response);
             }
             $xml = simplexml_load_string($response);
             // If we want the stream element itself, just return that,
             // otherwise check the contents of the stream.
             if ($tag == 'stream:stream') {
                 $fromServer = $xml;
             } else {
                 if ($xml instanceof SimpleXMLElement && $xml->getName() == 'stream') {
                     // Get the namespaces used at the root level of the
                     // document. Add a blank namespace on for anything that
                     // isn't namespaced. Then we can iterate over all of the
                     // elements in the doc.
                     $namespaces = $xml->getNamespaces();
                     $namespaces['blank'] = '';
                     foreach ($namespaces as $namespace) {
                         foreach ($xml->children($namespace) as $child) {
                             if ($child instanceof SimpleXMLElement) {
                                 $this->_buffer[] = $child;
                             }
                         }
                     }
                 }
             }
         }
     }
     $this->_logger->debug('Contents of $fromServer: ' . var_export($fromServer, true));
     $this->_logger->debug('Contents of $this->_buffer before foreach: ' . var_export($this->_buffer, true));
     // Now go over what is in the buffer and return anything necessary
     foreach ($this->_buffer as $key => $stanza) {
         // Only bother looking for more tags if one has not yet been found.
         if ($fromServer === false) {
             // Remove this element from the buffer because we do not want it to
             // be processed again.
             unset($this->_buffer[$key]);
             // If this the tag we want, save it for returning.
             if ($tag == '*' || $stanza->getName() == $tag) {
                 $fromServer = $stanza;
             }
         }
     }
     $this->_logger->debug('Contents of $this->_buffer after foreach: ' . var_export($this->_buffer, true));
     return $fromServer;
 }
示例#24
0
 protected function _handlePost()
 {
     if (count($_GET) == 1) {
         $arrayKeys = array_keys($_GET);
         $requestParameters = $this->_decodeRequestParameters($arrayKeys[0]);
     } else {
         $requestParameters = $this->_getRequestParameters();
     }
     if ($this->_logger instanceof Zend_Log) {
         $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' REQUEST ' . print_r($requestParameters, true));
     }
     $userAgent = $this->_request->getServer('HTTP_USER_AGENT', $requestParameters['deviceType']);
     $policyKey = $this->_request->getServer('HTTP_X_MS_POLICYKEY');
     if ($this->_logger instanceof Zend_Log) {
         $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " Agent: {$userAgent}  PolicyKey: {$policyKey} ASVersion: {$requestParameters['protocolVersion']} Command: {$requestParameters['command']}");
     }
     $className = 'Syncope_Command_' . $requestParameters['command'];
     if (!class_exists($className)) {
         throw new Syncope_Exception_CommandNotFound('unsupported command ' . $requestParameters['command']);
     }
     // get user device
     $device = $this->_getUserDevice($this->_userId, $requestParameters['deviceId'], $requestParameters['deviceType'], $userAgent, $requestParameters['protocolVersion']);
     if ($this->_request->getServer('CONTENT_TYPE') == 'application/vnd.ms-sync.wbxml') {
         // decode wbxml request
         try {
             $decoder = new Wbxml_Decoder($this->_body);
             $requestBody = $decoder->decode();
             if ($this->_logger instanceof Zend_Log) {
                 $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " xml request: " . $requestBody->saveXML());
             }
         } catch (Wbxml_Exception_UnexpectedEndOfFile $e) {
             $requestBody = NULL;
         }
     } else {
         $requestBody = $this->_body;
     }
     try {
         $command = new $className($requestBody, $device, $policyKey);
         $command->handle();
         if (PHP_SAPI !== 'cli') {
             header("MS-Server-ActiveSync: 8.3");
         }
         $response = $command->getResponse();
     } catch (Syncope_Exception_PolicyKeyMissing $sepkm) {
         if ($this->_logger instanceof Zend_Log) {
             $this->_logger->warn(__METHOD__ . '::' . __LINE__ . " X-MS-POLICYKEY missing (" . $_command . ')');
         }
         header("HTTP/1.1 400 header X-MS-POLICYKEY not found");
         return;
     } catch (Syncope_Exception_ProvisioningNeeded $sepn) {
         if ($this->_logger instanceof Zend_Log) {
             $this->_logger->info(__METHOD__ . '::' . __LINE__ . " provisioning needed");
         }
         header("HTTP/1.1 449 Retry after sending a PROVISION command");
         return;
     } catch (Exception $e) {
         if ($this->_logger instanceof Zend_Log) {
             $this->_logger->crit(__METHOD__ . '::' . __LINE__ . " unexpected exception occured: " . get_class($e));
         }
         if ($this->_logger instanceof Zend_Log) {
             $this->_logger->crit(__METHOD__ . '::' . __LINE__ . " exception message: " . $e->getMessage());
         }
         if ($this->_logger instanceof Zend_Log) {
             $this->_logger->info(__METHOD__ . '::' . __LINE__ . " " . $e->getTraceAsString());
         }
         header("HTTP/1.1 500 Internal server error");
         return;
     }
     if ($response instanceof DOMDocument) {
         if ($this->_logger instanceof Zend_Log) {
             $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " xml response: " . $response->saveXML());
         }
         $outputStream = fopen("php://temp", 'r+');
         $encoder = new Wbxml_Encoder($outputStream, 'UTF-8', 3);
         $encoder->encode($response);
         header("Content-Type: application/vnd.ms-sync.wbxml");
         rewind($outputStream);
         fpassthru($outputStream);
     }
 }
示例#25
0
文件: Util.php 项目: erickosma/e-ong
 public static function saveLog($errors)
 {
     $logger = new Zend_Log();
     $writer = new Zend_Log_Writer_Stream('application/tmp/erro/error.xml');
     $formatter = new Zend_Log_Formatter_Xml();
     $writer->setFormatter($formatter);
     $logger->addWriter($writer);
     //$exception->getTraceAsString();
     $msg = "<file>" . $errors->getFile() . "</file>";
     $msg .= "<line>" . $errors->getLine() . "</line>";
     $msg .= "<error>" . $errors->getMessage() . "</error>";
     $logger->debug($msg . "\r\n");
 }
示例#26
0
 /**
  * the constructor
  *
  * @param  mixed                    $_requestBody
  * @param  Syncope_Model_Device  $_device
  * @param  string                   $_policyKey
  */
 public function __construct($_requestBody, Syncope_Model_IDevice $_device, $_policyKey)
 {
     $this->_policyKey = $_policyKey;
     $this->_device = $_device;
     $this->_deviceBackend = Syncope_Registry::get('deviceBackend');
     $this->_folderBackend = Syncope_Registry::get('folderStateBackend');
     $this->_syncStateBackend = Syncope_Registry::get('syncStateBackend');
     $this->_contentStateBackend = Syncope_Registry::get('contentStateBackend');
     if (Syncope_Registry::isRegistered('loggerBackend')) {
         $this->_logger = Syncope_Registry::get('loggerBackend');
     }
     if ($this->_skipValidatePolicyKey !== true && $this->_policyKey === null) {
         #throw new Syncope_Exception_PolicyKeyMissing();
     }
     if ($this->_skipValidatePolicyKey !== true && ($this->_policyKey === 0 || $this->_device->policykey != $this->_policyKey)) {
         #throw new Syncope_Exception_ProvisioningNeeded();
     }
     // should we wipe the mobile phone?
     if ($this->_skipValidatePolicyKey !== true && !empty($this->_policyKey) && $this->_device->remotewipe >= Syncope_Command_Provision::REMOTEWIPE_REQUESTED) {
         throw new Syncope_Exception_ProvisioningNeeded();
     }
     $this->_inputDom = $_requestBody;
     $this->_syncTimeStamp = new DateTime(null, new DateTimeZone('UTC'));
     if ($this->_logger instanceof Zend_Log) {
         $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " sync timestamp: " . $this->_syncTimeStamp->format('Y-m-d H:i:s'));
     }
     // Creates an instance of the DOMImplementation class
     $imp = new DOMImplementation();
     // Creates a DOMDocumentType instance
     $dtd = $imp->createDocumentType('AirSync', "-//AIRSYNC//DTD AirSync//EN", "http://www.microsoft.com/");
     // Creates a DOMDocument instance
     $this->_outputDom = $imp->createDocument($this->_defaultNameSpace, $this->_documentElement, $dtd);
     $this->_outputDom->formatOutput = false;
     $this->_outputDom->encoding = 'utf-8';
 }
示例#27
0
 /**
  * @group ZF-9870
  */
 public function testLogWritesWithModifiedTimestampFormat()
 {
     $logger = new Zend_Log($this->writer);
     $logger->setTimestampFormat('Y-m-d');
     $logger->debug('ZF-9870');
     rewind($this->log);
     $message = stream_get_contents($this->log);
     $this->assertEquals(date('Y-m-d'), substr($message, 0, 10));
 }
 public static function debug($message)
 {
     self::$_logger->debug($message);
 }
示例#29
0
if (!isset($_SERVER['argv'][1]) || !in_array($_SERVER['argv'][1], array('install'))) {
    die('Usage: php lib/profilelib/shell.php command [option]
	Where command [option] can be:
		install profile_name [repository=profiles.tiki.org]
');
}
if (!file_exists('db/local.php')) {
    die("Tiki is not installed yet.\n");
}
require_once 'tiki-setup.php';
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);
    }
示例#30
0
require_once LIBRARY_PATH . '/loomp-backend/lib/arc/ARC2.php';
// loomp vocabulary class
require_once LIBRARY_PATH . '/loomp-backend/LOOMP_C.php';
// load loomp api
require_once LIBRARY_PATH . '/loomp-backend/api.php';
require_once LIBRARY_PATH . '/loomp-backend/search.php';
define('BASE_URL', $configuration->server->path);
define('LOOMP_HOST', $configuration->server->host);
define('LOOMP_BASE_PATH', $configuration->loomp->base);
// Loomp URIs
define("LOOMP_MODEL_URI", LOOMP_BASE_PATH . "/loomp/dbModel/");
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());