public function __construct()
 {
     // Logger
     $filter = new ezcLogFilter();
     $filter->severity = ezcLog::ERROR | ezcLog::INFO | ezcLog::WARNING;
     $this->logger = ezcLog::getInstance();
     $this->logger->getMapper()->appendRule(new ezcLogFilterRule( $filter, new ezcLogUnixFileWriter( "var/log/", "portugalWs.log", 157286400, 3 ), true ) );
 }
    public function __construct()
    {
        // Guzzle RESTclient
        $wsUrl = SolrSafeOperatorHelper::clusterIni('WebService', 'BaseUrlUUMP', 'merck.ini') . SolrSafeOperatorHelper::clusterIni('WebService', 'Prefix', 'merck.ini');
        $this->client = new Client( $wsUrl );

        // Logger
        $filter           = new ezcLogFilter();
        $filter->severity = ezcLog::ERROR | ezcLog::INFO | ezcLog::WARNING;
        $this->logger     = ezcLog::getInstance();
        $this->logger->getMapper()->appendRule( new ezcLogFilterRule( $filter, new ezcLogUnixFileWriter( "var/log/", "esb_uump.log", 157286400, 3 ), true ) );
    }
Exemplo n.º 3
0
 public function run()
 {
     // if sth. goes wrong with init (no requests), return false.
     if (!($mh = $this->initMultiHandle())) {
         return false;
     }
     $active = 0;
     do {
         do {
             $mrc = curl_multi_exec($mh, $active);
         } while (CURLM_CALL_MULTI_PERFORM === $mrc);
         switch ($mrc) {
             case CURLM_OK:
                 break;
             case CURLM_OUT_OF_MEMORY:
                 die('CURL out of memory.');
                 break;
             case CURLM_INTERNAL_ERROR:
                 ezcLog::getInstance()->log('CURL_INTERNAL ERROR', ezcLog::FATAL);
                 break;
         }
         // Did sth. happen? Did a handle finish?
         $moreMessages = 0;
         do {
             $this->handleMultiMessage(curl_multi_info_read($mh, $moreMessages));
         } while ($moreMessages);
         // wait for sth. to do
         if (-1 === curl_multi_select($mh)) {
             ezcLog::getInstance()->log('curl_multi_select returned -1', ezcLog::FATAL);
             $active = false;
             // break the loop
         }
     } while ($active);
     return TRUE;
 }
Exemplo n.º 4
0
	/**
	 * 
	 * @param string $message
	 */
	public function log($message, $severity = null, $verbosity='short', $format=null, $logger = null)
	{
	    $message = date('Y-m-d H:i:s') . ' : ' . $message;
	    switch ($verbosity)
		{
		    case 'long' :
		        $message = $message . $this->longTrace($format);
		        break;
		    default :
		        $message = $message . $this->shortTrace();
		        break;
		}
	    $filter = new ezcLogFilter();
	    $filter->severity = ezcLog::INFO;
	    if( $severity !== null )
	    {
	        $filter->severity = $severity;
	    }
        if( $logger === null )
        {		
	        $logger = ezcLog::getInstance();	        
        }
        $logger->getMapper()->appendRule( new ezcLogFilterRule( $filter, new ezcLogUnixFileWriter( "/tmp/", "error.log" ), true ) );
        $logger->log( $message, $severity );
	}
Exemplo n.º 5
0
 /**
  * Retrieving token as per section 5 of draft-ietf-oauth-v2-10
  *
  * Token can be present inside the Authorize header, inside a URI query
  * parameter, or in the HTTP body.
  *
  * According to section 5.1 the header is the preferred way, and the query
  * component and HTTP body are only looked at if no such header can be found.
  *
  * @TODO A configuration mechanism should alternatively let us select which
  * method to use: 1. header, 2. query component, 3. http body, in other words
  * to override the default behaviour according to spec.
  *
  * @param string $ezcMvcRequest
  * @return void
  */
 public static function getToken(ezcMvcRequest $request)
 {
     $logger = ezcLog::getInstance();
     $logger->source = __CLASS__;
     $logger->category = "oauth";
     // 1. Should first extract required token from the request object
     //    as we know that the request parser does not support this at the
     //    moment we, will skip to the fallback right away. That is to say,
     //    ideally the request parser would make this header available to us,
     //    when available, automatically.
     $token = null;
     $logger->log("Trying to get access token from http headers", ezcLog::DEBUG);
     $token = self::getTokenFromAuthorizationHeader();
     if ($token !== null) {
         $logger->log("Found token from header", ezcLog::DEBUG, array("token" => $token));
         return $token;
     }
     // 2
     $token = self::getTokenFromQueryComponent($request);
     if ($token !== null) {
         return $token;
     }
     // 3
     $token = self::getTokenFromHttpBody();
     if ($token !== null) {
         return $token;
     }
     return $token;
 }
Exemplo n.º 6
0
    /**
     * Sends an email and logs all data, with send result, to previously specified log file.
     *
     * @return bool
     */
    public function sendMail()
    {
        $this->logger->log(str_pad('', 77, '*'), ezcLog::INFO);
        $this->logger->log("[Subject] " . $this->subject, ezcLog::INFO);
        $this->logger->log("[From email] " . $this->sender, ezcLog::INFO);
        $this->logger->log("[To email] " . implode(", ", $this->recipients), ezcLog::INFO);
        $this->logger->log("[Message] " . $this->message, ezcLog::INFO);
        if (!$this->canBeSend()) {
            $this->logger->log("[Send status] " . 0 . "\nImproper email data.", ezcLog::INFO);
            return false;
        }

        $email = new eZMail();
        $email->setSubject($this->subject);
        $email->setSender($this->sender);
        foreach ( $this->recipients as $recipient) {
            $email->addReceiver($recipient);
        }
        $email->setBody($this->message);
        $email->setContentType('text/plain', 'UTF-8');

        $sendStatus = eZMailTransport::send($email);
        $this->logger->log("[Send status] " . $sendStatus, ezcLog::INFO);

        return $sendStatus;
    }
Exemplo n.º 7
0
 public function getLine($timeout)
 {
     if (!is_resource($this->server)) {
         $this->server = stream_socket_server('tcp://127.0.0.1:' . $this->port, $errno, $errstr);
         if (!is_resource($this->server)) {
             ezcLog::getInstance()->log(sprintf('Error opening socket: %d %s', $errno, $errstr), ezcLog::ERROR);
             return;
         }
     }
     if (!is_resource($this->client)) {
         ezcLog::getInstance()->log('waiting for client connect', ezcLog::DEBUG);
         $this->client = @stream_socket_accept($this->server, $timeout);
         if (is_resource($this->client)) {
             stream_set_blocking($this->client, 0);
             stream_set_timeout($this->client, $timeout);
         }
     }
     if (is_resource($this->client)) {
         ezcLog::getInstance()->log('reading input line from client', ezcLog::DEBUG);
         $line = trim(fgets($this->client));
         if ($line) {
             ezcLog::getInstance()->log('received input line ' . $line, ezcLog::DEBUG);
         } elseif (feof($this->client)) {
             ezcLog::getInstance()->log('client closed connection', ezcLog::INFO);
             $this->close();
         } else {
             //ezcLog::getInstance()->log( 'no client input, sleeping', ezcLog::INFO );
             sleep(1);
         }
         return $line;
     }
 }
/**
 * Callback function for the trigger_error function.
 */
function errorHandler($code, $msg, $file, $line)
{
    if (true && $code == E_USER_NOTICE) {
        // ezcDebug is auto_included, therefore when debug is disabled this class is not loaded at all.
        // Func: START_TIMER, STOP_TIMER, or LOG.
        // Msg: Message without the 'encoded parameters'.
        // source: Paynet, example, etc.
        // category: Template, SQL, etc.
        $dm = new ezcDebugMessage($msg);
        $dm->setDefaultSource("Paynet");
        if ($dm->isLog()) {
            ezcDebug::getInstance()->log($dm->message, $dm->verbosity, $dm->source, $dm->category, array("file" => $file, "line" => $line));
        } else {
            if ($parsedMsg->isStartTimer()) {
                $ezcDebug->getInstance()->startTimer($dm->name, $dm->source, $dm->category);
            } else {
                if ($dm->isStopTimer()) {
                    $ezcDebug->getInstance()->stopTimer($dm->name);
                }
            }
        }
    } else {
        // E_USER_WARNING, E_USER_ERROR
        $m = new ezcMessage($msg);
        $m->setDefaultSource("Paynet");
        // Severity is translated: E_USER_WARNING => WARNING, E_USER_ERROR => ERROR.
        ezcLog::getInstance()->log($m->message, $m->severity, $m->source, $m->category, array("file" => $file, "line" => $line));
    }
}
    /**
     * @return ezcLog
     */
    public static function getLogger()
    {
        if ( !isset(self::$logger) )
        {
            // Logger
            $filter           = new ezcLogFilter();
            $filter->severity = ezcLog::ERROR | ezcLog::INFO | ezcLog::WARNING;
            self::$logger     = ezcLog::getInstance();

            self::$logger->getMapper()->appendRule(new ezcLogFilterRule(
                $filter,
                new ezcLogUnixFileWriter( "var/log/", self::LOG_FILE, 157286400, 3 ),
                true )
            );
        }

        return self::$logger;
    }
Exemplo n.º 10
0
 public function testDelayedInit()
 {
     ezcBaseInit::setCallback('ezcInitLog', 'testDelayedInitLog');
     $log = ezcLog::getInstance();
     $rule = new ezcLogFilterRule(new ezcLogFilter(), $writer = new ezcLogUnixFileWriter('/'), true);
     $expected = new ezcLogFilterSet();
     $expected->appendRule($rule);
     $this->assertAttributeEquals($expected, 'writers', $log);
 }
Exemplo n.º 11
0
Arquivo: case.php Projeto: bmdevel/ezc
 protected function setUp()
 {
     parent::setUp();
     $writer = new ezcLogUnixFileWriter(dirname(__FILE__) . '/data', 'actual.log');
     $this->log = ezcLog::getInstance();
     $mapper = $this->log->getMapper();
     $filter = new ezcLogFilter();
     $rule = new ezcLogFilterRule($filter, $writer, true);
     $mapper->appendRule($rule);
     $this->setUpExecution();
 }
Exemplo n.º 12
0
    public function __construct()
    {
        // Guzzle RESTclient
        $this->builder = ServiceBuilder::factory(__DIR__ . '/../../classes/service/descriptor.php');


        $this->client = $this->builder['ldap'];

        // Logger
        $filter = new ezcLogFilter();
        $filter->severity = ezcLog::ERROR | ezcLog::INFO | ezcLog::WARNING;
        $this->logger = ezcLog::getInstance();
        $logFileName = "ws.log";
        if ( SolrSafeOperatorHelper::clusterIni('WebService', 'CountrySpecificLogs', 'merck.ini') == 'enabled' )
        {
            $clusterId = ClusterTool::clusterIdentifier();
            $logFileName = "ws_{$clusterId}.log";
        }
        $this->logger->getMapper()->appendRule(new ezcLogFilterRule( $filter, new ezcLogUnixFileWriter( "var/log/", $logFileName, 157286400, 3 ), true ) );
    }
Exemplo n.º 13
0
 /**
  * Write the logEntries to a file.
  *
  * Each line in the log file represents a log message. The log
  * messages have the following style:
  * <pre>
  * MMM dd HH:mm:ss [Severity] [Source] [Category] Message (ExtraInfo)
  * </pre>
  *
  * With:
  * - MMM: The 3 letter abbreviation of the month.
  * - dd: The day of the month.
  * - HH: The hour.
  * - mm: The minutes.
  * - ss: The seconds.
  *
  * Example:
  * <pre>
  * Jan 24 15:32:56 [Debug] [Paynet] [Shop] Connecting to the paynet server (file: paynet_server.php, line: 224).
  * Jan 24 15:33:01 [Debug] [Paynet] [Shop] Connected with the server (file: paynet_server.php, line: 710).
  * </pre>
  *
  * This method will be called by the {@link ezcLog} class.  The $eventSource and $eventCategory are either given
  * in the {@link ezcLog::log()} method or are the defaults from the {@link ezcLog} class.
  *
  * @param string $message
  * @param int $eventType
  * @param string $eventSource
  * @param string $eventCategory
  * @param array(string=>string) $extraInfo
  */
 public function writeLogMessage($message, $eventType, $eventSource, $eventCategory, $extraInfo = array())
 {
     $extra = "";
     if (sizeof($extraInfo) > 0) {
         $extra = " (" . $this->implodeWithKey(", ", ": ", $extraInfo) . ")";
     }
     if ($eventCategory == false) {
         $eventCategory = "";
     }
     $logMsg = date("M d H:i:s") . " [" . ezcLog::translateSeverityName($eventType) . "] " . ($eventSource == "" ? "" : "[{$eventSource}] ") . ($eventCategory == "" ? "" : "[{$eventCategory}] ") . "{$message}{$extra}\n";
     $this->write($eventType, $eventSource, $eventCategory, $logMsg);
 }
Exemplo n.º 14
0
 public function testWriteNotDefault()
 {
     $log = ezcLog::getInstance();
     $writer = new TempImplementation2($this->getTempDir(), 'broken.log');
     try {
         $writer->writeLogMessage('xxx', 'c', 'd', '');
         // $log->log( null, ezcLog::INFO, array() );
         $this->fail('Expected exception was not thrown');
     } catch (ezcLogWriterException $e) {
         self::assertSame("An error occurred while writing to 'broken.log'.", $e->getMessage());
     }
 }
Exemplo n.º 15
0
function shutdown_getfile()
{
    global $scriptStartTime;
    // Write a message to the log.
    $params = '';
    $params .= isset($_REQUEST['type']) ? '?type=' . $_REQUEST['type'] : '';
    $params .= isset($_REQUEST['domain']) ? '&domain=' . $_REQUEST['domain'] : '';
    $params .= isset($_REQUEST['file']) ? '&file=' . $_REQUEST['file'] : '';
    $params .= isset($_REQUEST['disposition']) ? '&disposition=' . $_REQUEST['disposition'] : '';
    if (defined('R3_FAST_SESSION') && R3_FAST_SESSION === true) {
        // Close immediatly the session to allow concurrency session
        session_write_close();
    }
    ezcLog::getInstance()->log(sprintf("Script [%s{$params}] execution time: %.2fsec", $_SERVER["SCRIPT_NAME"], microtime(true) - $scriptStartTime), ezcLog::DEBUG);
}
Exemplo n.º 16
0
 public function setup(ezcMvcRequest $request)
 {
     // Testing basic auth
     $logger = ezcLog::getInstance();
     $logger->source = __FUNCTION__;
     $logger->category = "auth";
     if ($request->authentication === null) {
         $logger->log("No credentials available", ezcLog::DEBUG);
         $request->uri = '/http-basic-auth';
         return new ezcMvcInternalRedirect($request);
     }
     $cred = new ezcAuthenticationPasswordCredentials($request->authentication->identifier, md5("{$request->authentication->identifier}\n{$request->authentication->password}"));
     $authDbInfo = new ezcAuthenticationDatabaseInfo(ezcDbInstance::get(), 'ezuser', array('login', 'password_hash'));
     $auth = new ezcAuthentication($cred);
     $auth->addFilter(new ezcAuthenticationDatabaseFilter($authDbInfo));
     return $auth;
 }
Exemplo n.º 17
0
 public function setup(ezcMvcRequest $request)
 {
     // Setup for testing credentials
     // Check for required components (fail if not present)
     // Fail if too many components are required (according to spec, later)
     // Validate components
     $logger = ezcLog::getInstance();
     $logger->source = __FUNCTION__;
     $logger->category = "oauth";
     $logger->log("Begin oauth verification", ezcLog::DEBUG);
     $token = ezpOauthUtility::getToken($request);
     $cred = new ezcAuthenticationIdCredentials($token);
     $oauthFilter = new ezpOauthFilter();
     $auth = new ezcAuthentication($cred);
     $auth->addFilter($oauthFilter);
     return $auth;
 }
Exemplo n.º 18
0
 static function write($msg)
 {
     // Get the one and only instance of the ezcLog.
     $log = ezcLog::getInstance();
     // Get an instance to the default log mapper.
     $mapper = $log->getMapper();
     // Create a new Unix file writer, that writes to the file: "default.log".
     $writer = new ezcLogUnixFileWriter("cache", "default.log");
     // Create a filter that accepts every message (default behavior).
     $filter = new ezcLogFilter();
     // Combine the filter with the writer in a filter rule.
     $rule = new ezcLogFilterRule($filter, $writer, true);
     // And finally assign the rule to the mapper.
     $mapper->appendRule($rule);
     // Write a message to the log
     $log->log($msg, ezcLog::WARNING);
 }
Exemplo n.º 19
0
 public function testWriteNotDefault()
 {
     $writer = new ezcLogDatabaseWriter($this->db, "logtable");
     $log = ezcLog::getInstance();
     $log->getMapper()->appendRule(new ezcLogFilterRule(new ezcLogFilter(), $writer, true));
     try {
         $log->log('Adding category', ezcLog::INFO, array('source' => 'mail'));
         $this->fail('Expected exception was not thrown');
     } catch (ezcLogWriterException $e) {
         if ($this->db instanceof ezcDbHandlerPgsql) {
             $this->assertEquals("SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation \"logtable\" does not exist", $e->getMessage());
         }
         if ($this->db instanceof ezcDbHandlerMysql) {
             $this->assertEquals("SQLSTATE[42S02]: Base table or view not found: 1146 Table 'ezc.logtable' doesn't exist", $e->getMessage());
         }
         if ($this->db instanceof ezcDbHandlerSqlite) {
             $this->assertEquals("SQLSTATE[HY000]: General error: 1 no such table: logtable", $e->getMessage());
         }
         if ($this->db instanceof ezcDbHandlerOracle) {
             $this->markTestIncomplete();
         }
     }
 }
Exemplo n.º 20
0
 /**
  * Writes the debug message $message with verbosity $verbosity.
  *
  * Arbitrary $extraInfo can be submitted. If $stackTrace is set to true, a
  * stack trace will be stored at the current program position.
  *
  * @param string $message
  * @param int $verbosity
  * @param array(string=>string) $extraInfo
  * @param bool $stackTrace
  */
 public function log($message, $verbosity, array $extraInfo = array(), $stackTrace = false)
 {
     // Add the verbosity
     $extraInfo = array_merge(array("verbosity" => $verbosity), $extraInfo);
     if ($this->options->stackTrace === true || $stackTrace === true) {
         $extraInfo['stackTrace'] = $this->getStackTrace();
     }
     $this->log->log($message, ezcLog::DEBUG, $extraInfo);
 }
<?php

require_once 'tutorial_autoload.php';
date_default_timezone_set("UTC");
// Same set up as the previous example.
$log = ezcLog::getInstance();
$writer = new ezcLogUnixFileWriter("/tmp/logs", "default.log");
$log->getmapper()->appendRule(new ezcLogFilterRule(new ezcLogFilter(), $writer, true));
// Set the source and category.
$log->source = "Payment module";
$log->category = "Template";
$log->log("Could not find cache file: </var/cache/payment1234.cache>.", ezcLog::WARNING);
// ...
// Write a SQL error. The category is set to SQL for this message only.
$log->log("Cannot execute query: <SELECT * FROM Orders WHERE ID = '123'>.", ezcLog::ERROR, array("category" => "SQL"));
// ...
// Write a debug message that includes the current filename and line number.
// The category is left out.
$log->log("Starting shutdown process.", ezcLog::DEBUG, array("category" => "", "file" => __FILE__, "line" => __LINE__));
Exemplo n.º 22
0
 public function checkLookupDomainSecurity($id, $act)
 {
     $id = (int) $id;
     $uid = $this->auth->getUID();
     if (!$this->auth->hasPerm(strtoupper($act), $this->getPermName())) {
         ezcLog::getInstance()->log("Security error for object=\"{$this->table}\", id=\"{$id}\", action=\"{$this->act}\" user={$uid}", ezcLog::ERROR);
         throw new Exception('Security error #1');
     }
     if (R3_IS_MULTIDOMAIN) {
         if ($this->checkDomian && !$this->auth->hasPerm(strtoupper($act), 'ALL_' . $this->getPermName())) {
             // Se non vedo nell elenco, non posso entrare in visualizaza, modifica, cancella
             if ($act != 'add') {
                 $db = ezcDbInstance::get();
                 $table = $this->view != '' ? $this->view : $this->table;
                 $sql = $this->getListSQL();
                 $pkName = $this->getPrimaryKeyName();
                 $sql = "SELECT do_id FROM ({$sql}) AS foo WHERE {$pkName}={$id}";
                 $data = $db->query($sql)->fetch();
                 if ($data === false) {
                     ezcLog::getInstance()->log("Security error for object=\"{$this->table}\", id=\"{$id}\", action=\"{$this->act}\" user={$uid}", ezcLog::ERROR);
                     throw new Exception('Security error #2');
                 }
                 if (strtoupper($act) != 'SHOW' && $data['do_id'] != $this->do_id) {
                     ezcLog::getInstance()->log("Security error for object=\"{$this->table}\", id=\"{$id}\", action=\"{$this->act}\" user={$uid}", ezcLog::ERROR);
                     throw new Exception('Security error #3');
                 }
             }
         }
     }
 }
Exemplo n.º 23
0
 public function log($level, $text)
 {
     ezcLog::getInstance()->log(sprintf("Export PAES: %s", $text), ezcLog::DEBUG);
 }
Exemplo n.º 24
0
 /**
  * Writes the message $message to the log.
  *
  * The writer can use the severity, source, and category to filter the
  * incoming messages and determine the location where the messages should
  * be written.
  *
  * The array $optional contains extra information that can be added to the log. For example:
  * line numbers, file names, usernames, etc.
  *
  * @throws ezcLogWriterException
  *         If the log writer was unable to write the log message
  *
  * @param string $message
  * @param int $severity
  *        ezcLog::DEBUG, ezcLog::SUCCESS_AUDIT, ezcLog::FAILED_AUDIT, ezcLog::INFO, ezcLog::NOTICE,
  *        ezcLog::WARNING, ezcLog::ERROR or ezcLog::FATAL.
  * @param string $source
  * @param string $category
  * @param array(string=>string) $extraInfo
  */
 public function writeLogMessage($message, $severity, $source, $category, $extraInfo = array())
 {
     // generate the log message
     $extra = "";
     if (sizeof($extraInfo) > 0) {
         $extra = " (" . $this->implodeWithKey(", ", ": ", $extraInfo) . ")";
     }
     $logMsg = "[" . ezcLog::translateSeverityName($severity) . "] " . ($source == "" ? "" : "[{$source}] ") . ($category == "" ? "" : "[{$category}] ") . "{$message}{$extra}";
     // Map severity to syslog severity
     $syslogSeverity = LOG_INFO;
     switch ($severity) {
         case ezcLog::DEBUG:
             $syslogSeverity = LOG_DEBUG;
             break;
         case ezcLog::SUCCESS_AUDIT:
         case ezcLog::FAILED_AUDIT:
         case ezcLog::INFO:
             $syslogSeverity = LOG_INFO;
             break;
         case ezcLog::NOTICE:
             $syslogSeverity = LOG_NOTICE;
             break;
         case ezcLog::WARNING:
             $syslogSeverity = LOG_WARNING;
             break;
         case ezcLog::ERROR:
             $syslogSeverity = LOG_ERR;
             break;
         case ezcLog::FATAL:
             $syslogSeverity = LOG_CRIT;
             break;
         default:
             $syslogSeverity = LOG_INFO;
             break;
     }
     // write to syslog
     $success = syslog($syslogSeverity, $logMsg);
     if (!$success) {
         throw new ezcLogWriterException(new Exception("Couldn't not write to syslog"));
     }
 }
Exemplo n.º 25
0
 /**
  * Wrapper around PHP's exit statement to be registered as callback.
  *
  * This method is here only as a convenience. Feel free to ignore it.
  * 
  * @param integer $signal 
  */
 public static function halt($signal)
 {
     ezcLog::getInstance()->log('halt in signal handler', ezcLog::DEBUG);
     exit;
 }
Exemplo n.º 26
0
 /**
  * (non-PHPdoc)
  * @see iProcessable::setUp()
  */
 public function setUp($logger = 'ezcLog', $settings = array())
 {
     switch ($logger) {
         default:
             $this->logger = ezcLog::getInstance();
             break;
     }
 }
Exemplo n.º 27
0
 protected static function log($message, $severity = ezcLog::DEBUG, array $attributes = array())
 {
     static $log;
     if (!$log) {
         $log = ezcLog::getInstance();
     }
     if (!array_key_exists('source', $attributes)) {
         $attributes['source'] = __CLASS__;
     }
     $log->log($message, $severity, $attributes);
 }
Exemplo n.º 28
0
 public function testLogStackTrace()
 {
     $dbg = $this->dbg;
     $dbg->log("bla", 1, array(), true);
     ezcLog::getInstance()->setMapper(new MyFakeMapper());
     $struct = $dbg->generateOutput();
     $this->assertInstanceOf('ezcDebugStacktraceIterator', $struct[0][0]->stackTrace);
 }
Exemplo n.º 29
0
 protected function downloadImages()
 {
     if (empty($this->wms)) {
         throw new Exception('No WMS to query');
     }
     $n = 0;
     foreach ($this->wms as $wmsKey => $wmsData) {
         $n++;
         $separator = '';
         if (!strpos($wmsData['url'], '?')) {
             $separator = '?';
         } else {
             $lastChar = substr($wmsData['url'], 0, -1);
             if ($lastChar != '?') {
                 if ($lastChar != '&' && substr($wmsData['url'], 0, -4) != '&amp;') {
                     $separator = '&';
                 }
             }
         }
         $parameters = array();
         foreach ($wmsData['parameters'] as $parameterKey => $parameterValue) {
             $parameters[strtoupper($parameterKey)] = $parameterValue;
         }
         $wmsData['parameters'] = $parameters;
         $wmsData['parameters']['BBOX'] = implode(',', $this->extent);
         $wmsData['parameters']['SERVICE'] = 'WMS';
         $wmsData['parameters']['REQUEST'] = 'GetMap';
         $wmsData['parameters']['VERSION'] = '1.1.1';
         $wmsData['parameters']['WIDTH'] = $this->size[0];
         $wmsData['parameters']['HEIGHT'] = $this->size[1];
         #$wmsData['parameters']['FORMAT'] = 'image/png';
         // Da precedenza ai parametri nell'url del WMS piuttosto che a quelli in $wmsData['parameters']
         $urlParts = parse_url($wmsData['url']);
         if (isset($urlParts['query'])) {
             parse_str($urlParts['query'], $queryParams);
             foreach ($queryParams as $key => $val) {
                 $key = strtoupper($key);
                 if (isset($wmsData['parameters'][$key])) {
                     unset($wmsData['parameters'][$key]);
                 }
             }
         }
         $url = $wmsData['url'] . $separator . http_build_query($wmsData['parameters']);
         //HACK: http_build_query trasforma da true a 1 e MS6 vuole true e non 1
         $url = str_replace("TRANSPARENT=1", "TRANSPARENT=true", $url);
         $this->wms[$wmsKey]['requesturl'] = $url;
         //SG: PHP BUG #52339 https://bugs.php.net/bug.php?id=52339&edit=1
         /*if (class_exists('R3AppInit')) {
               $elapsedTime = sprintf("elapsed time: %.3f s", microtime(true) - R3AppInit::$startTime);
               ezcLog::getInstance()->log(__METHOD__.", $elapsedTime, fetching $url", ezcLog::DEBUG);
           }*/
         $url = R3OgcMapUtils::addPrefixToRelativeUrl($url);
         $ch = curl_init($url);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
         $image = curl_exec($ch);
         if (!$image) {
             ezcLog::getInstance()->log("Error downloading image from [{$url}], curl error: [" . curl_error($ch) . "]", ezcLog::ERROR);
             throw new Exception("Error downloading image");
         }
         curl_close($ch);
         array_push($this->images, $image);
     }
 }
Exemplo n.º 30
0
 public static function updateDatabaseVersion($dbVersion)
 {
     $db = ezcDbInstance::get();
     ezcLog::getInstance()->log("R3EcoGisCustomerHelper::updateDatabaseVersion(\"{$dbVersion}\")", ezcLog::DEBUG);
     $dbName = $db->query("SELECT current_database()")->fetchColumn();
     $oldComment = explode("\n", $db->query("SELECT pg_catalog.shobj_description(d.oid, 'pg_database') \r\n                                                FROM pg_catalog.pg_database d\r\n                                                WHERE d.datname='{$dbName}'")->fetchColumn());
     $currentDbVersion = '0.0';
     foreach ($oldComment as $line) {
         $p = strpos($line, ':');
         if ($p !== false) {
             $param = trim(substr($line, 0, $p));
             $value = trim(substr($line, $p + 1));
             // echo "[$line -> '$param'='$value']";
             if ($param == 'database-version') {
                 $currentDbVersion = $value;
             }
         }
     }
     $cmp = version_compare($currentDbVersion, $dbVersion);
     if ($cmp < 0) {
         $date = date('Y-m-d H:i:s');
         $comments = "database-version: {$dbVersion}\n" . "database-update: {$date}";
         $sql = "COMMENT ON DATABASE {$dbName} IS '{$comments}'";
         $db->exec($sql);
     } else {
         if ($cmp > 0) {
             throw new exception("Invalid database version (>{$dbVersion})");
         }
     }
 }