Your IP : 18.191.86.218


Current Path : /home/soar/
Upload File :
Current File : //home/soar/api1.tar.gz

api/0000755000004100000410000000000014335266606011672 5ustar  www-datawww-dataapi/paystack_trans_init_handler.php0000644000004100000410000000234313466017021020140 0ustar  www-datawww-data<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.     
 */

require_once('log4php/main/php/Logger.php');
Logger::configure('log4php/resources/appender_dailyfile.properties');

$logger = Logger::getLogger('paystack_trans_init_handler');

$data = file_get_contents("php://input");

$path=parse_str($data,$params);

$logger->debug("Request Data: $data");




$headers = apache_request_headers();
$authToken = $headers['Authorization'];

$curl = curl_init();



curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.paystack.co/transaction/initialize",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => true,
    //CURLOPT_SSL_VERIFYPEER
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode($params),
    CURLOPT_HTTPHEADER => [
        "Authorization: $authToken",
        "content-type: application/json",
        "cache-control: no-cache"
    ],
));

$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
    echo $err;
    exit;
}
$logger->debug("Response : $response");

echo $response;

exit;

api/paystack_trans_verification_handler.php0000644000004100000410000000177513466017021021667 0ustar  www-datawww-data<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.     
 */
require_once('log4php/main/php/Logger.php');
Logger::configure('log4php/resources/appender_dailyfile.properties');

$logger = Logger::getLogger('paystack_trans_verification_handler');
	


$transRef = $_GET['transRef'];
$headers = apache_request_headers();	
$authToken = $headers['Authorization'];


$url = "https://api.paystack.co/transaction/verify/$transRef";
$logger->debug("URL: $url");

//$secretKey=PAYSTACK_LIVE_SECRET_KEY;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
        $ch, CURLOPT_HTTPHEADER, [
        "Authorization: $authToken"]
);



$response = curl_exec($ch);
$err = curl_error($ch);
if ($err) {
    echo $err;
    exit;
}
$logger->debug("Response Data: $response");

echo $response;
exit;
api/log4php/0000755000004100000410000000000013466017021013234 5ustar  www-datawww-dataapi/log4php/logs/0000755000004100000410000000000014550217327014206 5ustar  www-datawww-dataapi/log4php/resources/0000755000004100000410000000000014016470220015242 5ustar  www-datawww-dataapi/log4php/resources/layout_html.properties0000644000004100000410000000166113466017021021731 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutHtml
log4php.rootLogger = DEBUG, default
api/log4php/resources/configurator_php.php0000644000004100000410000000270513466017021021334 0ustar  www-datawww-data<?php
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# 
#         http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
return array(
        'threshold' => 'ALL',
        'rootLogger' => array(
            'level' => 'INFO',
            'appenders' => array('default'),
        ),
        'loggers' => array(
            'dev' => array(
                'level' => 'DEBUG',
                'appenders' => array('default'),
            ),
        ),
        'appenders' => array(
            'default' => array(
                'class' => 'LoggerAppenderEcho',
                'layout' => array(
                    'class' => 'LoggerLayoutPattern',
                    'conversionPattern' => "%d{Y-m-d H:i:s} %-5p %c %X{username}: %m in %F at %L%n",
                ),
            ),
        ),
    );
api/log4php/resources/appender_file.properties0000644000004100000410000000175213466017021022166 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderFile
log4php.appender.default.file = target/examples/file.log
log4php.appender.default.layout = LoggerLayoutTTCC
log4php.rootLogger = DEBUG, default
api/log4php/resources/renderer_default.properties0000644000004100000410000000166313466017021022704 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutSimple
log4php.rootLogger = DEBUG, default
api/log4php/resources/cache.properties0000644000004100000410000000170713466017021020434 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutSimple
log4php.rootLogger = DEBUG, default
api/log4php/resources/appender_firephp.xml0000644000004100000410000000241213466017021021302 0ustar  www-datawww-data<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at
 
         http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<configuration xmlns="http://logging.apache.org/log4php/">
    <appender name="firePhpAppender" class="LoggerAppenderFirephp">
        <layout class="LoggerLayoutSimple" />
        <param name="medium" value="page" />
    </appender>
    <appender name="consoleAppender" class="LoggerAppenderConsole" />

    <root>
        <level value="DEBUG" />
        <appender_ref ref="firePhpAppender" />
        <appender_ref ref="consoleAppender" />
    </root>
</configuration>
api/log4php/resources/ndc.properties0000644000004100000410000000205213466017021020127 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutPattern
log4php.appender.default.layout.conversionPattern="%d{Y-m-d H:i:s} %-5p %c %x: %m in %F at %L%n"
log4php.rootLogger = DEBUG, default
api/log4php/resources/appender_console.properties0000644000004100000410000000173713466017021022714 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.console = LoggerAppenderConsole
log4php.appender.console.target = STDOUT
log4php.appender.console.layout = LoggerLayoutSimple
log4php.rootLogger = DEBUG, console
api/log4php/resources/layout_xml.properties0000644000004100000410000000166013466017021021564 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutXml
log4php.rootLogger = DEBUG, default
api/log4php/resources/mdc.properties0000644000004100000410000000206613466017021020133 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutPattern
log4php.appender.default.layout.conversionPattern="%d{Y-m-d H:i:s} %-5p %c %X{username}: %m in %F at %L%n"
log4php.rootLogger = DEBUG, default

api/log4php/resources/filter_denyall.xml0000644000004100000410000000224713466017021020772 0ustar  www-datawww-data<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at
 
         http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<log4php:configuration xmlns:log4php="http://logging.apache.org/log4php/" threshold="all">
    <appender name="default" class="LoggerAppenderEcho">
        <layout class="LoggerLayoutTTCC"/>
        <filter class="LoggerFilterDenyAll"/>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender_ref ref="default" />
    </root>
</log4php:configuration>
api/log4php/resources/appender_echo.properties0000644000004100000410000000166113466017021022164 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutTTCC
log4php.rootLogger = DEBUG, default
api/log4php/resources/appender_syslog.properties0000644000004100000410000000210013466017021022553 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderSyslog
log4php.appender.default.layout = LoggerLayoutSimple
log4php.appender.default.ident = log4php-test
log4php.appender.default.facility = USER
log4php.appender.default.option = "PID|CONS|NDELAY"
log4php.rootLogger = DEBUG, default
api/log4php/resources/appender_mailevent.properties0000644000004100000410000000205413466017021023227 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.email = LoggerAppenderMail
log4php.appender.email.layout = LoggerLayoutTTCC
log4php.appender.email.from = someone@example.com
log4php.appender.email.to = root
log4php.appender.email.subject = Log4php test
log4php.rootLogger = FATAL, email
api/log4php/resources/layout_ttcc.properties0000644000004100000410000000213413466017021021716 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutTTCC
log4php.appender.default.layout.MicroSecondsPrinting = false
log4php.appender.default.layout.categoryPrefixing = true
log4php.appender.default.layout.dateFormat = "%H:%M"
log4php.rootLogger = DEBUG, default
api/log4php/resources/appender_socket_server.properties0000644000004100000410000000212013466017021024113 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.debug = true
log4php.appender.file = LoggerAppenderFile
log4php.appender.file.file = server.log
log4php.appender.file.layout = LoggerLayoutTTCC
log4php.appender.console = LoggerAppenderEcho
log4php.appender.console.layout = LoggerLayoutSimple
log4php.rootLogger = INFO, file, console
api/log4php/resources/appender_php.properties0000644000004100000410000000201613466017021022030 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderPhp
log4php.appender.default.layout = LoggerLayoutPattern
log4php.appender.default.layout.conversionPattern = "%d{Y-m-d H:i:s.u} %-5p [%t] %c: %m%n"
log4php.rootLogger = DEBUG, default
api/log4php/resources/filter_stringmatch.xml0000644000004100000410000000236313466017021021664 0ustar  www-datawww-data<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at
 
         http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<log4php:configuration xmlns:log4php="http://logging.apache.org/log4php/" threshold="all">
	<appender name="default" class="LoggerAppenderEcho">
		<layout class="LoggerLayoutTTCC" />
		<filter class="LoggerFilterStringMatch">
			<param name="StringToMatch" value="match" />
			<param name="AcceptOnMatch" value="false" />
		</filter>
	</appender>
	<root>
		<level value="DEBUG" />
		<appender_ref ref="default" />
	</root>
</log4php:configuration>
api/log4php/resources/appender_mail.properties0000644000004100000410000000206613466017021022170 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.email = LoggerAppenderMail
log4php.appender.email.layout = LoggerLayoutTTCC
log4php.appender.email.from = someone@example.com
log4php.appender.email.to = root@localhost
log4php.appender.email.subject = Log4php test
log4php.rootLogger = FATAL, email
api/log4php/resources/appender_null.properties0000644000004100000410000000157613466017021022225 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderNull
log4php.rootLogger = DEBUG, default
api/log4php/resources/layout_simple.properties0000644000004100000410000000166313466017021022260 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutSimple
log4php.rootLogger = DEBUG, default
api/log4php/resources/filter_levelmatch.xml0000644000004100000410000000236113466017021021463 0ustar  www-datawww-data<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at
 
         http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<log4php:configuration xmlns:log4php="http://logging.apache.org/log4php/" threshold="all">
	<appender name="default" class="LoggerAppenderEcho">
		<layout class="LoggerLayoutTTCC" />
		<filter class="LoggerFilterLevelMatch">
			<param name="LevelToMatch" value="DEBUG" />
			<param name="AcceptOnMatch" value="false" />
		</filter>
	</appender>
	<root>
		<level value="DEBUG" />
		<appender_ref ref="default" />
	</root>
</log4php:configuration>
api/log4php/resources/filter_levelrange.xml0000644000004100000410000000243013466017021021460 0ustar  www-datawww-data<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at
 
         http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<log4php:configuration xmlns:log4php="http://logging.apache.org/log4php/" threshold="all">
	<appender name="default" class="LoggerAppenderEcho">
		<layout class="LoggerLayoutTTCC" />
		<filter class="LoggerFilterLevelRange">
			<param name="levelMin" value="ERROR" />
			<param name="levelMax" value="FATAL" />
			<param name="acceptOnMatch" value="false" />
		</filter>
	</appender>
	<root>
		<level value="DEBUG" />
		<appender_ref ref="default" />
	</root>
</log4php:configuration>
api/log4php/resources/renderer_map.properties0000644000004100000410000000173513466017021022035 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.renderer.Person = PersonRenderer

log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutSimple
log4php.rootLogger = DEBUG, default
api/log4php/resources/appender_dailyfile.properties0000644000004100000410000000206414016470101023200 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderDailyFile
log4php.appender.default.layout = LoggerLayoutPattern
log4php.appender.default.datePattern = Ymd
log4php.appender.default.file = log4php/logs/daily_%s.log
log4php.rootLogger = DEBUG, default
api/log4php/resources/appender_mongodb.xml0000644000004100000410000000212113466017021021267 0ustar  www-datawww-data<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at
 
         http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<log4php:configuration xmlns:log4php="http://logging.apache.org/log4php/" threshold="all">
    <appender name="default" class="LoggerAppenderMongoDB">
    </appender>
    <root>
        <level value="DEBUG" />
        <appender_ref ref="default" />
    </root>
</log4php:configuration>
api/log4php/resources/appender_socket.properties0000644000004100000410000000213713466017021022535 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderSocket
log4php.appender.default.layout = LoggerLayoutSimple
log4php.appender.default.remoteHost = localhost
log4php.appender.default.port = 4242
log4php.appender.default.useXml = true
log4php.appender.default.locationInfo = false
log4php.rootLogger = DEBUG, default
api/log4php/resources/appender_rollingfile.properties0000644000004100000410000000213013466017021023544 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderRollingFile
log4php.appender.default.layout = LoggerLayoutTTCC
log4php.appender.default.file = target/examples/appender_rollingfile.log
log4php.appender.default.MaxFileSize = 100
log4php.appender.default.MaxBackupIndex = 3
log4php.rootLogger = DEBUG, default
api/log4php/resources/configurator_xml.xml0000644000004100000410000000213413466017021021352 0ustar  www-datawww-data<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at
 
         http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<log4php:configuration xmlns:log4php="http://logging.apache.org/log4php/" threshold="all">
	<appender name="default" class="LoggerAppenderEcho">
		<layout class="LoggerLayoutTTCC" />
	</appender>
	<root>
		<level value="DEBUG" />
		<appender_ref ref="default" />
	</root>
</log4php:configuration>
api/log4php/resources/appender_pdo.properties0000644000004100000410000000350613466017021022030 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.rootLogger = DEBUG, a1, a2, a3

; The table is created if necessary and filled using prepared statements.  
log4php.appender.a1 = LoggerAppenderPDO
log4php.appender.a1.dsn = "sqlite:target/appender_pdo.sqlite"

; The following shows an appender with customized INSERT statment and table name. 
log4php.appender.a2 = LoggerAppenderPDO
log4php.appender.a2.user = root
log4php.appender.a2.password = secret
log4php.appender.a2.dsn = "mysql:host=localhost;dbname=test"
log4php.appender.a2.table = log2
log4php.appender.a2.insertSql = "INSERT INTO log2 (timestamp, logger, level, message, thread, file, line) VALUES (?,?,?,?,?,?,?)"
log4php.appender.a2.insertPattern = "%d,%c,%p,%m, %t,%F,%L"

; DEPRECATED: Using old style LoggerPatternLayout is considered unsafe as %m can contain quotes that mess up the SQL! 
log4php.appender.a3 = LoggerAppenderPDO
log4php.appender.a3.dsn = "sqlite:target/appender_pdo.sqlite"
log4php.appender.a3.table = log3
log4php.appender.a3.sql = "INSERT INTO log3 (timestamp, level, message) VALUES ('%t', '%p', '%m')"
api/log4php/resources/layout_pattern.properties0000644000004100000410000000202413466017021022434 0ustar  www-datawww-data;
; Licensed to the Apache Software Foundation (ASF) under one or more
; contributor license agreements. See the NOTICE file distributed with
; this work for additional information regarding copyright ownership.
; The ASF licenses this file to You under the Apache License, Version 2.0
; (the "License"); you may not use this file except in compliance with
; the License. You may obtain a copy of the License at
; 
;         http://www.apache.org/licenses/LICENSE-2.0
; 
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; START SNIPPET: doxia
log4php.appender.default = LoggerAppenderEcho
log4php.appender.default.layout = LoggerLayoutPattern
log4php.appender.default.layout.ConversionPattern = "%d{ISO8601} [%p] %c: %m (at %F line %L)%n"
log4php.rootLogger = DEBUG, default
api/log4php/main/0000755000004100000410000000000013466017021014160 5ustar  www-datawww-dataapi/log4php/main/php/0000755000004100000410000000000013466017021014747 5ustar  www-datawww-dataapi/log4php/main/php/LoggerException.php0000644000004100000410000000174013466017021020560 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * LoggerException class
 *
 * @version $Revision: 1334369 $
 * @package log4php
 */
class LoggerException extends Exception {
}
api/log4php/main/php/LoggerNDC.php0000644000004100000410000001560013466017021017226 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * The NDC class implements <i>nested diagnostic contexts</i>.
 * 
 * NDC was defined by Neil Harrison in the article "Patterns for Logging
 * Diagnostic Messages" part of the book <i>"Pattern Languages of
 * Program Design 3"</i> edited by Martin et al.
 *
 * A Nested Diagnostic Context, or NDC in short, is an instrument
 * to distinguish interleaved log output from different sources. Log
 * output is typically interleaved when a server handles multiple
 * clients near-simultaneously.
 *
 * This class is similar to the {@link LoggerMDC} class except that it is
 * based on a stack instead of a map.
 *
 * Interleaved log output can still be meaningful if each log entry
 * from different contexts had a distinctive stamp. This is where NDCs
 * come into play.
 *
 * <b>Note that NDCs are managed on a per thread basis</b>. 
 * 
 * NDC operations such as {@link push()}, {@link pop()}, 
 * {@link clear()}, {@link getDepth()} and {@link setMaxDepth()}
 * affect the NDC of the <i>current</i> thread only. NDCs of other
 * threads remain unaffected.
 *
 * For example, a servlet can build a per client request NDC
 * consisting the clients host name and other information contained in
 * the the request. <i>Cookies</i> are another source of distinctive
 * information. To build an NDC one uses the {@link push()}
 * operation.
 * 
 * Simply put,
 *
 * - Contexts can be nested.
 * - When entering a context, call <kbd>LoggerNDC::push()</kbd>
 *	 As a side effect, if there is no nested diagnostic context for the
 *	 current thread, this method will create it.
 * - When leaving a context, call <kbd>LoggerNDC::pop()</kbd>
 * - <b>When exiting a thread make sure to call {@link remove()}</b>
 *	 
 * There is no penalty for forgetting to match each
 * <kbd>push</kbd> operation with a corresponding <kbd>pop</kbd>,
 * except the obvious mismatch between the real application context
 * and the context set in the NDC.
 *
 * If configured to do so, {@link LoggerPatternLayout} and {@link LoggerLayoutTTCC} 
 * instances automatically retrieve the nested diagnostic
 * context for the current thread without any user intervention.
 * Hence, even if a servlet is serving multiple clients
 * simultaneously, the logs emanating from the same code (belonging to
 * the same category) can still be distinguished because each client
 * request will have a different NDC tag.
 *
 * Example:
 *	
 * {@example ../../examples/php/ndc.php 19}<br>
 *
 * With the properties file:
 * 
 * {@example ../../examples/resources/ndc.properties 18}<br>
 * 
 * Will result in the following (notice the conn and client ids):
 * 
 * <pre>
 * 2009-09-13 19:04:27 DEBUG root conn=1234: just received a new connection in src/examples/php/ndc.php at 23
 * 2009-09-13 19:04:27 DEBUG root conn=1234 client=ab23: some more messages that can in src/examples/php/ndc.php at 25
 * 2009-09-13 19:04:27 DEBUG root conn=1234 client=ab23: now related to a client in src/examples/php/ndc.php at 26
 * 2009-09-13 19:04:27 DEBUG root : back and waiting for new connections in src/examples/php/ndc.php at 29
 * </pre>
 *	
 * @version $Revision: 1350602 $
 * @package log4php 
 * @since 0.3
 */
class LoggerNDC {
	
	/** This is the repository of NDC stack */
	private static $stack = array();
	
	/**
	 * Clear any nested diagnostic information if any. This method is
	 * useful in cases where the same thread can be potentially used
	 * over and over in different unrelated contexts.
	 *
	 * <p>This method is equivalent to calling the {@link setMaxDepth()}
	 * method with a zero <var>maxDepth</var> argument.
	 */
	public static function clear() {
		self::$stack = array();
	}

	/**
	 * Never use this method directly, use the {@link LoggerLoggingEvent::getNDC()} method instead.
	 * @return array
	 */
	public static function get() {
		return implode(' ', self::$stack);
	}
  
	/**
	 * Get the current nesting depth of this diagnostic context.
	 *
	 * @see setMaxDepth()
	 * @return integer
	 */
	public static function getDepth() {
		return count(self::$stack);
	}

	/**
	 * Clients should call this method before leaving a diagnostic
	 * context.
	 *
	 * <p>The returned value is the value that was pushed last. If no
	 * context is available, then the empty string "" is returned.</p>
	 *
	 * @return string The innermost diagnostic context.
	 */
	public static function pop() {
		if(count(self::$stack) > 0) {
			return array_pop(self::$stack);
		} else {
			return '';
		}
	}

	/**
	 * Looks at the last diagnostic context at the top of this NDC
	 * without removing it.
	 *
	 * <p>The returned value is the value that was pushed last. If no
	 * context is available, then the empty string "" is returned.</p>
	 * @return string The innermost diagnostic context.
	 */
	public static function peek() {
		if(count(self::$stack) > 0) {
			return end(self::$stack);
		} else {
			return '';
		}
	}
	
	/**
	 * Push new diagnostic context information for the current thread.
	 *
	 * <p>The contents of the <var>message</var> parameter is
	 * determined solely by the client.
	 *	
	 * @param string $message The new diagnostic context information.
	 */
	public static function push($message) {
		array_push(self::$stack, (string)$message);
	}

	/**
	 * Remove the diagnostic context for this thread.
	 */
	public static function remove() {
		LoggerNDC::clear();
	}

	/**
	 * Set maximum depth of this diagnostic context. If the current
	 * depth is smaller or equal to <var>maxDepth</var>, then no
	 * action is taken.
	 *
	 * <p>This method is a convenient alternative to multiple 
	 * {@link pop()} calls. Moreover, it is often the case that at 
	 * the end of complex call sequences, the depth of the NDC is
	 * unpredictable. The {@link setMaxDepth()} method circumvents
	 * this problem.
	 *
	 * @param integer $maxDepth
	 * @see getDepth()
	 */
	public static function setMaxDepth($maxDepth) {
		$maxDepth = (int)$maxDepth;
		if(LoggerNDC::getDepth() > $maxDepth) {
			self::$stack = array_slice(self::$stack, 0, $maxDepth);
		}
	}
}
api/log4php/main/php/layouts/0000755000004100000410000000000013466017021016447 5ustar  www-datawww-dataapi/log4php/main/php/layouts/LoggerLayoutSimple.php0000644000004100000410000000347513466017021022760 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * A simple layout.
 *
 * Returns the log statement in a format consisting of the
 * <b>level</b>, followed by " - " and then the <b>message</b>. 
 *
 * For example the following php and properties files
 * 
 * {@example ../../examples/php/layout_simple.php 19}<br>
 * 
 * {@example ../../examples/resources/layout_simple.properties 18}<br>
 *
 * would result in:
 * 
 * <samp>INFO - Hello World!</samp>
 *
 * @version $Revision: 1213283 $
 * @package log4php
 * @subpackage layouts
 */  
class LoggerLayoutSimple extends LoggerLayout {
	/**
	 * Returns the log statement in a format consisting of the
	 * <b>level</b>, followed by " - " and then the
	 * <b>message</b>. For example, 
	 * <samp> INFO - "A message" </samp>
	 *
	 * @param LoggerLoggingEvent $event
	 * @return string
	 */
	public function format(LoggerLoggingEvent $event) {
		$level = $event->getLevel();
		$message = $event->getRenderedMessage();
		return "$level - $message" . PHP_EOL;
	}
}
api/log4php/main/php/layouts/LoggerLayoutHtml.php0000644000004100000410000001601413466017021022424 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * This layout outputs events in a HTML table.
 *
 * Configurable parameters for this layout are:
 * 
 * - title
 * - locationInfo
 *
 * An example for this layout:
 * 
 * {@example ../../examples/php/layout_html.php 19}<br>
 * 
 * The corresponding XML file:
 * 
 * {@example ../../examples/resources/layout_html.properties 18}
 * 
 * The above will print a HTML table that looks, converted back to plain text, like the following:<br>
 * <pre>
 *    Log session start time Wed Sep 9 00:11:30 2009
 *
 *    Time Thread Level Category   Message
 *    0    8318   INFO  root       Hello World!
 * </pre>
 * 
 * @version $Revision: 1379731 $
 * @package log4php
 * @subpackage layouts
 */
class LoggerLayoutHtml extends LoggerLayout {
	/**
	 * The <b>LocationInfo</b> option takes a boolean value. By
	 * default, it is set to false which means there will be no location
	 * information output by this layout. If the the option is set to
	 * true, then the file name and line number of the statement
	 * at the origin of the log statement will be output.
	 *
	 * <p>If you are embedding this layout within a {@link LoggerAppenderMail}
	 * or a {@link LoggerAppenderMailEvent} then make sure to set the
	 * <b>LocationInfo</b> option of that appender as well.
	 * @var boolean
	 */
	protected $locationInfo = false;
	
	/**
	 * The <b>Title</b> option takes a String value. This option sets the
	 * document title of the generated HTML document.
	 * Defaults to 'Log4php Log Messages'.
	 * @var string
	 */
	protected $title = "Log4php Log Messages";
	
	/**
	 * The <b>LocationInfo</b> option takes a boolean value. By
	 * default, it is set to false which means there will be no location
	 * information output by this layout. If the the option is set to
	 * true, then the file name and line number of the statement
	 * at the origin of the log statement will be output.
	 *
	 * <p>If you are embedding this layout within a {@link LoggerAppenderMail}
	 * or a {@link LoggerAppenderMailEvent} then make sure to set the
	 * <b>LocationInfo</b> option of that appender as well.
	 */
	public function setLocationInfo($flag) {
		$this->setBoolean('locationInfo', $flag);
	}

	/**
	 * Returns the current value of the <b>LocationInfo</b> option.
	 */
	public function getLocationInfo() {
		return $this->locationInfo;
	}
	
	/**
	 * The <b>Title</b> option takes a String value. This option sets the
	 * document title of the generated HTML document.
	 * Defaults to 'Log4php Log Messages'.
	 */
	public function setTitle($title) {
		$this->setString('title', $title);
	}

	/**
	 * @return string Returns the current value of the <b>Title</b> option.
	 */
	public function getTitle() {
		return $this->title;
	}
	
	/**
	 * @return string Returns the content type output by this layout, i.e "text/html".
	 */
	public function getContentType() {
		return "text/html";
	}
	
	/**
	 * @param LoggerLoggingEvent $event
	 * @return string
	 */
	public function format(LoggerLoggingEvent $event) {
		$sbuf = PHP_EOL . "<tr>" . PHP_EOL;
	
		$sbuf .= "<td>";
		$sbuf .= round(1000 * $event->getRelativeTime());
		$sbuf .= "</td>" . PHP_EOL;
	
		$sbuf .= "<td title=\"" . $event->getThreadName() . " thread\">";
		$sbuf .= $event->getThreadName();
		$sbuf .= "</td>" . PHP_EOL;
	
		$sbuf .= "<td title=\"Level\">";
		
		$level = $event->getLevel();
		
		if ($level->equals(LoggerLevel::getLevelDebug())) {
			$sbuf .= "<font color=\"#339933\">$level</font>";
		} else if ($level->equals(LoggerLevel::getLevelWarn())) {
			$sbuf .= "<font color=\"#993300\"><strong>$level</strong></font>";
		} else {
			$sbuf .= $level;
		}
		$sbuf .= "</td>" . PHP_EOL;
	
		$sbuf .= "<td title=\"" . htmlentities($event->getLoggerName(), ENT_QUOTES) . " category\">";
		$sbuf .= htmlentities($event->getLoggerName(), ENT_QUOTES);
		$sbuf .= "</td>" . PHP_EOL;
	
		if ($this->locationInfo) {
			$locInfo = $event->getLocationInformation();
			$sbuf .= "<td>";
			$sbuf .= htmlentities($locInfo->getFileName(), ENT_QUOTES). ':' . $locInfo->getLineNumber();
			$sbuf .= "</td>" . PHP_EOL;
		}

		$sbuf .= "<td title=\"Message\">";
		$sbuf .= htmlentities($event->getRenderedMessage(), ENT_QUOTES);
		$sbuf .= "</td>" . PHP_EOL;

		$sbuf .= "</tr>" . PHP_EOL;
		
		if ($event->getNDC() != null) {
			$sbuf .= "<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : xx-small;\" colspan=\"6\" title=\"Nested Diagnostic Context\">";
			$sbuf .= "NDC: " . htmlentities($event->getNDC(), ENT_QUOTES);
			$sbuf .= "</td></tr>" . PHP_EOL;
		}
		return $sbuf;
	}

	/**
	 * @return string Returns appropriate HTML headers.
	 */
	public function getHeader() {
		$sbuf = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" . PHP_EOL;
		$sbuf .= "<html>" . PHP_EOL;
		$sbuf .= "<head>" . PHP_EOL;
		$sbuf .= "<title>" . $this->title . "</title>" . PHP_EOL;
		$sbuf .= "<style type=\"text/css\">" . PHP_EOL;
		$sbuf .= "<!--" . PHP_EOL;
		$sbuf .= "body, table {font-family: arial,sans-serif; font-size: x-small;}" . PHP_EOL;
		$sbuf .= "th {background: #336699; color: #FFFFFF; text-align: left;}" . PHP_EOL;
		$sbuf .= "-->" . PHP_EOL;
		$sbuf .= "</style>" . PHP_EOL;
		$sbuf .= "</head>" . PHP_EOL;
		$sbuf .= "<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">" . PHP_EOL;
		$sbuf .= "<hr size=\"1\" noshade>" . PHP_EOL;
		$sbuf .= "Log session start time " . strftime('%c', time()) . "<br>" . PHP_EOL;
		$sbuf .= "<br>" . PHP_EOL;
		$sbuf .= "<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">" . PHP_EOL;
		$sbuf .= "<tr>" . PHP_EOL;
		$sbuf .= "<th>Time</th>" . PHP_EOL;
		$sbuf .= "<th>Thread</th>" . PHP_EOL;
		$sbuf .= "<th>Level</th>" . PHP_EOL;
		$sbuf .= "<th>Category</th>" . PHP_EOL;
		if ($this->locationInfo) {
			$sbuf .= "<th>File:Line</th>" . PHP_EOL;
		}
		$sbuf .= "<th>Message</th>" . PHP_EOL;
		$sbuf .= "</tr>" . PHP_EOL;

		return $sbuf;
	}

	/**
	 * @return string Returns the appropriate HTML footers.
	 */
	public function getFooter() {
		$sbuf = "</table>" . PHP_EOL;
		$sbuf .= "<br>" . PHP_EOL;
		$sbuf .= "</body></html>";

		return $sbuf;
	}
}
api/log4php/main/php/layouts/LoggerLayoutTTCC.php0000644000004100000410000001403413466017021022255 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * TTCC layout format consists of <b>t</b>ime, <b>t</b>hread, <b>c</b>ategory and nested
 * diagnostic <b>c</b>ontext information, hence the name.
 * 
 * <p>Each of the four fields can be individually enabled or
 * disabled. The time format depends on the <b>DateFormat</b> used.</p>
 *
 * <p>If no dateFormat is specified it defaults to '%c'. 
 * See php {@link PHP_MANUAL#date} function for details.</p>
 *
 * Configurable parameters for this layout are:
 * - {@link $threadPrinting} (true|false) enable/disable pid reporting.
 * - {@link $categoryPrefixing} (true|false) enable/disable logger category reporting.
 * - {@link $contextPrinting} (true|false) enable/disable NDC reporting.
 * - {@link $microSecondsPrinting} (true|false) enable/disable micro seconds reporting in timestamp.
 * - {@link $dateFormat} (string) set date format. See php {@link PHP_MANUAL#date} function for details.
 *
 * An example how to use this layout:
 * 
 * {@example ../../examples/php/layout_ttcc.php 19}<br>
 * 
 * {@example ../../examples/resources/layout_ttcc.properties 18}<br>
 *
 * The above would print:<br>
 * <samp>02:28 [13714] INFO root - Hello World!</samp>
 *
 * @version $Revision: 1302503 $
 * @package log4php
 * @subpackage layouts
 * 
 * @deprecated LoggerLayout TTCC is deprecated and will be removed in a future release. Please use 
 *   LoggerLayoutPattern instead. 
 */
class LoggerLayoutTTCC extends LoggerLayout {

	// Internal representation of options
	protected $threadPrinting    = true;
	protected $categoryPrefixing = true;
	protected $contextPrinting   = true;
	protected $microSecondsPrinting = true;
	
	/**
	 * @var string date format. See {@link PHP_MANUAL#strftime} for details
	 */
	protected $dateFormat = '%c';

	/**
	 * Constructor
	 *
	 * @param string date format
	 * @see dateFormat
	 */
	public function __construct($dateFormat = '') {
		$this->warn("LoggerLayout TTCC is deprecated and will be removed in a future release. Please use LoggerLayoutPattern instead.");
		if (!empty($dateFormat)) {
			$this->dateFormat = $dateFormat;
		}
		return;
	}

	/**
	 * The <b>ThreadPrinting</b> option specifies whether the name of the
	 * current thread is part of log output or not. This is true by default.
	 */
	public function setThreadPrinting($threadPrinting) {
		$this->setBoolean('threadPrinting', $threadPrinting);
	}

	/**
	 * @return boolean Returns value of the <b>ThreadPrinting</b> option.
	 */
	public function getThreadPrinting() {
		return $this->threadPrinting;
	}

	/**
	 * The <b>CategoryPrefixing</b> option specifies whether {@link Category}
	 * name is part of log output or not. This is true by default.
	 */
	public function setCategoryPrefixing($categoryPrefixing) {
		$this->setBoolean('categoryPrefixing', $categoryPrefixing);
	}

	/**
	 * @return boolean Returns value of the <b>CategoryPrefixing</b> option.
	 */
	public function getCategoryPrefixing() {
		return $this->categoryPrefixing;
	}

	/**
	 * The <b>ContextPrinting</b> option specifies log output will include
	 * the nested context information belonging to the current thread.
	 * This is true by default.
	 */
	public function setContextPrinting($contextPrinting) {
		$this->setBoolean('contextPrinting', $contextPrinting);
	}

	/**
	 * @return boolean Returns value of the <b>ContextPrinting</b> option.
	 */
	public function getContextPrinting() {
		return $this->contextPrinting;
	}
	
	/**
	 * The <b>MicroSecondsPrinting</b> option specifies if microseconds infos
	 * should be printed at the end of timestamp.
	 * This is true by default.
	 */
	public function setMicroSecondsPrinting($microSecondsPrinting) {
		$this->setBoolean('microSecondsPrinting', $microSecondsPrinting);
	}

	/**
	 * @return boolean Returns value of the <b>MicroSecondsPrinting</b> option.
	 */
	public function getMicroSecondsPrinting() {
		return $this->microSecondsPrinting;
	}
	
	
	public function setDateFormat($dateFormat) {
		$this->setString('dateFormat', $dateFormat);
	}
	
	/**
	 * @return string
	 */
	public function getDateFormat() {
		return $this->dateFormat;
	}

	/**
	 * In addition to the level of the statement and message, the
	 * returned string includes time, thread, category.
	 * <p>Time, thread, category are printed depending on options.
	 *
	 * @param LoggerLoggingEvent $event
	 * @return string
	 */
	public function format(LoggerLoggingEvent $event) {
		$timeStamp = (float)$event->getTimeStamp();
		$format = strftime($this->dateFormat, (int)$timeStamp);
		
		if ($this->microSecondsPrinting) {
			$usecs = floor(($timeStamp - (int)$timeStamp) * 1000);
			$format .= sprintf(',%03d', $usecs);
		}
			
		$format .= ' ';
		
		if ($this->threadPrinting) {
			$format .= '['.getmypid().'] ';
		}
		
		$level = $event->getLevel();
		$format .= $level.' ';
		
		if($this->categoryPrefixing) {
			$format .= $event->getLoggerName().' ';
		}
	   
		if($this->contextPrinting) {
			$ndc = $event->getNDC();
			if($ndc != null) {
				$format .= $ndc.' ';
			}
		}
		
		$format .= '- '.$event->getRenderedMessage();
		$format .= PHP_EOL;
		
		return $format;
	}

	public function ignoresThrowable() {
		return true;
	}
}
api/log4php/main/php/layouts/LoggerLayoutXml.php0000644000004100000410000001512113466017021022256 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * The output of the LoggerXmlLayout consists of a series of log4php:event elements. 
 * 
 * Configurable parameters: 
 * - {@link $locationInfo} - If set to true then the file name and line number 
 *   of the origin of the log statement will be included in output.
 * - {@link $log4jNamespace} - If set to true then log4j namespace will be used
 *   instead of log4php namespace. This can be usefull when using log viewers 
 *   which can only parse the log4j namespace such as Apache Chainsaw. 
 * 
 * <p>It does not output a complete well-formed XML file. 
 * The output is designed to be included as an external entity in a separate file to form
 * a correct XML file.</p>
 * 
 * Example:
 * 
 * {@example ../../examples/php/layout_xml.php 19}<br>
 * 
 * {@example ../../examples/resources/layout_xml.properties 18}<br>
 *
 * The above would print:
 * 
 * <pre>
 * <log4php:eventSet xmlns:log4php="http://logging.apache.org/log4php/" version="0.3" includesLocationInfo="true">
 * 	<log4php:event logger="root" level="INFO" thread="13802" timestamp="1252456226491">
 * 		<log4php:message><![CDATA[Hello World!]]></log4php:message>
 * 		<log4php:locationInfo class="main" file="examples/php/layout_xml.php" line="6" method="main" />
 * 	</log4php:event>
 * </log4php:eventSet>
 * </pre>
 *
 * @version $Revision: 1213283 $
 * @package log4php
 * @subpackage layouts
 */
class LoggerLayoutXml extends LoggerLayout {
	const LOG4J_NS_PREFIX ='log4j';
	const LOG4J_NS = 'http://jakarta.apache.org/log4j/';
	
	const LOG4PHP_NS_PREFIX = 'log4php';
	const LOG4PHP_NS = 'http://logging.apache.org/log4php/';
	
	const CDATA_START = '<![CDATA[';
	const CDATA_END = ']]>';
	const CDATA_PSEUDO_END = ']]&gt;';
	const CDATA_EMBEDDED_END = ']]>]]&gt;<![CDATA[';

	/**
	 * If set to true then the file name and line number of the origin of the
	 * log statement will be output.
	 * @var boolean
	 */
	protected $locationInfo = true;
  
	/**
	 * If set to true, log4j namespace will be used instead of the log4php 
	 * namespace.
	 * @var boolean 
	 */
	protected $log4jNamespace = false;
	
	/** The namespace in use. */
	protected $namespace = self::LOG4PHP_NS;
	
	/** The namespace prefix in use */
	protected $namespacePrefix = self::LOG4PHP_NS_PREFIX;
	 
	public function activateOptions() {
		if ($this->getLog4jNamespace()) {
			$this->namespace        = self::LOG4J_NS;
			$this->namespacePrefix  = self::LOG4J_NS_PREFIX;
		} else {
			$this->namespace        = self::LOG4PHP_NS;
			$this->namespacePrefix  = self::LOG4PHP_NS_PREFIX;
		}
	}
	
	/**
	 * @return string
	 */
	public function getHeader() {
		return "<{$this->namespacePrefix}:eventSet ".
			"xmlns:{$this->namespacePrefix}=\"{$this->namespace}\" ".
			"version=\"0.3\" ".
			"includesLocationInfo=\"".($this->getLocationInfo() ? "true" : "false")."\"".
			">" . PHP_EOL;
	}

	/**
	 * Formats a {@link LoggerLoggingEvent} in conformance with the log4php.dtd.
	 *
	 * @param LoggerLoggingEvent $event
	 * @return string
	 */
	public function format(LoggerLoggingEvent $event) {
		$ns = $this->namespacePrefix;
		
		$loggerName = $event->getLoggerName();
		$timeStamp = number_format((float)($event->getTimeStamp() * 1000), 0, '', '');
		$thread = $event->getThreadName();
		$level = $event->getLevel()->toString();

		$buf  = "<$ns:event logger=\"{$loggerName}\" level=\"{$level}\" thread=\"{$thread}\" timestamp=\"{$timeStamp}\">".PHP_EOL;
		$buf .= "<$ns:message>"; 
		$buf .= $this->encodeCDATA($event->getRenderedMessage()); 
		$buf .= "</$ns:message>".PHP_EOL;

		$ndc = $event->getNDC();
		if(!empty($ndc)) {
			$buf .= "<$ns:NDC><![CDATA[";
			$buf .= $this->encodeCDATA($ndc);
			$buf .= "]]></$ns:NDC>".PHP_EOL;
		}
		
		$mdcMap = $event->getMDCMap();
		if (!empty($mdcMap)) {
			$buf .= "<$ns:properties>".PHP_EOL;
			foreach ($mdcMap as $name=>$value) {
				$buf .= "<$ns:data name=\"$name\" value=\"$value\" />".PHP_EOL;
			}
			$buf .= "</$ns:properties>".PHP_EOL;
		}

		if ($this->getLocationInfo()) {
			$locationInfo = $event->getLocationInformation();
			$buf .= "<$ns:locationInfo ". 
					"class=\"" . $locationInfo->getClassName() . "\" ".
					"file=\"" .  htmlentities($locationInfo->getFileName(), ENT_QUOTES) . "\" ".
					"line=\"" .  $locationInfo->getLineNumber() . "\" ".
					"method=\"" . $locationInfo->getMethodName() . "\" ";
			$buf .= "/>".PHP_EOL;
		}

		$buf .= "</$ns:event>".PHP_EOL;
		
		return $buf;
	}
	
	/**
	 * @return string
	 */
	public function getFooter() {
		return "</{$this->namespacePrefix}:eventSet>" . PHP_EOL;
	}
	
	
	/** 
	 * Whether or not file name and line number will be included in the output.
	 * @return boolean
	 */
	public function getLocationInfo() {
		return $this->locationInfo;
	}
  
	/**
	 * The {@link $locationInfo} option takes a boolean value. By default,
	 * it is set to false which means there will be no location
	 * information output by this layout. If the the option is set to
	 * true, then the file name and line number of the statement at the
	 * origin of the log statement will be output.
	 */
	public function setLocationInfo($flag) {
		$this->setBoolean('locationInfo', $flag);
	}
  
	/**
	 * @return boolean
	 */
	 public function getLog4jNamespace() {
	 	return $this->log4jNamespace;
	 }

	/**
	 * @param boolean
	 */
	public function setLog4jNamespace($flag) {
		$this->setBoolean('log4jNamespace', $flag);
	}
	
	/** 
	 * Encases a string in CDATA tags, and escapes any existing CDATA end 
	 * tags already present in the string.
	 * @param string $string 
	 */
	private function encodeCDATA($string) {
		$string = str_replace(self::CDATA_END, self::CDATA_EMBEDDED_END, $string);
		return self::CDATA_START . $string . self::CDATA_END;
	}
}

api/log4php/main/php/layouts/LoggerLayoutPattern.php0000644000004100000410000001252613466017021023141 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * A flexible layout configurable with a pattern string.
 * 
 * Configurable parameters:
 * 
 * * converionPattern - A string which controls the formatting of logging 
 *   events. See docs for full specification.
 * 
 * @package log4php
 * @subpackage layouts
 * @version $Revision: 1395470 $
 */
class LoggerLayoutPattern extends LoggerLayout {
	
	/** Default conversion pattern */
	const DEFAULT_CONVERSION_PATTERN = '%date %-5level %logger %message%newline';

	/** Default conversion TTCC Pattern */
	const TTCC_CONVERSION_PATTERN = '%d [%t] %p %c %x - %m%n';

	/** The conversion pattern. */ 
	protected $pattern = self::DEFAULT_CONVERSION_PATTERN;
	
	/** Maps conversion keywords to the relevant converter (default implementation). */
	protected static $defaultConverterMap = array(
		'c' => 'LoggerPatternConverterLogger',
		'lo' => 'LoggerPatternConverterLogger',
		'logger' => 'LoggerPatternConverterLogger',
		
		'C' => 'LoggerPatternConverterClass',
		'class' => 'LoggerPatternConverterClass',
		
		'cookie' => 'LoggerPatternConverterCookie',
		
		'd' => 'LoggerPatternConverterDate',
		'date' => 'LoggerPatternConverterDate',
		
		'e' => 'LoggerPatternConverterEnvironment',
		'env' => 'LoggerPatternConverterEnvironment',
		
		'ex' => 'LoggerPatternConverterThrowable',
		'exception' => 'LoggerPatternConverterThrowable',
		'throwable' => 'LoggerPatternConverterThrowable',
		
		'F' => 'LoggerPatternConverterFile',
		'file' => 'LoggerPatternConverterFile',
			
		'l' => 'LoggerPatternConverterLocation',
		'location' => 'LoggerPatternConverterLocation',
		
		'L' => 'LoggerPatternConverterLine',
		'line' => 'LoggerPatternConverterLine',
		
		'm' => 'LoggerPatternConverterMessage',
		'msg' => 'LoggerPatternConverterMessage',
		'message' => 'LoggerPatternConverterMessage',
		
		'M' => 'LoggerPatternConverterMethod',
		'method' => 'LoggerPatternConverterMethod',
		
		'n' => 'LoggerPatternConverterNewLine',
		'newline' => 'LoggerPatternConverterNewLine',
		
		'p' => 'LoggerPatternConverterLevel',
		'le' => 'LoggerPatternConverterLevel',
		'level' => 'LoggerPatternConverterLevel',
	
		'r' => 'LoggerPatternConverterRelative',
		'relative' => 'LoggerPatternConverterRelative',
		
		'req' => 'LoggerPatternConverterRequest',
		'request' => 'LoggerPatternConverterRequest',
		
		's' => 'LoggerPatternConverterServer',
		'server' => 'LoggerPatternConverterServer',
		
		'ses' => 'LoggerPatternConverterSession',
		'session' => 'LoggerPatternConverterSession',
		
		'sid' => 'LoggerPatternConverterSessionID',
		'sessionid' => 'LoggerPatternConverterSessionID',
	
		't' => 'LoggerPatternConverterProcess',
		'pid' => 'LoggerPatternConverterProcess',
		'process' => 'LoggerPatternConverterProcess',
		
		'x' => 'LoggerPatternConverterNDC',
		'ndc' => 'LoggerPatternConverterNDC',
			
		'X' => 'LoggerPatternConverterMDC',
		'mdc' => 'LoggerPatternConverterMDC',
	);

	/** Maps conversion keywords to the relevant converter. */
	protected $converterMap = array();
	
	/** 
	 * Head of a chain of Converters.
	 * @var LoggerPatternConverter 
	 */
	private $head;

	/** Returns the default converter map. */
	public static function getDefaultConverterMap() {
		return self::$defaultConverterMap;
	}
	
	/** Constructor. Initializes the converter map. */
	public function __construct() {
		$this->converterMap = self::$defaultConverterMap;
	}
	
	/**
	 * Sets the conversionPattern option. This is the string which
	 * controls formatting and consists of a mix of literal content and
	 * conversion specifiers.
	 * @param array $conversionPattern
	 */
	public function setConversionPattern($conversionPattern) {
		$this->pattern = $conversionPattern;
	}
	
	/**
	 * Processes the conversion pattern and creates a corresponding chain of 
	 * pattern converters which will be used to format logging events. 
	 */
	public function activateOptions() {
		if (!isset($this->pattern)) {
			throw new LoggerException("Mandatory parameter 'conversionPattern' is not set.");
		}
		
		$parser = new LoggerPatternParser($this->pattern, $this->converterMap);
		$this->head = $parser->parse();
	}
	
	/**
	 * Produces a formatted string as specified by the conversion pattern.
	 *
	 * @param LoggerLoggingEvent $event
	 * @return string
	 */
	public function format(LoggerLoggingEvent $event) {
		$sbuf = '';
		$converter = $this->head;
		while ($converter !== null) {
			$converter->format($sbuf, $event);
			$converter = $converter->next;
		}
		return $sbuf;
	}
}api/log4php/main/php/layouts/LoggerLayoutSerialized.php0000644000004100000410000000347513466017021023622 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Layout which formats the events using PHP's serialize() function.
 * 
 * Available options:
 * - locationInfo - If set to true, the event's location information will also
 *                  be serialized (slow, defaults to false).
 * 
 * @version $Revision: 1334369 $
 * @package log4php
 * @subpackage layouts
 * @since 2.2
 */  
class LoggerLayoutSerialized extends LoggerLayout {
	
	/** Whether to include the event's location information (slow). */
	protected $locationInfo = false;
	
	/** Sets the location information flag. */
	public function setLocationInfo($value) {
		$this->setBoolean('locationInfo', $value);
	}
	
	/** Returns the location information flag. */
	public function getLocationInfo() {
		return $this->locationInfo;
	}
	
	public function format(LoggerLoggingEvent $event) {
		// If required, initialize the location data
		if($this->locationInfo) {
			$event->getLocationInformation();
		}
		return serialize($event) . PHP_EOL;
	}
}
api/log4php/main/php/LoggerAppender.php0000644000004100000410000001636513466017021020371 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Abstract class that defines output logs strategies.
 *
 * @version $Revision: 1374777 $
 * @package log4php
 */
abstract class LoggerAppender extends LoggerConfigurable {
	
	/**
	 * Set to true when the appender is closed. A closed appender will not 
	 * accept any logging requests. 
	 * @var boolean 
	 */
	protected $closed = false;
	
	/**
	 * The first filter in the filter chain.
	 * @var LoggerFilter
	 */
	protected $filter;
			
	/**
	 * The appender's layout. Can be null if the appender does not use 
	 * a layout.
	 * @var LoggerLayout
	 */
	protected $layout; 
	
	/**
	 * Appender name. Used by other components to identify this appender.
	 * @var string
	 */
	protected $name;
	
	/**
	 * Appender threshold level. Events whose level is below the threshold 
	 * will not be logged.
	 * @var LoggerLevel
	 */
	protected $threshold;
	
	/**
	 * Set to true if the appender requires a layout.
	 * 
	 * True by default, appenders which do not use a layout should override 
	 * this property to false.
	 * 
	 * @var boolean
	 */
	protected $requiresLayout = true;
	
	/**
	 * Default constructor.
	 * @param string $name Appender name
	 */
	public function __construct($name = '') {
		$this->name = $name;

		if ($this->requiresLayout) {
			$this->layout = $this->getDefaultLayout();
		}
	}
	
	public function __destruct() {
		$this->close();
	}
	
	/**
	 * Returns the default layout for this appender. Can be overriden by 
	 * derived appenders.
	 * 
	 * @return LoggerLayout
	 */
	public function getDefaultLayout() {
		return new LoggerLayoutSimple();
	}
	
	/**
	 * Adds a filter to the end of the filter chain.
	 * @param LoggerFilter $filter add a new LoggerFilter
	 */
	public function addFilter($filter) {
		if($this->filter === null) {
			$this->filter = $filter;
		} else {
			$this->filter->addNext($filter);
		}
	}
	
	/**
	 * Clears the filter chain by removing all the filters in it.
	 */
	public function clearFilters() {
		$this->filter = null;
	}

	/**
	 * Returns the first filter in the filter chain. 
	 * The return value may be <i>null</i> if no is filter is set.
	 * @return LoggerFilter
	 */
	public function getFilter() {
		return $this->filter;
	} 
	
	/** 
	 * Returns the first filter in the filter chain. 
	 * The return value may be <i>null</i> if no is filter is set.
	 * @return LoggerFilter
	 */
	public function getFirstFilter() {
		return $this->filter;
	}
	
	/**
	 * Performs threshold checks and invokes filters before delegating logging 
	 * to the subclass' specific <i>append()</i> method.
	 * @see LoggerAppender::append()
	 * @param LoggerLoggingEvent $event
	 */
	public function doAppend(LoggerLoggingEvent $event) {
		if($this->closed) {
			return;
		}
		
		if(!$this->isAsSevereAsThreshold($event->getLevel())) {
			return;
		}

		$filter = $this->getFirstFilter();
		while($filter !== null) {
			switch ($filter->decide($event)) {
				case LoggerFilter::DENY: return;
				case LoggerFilter::ACCEPT: return $this->append($event);
				case LoggerFilter::NEUTRAL: $filter = $filter->getNext();
			}
		}
		$this->append($event);
	}	 

	/**
	 * Sets the appender layout.
	 * @param LoggerLayout $layout
	 */
	public function setLayout($layout) {
		if($this->requiresLayout()) {
			$this->layout = $layout;
		}
	} 
	
	/**
	 * Returns the appender layout.
	 * @return LoggerLayout
	 */
	public function getLayout() {
		return $this->layout;
	}
	
	/**
	 * Configurators call this method to determine if the appender
	 * requires a layout. 
	 *
	 * <p>If this method returns <i>true</i>, meaning that layout is required, 
	 * then the configurator will configure a layout using the configuration 
	 * information at its disposal.	 If this method returns <i>false</i>, 
	 * meaning that a layout is not required, then layout configuration will be
	 * skipped even if there is available layout configuration
	 * information at the disposal of the configurator.</p>
	 *
	 * <p>In the rather exceptional case, where the appender
	 * implementation admits a layout but can also work without it, then
	 * the appender should return <i>true</i>.</p>
	 * 
	 * @return boolean
	 */
	public function requiresLayout() {
		return $this->requiresLayout;
	}
	
	/**
	 * Retruns the appender name.
	 * @return string
	 */
	public function getName() {
		return $this->name;
	}
	
	/**
	 * Sets the appender name.
	 * @param string $name
	 */
	public function setName($name) {
		$this->name = $name;	
	}
	
	/**
	 * Returns the appender's threshold level. 
	 * @return LoggerLevel
	 */
	public function getThreshold() { 
		return $this->threshold;
	}
	
	/**
	 * Sets the appender threshold.
	 * 
	 * @param LoggerLevel|string $threshold Either a {@link LoggerLevel} 
	 *   object or a string equivalent.
	 * @see LoggerOptionConverter::toLevel()
	 */
	public function setThreshold($threshold) {
		$this->setLevel('threshold', $threshold);
	}
	
	/**
	 * Checks whether the message level is below the appender's threshold. 
	 *
	 * If there is no threshold set, then the return value is always <i>true</i>.
	 * 
	 * @param LoggerLevel $level
	 * @return boolean Returns true if level is greater or equal than 
	 *   threshold, or if the threshold is not set. Otherwise returns false.
	 */
	public function isAsSevereAsThreshold($level) {
		if($this->threshold === null) {
			return true;
		}
		return $level->isGreaterOrEqual($this->getThreshold());
	}

	/**
	 * Prepares the appender for logging.
	 * 
	 * Derived appenders should override this method if option structure
	 * requires it.
	 */
	public function activateOptions() {
		$this->closed = false;
	}
	
	/**
	 * Forwards the logging event to the destination.
	 * 
	 * Derived appenders should implement this method to perform actual logging.
	 * 
	 * @param LoggerLoggingEvent $event
	 */
	abstract protected function append(LoggerLoggingEvent $event); 

	/**
	 * Releases any resources allocated by the appender.
	 * 
	 * Derived appenders should override this method to perform proper closing
	 * procedures.
	 */
	public function close() {
		$this->closed = true;
	}
	
	/** Triggers a warning for this logger with the given message. */
	protected function warn($message) {
		$id = get_class($this) . (empty($this->name) ? '' : ":{$this->name}");
		trigger_error("log4php: [$id]: $message", E_USER_WARNING);
	}
	
}
api/log4php/main/php/pattern/0000755000004100000410000000000013466017021016424 5ustar  www-datawww-dataapi/log4php/main/php/pattern/LoggerPatternConverterSessionID.php0000644000004100000410000000224713466017021025370 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the active session ID, or an empty string if out of session. 
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterSessionID extends LoggerPatternConverter {
	public function convert(LoggerLoggingEvent $event) {
		return session_id();
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterDate.php0000644000004100000410000000554013466017021024404 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the date/time of the logging request.
 * 
 * Option: the datetime format, as used by the date() function. If 
 * the option is not given, the default format 'c' will be used.
 * 
 * There are several "special" values which can be given for this option:
 * 'ISO8601', 'ABSOLUTE' and 'DATE'.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterDate extends LoggerPatternConverter {

	const DATE_FORMAT_ISO8601 = 'c';
	
	const DATE_FORMAT_ABSOLUTE = 'H:i:s';
	
	const DATE_FORMAT_DATE = 'd M Y H:i:s.u';
	
	private $format = self::DATE_FORMAT_ISO8601;
	
	private $specials = array(
		'ISO8601' => self::DATE_FORMAT_ISO8601,
		'ABSOLUTE' => self::DATE_FORMAT_ABSOLUTE,
		'DATE' => self::DATE_FORMAT_DATE,
	);
	
	private $useLocalDate = false;
	
	public function activateOptions() {
		
		// Parse the option (date format)
		if (!empty($this->option)) {
			if(isset($this->specials[$this->option])) {
				$this->format = $this->specials[$this->option];
			} else {
				$this->format = $this->option;
			}
		}
		
		// Check whether the pattern contains milliseconds (u)
		if (preg_match('/(?<!\\\\)u/', $this->format)) {
			$this->useLocalDate = true;
		}
	}
	
	public function convert(LoggerLoggingEvent $event) {
		if ($this->useLocalDate) {
			return $this->date($this->format, $event->getTimeStamp());
		}
		return date($this->format, $event->getTimeStamp());
	}
	
	/**
	 * Currently, PHP date() function always returns zeros for milliseconds (u)
	 * on Windows. This is a replacement function for date() which correctly 
	 * displays milliseconds on all platforms. 
	 * 
	 * It is slower than PHP date() so it should only be used if necessary. 
	 */
	private function date($format, $utimestamp) {
		$timestamp = floor($utimestamp);
		$ms = floor(($utimestamp - $timestamp) * 1000);
		$ms = str_pad($ms, 3, '0', STR_PAD_LEFT);
	
		return date(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp);
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterRequest.php0000644000004100000410000000227613466017021025162 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns a value from the $_REQUEST superglobal array corresponding to the 
 * given key.
 * 
 * Options:
 *  [0] $_REQUEST key value
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterRequest extends LoggerPatternConverterSuperglobal {
	protected $name = '_REQUEST';
}api/log4php/main/php/pattern/LoggerPatternConverterRelative.php0000644000004100000410000000241313466017021025276 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the number of milliseconds elapsed since the start of the 
 * application until the creation of the logging event.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1379731 $
 * @since 2.3
 */
class LoggerPatternConverterRelative extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		$ts = $event->getRelativeTime();
		return number_format($ts, 4);
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterSuperglobal.php0000644000004100000410000000611113466017021026001 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns a value from a superglobal array corresponding to the 
 * given key.
 * 
 * Option: the key to look up within the superglobal array
 * 
 * Also, it is possible that a superglobal variable is not populated by PHP
 * because of the settings in the variables-order ini directive. In this case
 * the converter will return an empty value.
 * 
 * @see http://php.net/manual/en/language.variables.superglobals.php
 * @see http://www.php.net/manual/en/ini.core.php#ini.variables-order
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
abstract class LoggerPatternConverterSuperglobal extends LoggerPatternConverter {

	/** 
	 * Name of the superglobal variable, to be defined by subclasses. 
	 * For example: "_SERVER" or "_ENV". 
	 */
	protected $name;
	
	protected $value = '';
	
	public function activateOptions() {
		// Read the key from options array
		if (isset($this->option) && $this->option !== '') {
			$key = $this->option;
		}
	
		/*
		 * There is a bug in PHP which doesn't allow superglobals to be 
		 * accessed when their name is stored in a variable, e.g.:
		 * 
		 * $name = '_SERVER';
		 * $array = $$name;
		 * 
		 * This code does not work when run from within a method (only when run
		 * in global scope). But the following code does work: 
		 * 
		 * $name = '_SERVER';
		 * global $$name;
		 * $array = $$name;
		 * 
		 * That's why global is used here.
		 */
		global ${$this->name};
			
		// Check the given superglobal exists. It is possible that it is not initialized.
		if (!isset(${$this->name})) {
			$class = get_class($this);
			trigger_error("log4php: $class: Cannot find superglobal variable \${$this->name}.", E_USER_WARNING);
			return;
		}
		
		$source = ${$this->name};
		
		// When the key is set, display the matching value
		if (isset($key)) {
			if (isset($source[$key])) {
				$this->value = $source[$key]; 
			}
		}
		
		// When the key is not set, display all values
		else {
			$values = array();
			foreach($source as $key => $value) {
				$values[] = "$key=$value";
			}
			$this->value = implode(', ', $values);			
		}
	}
	
	public function convert(LoggerLoggingEvent $event) {
		return $this->value;
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterMessage.php0000644000004100000410000000221513466017021025107 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the logged message.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterMessage extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return $event->getRenderedMessage();
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterClass.php0000644000004100000410000000371113466017021024572 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the fully qualified class name of the class from which the logging 
 * request was issued.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterClass extends LoggerPatternConverter {

	/** Length to which to shorten the class name. */
	private $length;
	
	/** Holds processed class names. */
	private $cache = array();
	
	public function activateOptions() {
		// Parse the option (desired output length)
		if (isset($this->option) && is_numeric($this->option) && $this->option >= 0) {
			$this->length = (integer) $this->option;
		}
	}

	public function convert(LoggerLoggingEvent $event) {
		$name = $event->getLocationInformation()->getClassName();
	
		if (!isset($this->cache[$name])) {
	
			// If length is set return shortened class name
			if (isset($this->length)) {
				$this->cache[$name] = LoggerUtils::shortenClassName($name, $this->length);
			}
				
			// If no length is specified return the full class name
			else {
				$this->cache[$name] = $name;
			}
		}
	
		return $this->cache[$name];
	}
}
 api/log4php/main/php/pattern/LoggerPatternConverterLocation.php0000644000004100000410000000264213466017021025277 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the line number within the file from which the logging request was 
 * issued. 
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterLocation extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return 
			$event->getLocationInformation()->getClassName() . '.' .
			$event->getLocationInformation()->getMethodName() . '(' .
			$event->getLocationInformation()->getFileName() . ':' .
			$event->getLocationInformation()->getLineNumber() . ')';
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterProcess.php0000644000004100000410000000220713466017021025142 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the PID of the current process.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterProcess extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return getmypid();
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterCookie.php0000644000004100000410000000234113466017021024734 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns a value from the $_COOKIE superglobal array corresponding to the 
 * given key. If no key is given, return all values.
 * 
 * Options:
 *  [0] $_COOKIE key value
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterCookie extends LoggerPatternConverterSuperglobal {
	protected $name = '_COOKIE';
}api/log4php/main/php/pattern/LoggerPatternConverterLogger.php0000644000004100000410000000403413466017021024743 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the name of the logger which created the logging request.
 * 
 * Takes one option, which is an integer. If the option is given, the logger 
 * name will be shortened to the given length, if possible.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterLogger extends LoggerPatternConverter {

	/** Length to which to shorten the name. */
	private $length;
	
	/** Holds processed logger names. */
	private $cache = array();
	
	public function activateOptions() {
		// Parse the option (desired output length)
		if (isset($this->option) && is_numeric($this->option) && $this->option >= 0) {
			$this->length = (integer) $this->option;
		}
	}
	
	public function convert(LoggerLoggingEvent $event) {
		$name = $event->getLoggerName();
		
		if (!isset($this->cache[$name])) {

			// If length is set return shortened logger name 
			if (isset($this->length)) {
				$this->cache[$name] = LoggerUtils::shortenClassName($name, $this->length);
			} 
			
			// If no length is specified return full logger name
			else {
				$this->cache[$name] = $name;
			}
		} 
		
		return $this->cache[$name];
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterServer.php0000644000004100000410000000227413466017021024776 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns a value from the $_SERVER superglobal array corresponding to the 
 * given key.
 * 
 * Options:
 *  [0] $_SERVER key value
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterServer extends LoggerPatternConverterSuperglobal {
	protected $name = '_SERVER';
}
api/log4php/main/php/pattern/LoggerPatternConverter.php0000644000004100000410000000672313466017021023612 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * LoggerPatternConverter is an abstract class that provides the formatting 
 * functionality that derived classes need.
 * 
 * <p>Conversion specifiers in a conversion patterns are parsed to
 * individual PatternConverters. Each of which is responsible for
 * converting a logging event in a converter specific manner.</p>
 * 
 * @version $Revision: 1326626 $
 * @package log4php
 * @subpackage helpers
 * @since 0.3
 */
abstract class LoggerPatternConverter {
	
	/**
	 * Next converter in the converter chain.
	 * @var LoggerPatternConverter 
	 */
	public $next = null;
	
	/**
	 * Formatting information, parsed from pattern modifiers. 
	 * @var LoggerFormattingInfo
	 */
	protected $formattingInfo;
	
	/**
	 * Converter-specific formatting options.
	 * @var array
	 */
	protected $option;

	/**
	 * Constructor 
	 * @param LoggerFormattingInfo $formattingInfo
	 * @param array $option
	 */
	public function __construct(LoggerFormattingInfo $formattingInfo = null, $option = null) {  
		$this->formattingInfo = $formattingInfo;
		$this->option = $option;
		$this->activateOptions();
	}
	
	/**
	 * Called in constructor. Converters which need to process the options 
	 * can override this method. 
	 */
	public function activateOptions() { }
  
	/**
	 * Converts the logging event to the desired format. Derived pattern 
	 * converters must implement this method.
	 *
	 * @param LoggerLoggingEvent $event
	 */
	abstract public function convert(LoggerLoggingEvent $event);

	/**
	 * Converts the event and formats it according to setting in the 
	 * Formatting information object.
	 *
	 * @param string &$sbuf string buffer to write to
	 * @param LoggerLoggingEvent $event Event to be formatted.
	 */
	public function format(&$sbuf, $event) {
		$string = $this->convert($event);
		
		if (!isset($this->formattingInfo)) {
			$sbuf .= $string;
			return;	
		}
		
		$fi = $this->formattingInfo;
		
		// Empty string
		if($string === '' || is_null($string)) {
			if($fi->min > 0) {
				$sbuf .= str_repeat(' ', $fi->min);
			}
			return;
		}
		
		$len = strlen($string);
	
		// Trim the string if needed
		if($len > $fi->max) {
			if ($fi->trimLeft) {
				$sbuf .= substr($string, $len - $fi->max, $fi->max);
			} else {
				$sbuf .= substr($string , 0, $fi->max);
			}
		}
		
		// Add padding if needed
		else if($len < $fi->min) {
			if($fi->padLeft) {
				$sbuf .= str_repeat(' ', $fi->min - $len);
				$sbuf .= $string;
			} else {
				$sbuf .= $string;
				$sbuf .= str_repeat(' ', $fi->min - $len);
			}
		}
		
		// No action needed
		else {
			$sbuf .= $string;
		}
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterLine.php0000644000004100000410000000233413466017021024414 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the line number within the file from which the logging request was 
 * issued. 
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterLine extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return $event->getLocationInformation()->getLineNumber();
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterNDC.php0000644000004100000410000000221613466017021024130 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the full Nested Diagnostic Context.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterNDC extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return $event->getNDC();
	}
}
 api/log4php/main/php/pattern/LoggerPatternConverterThrowable.php0000644000004100000410000000245713466017021025462 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the throwable information linked to the logging event, if any.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1395470 $
 * @since 2.3
 */
class LoggerPatternConverterThrowable extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		$info = $event->getThrowableInformation();
		if (isset($info)) {
			$ex = $info->getThrowable();
			return (string) $ex . PHP_EOL;
		}
		return '';
	}
}
 api/log4php/main/php/pattern/LoggerPatternConverterEnvironment.php0000644000004100000410000000227013466017021026030 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns a value from the $_ENV superglobal array corresponding to the 
 * given key.
 * 
 * Options:
 *  [0] $_ENV key value
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterEnvironment extends LoggerPatternConverterSuperglobal {
	protected $name = '_ENV';
}
api/log4php/main/php/pattern/LoggerPatternConverterLevel.php0000644000004100000410000000221413466017021024571 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the event's level.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterLevel extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return $event->getLevel()->toString();
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterSession.php0000644000004100000410000000230013466017021025141 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns a value from the $_SESSION superglobal array corresponding to the 
 * given key.
 * 
 * Options:
 *  [0] $_SESSION key value
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterSession extends LoggerPatternConverterSuperglobal {
	protected $name = '_SESSION';
}
api/log4php/main/php/pattern/LoggerPatternConverterNewLine.php0000644000004100000410000000221513466017021025064 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns platform-specific newline character(s). 
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterNewLine extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return PHP_EOL;
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterMethod.php0000644000004100000410000000234113466017021024743 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the name of the function or method from which the logging request 
 * was issued. 
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterMethod extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return $event->getLocationInformation()->getMethodName();
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterFile.php0000644000004100000410000000231213466017021024400 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the name of the file from which the logging request was issued. 
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterFile extends LoggerPatternConverter {

	public function convert(LoggerLoggingEvent $event) {
		return $event->getLocationInformation()->getFileName();
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterLiteral.php0000644000004100000410000000245613466017021025126 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the literal value passed in the constructor, without modifications.
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterLiteral extends LoggerPatternConverter {

	private $literalValue;
	
	public function __construct($literalValue) {
		$this->literalValue = $literalValue;
	}
	
	public function convert(LoggerLoggingEvent $event) {
		return $this->literalValue;
	}
}
api/log4php/main/php/pattern/LoggerPatternConverterMDC.php0000644000004100000410000000311013466017021024121 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Returns the Mapped Diagnostic Context value corresponding to the given key.
 * 
 * Options:
 *  [0] the MDC key
 * 
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterMDC extends LoggerPatternConverter {

	private $key;

	public function activateOptions() {
		if (isset($this->option) && $this->option !== '') {
			$this->key = $this->option;
		}
	}
	
	public function convert(LoggerLoggingEvent $event) {
		if (isset($this->key)) {
			return $event->getMDC($this->key);
		} else {
			$buff = array();
			$map = $event->getMDCMap();
			foreach($map as $key => $value) {
				$buff []= "$key=$value";
			}
			return implode(', ', $buff);
		}
	}
}
 api/log4php/main/php/appenders/0000755000004100000410000000000013466017021016730 5ustar  www-datawww-dataapi/log4php/main/php/appenders/LoggerAppenderFirePHP.php0000644000004100000410000000624013466017021023517 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Logs messages as HTTP headers using the FirePHP Insight API.
 * 
 * This appender requires the FirePHP server library version 1.0 or later.
 * 
 * ## Configurable parameters: ##
 * 
 * - **target** - (string) The target to which messages will be sent. Possible options are 
 *            'page' (default), 'request', 'package' and 'controller'. For more details,
 *            see FirePHP documentation.
 * 
 * This class was originally contributed by Bruce Ingalls (Bruce.Ingalls-at-gmail-dot-com).
 * 
 * @link https://github.com/firephp/firephp FirePHP homepage.
 * @link http://sourcemint.com/github.com/firephp/firephp/1:1.0.0b1rc6/-docs/Welcome FirePHP documentation.
 * @link http://sourcemint.com/github.com/firephp/firephp/1:1.0.0b1rc6/-docs/Configuration/Constants FirePHP constants documentation.
 * @link http://logging.apache.org/log4php/docs/appenders/firephp.html Appender documentation
 * 
 * @version $Revision: 1343684 $
 * @package log4php
 * @subpackage appenders
 * @since 2.3
 */
class LoggerAppenderFirePHP extends LoggerAppender {
	
	/**
	 * Instance of the Insight console class.
	 * @var Insight_Plugin_Console
	 */
	protected $console;
	
	/**
	 * The target for log messages. Possible values are: 'page' (default), 
	 * 'request', 'package' and 'contoller'.
	 */
	protected $target = 'page';

	public function activateOptions() {
		if (method_exists('FirePHP', 'to')) {
			$this->console = FirePHP::to($this->target)->console();
			$this->closed = false;
		} else {
			$this->warn('FirePHP is not installed correctly. Closing appender.');
		}
	}
	
	public function append(LoggerLoggingEvent $event) {
		$msg = $event->getMessage();
		
		// Skip formatting for objects and arrays which are handled by FirePHP.
		if (!is_array($msg) && !is_object($msg)) {
			$msg = $this->getLayout()->format($event);
		}
		
		switch ($event->getLevel()->toInt()) {
			case LoggerLevel::TRACE:
			case LoggerLevel::DEBUG:
				$this->console->log($msg);
				break;
			case LoggerLevel::INFO:
				$this->console->info($msg);
				break;
			case LoggerLevel::WARN:
				$this->console->warn($msg);
				break;
			case LoggerLevel::ERROR:
			case LoggerLevel::FATAL:
				$this->console->error($msg);
				break;
		}
	}
	
	/** Returns the target. */
	public function getTarget() {
		return $this->target;
	}

	/** Sets the target. */
	public function setTarget($target) {
		$this->setString('target', $target);
	}
}api/log4php/main/php/appenders/LoggerAppenderNull.php0000644000004100000410000000275413466017021023202 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * A NullAppender merely exists, it never outputs a message to any device.	
 *
 * This appender has no configurable parameters.
 * 
 * @version $Revision: 1343601 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/null.html Appender documentation
 */
class LoggerAppenderNull extends LoggerAppender {

	/** 
	 * This appender does not require a layout. 
	 */
	protected $requiresLayout = false;
	
	/**
	 * Do nothing. 
	 * 
	 * @param LoggerLoggingEvent $event
	 */
	public function append(LoggerLoggingEvent $event) {
	}
}
api/log4php/main/php/appenders/LoggerAppenderFile.php0000644000004100000410000001325613466017021023146 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * LoggerAppenderFile appends log events to a file.
 *
 * This appender uses a layout.
 * 
 * ## Configurable parameters: ##
 * 
 * - **file** - Path to the target file. Relative paths are resolved based on 
 *     the working directory.
 * - **append** - If set to true, the appender will append to the file, 
 *     otherwise the file contents will be overwritten.
 *
 * @version $Revision: 1382274 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/file.html Appender documentation
 */
class LoggerAppenderFile extends LoggerAppender {

	/**
	 * If set to true, the file is locked before appending. This allows 
	 * concurrent access. However, appending without locking is faster so
	 * it should be used where appropriate.
	 * 
	 * TODO: make this a configurable parameter
	 * 
	 * @var boolean
	 */
	protected $locking = true;
	
	/**
	 * If set to true, appends to file. Otherwise overwrites it.
	 * @var boolean
	 */
	protected $append = true;
	
	/**
	 * Path to the target file.
	 * @var string 
	 */
	protected $file;

	/**
	 * The file resource.
	 * @var resource
	 */
	protected $fp;
	
	/** 
	 * Helper function which can be easily overriden by daily file appender. 
	 */
	protected function getTargetFile() {
		return $this->file;
	}
	
	/**
	 * Acquires the target file resource, creates the destination folder if 
	 * necessary. Writes layout header to file.
	 * 
	 * @return boolean FALSE if opening failed
	 */
	protected function openFile() {
		$file = $this->getTargetFile();

		// Create the target folder if needed
		if(!is_file($file)) {
			$dir = dirname($file);

			if(!is_dir($dir)) {
				$success = mkdir($dir, 0777, true);
				if ($success === false) {
					$this->warn("Failed creating target directory [$dir]. Closing appender.");
					$this->closed = true;
					return false;
				}
			}
		}
		
		$mode = $this->append ? 'a' : 'w';
		$this->fp = fopen($file, $mode);
		if ($this->fp === false) {
			$this->warn("Failed opening target file. Closing appender.");
			$this->fp = null;
			$this->closed = true;
			return false;
		}
		
		// Required when appending with concurrent access
		if($this->append) {
			fseek($this->fp, 0, SEEK_END);
		}
		
		// Write the header
		$this->write($this->layout->getHeader());
	}
	
	/**
	 * Writes a string to the target file. Opens file if not already open.
	 * @param string $string Data to write.
	 */
	protected function write($string) {
		// Lazy file open
		if(!isset($this->fp)) {
			if ($this->openFile() === false) {
				return; // Do not write if file open failed.
			}
		}
		
		if ($this->locking) {
			$this->writeWithLocking($string);
		} else {
			$this->writeWithoutLocking($string);
		}
	}
	
	protected function writeWithLocking($string) {
		if(flock($this->fp, LOCK_EX)) {
			if(fwrite($this->fp, $string) === false) {
				$this->warn("Failed writing to file. Closing appender.");
				$this->closed = true;				
			}
			flock($this->fp, LOCK_UN);
		} else {
			$this->warn("Failed locking file for writing. Closing appender.");
			$this->closed = true;
		}
	}
	
	protected function writeWithoutLocking($string) {
		if(fwrite($this->fp, $string) === false) {
			$this->warn("Failed writing to file. Closing appender.");
			$this->closed = true;				
		}
	}
	
	public function activateOptions() {
		if (empty($this->file)) {
			$this->warn("Required parameter 'file' not set. Closing appender.");
			$this->closed = true;
			return;
		}
	}
	
	public function close() {
		if (is_resource($this->fp)) {
			$this->write($this->layout->getFooter());
			fclose($this->fp);
		}
		$this->fp = null;
		$this->closed = true;
	}

	public function append(LoggerLoggingEvent $event) {
		$this->write($this->layout->format($event));
	}
	
	/**
	 * Sets the 'file' parameter.
	 * @param string $file
	 */
	public function setFile($file) {
		$this->setString('file', $file);
	}
	
	/**
	 * Returns the 'file' parameter.
	 * @return string
	 */
	public function getFile() {
		return $this->file;
	}
	
	/**
	 * Returns the 'append' parameter.
	 * @return boolean
	 */
	public function getAppend() {
		return $this->append;
	}

	/**
	 * Sets the 'append' parameter.
	 * @param boolean $append
	 */
	public function setAppend($append) {
		$this->setBoolean('append', $append);
	}

	/**
	 * Sets the 'file' parmeter. Left for legacy reasons.
	 * @param string $fileName
	 * @deprecated Use setFile() instead.
	 */
	public function setFileName($fileName) {
		$this->setFile($fileName);
	}
	
	/**
	 * Returns the 'file' parmeter. Left for legacy reasons.
	 * @return string
	 * @deprecated Use getFile() instead.
	 */
	public function getFileName() {
		return $this->getFile();
	}
}
api/log4php/main/php/appenders/LoggerAppenderPDO.php0000644000004100000410000002120113466017021022676 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * LoggerAppenderPDO appender logs to a database using the PHP's PDO extension.
 *
 * ## Configurable parameters: ##
 *
 * - dsn             - The Data Source Name (DSN) used to connect to the database.
 * - user            - Username used to connect to the database.
 * - password        - Password used to connect to the database.
 * - table           - Name of the table to which log entries are be inserted.
 * - insertSQL       - Sets the insert statement for a logging event. Defaults
 *                     to the correct one - change only if you are sure what you are doing.
 * - insertPattern   - The conversion pattern to use in conjuction with insert 
 *                     SQL. Must contain the same number of comma separated 
 *                     conversion patterns as there are question marks in the 
 *                     insertSQL.
 *
 * @version $Revision: 1374546 $
 * @package log4php
 * @subpackage appenders
 * @since 2.0
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/pdo.html Appender documentation
 */
class LoggerAppenderPDO extends LoggerAppender {

	// ******************************************
	// *** Configurable parameters            ***
	// ******************************************
	
	/** 
	 * DSN string used to connect to the database.
	 * @see http://www.php.net/manual/en/pdo.construct.php
	 */
	protected $dsn;

	/** Database user name. */
	protected $user;
	
	/** Database password. */
	protected $password;
	
	/** 
	 * The insert query.
	 * 
	 * The __TABLE__ placeholder will be replaced by the table name from 
	 * {@link $table}.
	 *  
	 * The questionmarks are part of the prepared statement, and they must 
	 * match the number of conversion specifiers in {@link insertPattern}.
	 */
	protected $insertSQL = "INSERT INTO __TABLE__ (timestamp, logger, level, message, thread, file, line) VALUES (?, ?, ?, ?, ?, ?, ?)";

	/** 
	 * A comma separated list of {@link LoggerPatternLayout} format strings 
	 * which replace the "?" in {@link $insertSQL}.
	 * 
	 * Must contain the same number of comma separated conversion patterns as 
	 * there are question marks in {@link insertSQL}.
 	 * 
 	 * @see LoggerPatternLayout For conversion patterns.
	 */
	protected $insertPattern = "%date{Y-m-d H:i:s},%logger,%level,%message,%pid,%file,%line";

	/** Name of the table to which to append log events. */
	protected $table = 'log4php_log';
	
	/** The number of recconect attempts to make on failed append. */
	protected $reconnectAttempts = 3;
	
	
	// ******************************************
	// *** Private memebers                   ***
	// ******************************************
	
	/** 
	 * The PDO instance.
	 * @var PDO 
	 */
	protected $db;
	
	/** 
	 * Prepared statement for the insert query.
	 * @var PDOStatement 
	 */
	protected $preparedInsert;
	
	/** This appender does not require a layout. */
	protected $requiresLayout = false;


	// ******************************************
	// *** Appender methods                   ***
	// ******************************************
	
	/**
	 * Acquires a database connection based on parameters.
	 * Parses the insert pattern to create a chain of converters which will be
	 * used in forming query parameters from logging events.
	 */
	public function activateOptions() {
		try {
			$this->establishConnection();
		} catch (PDOException $e) {
			$this->warn("Failed connecting to database. Closing appender. Error: " . $e->getMessage());
			$this->close();
			return;
		}

		// Parse the insert patterns; pattern parts are comma delimited
		$pieces = explode(',', $this->insertPattern);
		$converterMap = LoggerLayoutPattern::getDefaultConverterMap();
		foreach($pieces as $pattern) {
			$parser = new LoggerPatternParser($pattern, $converterMap);
			$this->converters[] = $parser->parse(); 
		}
		
		$this->closed = false;
	}
	
	/** 
	 * Connects to the database, and prepares the insert query.
	 * @throws PDOException If connect or prepare fails.  
	 */
	protected function establishConnection() {
		// Acquire database connection
		$this->db = new PDO($this->dsn, $this->user, $this->password);
		$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		
		// Prepare the insert statement
		$insertSQL = str_replace('__TABLE__', $this->table, $this->insertSQL);
		$this->preparedInsert = $this->db->prepare($insertSQL);
	}
	
	/**
	 * Appends a new event to the database.
	 * 
	 * If writing to database fails, it will retry by re-establishing the 
	 * connection up to $reconnectAttempts times. If writing still fails, 
	 * the appender will close.
	 */
	public function append(LoggerLoggingEvent $event) {

		for ($attempt = 1; $attempt <= $this->reconnectAttempts + 1; $attempt++) {
			try {
				// Attempt to write to database
				$this->preparedInsert->execute($this->format($event));
				$this->preparedInsert->closeCursor();
				break;
			} catch (PDOException $e) {
				$this->warn("Failed writing to database: ". $e->getMessage());
				
				// Close the appender if it's the last attempt
				if ($attempt > $this->reconnectAttempts) {
					$this->warn("Failed writing to database after {$this->reconnectAttempts} reconnect attempts. Closing appender.");
					$this->close();
				// Otherwise reconnect and try to write again
				} else {
					$this->warn("Attempting a reconnect (attempt $attempt of {$this->reconnectAttempts}).");
					$this->establishConnection();
				}
			}
		}
	}
	
	/**
	 * Converts the logging event to a series of database parameters by using 
	 * the converter chain which was set up on activation. 
	 */
	protected function format(LoggerLoggingEvent $event) {
		$params = array();
		foreach($this->converters as $converter) {
			$buffer = '';
			while ($converter !== null) {
				$converter->format($buffer, $event);
				$converter = $converter->next;
			}
			$params[] = $buffer;
		}
		return $params;
	}
	
	/**
	 * Closes the connection to the logging database
	 */
	public function close() {
		// Close the connection (if any)
		$this->db = null;
		
		// Close the appender
		$this->closed = true;
	}
	
	// ******************************************
	// *** Accessor methods                   ***
	// ******************************************
	
	/**
	 * Returns the active database handle or null if not established.
	 * @return PDO
	 */
	public function getDatabaseHandle() {
		return $this->db;
	}
	
	/** Sets the username. */
	public function setUser($user) {
		$this->setString('user', $user);
	}
	
	/** Returns the username. */
	public function getUser($user) {
		return $this->user;
	}
	
	/** Sets the password. */
	public function setPassword($password) {
		$this->setString('password', $password);
	}
	
	/** Returns the password. */
	public function getPassword($password) {
		return $this->password;
	}
	
	/** Sets the insert SQL. */
	public function setInsertSQL($sql) {
		$this->setString('insertSQL', $sql);
	}
	
	/** Returns the insert SQL. */
	public function getInsertSQL($sql) {
		return $this->insertSQL;
	}

	/** Sets the insert pattern. */
	public function setInsertPattern($pattern) {
		$this->setString('insertPattern', $pattern);
	}
	
	/** Returns the insert pattern. */
	public function getInsertPattern($pattern) {
		return $this->insertPattern;
	}

	/** Sets the table name. */
	public function setTable($table) {
		$this->setString('table', $table);
	}
	
	/** Returns the table name. */
	public function getTable($table) {
		return $this->table;
	}
	
	/** Sets the DSN string. */
	public function setDSN($dsn) {
		$this->setString('dsn', $dsn);
	}
	
	/** Returns the DSN string. */
	public function getDSN($dsn) {
		return $this->setString('dsn', $dsn);
	}	
}
api/log4php/main/php/appenders/LoggerAppenderMongoDB.php0000644000004100000410000002463613466017021023560 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/**
 * Appender for writing to MongoDB.
 * 
 * This class was originally contributed by Vladimir Gorej.
 * 
 * ## Configurable parameters: ##
 * 
 * - **host** - Server on which mongodb instance is located. 
 * - **port** - Port on which the instance is bound.
 * - **databaseName** - Name of the database to which to log.
 * - **collectionName** - Name of the target collection within the given database.
 * - **username** - Username used to connect to the database.
 * - **password** - Password used to connect to the database.
 * - **timeout** - For how long the driver should try to connect to the database (in milliseconds).
 * 
 * @version $Revision: 1346363 $
 * @package log4php
 * @subpackage appenders
 * @since 2.1
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/mongodb.html Appender documentation
 * @link http://github.com/log4mongo/log4mongo-php Vladimir Gorej's original submission.
 * @link http://www.mongodb.org/ MongoDB website.
 */
class LoggerAppenderMongoDB extends LoggerAppender {
	
	// ******************************************
	// ** Constants                            **
	// ******************************************
	
	/** Default prefix for the {@link $host}. */	
	const DEFAULT_MONGO_URL_PREFIX = 'mongodb://';
	
	/** Default value for {@link $host}, without a prefix. */
	const DEFAULT_MONGO_HOST = 'localhost';
	
	/** Default value for {@link $port} */
	const DEFAULT_MONGO_PORT = 27017;
	
	/** Default value for {@link $databaseName} */
	const DEFAULT_DB_NAME = 'log4php_mongodb';
	
	/** Default value for {@link $collectionName} */
	const DEFAULT_COLLECTION_NAME = 'logs';
	
	/** Default value for {@link $timeout} */
	const DEFAULT_TIMEOUT_VALUE = 3000;
	
	// ******************************************
	// ** Configurable parameters              **
	// ******************************************
	
	/** Server on which mongodb instance is located. */
	protected $host;
	
	/** Port on which the instance is bound. */
	protected $port;
	
	/** Name of the database to which to log. */
	protected $databaseName;
	
	/** Name of the collection within the given database. */
	protected $collectionName;
			
	/** Username used to connect to the database. */
	protected $userName;
	
	/** Password used to connect to the database. */
	protected $password;
	
	/** Timeout value used when connecting to the database (in milliseconds). */
	protected $timeout;
	
	// ******************************************
	// ** Member variables                     **
	// ******************************************

	/** 
	 * Connection to the MongoDB instance.
	 * @var Mongo
	 */
	protected $connection;
	
	/** 
	 * The collection to which log is written. 
	 * @var MongoCollection
	 */
	protected $collection;

	public function __construct($name = '') {
		parent::__construct($name);
		$this->host = self::DEFAULT_MONGO_URL_PREFIX . self::DEFAULT_MONGO_HOST;
		$this->port = self::DEFAULT_MONGO_PORT;
		$this->databaseName = self::DEFAULT_DB_NAME;
		$this->collectionName = self::DEFAULT_COLLECTION_NAME;
		$this->timeout = self::DEFAULT_TIMEOUT_VALUE;
		$this->requiresLayout = false;
	}
	
	/**
	 * Setup db connection.
	 * Based on defined options, this method connects to the database and 
	 * creates a {@link $collection}. 
	 */
	public function activateOptions() {
		try {
			$this->connection = new Mongo(sprintf('%s:%d', $this->host, $this->port), array('timeout' => $this->timeout));
			$db	= $this->connection->selectDB($this->databaseName);
			if ($this->userName !== null && $this->password !== null) {
				$authResult = $db->authenticate($this->userName, $this->password);
				if ($authResult['ok'] == floatval(0)) {
					throw new Exception($authResult['errmsg'], $authResult['ok']);
				}
			}
			$this->collection = $db->selectCollection($this->collectionName);
		} catch (MongoConnectionException $ex) {
			$this->closed = true;
			$this->warn(sprintf('Failed to connect to mongo deamon: %s', $ex->getMessage()));
		} catch (InvalidArgumentException $ex) {
			$this->closed = true;
			$this->warn(sprintf('Error while selecting mongo database: %s', $ex->getMessage()));
		} catch (Exception $ex) {
			$this->closed = true;
			$this->warn('Invalid credentials for mongo database authentication');
		}
	}

	/**
	 * Appends a new event to the mongo database.
	 *
	 * @param LoggerLoggingEvent $event
	 */
	public function append(LoggerLoggingEvent $event) {
		try {
			if ($this->collection != null) {
				$this->collection->insert($this->format($event));
			}
		} catch (MongoCursorException $ex) {
			$this->warn(sprintf('Error while writing to mongo collection: %s', $ex->getMessage()));
		}
	}
	
	/**
	 * Converts the logging event into an array which can be logged to mongodb.
	 * 
	 * @param LoggerLoggingEvent $event
	 * @return array The array representation of the logging event.
	 */
	protected function format(LoggerLoggingEvent $event) {
		$timestampSec = (int) $event->getTimestamp();
		$timestampUsec = (int) (($event->getTimestamp() - $timestampSec) * 1000000);

		$document = array(
			'timestamp' => new MongoDate($timestampSec, $timestampUsec),
			'level' => $event->getLevel()->toString(),
			'thread' => (int) $event->getThreadName(),
			'message' => $event->getMessage(),
			'loggerName' => $event->getLoggerName() 
		);	

		$locationInfo = $event->getLocationInformation();
		if ($locationInfo != null) {
			$document['fileName'] = $locationInfo->getFileName();
			$document['method'] = $locationInfo->getMethodName();
			$document['lineNumber'] = ($locationInfo->getLineNumber() == 'NA') ? 'NA' : (int) $locationInfo->getLineNumber();
			$document['className'] = $locationInfo->getClassName();
		}	

		$throwableInfo = $event->getThrowableInformation();
		if ($throwableInfo != null) {
			$document['exception'] = $this->formatThrowable($throwableInfo->getThrowable());
		}
		
		return $document;
	}
	
	/**
	 * Converts an Exception into an array which can be logged to mongodb.
	 * 
	 * Supports innner exceptions (PHP >= 5.3)
	 * 
	 * @param Exception $ex
	 * @return array
	 */
	protected function formatThrowable(Exception $ex) {
		$array = array(				
			'message' => $ex->getMessage(),
			'code' => $ex->getCode(),
			'stackTrace' => $ex->getTraceAsString(),
		);
        
		if (method_exists($ex, 'getPrevious') && $ex->getPrevious() !== null) {
			$array['innerException'] = $this->formatThrowable($ex->getPrevious());
		}
		
		return $array;
	}
		
	/**
	 * Closes the connection to the logging database
	 */
	public function close() {
		if($this->closed != true) {
			$this->collection = null;
			if ($this->connection !== null) {
				$this->connection->close();
				$this->connection = null;
			}
			$this->closed = true;
		}
	}
	
	/** 
	 * Sets the value of {@link $host} parameter.
	 * @param string $host
	 */
	public function setHost($host) {
		if (!preg_match('/^mongodb\:\/\//', $host)) {
			$host = self::DEFAULT_MONGO_URL_PREFIX . $host;
		}
		$this->host = $host;
	}
		
	/** 
	 * Returns the value of {@link $host} parameter.
	 * @return string
	 */
	public function getHost() {
		return $this->host;
	}

	/** 
	 * Sets the value of {@link $port} parameter.
	 * @param int $port
	 */
	public function setPort($port) {
		$this->setPositiveInteger('port', $port);
	}
		
	/** 
	 * Returns the value of {@link $port} parameter.
	 * @return int
	 */
	public function getPort() {
		return $this->port;
	}

	/** 
	 * Sets the value of {@link $databaseName} parameter.
	 * @param string $databaseName
	 */
	public function setDatabaseName($databaseName) {
		$this->setString('databaseName', $databaseName);
	}
		
	/** 
	 * Returns the value of {@link $databaseName} parameter.
	 * @return string
	 */
	public function getDatabaseName() {
		return $this->databaseName;
	}

	/** 
	 * Sets the value of {@link $collectionName} parameter.
	 * @param string $collectionName
	 */
	public function setCollectionName($collectionName) {
		$this->setString('collectionName', $collectionName);
	}
		
	/** 
	 * Returns the value of {@link $collectionName} parameter.
	 * @return string
	 */
	public function getCollectionName() {
		return $this->collectionName;
	}

	/** 
	 * Sets the value of {@link $userName} parameter.
	 * @param string $userName
	 */
	public function setUserName($userName) {
		$this->setString('userName', $userName, true);
	}
	
	/** 
	 * Returns the value of {@link $userName} parameter.
	 * @return string
	 */
	public function getUserName() {
		return $this->userName;
	}

	/** 
	 * Sets the value of {@link $password} parameter.
	 * @param string $password
	 */
	public function setPassword($password) {
		$this->setString('password', $password, true);
	}
		
	/** 
	 * Returns the value of {@link $password} parameter.
	 * @return string 
	 */
	public function getPassword() {
		return $this->password;
	}

	/** 
	 * Sets the value of {@link $timeout} parameter.
	 * @param int $timeout
	 */
	public function setTimeout($timeout) {
		$this->setPositiveInteger('timeout', $timeout);
	}

	/** 
	 * Returns the value of {@link $timeout} parameter.
	 * @return int
	 */
	public function getTimeout() {
		return $this->timeout;
	}
	/** 
	 * Returns the mongodb connection.
	 * @return Mongo
	 */
	public function getConnection() {
		return $this->connection;
	}
	
	/** 
	 * Returns the active mongodb collection.
	 * @return MongoCollection
	 */
	public function getCollection() {
		return $this->collection;
	}
}
api/log4php/main/php/appenders/LoggerAppenderMail.php0000644000004100000410000000761613466017021023154 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * LoggerAppenderMail appends log events via email.
 *
 * This appender does not send individual emails for each logging requests but 
 * will collect them in a buffer and send them all in a single email once the 
 * appender is closed (i.e. when the script exists). Because of this, it may 
 * not appropriate for long running scripts, in which case 
 * LoggerAppenderMailEvent might be a better choice.
 * 
 * This appender uses a layout.
 * 
 * ## Configurable parameters: ##
 * 
 * - **to** - Email address(es) to which the log will be sent. Multiple email 
 *     addresses may be specified by separating them with a comma.
 * - **from** - Email address which will be used in the From field.
 * - **subject** - Subject of the email message.
 * 
 * @version $Revision: 1337820 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/mail.html Appender documentation
 */
class LoggerAppenderMail extends LoggerAppender {

	/** 
	 * Email address to put in From field of the email.
	 * @var string
	 */
	protected $from = null;

	/** 
	 * The subject of the email.
	 * @var string
	 */
	protected $subject = 'Log4php Report';
	
	/**
	 * One or more comma separated email addresses to which to send the email. 
	 * @var string
	 */
	protected $to = null;

	/** 
	 * Indiciates whether this appender should run in dry mode.
	 * @deprecated
	 * @var boolean 
	 */
	protected $dry = false;

	/** 
	 * Buffer which holds the email contents before it is sent. 
	 * @var string  
	 */
	protected $body = '';
	
	public function append(LoggerLoggingEvent $event) {
		if($this->layout !== null) {
			$this->body .= $this->layout->format($event);
		}
	}
	
	public function close() {
		if($this->closed != true) {
			$from = $this->from;
			$to = $this->to;
	
			if(!empty($this->body) and $from !== null and $to !== null and $this->layout !== null) {
				$subject = $this->subject;
				if(!$this->dry) {
					mail(
						$to, $subject, 
						$this->layout->getHeader() . $this->body . $this->layout->getFooter(),
						"From: {$from}\r\n");
				} else {
				    echo "DRY MODE OF MAIL APP.: Send mail to: ".$to." with content: ".$this->body;
				}
			}
			$this->closed = true;
		}
	}
	
	/** Sets the 'subject' parameter. */
	public function setSubject($subject) {
		$this->setString('subject', $subject);
	}
	
	/** Returns the 'subject' parameter. */
	public function getSubject() {
		return $this->subject;
	}
	
	/** Sets the 'to' parameter. */
	public function setTo($to) {
		$this->setString('to', $to);
	}
	
	/** Returns the 'to' parameter. */
	public function getTo() {
		return $this->to;
	}

	/** Sets the 'from' parameter. */
	public function setFrom($from) {
		$this->setString('from', $from);
	}
	
	/** Returns the 'from' parameter. */
	public function getFrom() {
		return $this->from;
	}

	/** Enables or disables dry mode. */
	public function setDry($dry) {
		$this->setBoolean('dry', $dry);
	}
}
api/log4php/main/php/appenders/LoggerAppenderRollingFile.php0000644000004100000410000002206313466017021024471 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * LoggerAppenderRollingFile writes logging events to a specified file. The 
 * file is rolled over after a specified size has been reached.
 * 
 * This appender uses a layout.
 *
 * ## Configurable parameters: ##
 * 
 * - **file** - Path to the target file.
 * - **append** - If set to true, the appender will append to the file, 
 *     otherwise the file contents will be overwritten.
 * - **maxBackupIndex** - Maximum number of backup files to keep. Default is 1.
 * - **maxFileSize** - Maximum allowed file size (in bytes) before rolling 
 *     over. Suffixes "KB", "MB" and "GB" are allowed. 10KB = 10240 bytes, etc.
 *     Default is 10M.
 * - **compress** - If set to true, rolled-over files will be compressed. 
 *     Requires the zlib extension.
 *
 * @version $Revision: 1394975 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/rolling-file.html Appender documentation
 */
class LoggerAppenderRollingFile extends LoggerAppenderFile {

	/** Compressing backup files is done in chunks, this determines how large. */
	const COMPRESS_CHUNK_SIZE = 102400; // 100KB
	
	/**
	 * The maximum size (in bytes) that the output file is allowed to reach 
	 * before being rolled over to backup files.
	 *
	 * The default maximum file size is 10MB (10485760 bytes). Maximum value 
	 * for this option may depend on the file system.
	 *
	 * @var integer
	 */
	protected $maxFileSize = 10485760;
	
	/**
	 * Set the maximum number of backup files to keep around.
	 * 
	 * Determines how many backup files are kept before the oldest is erased. 
	 * This option takes a positive integer value. If set to zero, then there 
	 * will be no backup files and the log file will be truncated when it 
	 * reaches <var>maxFileSize</var>.
	 * 
	 * There is one backup file by default.
	 *
	 * @var integer 
	 */
	protected $maxBackupIndex = 1;
	
	/**
	 * The <var>compress</var> parameter determindes the compression with zlib. 
	 * If set to true, the rollover files are compressed and saved with the .gz extension.
	 * @var boolean
	 */
	protected $compress = false;

	/**
	 * Set to true in the constructor if PHP >= 5.3.0. In that case clearstatcache
	 * supports conditional clearing of statistics.
	 * @var boolean
	 * @see http://php.net/manual/en/function.clearstatcache.php
	 */
	private $clearConditional = false;
	
	/**
	 * Get the maximum size that the output file is allowed to reach
	 * before being rolled over to backup files.
	 * @return integer
	 */
	public function getMaximumFileSize() {
		return $this->maxFileSize;
	}

	public function __construct($name = '') {
		parent::__construct($name);
		if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
			$this->clearConditional = true;
		}
	}
	
	/**
	 * Implements the usual roll over behaviour.
	 *
	 * If MaxBackupIndex is positive, then files File.1, ..., File.MaxBackupIndex -1 are renamed to File.2, ..., File.MaxBackupIndex. 
	 * Moreover, File is renamed File.1 and closed. A new File is created to receive further log output.
	 * 
	 * If MaxBackupIndex is equal to zero, then the File is truncated with no backup files created.
	 * 
	 * Rollover must be called while the file is locked so that it is safe for concurrent access. 
	 * 
	 * @throws LoggerException If any part of the rollover procedure fails.
	 */
	private function rollOver() {
		// If maxBackups <= 0, then there is no file renaming to be done.
		if($this->maxBackupIndex > 0) {
			// Delete the oldest file, to keep Windows happy.
			$file = $this->file . '.' . $this->maxBackupIndex;
			
			if (file_exists($file) && !unlink($file)) {
				throw new LoggerException("Unable to delete oldest backup file from [$file].");
			}

			// Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
			$this->renameArchievedLogs($this->file);
	
			// Backup the active file
			$this->moveToBackup($this->file);
		}
		
		// Truncate the active file
		ftruncate($this->fp, 0);
		rewind($this->fp);
	}
	
	private function moveToBackup($source) {
		if ($this->compress) {
			$target = $source . '.1.gz';
			$this->compressFile($source, $target);
		} else {
			$target = $source . '.1';
			copy($source, $target);
		}
	}
	
	private function compressFile($source, $target) {
		$target = 'compress.zlib://' . $target;
		
		$fin = fopen($source, 'rb');
		if ($fin === false) {
			throw new LoggerException("Unable to open file for reading: [$source].");
		}
		
		$fout = fopen($target, 'wb');
		if ($fout === false) {
			throw new LoggerException("Unable to open file for writing: [$target].");
		}
	
		while (!feof($fin)) {
			$chunk = fread($fin, self::COMPRESS_CHUNK_SIZE);
			if (false === fwrite($fout, $chunk)) {
				throw new LoggerException("Failed writing to compressed file.");
			}
		}
	
		fclose($fin);
		fclose($fout);
	}
	
	private function renameArchievedLogs($fileName) {
		for($i = $this->maxBackupIndex - 1; $i >= 1; $i--) {
			
			$source = $fileName . "." . $i;
			if ($this->compress) {
				$source .= '.gz';
			}
			
			if(file_exists($source)) {
				$target = $fileName . '.' . ($i + 1);
				if ($this->compress) {
					$target .= '.gz';
				}				
				
				rename($source, $target);
			}
		}
	}
	
	/**
	 * Writes a string to the target file. Opens file if not already open.
	 * @param string $string Data to write.
	 */
	protected function write($string) {
		// Lazy file open
		if(!isset($this->fp)) {
			if ($this->openFile() === false) {
				return; // Do not write if file open failed.
			}
		}
		
		// Lock the file while writing and possible rolling over
		if(flock($this->fp, LOCK_EX)) {
			
			// Write to locked file
			if(fwrite($this->fp, $string) === false) {
				$this->warn("Failed writing to file. Closing appender.");
				$this->closed = true;
			}
			
			// Stats cache must be cleared, otherwise filesize() returns cached results
			// If supported (PHP 5.3+), clear only the state cache for the target file
			if ($this->clearConditional) {
				clearstatcache(true, $this->file);
			} else {
				clearstatcache();
			}
			
			// Rollover if needed
			if (filesize($this->file) > $this->maxFileSize) {
				try {
					$this->rollOver();
				} catch (LoggerException $ex) {
					$this->warn("Rollover failed: " . $ex->getMessage() . " Closing appender.");
					$this->closed = true;
				}
			}
			
			flock($this->fp, LOCK_UN);
		} else {
			$this->warn("Failed locking file for writing. Closing appender.");
			$this->closed = true;
		}
	}
	
	public function activateOptions() {
		parent::activateOptions();
		
		if ($this->compress && !extension_loaded('zlib')) {
			$this->warn("The 'zlib' extension is required for file compression. Disabling compression.");
			$this->compression = false;
		}
	}
	
	/**
	 * Set the 'maxBackupIndex' parameter.
	 * @param integer $maxBackupIndex
	 */
	public function setMaxBackupIndex($maxBackupIndex) {
		$this->setPositiveInteger('maxBackupIndex', $maxBackupIndex);
	}
	
	/**
	 * Returns the 'maxBackupIndex' parameter.
	 * @return integer
	 */
	public function getMaxBackupIndex() {
		return $this->maxBackupIndex;
	}
	
	/**
	 * Set the 'maxFileSize' parameter.
	 * @param mixed $maxFileSize
	 */
	public function setMaxFileSize($maxFileSize) {
		$this->setFileSize('maxFileSize', $maxFileSize);
	}
	
	/**
	 * Returns the 'maxFileSize' parameter.
	 * @return integer
	 */
	public function getMaxFileSize() {
		return $this->maxFileSize;
	}
	
	/**
	 * Set the 'maxFileSize' parameter (kept for backward compatibility).
	 * @param mixed $maxFileSize
	 * @deprecated Use setMaxFileSize() instead.
	 */
	public function setMaximumFileSize($maxFileSize) {
		$this->warn("The 'maximumFileSize' parameter is deprecated. Use 'maxFileSize' instead.");
		return $this->setMaxFileSize($maxFileSize);
	}
	
	/**
	 * Sets the 'compress' parameter.
	 * @param boolean $compress
	 */
	public function setCompress($compress) {
		$this->setBoolean('compress', $compress);
	}
	
	/**
	 * Returns the 'compress' parameter.
	 * @param boolean 
	 */
	public function getCompress() {
		return $this->compress;
	}
}
api/log4php/main/php/appenders/LoggerAppenderMailEvent.php0000644000004100000410000001212413466017021024144 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * LoggerAppenderMailEvent appends individual log events via email.
 * 
 * This appender is similar to LoggerAppenderMail, except that it sends each 
 * each log event in an individual email message at the time when it occurs.
 * 
 * This appender uses a layout.
 * 
 * ## Configurable parameters: ##
 * 
 * - **to** - Email address(es) to which the log will be sent. Multiple email
 *     addresses may be specified by separating them with a comma.
 * - **from** - Email address which will be used in the From field.
 * - **subject** - Subject of the email message.
 * - **smtpHost** - Used to override the SMTP server. Only works on Windows.
 * - **port** - Used to override the default SMTP server port. Only works on 
 *     Windows.
 *
 * @version $Revision: 1343601 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/mail-event.html Appender documentation
 */
class LoggerAppenderMailEvent extends LoggerAppender {

	/** 
	 * Email address to put in From field of the email.
	 * @var string
	 */
	protected $from;

	/** 
	 * Mail server port (widnows only).
	 * @var integer 
	 */
	protected $port = 25;

	/** 
	 * Mail server hostname (windows only).
	 * @var string   
	 */
	protected $smtpHost;

	/** 
	 * The subject of the email.
	 * @var string
	 */
	protected $subject = 'Log4php Report';

	/**
	 * One or more comma separated email addresses to which to send the email. 
	 * @var string
	 */
	protected $to = null;
	
	/** 
	 * Indiciates whether this appender should run in dry mode.
	 * @deprecated
	 * @var boolean 
	 */
	protected $dry = false;
	
	public function activateOptions() {
		if (empty($this->to)) {
			$this->warn("Required parameter 'to' not set. Closing appender.");
			$this->close = true;
			return;
		}
		
		$sendmail_from = ini_get('sendmail_from');
		if (empty($this->from) and empty($sendmail_from)) {
			$this->warn("Required parameter 'from' not set. Closing appender.");
			$this->close = true;
			return;
		}
		
		$this->closed = false;
	}

	public function append(LoggerLoggingEvent $event) {
		$smtpHost = $this->smtpHost;
		$prevSmtpHost = ini_get('SMTP');
		if(!empty($smtpHost)) {
			ini_set('SMTP', $smtpHost);
		}
	
		$smtpPort = $this->port;
		$prevSmtpPort= ini_get('smtp_port');
		if($smtpPort > 0 and $smtpPort < 65535) {
			ini_set('smtp_port', $smtpPort);
		}
	
		// On unix only sendmail_path, which is PHP_INI_SYSTEM i.e. not changeable here, is used.
	
		$addHeader = empty($this->from) ? '' : "From: {$this->from}\r\n";
	
		if(!$this->dry) {
			$result = mail($this->to, $this->subject, $this->layout->getHeader() . $this->layout->format($event) . $this->layout->getFooter($event), $addHeader);
		} else {
			echo "DRY MODE OF MAIL APP.: Send mail to: ".$this->to." with additional headers '".trim($addHeader)."' and content: ".$this->layout->format($event);
		}
			
		ini_set('SMTP', $prevSmtpHost);
		ini_set('smtp_port', $prevSmtpPort);
	}
	
	/** Sets the 'from' parameter. */
	public function setFrom($from) {
		$this->setString('from', $from);
	}
	
	/** Returns the 'from' parameter. */
	public function getFrom() {
		return $this->from;
	}
	
	/** Sets the 'port' parameter. */
	public function setPort($port) {
		$this->setPositiveInteger('port', $port);
	}
	
	/** Returns the 'port' parameter. */
	public function getPort() {
		return $this->port;
	}
	
	/** Sets the 'smtpHost' parameter. */
	public function setSmtpHost($smtpHost) {
		$this->setString('smtpHost', $smtpHost);
	}
	
	/** Returns the 'smtpHost' parameter. */
	public function getSmtpHost() {
		return $this->smtpHost;
	}
	
	/** Sets the 'subject' parameter. */
	public function setSubject($subject) {
		$this->setString('subject',  $subject);
	}
	
	/** Returns the 'subject' parameter. */
	public function getSubject() {
		return $this->subject;
	}
	
	/** Sets the 'to' parameter. */
	public function setTo($to) {
		$this->setString('to',  $to);
	}
	
	/** Returns the 'to' parameter. */
	public function getTo() {
		return $this->to;
	}

	/** Enables or disables dry mode. */
	public function setDry($dry) {
		$this->setBoolean('dry', $dry);
	}
}
api/log4php/main/php/appenders/LoggerAppenderPhp.php0000644000004100000410000000365513466017021023020 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * LoggerAppenderPhp logs events by creating a PHP user-level message using 
 * the PHP's trigger_error()function.
 *
 * This appender has no configurable parameters.
 *
 * Levels are mapped as follows:
 * 
 * - <b>level < WARN</b> mapped to E_USER_NOTICE
 * - <b>WARN <= level < ERROR</b> mapped to E_USER_WARNING
 * - <b>level >= ERROR</b> mapped to E_USER_ERROR  
 *
 * @version $Revision: 1337820 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/php.html Appender documentation
 */ 
class LoggerAppenderPhp extends LoggerAppender {

	public function append(LoggerLoggingEvent $event) {
		$level = $event->getLevel();
		if($level->isGreaterOrEqual(LoggerLevel::getLevelError())) {
			trigger_error($this->layout->format($event), E_USER_ERROR);
		} else if ($level->isGreaterOrEqual(LoggerLevel::getLevelWarn())) {
			trigger_error($this->layout->format($event), E_USER_WARNING);
		} else {
			trigger_error($this->layout->format($event), E_USER_NOTICE);
		}
	}
}
api/log4php/main/php/appenders/LoggerAppenderConsole.php0000644000004100000410000000620313466017021023663 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * LoggerAppenderConsole appends log events either to the standard output 
 * stream (php://stdout) or the standard error stream (php://stderr).
 * 
 * **Note**: Use this Appender with command-line php scripts. On web scripts 
 * this appender has no effects.
 *
 * This appender uses a layout.
 *
 * ## Configurable parameters: ##
 * 
 * - **target** - the target stream: "stdout" or "stderr"
 * 
 * @version $Revision: 1343601 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/console.html Appender documentation
 */
 class LoggerAppenderConsole extends LoggerAppender {

	/** The standard otuput stream.  */
	const STDOUT = 'php://stdout';
	
	/** The standard error stream.*/
	const STDERR = 'php://stderr';

	/** The 'target' parameter. */
	protected $target = self::STDOUT;
	
	/**
	 * Stream resource for the target stream.
	 * @var resource
	 */
	protected $fp = null;

	public function activateOptions() {
		$this->fp = fopen($this->target, 'w');
		if(is_resource($this->fp) && $this->layout !== null) {
			fwrite($this->fp, $this->layout->getHeader());
		}
		$this->closed = (bool)is_resource($this->fp) === false;
	}
	
	
	public function close() {
		if($this->closed != true) {
			if (is_resource($this->fp) && $this->layout !== null) {
				fwrite($this->fp, $this->layout->getFooter());
				fclose($this->fp);
			}
			$this->closed = true;
		}
	}

	public function append(LoggerLoggingEvent $event) {
		if (is_resource($this->fp) && $this->layout !== null) {
			fwrite($this->fp, $this->layout->format($event));
		}
	}
	
	/**
	 * Sets the 'target' parameter.
	 * @param string $target
	 */
	public function setTarget($target) {
		$value = trim($target);
		if ($value == self::STDOUT || strtoupper($value) == 'STDOUT') {
			$this->target = self::STDOUT;
		} elseif ($value == self::STDERR || strtoupper($value) == 'STDERR') {
			$this->target = self::STDERR;
		} else {
			$target = var_export($target);
			$this->warn("Invalid value given for 'target' property: [$target]. Property not set.");
		}
	}
	
	/**
	 * Returns the value of the 'target' parameter.
	 * @return string
	 */
	public function getTarget() {
		return $this->target;
	}
}
api/log4php/main/php/appenders/LoggerAppenderDailyFile.php0000644000004100000410000001023613466017021024124 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * An Appender that automatically creates a new logfile each day.
 *
 * The file is rolled over once a day. That means, for each day a new file 
 * is created. A formatted version of the date pattern is used as to create 
 * the file name using the {@link PHP_MANUAL#sprintf} function.
 *
 * This appender uses a layout.
 * 
 * ##Configurable parameters:##
 * 
 * - **datePattern** - Format for the date in the file path, follows formatting
 *     rules used by the PHP date() function. Default value: "Ymd".
 * - **file** - Path to the target file. Should contain a %s which gets 
 *     substituted by the date.
 * - **append** - If set to true, the appender will append to the file, 
 *     otherwise the file contents will be overwritten. Defaults to true.
 * 
 * @version $Revision: 1382274 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/daily-file.html Appender documentation
 */
class LoggerAppenderDailyFile extends LoggerAppenderFile {

	/**
	 * The 'datePattern' parameter.
	 * Determines how date will be formatted in file name.
	 * @var string
	 */
	protected $datePattern = "Ymd";
	
	/**
	 * Current date which was used when opening a file.
	 * Used to determine if a rollover is needed when the date changes.
	 * @var string
	 */
	protected $currentDate;

	/** Additional validation for the date pattern. */
	public function activateOptions() {
		parent::activateOptions();
	
		if (empty($this->datePattern)) {
			$this->warn("Required parameter 'datePattern' not set. Closing appender.");
			$this->closed = true;
			return;
		}
	}

	/**
	 * Appends a logging event.
	 * 
	 * If the target file changes because of passage of time (e.g. at midnight) 
	 * the current file is closed. A new file, with the new date, will be 
	 * opened by the write() method. 
	 */
	public function append(LoggerLoggingEvent $event) {
		$eventDate = $this->getDate($event->getTimestamp());
		
		// Initial setting of current date
		if (!isset($this->currentDate)) {
			$this->currentDate = $eventDate;
		} 
		
		// Check if rollover is needed
		else if ($this->currentDate !== $eventDate) {
			$this->currentDate = $eventDate;
			
			// Close the file if it's open.
			// Note: $this->close() is not called here because it would set
			//       $this->closed to true and the appender would not recieve
			//       any more logging requests
			if (is_resource($this->fp)) {
				$this->write($this->layout->getFooter());
				fclose($this->fp);
			}
			$this->fp = null;
		}
	
		parent::append($event);
	}
	
	/** Renders the date using the configured <var>datePattern<var>. */
	protected function getDate($timestamp = null) {
		return date($this->datePattern, $timestamp);
	}
	
	/**
	 * Determines target file. Replaces %s in file path with a date. 
	 */
	protected function getTargetFile() {
		return str_replace('%s', $this->currentDate, $this->file);
	}
	
	/**
	 * Sets the 'datePattern' parameter.
	 * @param string $datePattern
	 */
	public function setDatePattern($datePattern) {
		$this->setString('datePattern', $datePattern);
	}
	
	/**
	 * Returns the 'datePattern' parameter.
	 * @return string
	 */
	public function getDatePattern() {
		return $this->datePattern;
	}
}
api/log4php/main/php/appenders/LoggerAppenderSocket.php0000644000004100000410000000717413466017021023521 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * LoggerAppenderSocket appends to a network socket.
 *
 * ## Configurable parameters: ##
 * 
 * - **remoteHost** - Target remote host.
 * - **port** - Target port (optional, defaults to 4446).
 * - **timeout** - Connection timeout in seconds (optional, defaults to 
 *     'default_socket_timeout' from php.ini)
 * 
 * The socket will by default be opened in blocking mode.
 * 
 * @version $Revision: 1337820 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/socket.html Appender documentation
 */ 
class LoggerAppenderSocket extends LoggerAppender {
	
	/** 
	 * Target host.
	 * @see http://php.net/manual/en/function.fsockopen.php 
	 */
	protected $remoteHost;
	
	/** Target port */
	protected $port = 4446;
	
	/** Connection timeout in ms. */
	protected $timeout;
	
	// ******************************************
	// *** Appender methods                   ***
	// ******************************************
	
	/** Override the default layout to use serialized. */
	public function getDefaultLayout() {
		return new LoggerLayoutSerialized();
	}
	
	public function activateOptions() {
		if (empty($this->remoteHost)) {
			$this->warn("Required parameter [remoteHost] not set. Closing appender.");
			$this->closed = true;
			return;
		}
	
		if (empty($this->timeout)) {
			$this->timeout = ini_get("default_socket_timeout");
		}
	
		$this->closed = false;
	}
	
	public function append(LoggerLoggingEvent $event) {
		$socket = fsockopen($this->remoteHost, $this->port, $errno, $errstr, $this->timeout);
		if ($socket === false) {
			$this->warn("Could not open socket to {$this->remoteHost}:{$this->port}. Closing appender.");
			$this->closed = true;
			return;
		}
	
		if (false === fwrite($socket, $this->layout->format($event))) {
			$this->warn("Error writing to socket. Closing appender.");
			$this->closed = true;
		}
		fclose($socket);
	}
	
	// ******************************************
	// *** Accessor methods                   ***
	// ******************************************
	
	/** Sets the target host. */
	public function setRemoteHost($hostname) {
		$this->setString('remoteHost', $hostname);
	}
	
	/** Sets the target port */
	public function setPort($port) {
		$this->setPositiveInteger('port', $port);
	}
	 
	/** Sets the timeout. */
	public function setTimeout($timeout) {
		$this->setPositiveInteger('timeout', $timeout);
	}
	
	/** Returns the target host. */
	public function getRemoteHost() {
		return $this->getRemoteHost();
	}
	
	/** Returns the target port. */
	public function getPort() {
		return $this->port;
	}
	
	/** Returns the timeout */
	public function getTimeout() {
		return $this->timeout;
	}
}
api/log4php/main/php/appenders/LoggerAppenderEcho.php0000644000004100000410000000510413466017021023136 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * LoggerAppenderEcho uses the PHP echo() function to output events. 
 * 
 * This appender uses a layout.
 * 
 * ## Configurable parameters: ##
 * 
 * - **htmlLineBreaks** - If set to true, a <br /> element will be inserted 
 *     before each line break in the logged message. Default is false.
 *
 * @version $Revision: 1337820 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/echo.html Appender documentation
 */
class LoggerAppenderEcho extends LoggerAppender {
	/** 
	 * Used to mark first append. Set to false after first append.
	 * @var boolean 
	 */
	protected $firstAppend = true;
	
	/** 
	 * If set to true, a <br /> element will be inserted before each line
	 * break in the logged message. Default value is false. @var boolean 
	 */
	protected $htmlLineBreaks = false;
	
	public function close() {
		if($this->closed != true) {
			if(!$this->firstAppend) {
				echo $this->layout->getFooter();
			}
		}
		$this->closed = true;
	}

	public function append(LoggerLoggingEvent $event) {
		if($this->layout !== null) {
			if($this->firstAppend) {
				echo $this->layout->getHeader();
				$this->firstAppend = false;
			}
			$text = $this->layout->format($event);
			
			if ($this->htmlLineBreaks) {
				$text = nl2br($text);
			}
			echo $text;
		} 
	}
	
	/**
	 * Sets the 'htmlLineBreaks' parameter.
	 * @param boolean $value
	 */
	public function setHtmlLineBreaks($value) {
		$this->setBoolean('htmlLineBreaks', $value);
	}
	
	/**
	 * Returns the 'htmlLineBreaks' parameter.
	 * @returns boolean
	 */
	public function getHtmlLineBreaks() {
		return $this->htmlLineBreaks;
	}
}

api/log4php/main/php/appenders/LoggerAppenderSyslog.php0000644000004100000410000001732513466017021023550 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Log events to a system log using the PHP syslog() function.
 *
 * This appenders requires a layout.
 *
 * ## Configurable parameters: ##
 * 
 * - **ident** - The ident of the syslog message.
 * - **priority** - The priority for the syslog message (used when overriding 
 *     priority).
 * - **facility** - The facility for the syslog message
 * - **overridePriority** - If set to true, the message priority will always 
 *     use the value defined in {@link $priority}, otherwise the priority will
 *     be determined by the message's log level.  
 * - **option** - The option value for the syslog message. 
 *
 * Recognised syslog options are:
 * 
 * - CONS 	 - if there is an error while sending data to the system logger, write directly to the system console
 * - NDELAY - open the connection to the logger immediately
 * - ODELAY - delay opening the connection until the first message is logged (default)
 * - PERROR - print log message also to standard error
 * - PID    - include PID with each message
 * 
 * Multiple options can be set by delimiting them with a pipe character, 
 * e.g.: "CONS|PID|PERROR".
 * 
 * Recognised syslog priorities are:
 * 
 * - EMERG
 * - ALERT
 * - CRIT
 * - ERR
 * - WARNING
 * - NOTICE
 * - INFO
 * - DEBUG
 *
 * Levels are mapped as follows:
 * 
 * - <b>FATAL</b> to LOG_ALERT
 * - <b>ERROR</b> to LOG_ERR 
 * - <b>WARN</b> to LOG_WARNING
 * - <b>INFO</b> to LOG_INFO
 * - <b>DEBUG</b> to LOG_DEBUG
 * - <b>TRACE</b> to LOG_DEBUG
 *
 * @version $Revision: 1337820 $
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/syslog.html Appender documentation
 */ 
class LoggerAppenderSyslog extends LoggerAppender {
	
	/**
	 * The ident string is added to each message. Typically the name of your application.
	 * 
	 * @var string 
	 */
	protected $ident = "Apache log4php";

	/**
	 * The syslog priority to use when overriding priority. This setting is 
	 * required if {@link overridePriority} is set to true. 
	 * 
	 * @var string 
	 */
	protected $priority;
	
	/**
	 * The option used when opening the syslog connection.
	 * 
	 * @var string
	 */
	protected $option = 'PID|CONS';
	
	/**
	 * The facility value indicates the source of the message.
	 *
	 * @var string
	 */
	protected $facility = 'USER';
	
	/**
	 * If set to true, the message priority will always use the value defined 
	 * in {@link $priority}, otherwise the priority will be determined by the 
	 * message's log level.
	 *
	 * @var string
	 */
	protected $overridePriority = false;

	/**
	 * Holds the int value of the {@link $priority}.
	 * @var int
	 */
	private $intPriority;
	
	/**
	 * Holds the int value of the {@link $facility}.
	 * @var int
	 */
	private $intFacility;
	
	/**
	 * Holds the int value of the {@link $option}.
	 * @var int
	 */
	private $intOption;

	/**
	 * Sets the {@link $ident}.
	 *
	 * @param string $ident
	 */
	public function setIdent($ident) {
		$this->ident = $ident; 
	}
	
	/**
	 * Sets the {@link $priority}.
	 *
	 * @param string $priority
	 */
	public function setPriority($priority) {
		$this->priority = $priority;
	}
	
	/**
	 * Sets the {@link $facility}.
	 *
	 * @param string $facility
	 */
	public function setFacility($facility) {
		$this->facility = $facility;
	} 
	
	/**
	 * Sets the {@link $overridePriority}.
	 *
	 * @param string $overridePriority
	 */
	public function setOverridePriority($overridePriority) {
		$this->overridePriority = $overridePriority;
	} 
	
	/**
	* Sets the 'option' parameter.
	*
	* @param string $option
	*/
	public function setOption($option) {
		$this->option = $option;
	}
	
	/**
	* Returns the 'ident' parameter.
	*
	* @return string $ident
	*/
	public function getIdent() {
		return $this->ident;
	}
	
	/**
	 * Returns the 'priority' parameter.
	 *
	 * @return string
	 */
	public function getPriority() {
		return $this->priority;
	}
	
	/**
	 * Returns the 'facility' parameter.
	 *
	 * @return string
	 */
	public function getFacility() {
		return $this->facility;
	}
	
	/**
	 * Returns the 'overridePriority' parameter.
	 *
	 * @return string
	 */
	public function getOverridePriority() {
		return $this->overridePriority;
	}
	
	/**
	 * Returns the 'option' parameter.
	 *
	 * @return string
	 */
	public function getOption() {
		return $this->option;
	}
	
	
	public function activateOptions() {
		$this->intPriority = $this->parsePriority();
		$this->intOption   = $this->parseOption();
		$this->intFacility = $this->parseFacility();
		
		$this->closed = false;
	}
	
	public function close() {
		if($this->closed != true) {
			closelog();
			$this->closed = true;
		}
	}

	/** 
	 * Appends the event to syslog.
	 * 
	 * Log is opened and closed each time because if it is not closed, it
	 * can cause the Apache httpd server to log to whatever ident/facility 
	 * was used in openlog().
	 *
	 * @see http://www.php.net/manual/en/function.syslog.php#97843
	 */
	public function append(LoggerLoggingEvent $event) {
		$priority = $this->getSyslogPriority($event->getLevel());
		$message = $this->layout->format($event);
	
		openlog($this->ident, $this->intOption, $this->intFacility);
		syslog($priority, $message);
		closelog();
	}
	
	/** Determines which syslog priority to use based on the given level. */
	private function getSyslogPriority(LoggerLevel $level) {
		if($this->overridePriority) {
			return $this->intPriority;
		}
		return $level->getSyslogEquivalent();
	}
	
	/** Parses a syslog option string and returns the correspodning int value. */
	private function parseOption() {
		$value = 0;
		$options = explode('|', $this->option);
	
		foreach($options as $option) {
			if (!empty($option)) {
				$constant = "LOG_" . trim($option);
				if (defined($constant)) {
					$value |= constant($constant);
				} else {
					trigger_error("log4php: Invalid syslog option provided: $option. Whole option string: {$this->option}.", E_USER_WARNING);
				}
			}
		}
		return $value;
	}
	
	/** Parses the facility string and returns the corresponding int value. */
	private function parseFacility() {
		if (!empty($this->facility)) {   
			$constant = "LOG_" . trim($this->facility);
			if (defined($constant)) {
				return constant($constant);
			} else {
				trigger_error("log4php: Invalid syslog facility provided: {$this->facility}.", E_USER_WARNING);
			}
		}
	}

	/** Parses the priority string and returns the corresponding int value. */
	private function parsePriority() {
		if (!empty($this->priority)) {
			$constant = "LOG_" . trim($this->priority);
			if (defined($constant)) {
				return constant($constant);
			} else {
				trigger_error("log4php: Invalid syslog priority provided: {$this->priority}.", E_USER_WARNING);
			}
		}	
	}
}
api/log4php/main/php/LoggerRoot.php0000644000004100000410000000374013466017021017547 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * The root logger.
 *
 * @version $Revision: 1343190 $
 * @package log4php
 * @see Logger
 */
class LoggerRoot extends Logger {
	/**
	 * Constructor
	 *
	 * @param integer $level initial log level
	 */
	public function __construct(LoggerLevel $level = null) {
		parent::__construct('root');

		if($level == null) {
			$level = LoggerLevel::getLevelAll();
		}
		$this->setLevel($level);
	} 
	
	/**
	 * @return LoggerLevel the level
	 */
	public function getEffectiveLevel() {
		return $this->getLevel();
	}
	
	/**
	 * Override level setter to prevent setting the root logger's level to 
	 * null. Root logger must always have a level.
	 * 
	 * @param LoggerLevel $level
	 */
	public function setLevel(LoggerLevel $level = null) {
		if (isset($level)) {
			parent::setLevel($level);
		} else {
			trigger_error("log4php: Cannot set LoggerRoot level to null.", E_USER_WARNING);
		}
	}
	
	/**
	 * Override parent setter. Root logger cannot have a parent.
	 * @param Logger $parent
	 */
	public function setParent(Logger $parent) {
		trigger_error("log4php: LoggerRoot cannot have a parent.", E_USER_WARNING);
	}
}
api/log4php/main/php/LoggerConfigurator.php0000644000004100000410000000275513466017021021273 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Interface for logger configurators.
 * 
 * @package log4php
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version $Revision: 1213710 $
 * @since 2.2
 */
interface LoggerConfigurator
{
	/**
	 * Configures log4php based on the given configuration. 
	 * 
	 * All configurators implementations must implement this interface.
	 * 
	 * @param LoggerHierarchy $hierarchy The hierarchy on which to perform 
	 * 		the configuration. 
	 * @param mixed $input Either path to the config file or the 
	 * 		configuration as an array.
	 */
	public function configure(LoggerHierarchy $hierarchy, $input = null);
}api/log4php/main/php/LoggerFilter.php0000644000004100000410000001056013466017021020047 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Users should extend this class to implement customized logging
 * event filtering. Note that {@link LoggerCategory} and {@link LoggerAppender}, 
 * the parent class of all standard
 * appenders, have built-in filtering rules. It is suggested that you
 * first use and understand the built-in rules before rushing to write
 * your own custom filters.
 * 
 * <p>This abstract class assumes and also imposes that filters be
 * organized in a linear chain. The {@link #decide
 * decide(LoggerLoggingEvent)} method of each filter is called sequentially,
 * in the order of their addition to the chain.
 * 
 * <p>The {@link decide()} method must return one
 * of the integer constants {@link LoggerFilter::DENY}, 
 * {@link LoggerFilter::NEUTRAL} or {@link LoggerFilter::ACCEPT}.
 * 
 * <p>If the value {@link LoggerFilter::DENY} is returned, then the log event is
 * dropped immediately without consulting with the remaining
 * filters. 
 * 
 * <p>If the value {@link LoggerFilter::NEUTRAL} is returned, then the next filter
 * in the chain is consulted. If there are no more filters in the
 * chain, then the log event is logged. Thus, in the presence of no
 * filters, the default behaviour is to log all logging events.
 * 
 * <p>If the value {@link LoggerFilter::ACCEPT} is returned, then the log
 * event is logged without consulting the remaining filters. 
 * 
 * <p>The philosophy of log4php filters is largely inspired from the
 * Linux ipchains. 
 * 
 * @version $Revision: 1213283 $
 * @package log4php
 */
abstract class LoggerFilter extends LoggerConfigurable {

	/**
	 * The log event must be logged immediately without consulting with
	 * the remaining filters, if any, in the chain.	 
	 */
	const ACCEPT = 1;
	
	/**
	 * This filter is neutral with respect to the log event. The
	 * remaining filters, if any, should be consulted for a final decision.
	 */
	const NEUTRAL = 0;
	
	/**
	 * The log event must be dropped immediately without consulting
	 * with the remaining filters, if any, in the chain.
	 */
	const DENY = -1;

	/**
	 * @var LoggerFilter Points to the next {@link LoggerFilter} in the filter chain.
	 */
	protected $next;

	/**
	 * Usually filters options become active when set. We provide a
	 * default do-nothing implementation for convenience.
	*/
	public function activateOptions() {
	}

	/**
	 * Decide what to do.
	 * <p>If the decision is {@link LoggerFilter::DENY}, then the event will be
	 * dropped. If the decision is {@link LoggerFilter::NEUTRAL}, then the next
	 * filter, if any, will be invoked. If the decision is {@link LoggerFilter::ACCEPT} then
	 * the event will be logged without consulting with other filters in
	 * the chain.
	 *
	 * @param LoggerLoggingEvent $event The {@link LoggerLoggingEvent} to decide upon.
	 * @return integer {@link LoggerFilter::NEUTRAL} or {@link LoggerFilter::DENY}|{@link LoggerFilter::ACCEPT}
	 */
	public function decide(LoggerLoggingEvent $event) {
		return self::NEUTRAL;
	}

	/**
	 * Adds a new filter to the filter chain this filter is a part of.
	 * If this filter has already and follow up filter, the param filter
	 * is passed on until it is the last filter in chain.
	 * 
	 * @param $filter - the filter to add to this chain
	 */
	public function addNext($filter) {
		if($this->next !== null) {
			$this->next->addNext($filter);
		} else {
			$this->next = $filter;
		}
	}
	
	/**
	 * Returns the next filter in this chain
	 * @return the next filter
	 */
	public function getNext() {
		return $this->next;
	}

}
api/log4php/main/php/LoggerMDC.php0000644000004100000410000000501113466017021017220 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * The LoggerMDC class provides _mapped diagnostic contexts_.
 * 
 * A Mapped Diagnostic Context, or MDC in short, is an instrument for 
 * distinguishing interleaved log output from different sources. Log output 
 * is typically interleaved when a server handles multiple clients 
 * near-simultaneously.
 * 
 * This class is similar to the {@link LoggerNDC} class except that 
 * it is based on a map instead of a stack.
 * 
 * @version $Revision: 1343630 $
 * @since 0.3
 * @package log4php
 */
class LoggerMDC {
	
	/** Holds the context map. */
	private static $map = array();
		
	/**
	 * Stores a context value as identified with the key parameter into the 
	 * context map.
	 *
	 * @param string $key the key
	 * @param string $value the value
	 */
	public static function put($key, $value) {
		self::$map[$key] = $value;
	}
  
	/**
	 * Returns the context value identified by the key parameter.
	 *
	 * @param string $key The key.
	 * @return string The context or an empty string if no context found
	 * 	for given key.
	 */
	public static function get($key) {
		return isset(self::$map[$key]) ? self::$map[$key] : '';
	}

	/**
	 * Returns the contex map as an array.
	 * @return array The MDC context map.
	 */
	public static function getMap() {
		return self::$map;
	}

	/**
	 * Removes the the context identified by the key parameter. 
	 *
	 * Only affects user mappings, not $_ENV or $_SERVER.
	 *
	 * @param string $key The key to be removed.
	 */
	public static function remove($key) {
		unset(self::$map[$key]);
	}
	
	/**
	 * Clears the mapped diagnostic context.
	 */
	public static function clear() {
		self::$map = array();
	}
}
api/log4php/main/php/configurators/0000755000004100000410000000000013466017021017634 5ustar  www-datawww-dataapi/log4php/main/php/configurators/LoggerConfigurationAdapter.php0000644000004100000410000000253613466017021025623 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @package log4php
 */

/**
 * The interface for configurator adapters.
 * 
 * Adapters convert configuration in several formats such as XML, ini and PHP 
 * file to a PHP array. 
 * 
 * @package log4php
 * @subpackage configurators
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version $Revision: 1343601 $
 * @since 2.2
 */
interface LoggerConfigurationAdapter
{
	/** Converts the configuration file to PHP format usable by the configurator. */
	public function convert($input); 

}

api/log4php/main/php/configurators/LoggerConfigurationAdapterXML.php0000644000004100000410000001746313466017021026211 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @package log4php
 */

/**
 * Converts XML configuration files to a PHP array.
 * 
 * @package log4php
 * @subpackage configurators
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version $Revision: 1394956 $
 * @since 2.2
 */
class LoggerConfigurationAdapterXML implements LoggerConfigurationAdapter
{
	/** Path to the XML schema used for validation. */
	const SCHEMA_PATH = '/../xml/log4php.xsd';
	
	private $config = array(
		'appenders' => array(),
		'loggers' => array(),
		'renderers' => array(),
	);
	
	public function convert($url) {
		$xml = $this->loadXML($url);
		
		$this->parseConfiguration($xml);

		// Parse the <root> node
		if (isset($xml->root)) {		
			$this->parseRootLogger($xml->root);
		}
		
		// Process <logger> nodes
		foreach($xml->logger as $logger) {
			$this->parseLogger($logger);
		} 
		
		// Process <appender> nodes
		foreach($xml->appender as $appender) {
			$this->parseAppender($appender);
		}
		
		// Process <renderer> nodes
		foreach($xml->renderer as $rendererNode) {
			$this->parseRenderer($rendererNode);
		}

		// Process <defaultRenderer> node
		foreach($xml->defaultRenderer as $rendererNode) {
			$this->parseDefaultRenderer($rendererNode);
		}

		return $this->config;
	}
	
	/**
	 * Loads and validates the XML.
	 * @param string $url Input XML.
	 */
	private function loadXML($url) {
		if (!file_exists($url)) {
			throw new LoggerException("File [$url] does not exist.");
		}

		libxml_clear_errors();
		$oldValue = libxml_use_internal_errors(true);
		
		// Load XML
		$xml = @simplexml_load_file($url);
		if ($xml === false) {
			
			$errorStr = "";
			foreach(libxml_get_errors() as $error) {
				$errorStr .= $error->message;
			}
			
			throw new LoggerException("Error loading configuration file: " . trim($errorStr));
		}
		
		libxml_clear_errors();
		libxml_use_internal_errors($oldValue);
		
		return $xml;
	}
	
	/**
	 * Parses the <configuration> node.
	 */
	private function parseConfiguration(SimpleXMLElement $xml) {
		$attributes = $xml->attributes();
		if (isset($attributes['threshold'])) {
			$this->config['threshold'] = (string) $attributes['threshold'];
		}
	}
	
	/** Parses an <appender> node. */
	private function parseAppender(SimpleXMLElement $node) {
		$name = $this->getAttributeValue($node, 'name');
		if (empty($name)) {
			$this->warn("An <appender> node is missing the required 'name' attribute. Skipping appender definition.");
			return;
		}
		
		$appender = array();
		$appender['class'] = $this->getAttributeValue($node, 'class');
		
		if (isset($node['threshold'])) {
			$appender['threshold'] = $this->getAttributeValue($node, 'threshold');
		}
		
		if (isset($node->layout)) {
			$appender['layout']= $this->parseLayout($node->layout, $name);
		}
		
		if (count($node->param) > 0) {
			$appender['params'] = $this->parseParameters($node);
		}
		
		foreach($node->filter as $filterNode) {
			$appender['filters'][] = $this->parseFilter($filterNode);
		}
		
		$this->config['appenders'][$name] = $appender;
	}
	
	/** Parses a <layout> node. */
	private function parseLayout(SimpleXMLElement $node, $appenderName) {
		$layout = array();
		$layout['class'] = $this->getAttributeValue($node, 'class');
		
		if (count($node->param) > 0) {
			$layout['params'] = $this->parseParameters($node);
		}
		
		return $layout;
	}

	/** Parses any <param> child nodes returning them in an array. */
	private function parseParameters($paramsNode) {
		$params = array();

		foreach($paramsNode->param as $paramNode) {
			if (empty($paramNode['name'])) {
				$this->warn("A <param> node is missing the required 'name' attribute. Skipping parameter.");
				continue;
			}
			
			$name = $this->getAttributeValue($paramNode, 'name');
			$value = $this->getAttributeValue($paramNode, 'value');
			
			$params[$name] = $value;
		}

		return $params;
	}
	
	/** Parses a <root> node. */
	private function parseRootLogger(SimpleXMLElement $node) {
		$logger = array();
		
		if (isset($node->level)) {
			$logger['level'] = $this->getAttributeValue($node->level, 'value');
		}
		
		$logger['appenders'] = $this->parseAppenderReferences($node);
		
		$this->config['rootLogger'] = $logger;
	}
	
	/** Parses a <logger> node. */
	private function parseLogger(SimpleXMLElement $node) {
		$logger = array();
		
		$name = $this->getAttributeValue($node, 'name');
		if (empty($name)) {
			$this->warn("A <logger> node is missing the required 'name' attribute. Skipping logger definition.");
			return;
		}
		
		if (isset($node->level)) {
			$logger['level'] = $this->getAttributeValue($node->level, 'value');
		}
		
		if (isset($node['additivity'])) {
			$logger['additivity'] = $this->getAttributeValue($node, 'additivity');
		}
		
		$logger['appenders'] = $this->parseAppenderReferences($node);

		// Check for duplicate loggers
		if (isset($this->config['loggers'][$name])) {
			$this->warn("Duplicate logger definition [$name]. Overwriting.");
		}
		
		$this->config['loggers'][$name] = $logger;
	}
	
	/** 
	 * Parses a <logger> node for appender references and returns them in an array.
	 * 
	 * Previous versions supported appender-ref, as well as appender_ref so both
	 * are parsed for backward compatibility.
	 */
	private function parseAppenderReferences(SimpleXMLElement $node) {
		$refs = array();
		foreach($node->appender_ref as $ref) {
			$refs[] = $this->getAttributeValue($ref, 'ref');
		}
		
		foreach($node->{'appender-ref'} as $ref) {
			$refs[] = $this->getAttributeValue($ref, 'ref');
		}

		return $refs;
	}
	
	/** Parses a <filter> node. */
	private function parseFilter($filterNode) {
		$filter = array();
		$filter['class'] = $this->getAttributeValue($filterNode, 'class');
		
		if (count($filterNode->param) > 0) {
			$filter['params'] = $this->parseParameters($filterNode);
		}
		
		return $filter;
	}
	
	/** Parses a <renderer> node. */
	private function parseRenderer(SimpleXMLElement $node) {
		$renderedClass = $this->getAttributeValue($node, 'renderedClass');
		$renderingClass = $this->getAttributeValue($node, 'renderingClass');
		
		$this->config['renderers'][] = compact('renderedClass', 'renderingClass');
	}
	
	/** Parses a <defaultRenderer> node. */
	private function parseDefaultRenderer(SimpleXMLElement $node) {
		$renderingClass = $this->getAttributeValue($node, 'renderingClass');
		
		// Warn on duplicates
		if(isset($this->config['defaultRenderer'])) {
			$this->warn("Duplicate <defaultRenderer> node. Overwriting.");
		}
		
		$this->config['defaultRenderer'] = $renderingClass; 
	}
	
	// ******************************************
	// ** Helper methods                       **
	// ******************************************
	
	private function getAttributeValue(SimpleXMLElement $node, $name) {
		return isset($node[$name]) ? (string) $node[$name] : null;
	}
	
	private function warn($message) {
		trigger_error("log4php: " . $message, E_USER_WARNING);
	}
}

api/log4php/main/php/configurators/LoggerConfigurationAdapterINI.php0000644000004100000410000002072313466017021026161 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @package log4php
 */

/**
 * Converts ini configuration files to a PHP array.
 * 
 * These used to be called "properties" files (inherited from log4j), and that 
 * file extension is still supported. 
 *
 * @package log4php
 * @subpackage configurators
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version $Revision: 1343601 $
 * @since 2.2
 */
class LoggerConfigurationAdapterINI implements LoggerConfigurationAdapter {
	
	/** Name to assign to the root logger. */
	const ROOT_LOGGER_NAME = "root";

	/** Prefix used for defining logger additivity. */
	const ADDITIVITY_PREFIX = "log4php.additivity.";
	
	/** Prefix used for defining logger threshold. */
	const THRESHOLD_PREFIX = "log4php.threshold";
	
	/** Prefix used for defining the root logger. */
	const ROOT_LOGGER_PREFIX = "log4php.rootLogger";
	
	/** Prefix used for defining a logger. */
	const LOGGER_PREFIX = "log4php.logger.";
	
	/** Prefix used for defining an appender. */
	const APPENDER_PREFIX = "log4php.appender.";
	
	/** Prefix used for defining a renderer. */
	const RENDERER_PREFIX = "log4php.renderer.";
	
	/** Holds the configuration. */
	private $config = array();
	
	/**
	 * Loads and parses the INI configuration file.
	 * 
	 * @param string $url Path to the config file.
	 * @throws LoggerException
	 */
	private function load($url) {
		if (!file_exists($url)) {
			throw new LoggerException("File [$url] does not exist.");
		}
		
		$properties = @parse_ini_file($url, true);
		if ($properties === false) {
			$error = error_get_last();
			throw new LoggerException("Error parsing configuration file: {$error['message']}");
		}
		
		return $properties;
	}
	
	/**
	* Converts the provided INI configuration file to a PHP array config.
	*
	* @param string $path Path to the config file.
	* @throws LoggerException If the file cannot be loaded or parsed.
	*/
	public function convert($path) {
		// Load the configuration
		$properties = $this->load($path);
		
		// Parse threshold
		if (isset($properties[self::THRESHOLD_PREFIX])) {
			$this->config['threshold'] = $properties[self::THRESHOLD_PREFIX]; 
		}
		
		// Parse root logger
		if (isset($properties[self::ROOT_LOGGER_PREFIX])) {
			$this->parseLogger($properties[self::ROOT_LOGGER_PREFIX], self::ROOT_LOGGER_NAME);
		}
		
		$appenders = array();
		
		foreach($properties as $key => $value) {
			// Parse loggers
			if ($this->beginsWith($key, self::LOGGER_PREFIX)) {
				$name = substr($key, strlen(self::LOGGER_PREFIX));
				$this->parseLogger($value, $name);
			}
			
			// Parse additivity
			if ($this->beginsWith($key, self::ADDITIVITY_PREFIX)) {
				$name = substr($key, strlen(self::ADDITIVITY_PREFIX));
				$this->config['loggers'][$name]['additivity'] = $value;
			}
			
			// Parse appenders
			else if ($this->beginsWith($key, self::APPENDER_PREFIX)) {
				$this->parseAppender($key, $value);
			}
			
			// Parse renderers
			else if ($this->beginsWith($key, self::RENDERER_PREFIX)) {
				$this->parseRenderer($key, $value);
			}
		}
		
		return $this->config;
	}
	
	
	/**
	 * Parses a logger definition.
	 * 
	 * Loggers are defined in the following manner:
	 * <pre>
	 * log4php.logger.<name> = [<level>], [<appender-ref>, <appender-ref>, ...] 
	 * </pre>
	 * 
	 * @param string $value The configuration value (level and appender-refs).
	 * @param string $name Logger name. 
	 */
	private function parseLogger($value, $name) {
		// Value is divided by commas
		$parts = explode(',', $value);
		if (empty($value) || empty($parts)) {
			return;
		}

		// The first value is the logger level 
		$level = array_shift($parts);
		
		// The remaining values are appender references 
		$appenders = array();
		while($appender = array_shift($parts)) {
			$appender = trim($appender);
			if (!empty($appender)) {
				$appenders[] = trim($appender);
			}
		}

		// Find the target configuration 
		if ($name == self::ROOT_LOGGER_NAME) {
			$this->config['rootLogger']['level'] = trim($level);
			$this->config['rootLogger']['appenders'] = $appenders;
		} else {
			$this->config['loggers'][$name]['level'] = trim($level);
			$this->config['loggers'][$name]['appenders'] = $appenders;
		}
	}
	
	/**
	 * Parses an configuration line pertaining to an appender.
	 * 
	 * Parses the following patterns:
	 * 
	 * Appender class:
	 * <pre>
	 * log4php.appender.<name> = <class>
	 * </pre>
	 * 
	 * Appender parameter:
	 * <pre>
	 * log4php.appender.<name>.<param> = <value>
	 * </pre>
	 * 
 	 * Appender threshold:
	 * <pre>
	 * log4php.appender.<name>.threshold = <level>
	 * </pre>
	 * 
 	 * Appender layout:
	 * <pre>
	 * log4php.appender.<name>.layout = <layoutClass>
	 * </pre>
	 * 
	 * Layout parameter:
	 * <pre>
	 * log4php.appender.<name>.layout.<param> = <value>
	 * </pre> 
	 * 
	 * For example, a full appender config might look like:
	 * <pre>
	 * log4php.appender.myAppender = LoggerAppenderConsole
	 * log4php.appender.myAppender.threshold = info
	 * log4php.appender.myAppender.target = stdout
	 * log4php.appender.myAppender.layout = LoggerLayoutPattern
	 * log4php.appender.myAppender.layout.conversionPattern = "%d %c: %m%n"
	 * </pre>
	 * 
	 * After parsing all these options, the following configuration can be 
	 * found under $this->config['appenders']['myAppender']:
	 * <pre>
	 * array(
	 * 	'class' => LoggerAppenderConsole,
	 * 	'threshold' => info,
	 * 	'params' => array(
	 * 		'target' => 'stdout'
	 * 	),
	 * 	'layout' => array(
	 * 		'class' => 'LoggerAppenderConsole',
	 * 		'params' => array(
	 * 			'conversionPattern' => '%d %c: %m%n'
	 * 		)
	 * 	)
	 * )
	 * </pre>
	 * 
	 * @param string $key
	 * @param string $value
	 */
	private function parseAppender($key, $value) {

		// Remove the appender prefix from key
		$subKey = substr($key, strlen(self::APPENDER_PREFIX));
		
		// Divide the string by dots
		$parts = explode('.', $subKey);
		$count = count($parts);
		
		// The first part is always the appender name
		$name = trim($parts[0]);
		
		// Only one part - this line defines the appender class 
		if ($count == 1) {
			$this->config['appenders'][$name]['class'] = $value;
			return;
		}
		
		// Two parts - either a parameter, a threshold or layout class
		else if ($count == 2) {
			
			if ($parts[1] == 'layout') {
				$this->config['appenders'][$name]['layout']['class'] = $value;
				return;
			} else if ($parts[1] == 'threshold') {
				$this->config['appenders'][$name]['threshold'] = $value;
				return;
			} else {
				$this->config['appenders'][$name]['params'][$parts[1]] = $value;
				return;
			}
		}
		
		// Three parts - this can only be a layout parameter
		else if ($count == 3) {
			if ($parts[1] == 'layout') {
				$this->config['appenders'][$name]['layout']['params'][$parts[2]] = $value;
				return;
			}
		}
		
		trigger_error("log4php: Don't know how to parse the following line: \"$key = $value\". Skipping.");
	}

	/**
	 * Parses a renderer definition.
	 * 
	 * Renderers are defined as:
	 * <pre>
	 * log4php.renderer.<renderedClass> = <renderingClass> 
	 * </pre>
	 * 
	 * @param string $key log4php.renderer.<renderedClass>
	 * @param string $value <renderingClass>
	 */
	private function parseRenderer($key, $value) {
		// Remove the appender prefix from key
		$renderedClass = substr($key, strlen(self::APPENDER_PREFIX));
		$renderingClass = $value;
		
		$this->config['renderers'][] = compact('renderedClass', 'renderingClass');
	}
	
	/** Helper method. Returns true if $str begins with $sub. */
	private function beginsWith($str, $sub) {
		return (strncmp($str, $sub, strlen($sub)) == 0);
	}
	
	
}

api/log4php/main/php/configurators/LoggerConfiguratorDefault.php0000644000004100000410000003573213466017021025466 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Default implementation of the logger configurator.
 * 
 * Configures log4php based on a provided configuration file or array.
 * 
 * @package log4php
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version $Revision: 1394956 $
 * @since 2.2
 */
class LoggerConfiguratorDefault implements LoggerConfigurator
{
	/** XML configuration file format. */
	const FORMAT_XML = 'xml';
	
	/** PHP configuration file format. */
	const FORMAT_PHP = 'php';
	
	/** INI (properties) configuration file format. */
	const FORMAT_INI = 'ini';

	/** Defines which adapter should be used for parsing which format. */
	private $adapters = array(
		self::FORMAT_XML => 'LoggerConfigurationAdapterXML',
		self::FORMAT_INI => 'LoggerConfigurationAdapterINI',
		self::FORMAT_PHP => 'LoggerConfigurationAdapterPHP',
	);
	
	/** Default configuration; used if no configuration file is provided. */
	private static $defaultConfiguration = array(
        'threshold' => 'ALL',
        'rootLogger' => array(
            'level' => 'DEBUG',
            'appenders' => array('default'),
        ),
        'appenders' => array(
            'default' => array(
                'class' => 'LoggerAppenderEcho'
            ),
        ),
	);
	
	/** Holds the appenders before they are linked to loggers. */
	private $appenders = array();
	
	/**
	 * Configures log4php based on the given configuration. The input can 
	 * either be a path to the config file, or a PHP array holding the 
	 * configuration. 
	 * 
	 * If no configuration is given, or if the given configuration cannot be
	 * parsed for whatever reason, a warning will be issued, and log4php
	 * will use the default configuration contained in 
	 * {@link $defaultConfiguration}.
	 * 
	 * @param LoggerHierarchy $hierarchy The hierarchy on which to perform 
	 * 		the configuration. 
	 * @param string|array $input Either path to the config file or the 
	 * 		configuration as an array. If not set, default configuration 
	 * 		will be used.
	 */
	public function configure(LoggerHierarchy $hierarchy, $input = null) {
		$config = $this->parse($input);
		$this->doConfigure($hierarchy, $config);
	}
	
	/**
	 * Parses the given configuration and returns the parsed configuration
	 * as a PHP array. Does not perform any configuration. 
	 * 
	 * If no configuration is given, or if the given configuration cannot be
	 * parsed for whatever reason, a warning will be issued, and the default 
	 * configuration will be returned ({@link $defaultConfiguration}).
	 * 
	 * @param string|array $input Either path to the config file or the 
	 * 		configuration as an array. If not set, default configuration 
	 * 		will be used.
	 * @return array The parsed configuration.
	 */
	public function parse($input) {
		// No input - use default configuration
		if (!isset($input)) {
			$config = self::$defaultConfiguration;
		}
		
		// Array input - contains configuration within the array
		else if (is_array($input)) {
			$config = $input;
		}
		
		// String input - contains path to configuration file
		else if (is_string($input)) {
			try {
				$config = $this->parseFile($input);
			} catch (LoggerException $e) {
				$this->warn("Configuration failed. " . $e->getMessage() . " Using default configuration.");
				$config = self::$defaultConfiguration;
			}
		}
		
		// Anything else is an error
		else {
			$this->warn("Invalid configuration param given. Reverting to default configuration.");
			$config = self::$defaultConfiguration;
		}
		
		return $config;
	}

	/** 
	 * Returns the default log4php configuration.
	 * @return array
	 */
	public static function getDefaultConfiguration() {
		return self::$defaultConfiguration;
	} 
	
	/**
	 * Loads the configuration file from the given URL, determines which
	 * adapter to use, converts the configuration to a PHP array and
	 * returns it.
	 *
	 * @param string $url Path to the config file.
	 * @return The configuration from the config file, as a PHP array.
	 * @throws LoggerException If the configuration file cannot be loaded, or
	 * 		if the parsing fails.
	 */
	private function parseFile($url) {
		
		if (!file_exists($url)) {
			throw new LoggerException("File not found at [$url].");
		}
		
		$type = $this->getConfigType($url);
		$adapterClass = $this->adapters[$type];

		$adapter = new $adapterClass();
		return $adapter->convert($url);
	}
	
	/** Determines configuration file type based on the file extension. */
	private function getConfigType($url) {
		$info = pathinfo($url);
		$ext = strtolower($info['extension']);
		
		switch($ext) {
			case 'xml':
				return self::FORMAT_XML;
			
			case 'ini':
			case 'properties':
				return self::FORMAT_INI;
			
			case 'php':
				return self::FORMAT_PHP;
				
			default:
				throw new LoggerException("Unsupported configuration file extension: $ext");
		}
	}
	
	/**
	 * Constructs the logger hierarchy based on configuration.
	 * 
	 * @param LoggerHierarchy $hierarchy
	 * @param array $config
	 */
	private function doConfigure(LoggerHierarchy $hierarchy, $config) {
		if (isset($config['threshold'])) {
			$threshold = LoggerLevel::toLevel($config['threshold']);
			if (isset($threshold)) {
				$hierarchy->setThreshold($threshold);
			} else {
				$this->warn("Invalid threshold value [{$config['threshold']}] specified. Ignoring threshold definition.");
			}
		}
		
		// Configure appenders and add them to the appender pool
		if (isset($config['appenders']) && is_array($config['appenders'])) {
			foreach($config['appenders'] as $name => $appenderConfig) {
				$this->configureAppender($name, $appenderConfig);
			}
		}
		
		// Configure root logger 
		if (isset($config['rootLogger'])) {
			$this->configureRootLogger($hierarchy, $config['rootLogger']);
		}
		
		// Configure loggers
		if (isset($config['loggers']) && is_array($config['loggers'])) {
			foreach($config['loggers'] as $loggerName => $loggerConfig) {
				$this->configureOtherLogger($hierarchy, $loggerName, $loggerConfig);
			}
		}

		// Configure renderers
		if (isset($config['renderers']) && is_array($config['renderers'])) {
			foreach($config['renderers'] as $rendererConfig) {
				$this->configureRenderer($hierarchy, $rendererConfig);
			}
		}
		
		if (isset($config['defaultRenderer'])) {
			$this->configureDefaultRenderer($hierarchy, $config['defaultRenderer']);
		}
	}
	
	private function configureRenderer(LoggerHierarchy $hierarchy, $config) {
		if (empty($config['renderingClass'])) {
			$this->warn("Rendering class not specified. Skipping renderer definition.");
			return;
		}
		
		if (empty($config['renderedClass'])) {
			$this->warn("Rendered class not specified. Skipping renderer definition.");
			return;
		}
		
		// Error handling performed by RendererMap
		$hierarchy->getRendererMap()->addRenderer($config['renderedClass'], $config['renderingClass']);
	}
	
	private function configureDefaultRenderer(LoggerHierarchy $hierarchy, $class) {
		if (empty($class)) {
			$this->warn("Rendering class not specified. Skipping default renderer definition.");
			return;
		}
		
		// Error handling performed by RendererMap
		$hierarchy->getRendererMap()->setDefaultRenderer($class);
	}
	
	/** 
	 * Configures an appender based on given config and saves it to 
	 * {@link $appenders} array so it can be later linked to loggers. 
	 * @param string $name Appender name. 
	 * @param array $config Appender configuration options.
	 */
	private function configureAppender($name, $config) {

		// TODO: add this check to other places where it might be useful
		if (!is_array($config)) {
			$type = gettype($config);
			$this->warn("Invalid configuration provided for appender [$name]. Expected an array, found <$type>. Skipping appender definition.");
			return;
		}
		
		// Parse appender class
		$class = $config['class'];
		if (empty($class)) {
			$this->warn("No class given for appender [$name]. Skipping appender definition.");
			return;
		}
		if (!class_exists($class)) {
			$this->warn("Invalid class [$class] given for appender [$name]. Class does not exist. Skipping appender definition.");
			return;
		}
		
		// Instantiate the appender
		$appender = new $class($name);
		if (!($appender instanceof LoggerAppender)) {
			$this->warn("Invalid class [$class] given for appender [$name]. Not a valid LoggerAppender class. Skipping appender definition.");
			return;
		}
		
		// Parse the appender threshold
		if (isset($config['threshold'])) {
			$threshold = LoggerLevel::toLevel($config['threshold']);
			if ($threshold instanceof LoggerLevel) {
				$appender->setThreshold($threshold);
			} else {
				$this->warn("Invalid threshold value [{$config['threshold']}] specified for appender [$name]. Ignoring threshold definition.");
			}
		}
		
		// Parse the appender layout
		if ($appender->requiresLayout() && isset($config['layout'])) {
			$this->createAppenderLayout($appender, $config['layout']);
		}
		
		// Parse filters
		if (isset($config['filters']) && is_array($config['filters'])) {
			foreach($config['filters'] as $filterConfig) {
				$this->createAppenderFilter($appender, $filterConfig);
			}
		}
		
		// Set options if any
		if (isset($config['params'])) {
			$this->setOptions($appender, $config['params']);
		}

		// Activate and save for later linking to loggers
		$appender->activateOptions();
		$this->appenders[$name] = $appender;
	}
	
	/**
	 * Parses layout config, creates the layout and links it to the appender.
	 * @param LoggerAppender $appender
	 * @param array $config Layout configuration.
	 */
	private function createAppenderLayout(LoggerAppender $appender, $config) {
		$name = $appender->getName();
		$class = $config['class'];
		if (empty($class)) {
			$this->warn("Layout class not specified for appender [$name]. Reverting to default layout.");
			return;
		}
		if (!class_exists($class)) {
			$this->warn("Nonexistant layout class [$class] specified for appender [$name]. Reverting to default layout.");
			return;
		}
		
		$layout = new $class();
		if (!($layout instanceof LoggerLayout)) {
			$this->warn("Invalid layout class [$class] sepcified for appender [$name]. Reverting to default layout.");
			return;
		}
		
		if (isset($config['params'])) {
			$this->setOptions($layout, $config['params']);
		}
		
		$layout->activateOptions();
		$appender->setLayout($layout);
	}
	
	/**
	 * Parses filter config, creates the filter and adds it to the appender's 
	 * filter chain.
	 * @param LoggerAppender $appender
	 * @param array $config Filter configuration.
	 */
	private function createAppenderFilter(LoggerAppender $appender, $config) {
		$name = $appender->getName();
		$class = $config['class'];
		if (!class_exists($class)) {
			$this->warn("Nonexistant filter class [$class] specified on appender [$name]. Skipping filter definition.");
			return;
		}
	
		$filter = new $class();
		if (!($filter instanceof LoggerFilter)) {
			$this->warn("Invalid filter class [$class] sepcified on appender [$name]. Skipping filter definition.");
			return;
		}
	
		if (isset($config['params'])) {
			$this->setOptions($filter, $config['params']);
		}
	
		$filter->activateOptions();
		$appender->addFilter($filter);
	}
	
	/** 
	 * Configures the root logger
	 * @see configureLogger() 
	 */
	private function configureRootLogger(LoggerHierarchy $hierarchy, $config) {
		$logger = $hierarchy->getRootLogger();
		$this->configureLogger($logger, $config);
	}

	/**
	 * Configures a logger which is not root.
	 * @see configureLogger()
	 */
	private function configureOtherLogger(LoggerHierarchy $hierarchy, $name, $config) {
		// Get logger from hierarchy (this creates it if it doesn't already exist)
		$logger = $hierarchy->getLogger($name);
		$this->configureLogger($logger, $config);
	}
	
	/**
	 * Configures a logger. 
	 * 
	 * @param Logger $logger The logger to configure
	 * @param array $config Logger configuration options.
	 */
	private function configureLogger(Logger $logger, $config) {
		$loggerName = $logger->getName();
		
		// Set logger level
		if (isset($config['level'])) {
			$level = LoggerLevel::toLevel($config['level']);
			if (isset($level)) {
				$logger->setLevel($level);
			} else {
				$this->warn("Invalid level value [{$config['level']}] specified for logger [$loggerName]. Ignoring level definition.");
			}
		}
		
		// Link appenders to logger
		if (isset($config['appenders'])) {
			foreach($config['appenders'] as $appenderName) {
				if (isset($this->appenders[$appenderName])) {
					$logger->addAppender($this->appenders[$appenderName]);
				} else {
					$this->warn("Nonexistnant appender [$appenderName] linked to logger [$loggerName].");
				}
			}
		}
		
		// Set logger additivity
		if (isset($config['additivity'])) {
			try {
				$additivity = LoggerOptionConverter::toBooleanEx($config['additivity'], null);
				$logger->setAdditivity($additivity);
			} catch (Exception $ex) {
				$this->warn("Invalid additivity value [{$config['additivity']}] specified for logger [$loggerName]. Ignoring additivity setting.");
			}
		}
	}

	/**
	 * Helper method which applies given options to an object which has setters
	 * for these options (such as appenders, layouts, etc.).
	 * 
	 * For example, if options are:
	 * <code>
	 * array(
	 * 	'file' => '/tmp/myfile.log',
	 * 	'append' => true
	 * )
	 * </code>
	 * 
	 * This method will call:
	 * <code>
	 * $object->setFile('/tmp/myfile.log')
	 * $object->setAppend(true)
	 * </code>
	 * 
	 * If required setters do not exist, it will produce a warning. 
	 * 
	 * @param mixed $object The object to configure.
	 * @param unknown_type $options
	 */
	private function setOptions($object, $options) {
		foreach($options as $name => $value) {
			$setter = "set$name";
			if (method_exists($object, $setter)) {
				$object->$setter($value);
			} else {
				$class = get_class($object);
				$this->warn("Nonexistant option [$name] specified on [$class]. Skipping.");
			}
		}
	}
	
	/** Helper method to simplify error reporting. */
	private function warn($message) {
		trigger_error("log4php: $message", E_USER_WARNING);
	}
}
api/log4php/main/php/configurators/LoggerConfigurationAdapterPHP.php0000644000004100000410000000462613466017021026175 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @package log4php
 */

/**
 * Converts PHP configuration files to a PHP array.
 * 
 * The file should only hold the PHP config array preceded by "return".
 * 
 * Example PHP config file:
 * <code>
 * <?php
 * return array(
 *   'rootLogger' => array(
 *     'level' => 'info',
 *     'appenders' => array('default')
 *   ),
 *   'appenders' => array(
 *     'default' => array(
 *       'class' => 'LoggerAppenderEcho',
 *       'layout' => array(
 *       	'class' => 'LoggerLayoutSimple'
 *        )
 *     )
 *   )
 * )
 * ?>
 * </code>
 * 
 * @package log4php
 * @subpackage configurators
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version $Revision: 1343601 $
 * @since 2.2
 */
class LoggerConfigurationAdapterPHP implements LoggerConfigurationAdapter
{
	public function convert($url) {
		if (!file_exists($url)) {
			throw new LoggerException("File [$url] does not exist.");
		}
		
		// Load the config file
		$data = @file_get_contents($url);
		if ($data === false) {
			$error = error_get_last();
			throw new LoggerException("Error loading config file: {$error['message']}");
		}
		
		$config = @eval('?>' . $data);
		
		if ($config === false) {
			$error = error_get_last();
			throw new LoggerException("Error parsing configuration: " . $error['message']);
		}
		
		if (empty($config)) {
			throw new LoggerException("Invalid configuration: empty configuration array.");
		}
		
		if (!is_array($config)) {
			throw new LoggerException("Invalid configuration: not an array.");
		}
		
		return $config;
	}
}

api/log4php/main/php/LoggerConfigurable.php0000644000004100000410000001026313466017021021222 0ustar  www-datawww-data<?php
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
*	   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @package log4php
*/

/** 
 * A base class from which all classes which have configurable properties are 
 * extended. Provides a generic setter with integrated validation.  
 * 
 * @package log4php
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version $Revision $
 * @since 2.2
 */
abstract class LoggerConfigurable {
	
	/** Setter function for boolean type. */
	protected function setBoolean($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toBooleanEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a boolean value. Property not changed.");
		}
	}
	
	/** Setter function for integer type. */
	protected function setInteger($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toIntegerEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected an integer. Property not changed.");
		}
	}
	
	/** Setter function for LoggerLevel values. */
	protected function setLevel($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toLevelEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a level value. Property not changed.");
		}
	}
	
	/** Setter function for integer type. */
	protected function setPositiveInteger($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toPositiveIntegerEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a positive integer. Property not changed.");
		}
	}
	
	/** Setter for file size. */
	protected function setFileSize($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toFileSizeEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a file size value.  Property not changed.");
		}
	}
	
	/** Setter function for numeric type. */
	protected function setNumeric($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toNumericEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a number. Property not changed.");
		}
	}
	
	/** Setter function for string type. */
	protected function setString($property, $value, $nullable = false) {
		if ($value === null) {
			if($nullable) {
				$this->$property= null;
			} else {
				$this->warn("Null value given for '$property' property. Expected a string. Property not changed.");
			}
		} else {
			try {
				$value = LoggerOptionConverter::toStringEx($value);
				$this->$property = LoggerOptionConverter::substConstants($value);
			} catch (Exception $ex) {
				$value = var_export($value, true);
				$this->warn("Invalid value given for '$property' property: [$value]. Expected a string. Property not changed.");
			}
		}
	}
	
	/** Triggers a warning. */
	protected function warn($message) {
		$class = get_class($this);
		trigger_error("log4php: $class: $message", E_USER_WARNING);
	}
}
api/log4php/main/php/LoggerLevel.php0000644000004100000410000001564513466017021017702 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Defines the minimum set of levels recognized by the system, that is
 * <i>OFF</i>, <i>FATAL</i>, <i>ERROR</i>,
 * <i>WARN</i>, <i>INFO</i>, <i>DEBUG</i> and
 * <i>ALL</i>.
 *
 * <p>The <i>LoggerLevel</i> class may be subclassed to define a larger
 * level set.</p>
 *
 * @version $Revision: 1379729 $
 * @package log4php
 * @since 0.5
 */
class LoggerLevel {
	
	const OFF = 2147483647;
	const FATAL = 50000;
	const ERROR = 40000;
	const WARN = 30000;
	const INFO = 20000;
	const DEBUG = 10000;
	const TRACE = 5000;
	const ALL = -2147483647;

	/** Integer level value. */
	private $level;
	
	/** Contains a list of instantiated levels. */
	private static $levelMap;

	/** String representation of the level. */
	private $levelStr;

	/** 
	 * Equivalent syslog level.
	 * @var integer
	 */
	private $syslogEquivalent;

	/**
	 * Constructor
	 *
	 * @param integer $level
	 * @param string $levelStr
	 * @param integer $syslogEquivalent
	 */
	private function __construct($level, $levelStr, $syslogEquivalent) {
		$this->level = $level;
		$this->levelStr = $levelStr;
		$this->syslogEquivalent = $syslogEquivalent;
	}

	/**
	 * Compares two logger levels.
	 *
	 * @param LoggerLevels $other
	 * @return boolean 
	 */
	public function equals($other) {
		if($other instanceof LoggerLevel) {
			if($this->level == $other->level) {
				return true;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * Returns an Off Level
	 * @return LoggerLevel
	 */
	public static function getLevelOff() {
		if(!isset(self::$levelMap[LoggerLevel::OFF])) {
			self::$levelMap[LoggerLevel::OFF] = new LoggerLevel(LoggerLevel::OFF, 'OFF', LOG_ALERT);
		}
		return self::$levelMap[LoggerLevel::OFF];
	}

	/**
	 * Returns a Fatal Level
	 * @return LoggerLevel
	 */
	public static function getLevelFatal() {
		if(!isset(self::$levelMap[LoggerLevel::FATAL])) {
			self::$levelMap[LoggerLevel::FATAL] = new LoggerLevel(LoggerLevel::FATAL, 'FATAL', LOG_ALERT);
		}
		return self::$levelMap[LoggerLevel::FATAL];
	}
	
	/**
	 * Returns an Error Level
	 * @return LoggerLevel
	 */
	public static function getLevelError() {
		if(!isset(self::$levelMap[LoggerLevel::ERROR])) {
			self::$levelMap[LoggerLevel::ERROR] = new LoggerLevel(LoggerLevel::ERROR, 'ERROR', LOG_ERR);
		}
		return self::$levelMap[LoggerLevel::ERROR];
	}
	
	/**
	 * Returns a Warn Level
	 * @return LoggerLevel
	 */
	public static function getLevelWarn() {
		if(!isset(self::$levelMap[LoggerLevel::WARN])) {
			self::$levelMap[LoggerLevel::WARN] = new LoggerLevel(LoggerLevel::WARN, 'WARN', LOG_WARNING);
		}
		return self::$levelMap[LoggerLevel::WARN];
	}

	/**
	 * Returns an Info Level
	 * @return LoggerLevel
	 */
	public static function getLevelInfo() {
		if(!isset(self::$levelMap[LoggerLevel::INFO])) {
			self::$levelMap[LoggerLevel::INFO] = new LoggerLevel(LoggerLevel::INFO, 'INFO', LOG_INFO);
		}
		return self::$levelMap[LoggerLevel::INFO];
	}

	/**
	 * Returns a Debug Level
	 * @return LoggerLevel
	 */
	public static function getLevelDebug() {
		if(!isset(self::$levelMap[LoggerLevel::DEBUG])) {
			self::$levelMap[LoggerLevel::DEBUG] = new LoggerLevel(LoggerLevel::DEBUG, 'DEBUG', LOG_DEBUG);
		}
		return self::$levelMap[LoggerLevel::DEBUG];
	}
	
	/**
	 * Returns a Trace Level
	 * @return LoggerLevel
	 */
	public static function getLevelTrace() {
		if(!isset(self::$levelMap[LoggerLevel::TRACE])) {
			self::$levelMap[LoggerLevel::TRACE] = new LoggerLevel(LoggerLevel::TRACE, 'TRACE', LOG_DEBUG);
		}
		return self::$levelMap[LoggerLevel::TRACE];
	}	

	/**
	 * Returns an All Level
	 * @return LoggerLevel
	 */
	public static function getLevelAll() {
		if(!isset(self::$levelMap[LoggerLevel::ALL])) {
			self::$levelMap[LoggerLevel::ALL] = new LoggerLevel(LoggerLevel::ALL, 'ALL', LOG_DEBUG);
		}
		return self::$levelMap[LoggerLevel::ALL];
	}
	
	/**
	 * Return the syslog equivalent of this level as an integer.
	 * @return integer
	 */
	public function getSyslogEquivalent() {
		return $this->syslogEquivalent;
	}

	/**
	 * Returns <i>true</i> if this level has a higher or equal
	 * level than the level passed as argument, <i>false</i>
	 * otherwise.
	 *
	 * @param LoggerLevel $other
	 * @return boolean
	 */
	public function isGreaterOrEqual($other) {
		return $this->level >= $other->level;
	}

	/**
	 * Returns the string representation of this level.
	 * @return string
	 */
	public function toString() {
		return $this->levelStr;
	}
	
	/**
	 * Returns the string representation of this level.
	 * @return string
	 */
	public function __toString() {
		return $this->toString();
	}

	/**
	 * Returns the integer representation of this level.
	 * @return integer
	 */
	public function toInt() {
		return $this->level;
	}

	/**
	 * Convert the input argument to a level. If the conversion fails, then 
	 * this method returns the provided default level.
	 *
	 * @param mixed $arg The value to convert to level.
	 * @param LoggerLevel $default Value to return if conversion is not possible.
	 * @return LoggerLevel 
	 */
	public static function toLevel($arg, $defaultLevel = null) {
		if(is_int($arg)) {
			switch($arg) {
				case self::ALL:	return self::getLevelAll();
				case self::TRACE: return self::getLevelTrace();
				case self::DEBUG: return self::getLevelDebug();
				case self::INFO: return self::getLevelInfo();
				case self::WARN: return self::getLevelWarn();
				case self::ERROR: return self::getLevelError();
				case self::FATAL: return self::getLevelFatal();
				case self::OFF:	return self::getLevelOff();
				default: return $defaultLevel;
			}
		} else {
			switch(strtoupper($arg)) {
				case 'ALL':	return self::getLevelAll();
				case 'TRACE': return self::getLevelTrace();
				case 'DEBUG': return self::getLevelDebug();
				case 'INFO': return self::getLevelInfo();
				case 'WARN': return self::getLevelWarn();
				case 'ERROR': return self::getLevelError();
				case 'FATAL': return self::getLevelFatal();
				case 'OFF':	return self::getLevelOff();
				default: return $defaultLevel;
			}
		}
	}
}
api/log4php/main/php/Logger.php0000644000004100000410000004157313466017021016711 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 *		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @package log4php
 */

require dirname(__FILE__) . '/LoggerAutoloader.php';

/**
 * This is the central class in the log4php package. All logging operations 
 * are done through this class.
 * 
 * The main logging methods are:
 * 	<ul>
 * 		<li>{@link trace()}</li>
 * 		<li>{@link debug()}</li>
 * 		<li>{@link info()}</li>
 * 		<li>{@link warn()}</li>
 * 		<li>{@link error()}</li>
 * 		<li>{@link fatal()}</li>
 * 	</ul>
 * 
 * @package    log4php
 * @license	   http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version	   SVN: $Id: Logger.php 1395241 2012-10-07 08:28:53Z ihabunek $
 * @link	   http://logging.apache.org/log4php
 */
class Logger {
	
	/**
	 * Logger additivity. If set to true then child loggers will inherit
	 * the appenders of their ancestors by default.
	 * @var boolean
	 */
	private $additive = true;
	
	/** 
	 * The Logger's fully qualified class name.
	 * TODO: Determine if this is useful. 
	 */
	private $fqcn = 'Logger';

	/** The assigned Logger level. */
	private $level;
	
	/** The name of this Logger instance. */
	private $name;
	
	/** The parent logger. Set to null if this is the root logger. */
	private $parent;
	
	/** A collection of appenders linked to this logger. */
	private $appenders = array();

	/**
	 * Constructor.
	 * @param string $name Name of the logger.	  
	 */
	public function __construct($name) {
		$this->name = $name;
	}
	
	/**
	 * Returns the logger name.
	 * @return string
	 */
	public function getName() {
		return $this->name;
	} 

	/**
	 * Returns the parent Logger. Can be null if this is the root logger.
	 * @return Logger
	 */
	public function getParent() {
		return $this->parent;
	}
	
	// ******************************************
	// *** Logging methods                    ***
	// ******************************************
	
	/**
	 * Log a message object with the TRACE level.
	 *
	 * @param mixed $message message
 	 * @param Exception $throwable Optional throwable information to include 
	 *   in the logging event.
	 */
	public function trace($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelTrace(), $message, $throwable);
	} 		
	
	/**
	 * Log a message object with the DEBUG level.
	 *
	 * @param mixed $message message
 	 * @param Exception $throwable Optional throwable information to include 
	 *   in the logging event.
	 */
	public function debug($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelDebug(), $message, $throwable);
	} 

	/**
	 * Log a message object with the INFO Level.
	 *
	 * @param mixed $message message
 	 * @param Exception $throwable Optional throwable information to include 
	 *   in the logging event.
	 */
	public function info($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelInfo(), $message, $throwable);
	}

	/**
	 * Log a message with the WARN level.
	 *
	 * @param mixed $message message
  	 * @param Exception $throwable Optional throwable information to include 
	 *   in the logging event.
	 */
	public function warn($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelWarn(), $message, $throwable);
	}
	
	/**
	 * Log a message object with the ERROR level.
	 *
	 * @param mixed $message message
	 * @param Exception $throwable Optional throwable information to include 
	 *   in the logging event.
	 */
	public function error($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelError(), $message, $throwable);
	}
	
	/**
	 * Log a message object with the FATAL level.
	 *
	 * @param mixed $message message
	 * @param Exception $throwable Optional throwable information to include 
	 *   in the logging event.
	 */
	public function fatal($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelFatal(), $message, $throwable);
	}

	/**
	 * Log a message using the provided logging level.
	 *
	 * @param LoggerLevel $level The logging level.
	 * @param mixed $message Message to log.
 	 * @param Exception $throwable Optional throwable information to include 
	 *   in the logging event.
	 */
	public function log(LoggerLevel $level, $message, $throwable = null) {
		if($this->isEnabledFor($level)) {
			$event = new LoggerLoggingEvent($this->fqcn, $this, $level, $message, null, $throwable);
			$this->callAppenders($event);
		}
		
		// Forward the event upstream if additivity is turned on
		if(isset($this->parent) && $this->getAdditivity()) {
			
			// Use the event if already created
			if (isset($event)) {
				$this->parent->logEvent($event);
			} else {
				$this->parent->log($level, $message, $throwable);
			}
		}
	}
	
	/**
	 * Logs an already prepared logging event object. 
	 * @param LoggerLoggingEvent $event
	 */
	public function logEvent(LoggerLoggingEvent $event) {
		if($this->isEnabledFor($event->getLevel())) {
			$this->callAppenders($event);
		}
		
		// Forward the event upstream if additivity is turned on
		if(isset($this->parent) && $this->getAdditivity()) {
			$this->parent->logEvent($event);
		}
	}
	
	/**
	 * If assertion parameter evaluates as false, then logs the message 
	 * using the ERROR level.
	 *
	 * @param bool $assertion
	 * @param string $msg message to log
	 */
	public function assertLog($assertion = true, $msg = '') {
		if($assertion == false) {
			$this->error($msg);
		}
	}
	
	/**
	 * This method creates a new logging event and logs the event without 
	 * further checks.
	 *
	 * It should not be called directly. Use {@link trace()}, {@link debug()},
	 * {@link info()}, {@link warn()}, {@link error()} and {@link fatal()} 
	 * wrappers.
	 *
	 * @param string $fqcn Fully qualified class name of the Logger
	 * @param Exception $throwable Optional throwable information to include 
	 *   in the logging event.
	 * @param LoggerLevel $level log level	   
	 * @param mixed $message message to log
	 */
	public function forcedLog($fqcn, $throwable, LoggerLevel $level, $message) {
		$event = new LoggerLoggingEvent($fqcn, $this, $level, $message, null, $throwable);
		$this->callAppenders($event);
		
		// Forward the event upstream if additivity is turned on
		if(isset($this->parent) && $this->getAdditivity()) {
			$this->parent->logEvent($event);
		}
	}

	/**
	 * Forwards the given logging event to all linked appenders.
	 * @param LoggerLoggingEvent $event
	 */
	public function callAppenders($event) {
		foreach($this->appenders as $appender) {
			$appender->doAppend($event);
		}
	}
	
	// ******************************************
	// *** Checker methods                    ***
	// ******************************************
	
	/**
	 * Check whether this Logger is enabled for a given Level passed as parameter.
	 *
	 * @param LoggerLevel level
	 * @return boolean
	 */
	public function isEnabledFor(LoggerLevel $level) {
		return $level->isGreaterOrEqual($this->getEffectiveLevel());
	}
	
	/**
	 * Check whether this Logger is enabled for the TRACE Level.
	 * @return boolean
	 */
	public function isTraceEnabled() {
		return $this->isEnabledFor(LoggerLevel::getLevelTrace());
	}
	
	/**
	 * Check whether this Logger is enabled for the DEBUG Level.
	 * @return boolean
	 */
	public function isDebugEnabled() {
		return $this->isEnabledFor(LoggerLevel::getLevelDebug());
	}

	/**
	 * Check whether this Logger is enabled for the INFO Level.
	 * @return boolean
	 */
	public function isInfoEnabled() {
		return $this->isEnabledFor(LoggerLevel::getLevelInfo());
	}
	
	/**
	 * Check whether this Logger is enabled for the WARN Level.
	 * @return boolean
	 */
	public function isWarnEnabled() {
		return $this->isEnabledFor(LoggerLevel::getLevelWarn());
	}
	
	/**
	 * Check whether this Logger is enabled for the ERROR Level.
	 * @return boolean
	 */
	public function isErrorEnabled() {
		return $this->isEnabledFor(LoggerLevel::getLevelError());
	}
	
	/**
	 * Check whether this Logger is enabled for the FATAL Level.
	 * @return boolean
	 */
	public function isFatalEnabled() {
		return $this->isEnabledFor(LoggerLevel::getLevelFatal());
	}
	
	// ******************************************
	// *** Configuration methods              ***
	// ******************************************
	
	/**
	 * Adds a new appender to the Logger.
	 * @param LoggerAppender $appender The appender to add.
	 */
	public function addAppender($appender) {
		$appenderName = $appender->getName();
		$this->appenders[$appenderName] = $appender;
	}
	
	/** Removes all appenders from the Logger. */
	public function removeAllAppenders() {
		foreach($this->appenders as $name => $appender) {
			$this->removeAppender($name);
		}
	} 
			
	/**
	 * Remove the appender passed as parameter form the Logger.
	 * @param mixed $appender an appender name or a {@link LoggerAppender} instance.
	 */
	public function removeAppender($appender) {
		if($appender instanceof LoggerAppender) {
			$appender->close();
			unset($this->appenders[$appender->getName()]);
		} else if (is_string($appender) and isset($this->appenders[$appender])) {
			$this->appenders[$appender]->close();
			unset($this->appenders[$appender]);
		}
	}
	
	/**
	 * Returns the appenders linked to this logger as an array.
	 * @return array collection of appender names
	 */
	public function getAllAppenders() {
		return $this->appenders;
	}
	
	/**
	 * Returns a linked appender by name.
	 * @return LoggerAppender
	 */
	public function getAppender($name) {
		return $this->appenders[$name];
	}

	/**
	 * Sets the additivity flag.
	 * @param boolean $additive
	 */
	public function setAdditivity($additive) {
		$this->additive = (bool)$additive;
	}
	
	/**
	 * Returns the additivity flag.
	 * @return boolean
	 */
	public function getAdditivity() {
		return $this->additive;
	}
 
	/**
	 * Starting from this Logger, search the Logger hierarchy for a non-null level and return it.
	 * @see LoggerLevel
	 * @return LoggerLevel or null
	 */
	public function getEffectiveLevel() {
		for($logger = $this; $logger !== null; $logger = $logger->getParent()) {
			if($logger->getLevel() !== null) {
				return $logger->getLevel();
			}
		}
	}
  
	/**
	 * Get the assigned Logger level.
	 * @return LoggerLevel The assigned level or null if none is assigned. 
	 */
	public function getLevel() {
		return $this->level;
	}
	
	/**
	 * Set the Logger level.
	 *
	 * Use LoggerLevel::getLevelXXX() methods to get a LoggerLevel object, e.g.
	 * <code>$logger->setLevel(LoggerLevel::getLevelInfo());</code>
	 *
	 * @param LoggerLevel $level The level to set, or NULL to clear the logger level.
	 */
	public function setLevel(LoggerLevel $level = null) {
		$this->level = $level;
	}
	
	/**
	 * Checks whether an appender is attached to this logger instance.
	 *
	 * @param LoggerAppender $appender
	 * @return boolean
	 */
	public function isAttached(LoggerAppender $appender) {
		return isset($this->appenders[$appender->getName()]);
	}
	
	/**
	 * Sets the parent logger.
	 * @param Logger $logger
	 */
	public function setParent(Logger $logger) {
		$this->parent = $logger;
	} 
	
	// ******************************************
	// *** Static methods and properties      ***
	// ******************************************
	
	/** The logger hierarchy used by log4php. */
	private static $hierarchy;
	
	/** Inidicates if log4php has been initialized */
	private static $initialized = false;
	
	/**
	 * Returns the hierarchy used by this Logger.
	 *
	 * Caution: do not use this hierarchy unless you have called initialize().
	 * To get Loggers, use the Logger::getLogger and Logger::getRootLogger
	 * methods instead of operating on on the hierarchy directly.
	 *
	 * @return LoggerHierarchy
	 */
	public static function getHierarchy() {
		if(!isset(self::$hierarchy)) {
			self::$hierarchy = new LoggerHierarchy(new LoggerRoot());
		}
		return self::$hierarchy;
	}
	
	/**
	 * Returns a Logger by name. If it does not exist, it will be created.
	 *
	 * @param string $name The logger name
	 * @return Logger
	 */
	public static function getLogger($name) {
		if(!self::isInitialized()) {
			self::configure();
		}
		return self::getHierarchy()->getLogger($name);
	}
	
	/**
	 * Returns the Root Logger.
	 * @return LoggerRoot
	 */
	public static function getRootLogger() {
		if(!self::isInitialized()) {
			self::configure();
		}
		return self::getHierarchy()->getRootLogger();
	}
	
	/**
	 * Clears all Logger definitions from the logger hierarchy.
	 * @return boolean
	 */
	public static function clear() {
		return self::getHierarchy()->clear();
	}
	
	/**
	 * Destroy configurations for logger definitions
	 */
	public static function resetConfiguration() {
		self::getHierarchy()->resetConfiguration();
		self::getHierarchy()->clear(); // TODO: clear or not?
		self::$initialized = false;
	}
	
	/**
	 * Safely close all appenders.
	 * @deprecated This is no longer necessary due the appenders shutdown via
	 * destructors.
	 */
	public static function shutdown() {
		return self::getHierarchy()->shutdown();
	}
	
	/**
	 * check if a given logger exists.
	 *
	 * @param string $name logger name
	 * @return boolean
	 */
	public static function exists($name) {
		return self::getHierarchy()->exists($name);
	}
	
	/**
	 * Returns an array this whole Logger instances.
	 * @see Logger
	 * @return array
	 */
	public static function getCurrentLoggers() {
		return self::getHierarchy()->getCurrentLoggers();
	}
	
	/**
	 * Configures log4php.
	 * 
	 * This method needs to be called before the first logging event has 
	 * occured. If this method is not called before then the default
	 * configuration will be used.
	 *
	 * @param string|array $configuration Either a path to the configuration
	 *   file, or a configuration array.
	 *   
	 * @param string|LoggerConfigurator $configurator A custom 
	 * configurator class: either a class name (string), or an object which 
	 * implements the LoggerConfigurator interface. If left empty, the default
	 * configurator implementation will be used. 
	 */
	public static function configure($configuration = null, $configurator = null) {
		self::resetConfiguration();
		$configurator = self::getConfigurator($configurator);
		$configurator->configure(self::getHierarchy(), $configuration);
		self::$initialized = true;
	}
	
	/**
	 * Creates a logger configurator instance based on the provided 
	 * configurator class. If no class is given, returns an instance of
	 * the default configurator.
	 * 
	 * @param string|LoggerConfigurator $configurator The configurator class 
	 * or LoggerConfigurator instance.
	 */
	private static function getConfigurator($configurator = null) {
		if ($configurator === null) {
			return new LoggerConfiguratorDefault();
		}
		
		if (is_object($configurator)) {
			if ($configurator instanceof LoggerConfigurator) {
				return $configurator;
			} else {
				trigger_error("log4php: Given configurator object [$configurator] does not implement the LoggerConfigurator interface. Reverting to default configurator.", E_USER_WARNING);
				return new LoggerConfiguratorDefault();
			}
		}
		
		if (is_string($configurator)) {
			if (!class_exists($configurator)) {
				trigger_error("log4php: Specified configurator class [$configurator] does not exist. Reverting to default configurator.", E_USER_WARNING);
				return new LoggerConfiguratorDefault();
			}
			
			$instance = new $configurator();
				
			if (!($instance instanceof LoggerConfigurator)) {
				trigger_error("log4php: Specified configurator class [$configurator] does not implement the LoggerConfigurator interface. Reverting to default configurator.", E_USER_WARNING);
				return new LoggerConfiguratorDefault();
			}
			
			return $instance;
		}
		
		trigger_error("log4php: Invalid configurator specified. Expected either a string or a LoggerConfigurator instance. Reverting to default configurator.", E_USER_WARNING);
		return new LoggerConfiguratorDefault();
	}
	
	/**
	 * Returns true if the log4php framework has been initialized.
	 * @return boolean 
	 */
	private static function isInitialized() {
		return self::$initialized;
	}
}
api/log4php/main/php/LoggerLocationInfo.php0000644000004100000410000000574613466017021021220 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * The internal representation of caller location information.
 *
 * @version $Revision: 1379738 $
 * @package log4php
 * @since 0.3
 */
class LoggerLocationInfo {
	
	/** The value to return when the location information is not available. */
	const LOCATION_INFO_NA = 'NA';
	
	/**
	 * Caller line number.
	 * @var integer 
	 */
	protected $lineNumber;
	
	/**
	 * Caller file name.
	 * @var string 
	 */
	protected $fileName;
	
	/**
	 * Caller class name.
	 * @var string 
	 */
	protected $className;
	
	/**
	 * Caller method name.
	 * @var string 
	 */
	protected $methodName;
	
	/**
	 * All the information combined.
	 * @var string 
	 */
	protected $fullInfo;

	/**
	 * Instantiate location information based on a {@link PHP_MANUAL#debug_backtrace}.
	 *
	 * @param array $trace
	 * @param mixed $caller
	 */
	public function __construct($trace, $fqcn = null) {
		$this->lineNumber = isset($trace['line']) ? $trace['line'] : null;
		$this->fileName = isset($trace['file']) ? $trace['file'] : null;
		$this->className = isset($trace['class']) ? $trace['class'] : null;
		$this->methodName = isset($trace['function']) ? $trace['function'] : null;
		$this->fullInfo = $this->getClassName() . '.' . $this->getMethodName() . 
			'(' . $this->getFileName() . ':' . $this->getLineNumber() . ')';
	}

	/** Returns the caller class name. */
	public function getClassName() {
		return ($this->className === null) ? self::LOCATION_INFO_NA : $this->className; 
	}

	/** Returns the caller file name. */
	public function getFileName() {
		return ($this->fileName === null) ? self::LOCATION_INFO_NA : $this->fileName; 
	}

	/** Returns the caller line number. */
	public function getLineNumber() {
		return ($this->lineNumber === null) ? self::LOCATION_INFO_NA : $this->lineNumber; 
	}

	/** Returns the caller method name. */
	public function getMethodName() {
		return ($this->methodName === null) ? self::LOCATION_INFO_NA : $this->methodName; 
	}

	/** Returns the full information of the caller. */
	public function getFullInfo() {
		return ($this->fullInfo === null) ? self::LOCATION_INFO_NA : $this->fullInfo;
	}

}
api/log4php/main/php/LoggerAppenderPool.php0000644000004100000410000000562413466017021021217 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Pool implmentation for LoggerAppender instances.
 * 
 * The pool is used when configuring log4php. First all appender instances 
 * are created in the pool. Afterward, they are linked to loggers, each 
 * appender can be linked to multiple loggers. This makes sure duplicate 
 * appenders are not created.
 *
 * @version $Revision: 1350602 $
 * @package log4php
 */
class LoggerAppenderPool {
	
	/** Holds appenders indexed by their name */
	public static $appenders =  array();

	/**
	 * Adds an appender to the pool. 
	 * The appender must be named for this operation. 
	 * @param LoggerAppender $appender
	 */
	public static function add(LoggerAppender $appender) {
		$name = $appender->getName();
		
		if(empty($name)) {
			trigger_error('log4php: Cannot add unnamed appender to pool.', E_USER_WARNING);
			return;
		}
		
		if (isset(self::$appenders[$name])) {
			trigger_error("log4php: Appender [$name] already exists in pool. Overwriting existing appender.", E_USER_WARNING);
		}
		
		self::$appenders[$name] = $appender;
	}
	
	/** 
	 * Retrieves an appender from the pool by name. 
	 * @param string $name Name of the appender to retrieve.
	 * @return LoggerAppender The named appender or NULL if no such appender 
	 *  exists in the pool.
	 */
	public static function get($name) {
		return isset(self::$appenders[$name]) ? self::$appenders[$name] : null;
	}
	
	/**
	* Removes an appender from the pool by name.
	* @param string $name Name of the appender to remove.
	*/
	public static function delete($name) {
		unset(self::$appenders[$name]);
	}
	
	/**
	 * Returns all appenders from the pool.
	 * @return array Array of LoggerAppender objects.
	 */
	public static function getAppenders() {
		return self::$appenders;
	}
	
	/**
	 * Checks whether an appender exists in the pool.
	 * @param string $name Name of the appender to look for.
	 * @return boolean TRUE if the appender with the given name exists.
	 */
	public static function exists($name) {
		return isset(self::$appenders[$name]);
	}

	/**
	 * Clears all appenders from the pool.
	 */
	public static function clear() {
		 self::$appenders =  array();
	}
}api/log4php/main/php/xml/0000755000004100000410000000000013466017021015547 5ustar  www-datawww-dataapi/log4php/main/php/xml/log4php.dtd0000644000004100000410000001204113466017021017617 0ustar  www-datawww-data<?xml version="1.0" encoding="UTF-8" ?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 -->
<!-- Authors: Chris Taylor, Ceki Gülcü. -->
<!-- Version: 1.2 -->

<!-- PHP Port Modifications Author: Marco Vassura -->
<!-- PHP dtd Version: $Revision: 823875 $ -->

<!-- A configuration element consists of optional renderer
elements,appender elements, categories and an optional root
element. -->
<!-- [log4php] -->
<!--
    category instead of logger cannot be used. categoryFactory is not implemented in log4php.
-->
<!-- [/log4php] -->
<!ELEMENT log4php:configuration (renderer*, appender*,(logger)*,root?)>

<!-- The "threshold" attribute takes a level value such that all -->
<!-- logging statements with a level equal or below this value are -->
<!-- disabled. -->

<!-- Setting the "debug" enable the printing of internal log4j logging   -->
<!-- statements.                                                         -->

<!-- By default, debug attribute is "null", meaning that we not do touch -->
<!-- internal log4j logging settings. The "null" value for the threshold -->
<!-- attribute can be misleading. The threshold field of a repository    -->
<!-- cannot be set to null. The "null" value for the threshold attribute -->
<!-- simply means don't touch the threshold field, the threshold field   --> 
<!-- keeps its old value.                                                -->
     
<!ATTLIST log4php:configuration
  xmlns:log4php            CDATA #FIXED "http://logging.apache.org/log4php"
  threshold                (all|debug|info|warn|error|fatal|off|null) "null"
>

<!-- renderer elements allow the user to customize the conversion of  -->
<!-- message objects to String.                                       -->
<!ELEMENT renderer EMPTY>
<!ATTLIST renderer
    renderedClass  CDATA #REQUIRED
    renderingClass CDATA #REQUIRED
>

<!-- Appenders must have a name and a class. -->
<!-- Appenders may contain an error handler, a layout, optional parameters -->
<!-- and filters. They may also reference (or include) other appenders. -->
<!-- [log4php] -->
<!-- error handler tag has no effects since log4php does not handle errors. Defintion deleted. -->
<!-- [/log4php] -->
<!ELEMENT appender (param*, layout?, filter*, appender-ref*)>
<!ATTLIST appender
  name      ID  #REQUIRED
  class     CDATA   #REQUIRED
>

<!ELEMENT layout (param*)>
<!ATTLIST layout
  class     CDATA   #REQUIRED
>

<!ELEMENT filter (param*)>
<!ATTLIST filter
  class     CDATA   #REQUIRED
>


<!ELEMENT param EMPTY>
<!ATTLIST param
  name      CDATA   #REQUIRED
  value     CDATA   #REQUIRED
>

<!ELEMENT priority EMPTY>
<!ATTLIST priority
  value   CDATA #REQUIRED
>

<!ELEMENT level EMPTY>
<!ATTLIST level
  value   CDATA #REQUIRED
>

<!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named logger. -->
<!ELEMENT logger (level?,appender-ref*)>
<!ATTLIST logger
  name      ID  #REQUIRED
  additivity    (true|false) "true"  
>

<!ELEMENT appender-ref EMPTY>
<!ATTLIST appender-ref
  ref IDREF #REQUIRED
>

<!-- If no priority element is specified, then the configurator MUST not -->
<!-- touch the priority of root. -->
<!-- The root category always exists and cannot be subclassed. -->
<!ELEMENT root (param*, (priority|level)?, appender-ref*)>


<!-- ==================================================================== -->
<!--                       A logging event                                -->
<!-- ==================================================================== -->
<!ELEMENT log4php:eventSet (log4php:event*)>
<!ATTLIST log4php:eventSet
  xmlns:log4php          CDATA #FIXED "http://www.vxr.it/log4php/" 
  version                (0.2|0.3) "0.3" 
  includesLocationInfo   (true|false) "true"
>

<!ELEMENT log4php:event (log4php:message, log4php:locationInfo?) >

<!-- The timestamp format is application dependent. -->
<!ATTLIST log4php:event
    logger     CDATA #REQUIRED
    level      CDATA #REQUIRED
    thread     CDATA #REQUIRED
    timestamp  CDATA #REQUIRED
>

<!ELEMENT log4php:message (#PCDATA)>
<!ELEMENT log4php:NDC (#PCDATA)>

<!ELEMENT log4php:locationInfo EMPTY>
<!ATTLIST log4php:locationInfo
  class  CDATA  #REQUIRED
  method CDATA  #REQUIRED
  file   CDATA  #REQUIRED
  line   CDATA  #REQUIRED
>
api/log4php/main/php/LoggerReflectionUtils.php0000644000004100000410000001123113466017021021731 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @package log4php
 */
 
/**
 * Provides methods for reflective use on php objects
 * @package log4php
 */
class LoggerReflectionUtils {
		/** the target object */
	private $obj;
	
	/**
	 * Create a new LoggerReflectionUtils for the specified Object. 
	 * This is done in prepartion for invoking {@link setProperty()} 
	 * one or more times.
	 * @param object &$obj the object for which to set properties
	 */
	public function __construct($obj) {
		$this->obj = $obj;
	}
	
	/**
	 * Set the properties of an object passed as a parameter in one
	 * go. The <code>properties</code> are parsed relative to a
	 * <code>prefix</code>.
	 *
	 * @param object $obj The object to configure.
	 * @param array $properties An array containing keys and values.
	 * @param string $prefix Only keys having the specified prefix will be set.
	 */
	 // TODO: check, if this is really useful
	public static function setPropertiesByObject($obj, $properties, $prefix) {
		$pSetter = new LoggerReflectionUtils($obj);
		return $pSetter->setProperties($properties, $prefix);
	}
	
	
	/**
	 * Set the properites for the object that match the
	 * <code>prefix</code> passed as parameter.
	 * 
	 * Example:
	 * 
	 * $arr['xxxname'] = 'Joe';
 	 * $arr['xxxmale'] = true;
	 * and prefix xxx causes setName and setMale.	
	 *
	 * @param array $properties An array containing keys and values.
	 * @param string $prefix Only keys having the specified prefix will be set.
	 */
	public function setProperties($properties, $prefix) {
		$len = strlen($prefix);
		reset($properties);
		while(list($key,) = each($properties)) {
			if(strpos($key, $prefix) === 0) {
				if(strpos($key, '.', ($len + 1)) > 0) {
					continue;
				}
				$value = $properties[$key];
				$key = substr($key, $len);
				if($key == 'layout' and ($this->obj instanceof LoggerAppender)) {
					continue;
				}
				$this->setProperty($key, $value);
			}
		}
		$this->activate();
	}
	
	/**
	 * Set a property on this PropertySetter's Object. If successful, this
	 * method will invoke a setter method on the underlying Object. The
	 * setter is the one for the specified property name and the value is
	 * determined partly from the setter argument type and partly from the
	 * value specified in the call to this method.
	 *
	 * <p>If the setter expects a String no conversion is necessary.
	 * If it expects an int, then an attempt is made to convert 'value'
	 * to an int using new Integer(value). If the setter expects a boolean,
	 * the conversion is by new Boolean(value).
	 *
	 * @param string $name	name of the property
	 * @param string $value	String value of the property
	 */
	public function setProperty($name, $value) {
		if($value === null) {
			return;
		}
		
		$method = "set" . ucfirst($name);
		
		if(!method_exists($this->obj, $method)) {
			throw new Exception("Error setting log4php property $name to $value: no method $method in class ".get_class($this->obj)."!");
		} else {
			return call_user_func(array($this->obj, $method), $value);
		} 
	}
	
	public function activate() {
		if(method_exists($this->obj, 'activateoptions')) {
			return call_user_func(array($this->obj, 'activateoptions'));
		} 
	}
	
	/**
	 * Creates an instances from the given class name.
	 *
	 * @param string $classname
	 * @return an object from the class with the given classname
	 */
	public static function createObject($class) {
		if(!empty($class)) {
			return new $class();
		}
		return null;
	}
	
	/**
	 * @param object $object
	 * @param string $name
	 * @param mixed $value
	 */
	public static function setter($object, $name, $value) {
		if (empty($name)) {
			return false;
		}
		$methodName = 'set'.ucfirst($name);
		if (method_exists($object, $methodName)) {
			return call_user_func(array($object, $methodName), $value);
		} else {
			return false;
		}
	}
	
}
api/log4php/main/php/renderers/0000755000004100000410000000000013466017021016740 5ustar  www-datawww-dataapi/log4php/main/php/renderers/LoggerRendererException.php0000644000004100000410000000223313466017021024236 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Renderer used for Exceptions.
 *
 * @package log4php
 * @subpackage renderers
 * @since 2.1
 */
class LoggerRendererException implements LoggerRenderer {

	public function render($input) {
		
		// Exception class has a very decent __toString method
		// so let's just use that instead of writing lots of code.
		return (string) $input; 
	}
}
api/log4php/main/php/renderers/LoggerRendererDefault.php0000644000004100000410000000226713466017021023673 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * The default renderer, which is used when no other renderer is found.
 * 
 * Renders the input using <var>print_r</var>.
 *
 * @package log4php
 * @subpackage renderers
 * @since 0.3
 */
class LoggerRendererDefault implements LoggerRenderer {

	/** @inheritdoc */
	public function render($input) {
		return print_r($input, true);
	}
}
api/log4php/main/php/renderers/LoggerRendererMap.php0000644000004100000410000001244513466017021023023 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Manages defined renderers and determines which renderer to use for a given 
 * input. 
 *
 * @version $Revision: 1394956 $
 * @package log4php
 * @subpackage renderers
 * @since 0.3
 */
class LoggerRendererMap {

	/**
	 * Maps class names to appropriate renderers.
	 * @var array
	 */
	private $map = array();

	/**
	 * The default renderer to use if no specific renderer is found. 
	 * @var LoggerRenderer
	 */
	private $defaultRenderer;
	
	public function __construct() {
		
		// Set default config
		$this->reset();
	}

	/**
	 * Adds a renderer to the map.
	 * 
	 * If a renderer already exists for the given <var>$renderedClass</var> it 
	 * will be overwritten without warning.
	 *
	 * @param string $renderedClass The name of the class which will be 
	 * 		rendered by the renderer.
	 * @param string $renderingClass The name of the class which will 
	 * 		perform the rendering.
	 */
	public function addRenderer($renderedClass, $renderingClass) {
		// Check the rendering class exists
		if (!class_exists($renderingClass)) {
			trigger_error("log4php: Failed adding renderer. Rendering class [$renderingClass] not found.");
			return;
		}
		
		// Create the instance
		$renderer = new $renderingClass();
		
		// Check the class implements the right interface
		if (!($renderer instanceof LoggerRenderer)) {
			trigger_error("log4php: Failed adding renderer. Rendering class [$renderingClass] does not implement the LoggerRenderer interface.");
			return;
		}
		
		// Convert to lowercase since class names in PHP are not case sensitive
		$renderedClass = strtolower($renderedClass);
		
		$this->map[$renderedClass] = $renderer;
	}
	
	/**
	 * Sets a custom default renderer class.
	 * 
	 * TODO: there's code duplication here. This method is almost identical to 
	 * addRenderer(). However, it has custom error messages so let it sit for 
	 * now.
	 *
	 * @param string $renderingClass The name of the class which will 
	 * 		perform the rendering.
	 */
	public function setDefaultRenderer($renderingClass) {
		// Check the class exists
		if (!class_exists($renderingClass)) {
			trigger_error("log4php: Failed setting default renderer. Rendering class [$renderingClass] not found.");
			return;
		}
		
		// Create the instance
		$renderer = new $renderingClass();
		
		// Check the class implements the right interface
		if (!($renderer instanceof LoggerRenderer)) {
			trigger_error("log4php: Failed setting default renderer. Rendering class [$renderingClass] does not implement the LoggerRenderer interface.");
			return;
		}
		
		$this->defaultRenderer = $renderer;
	}
	
	/**
	 * Returns the default renderer.
	 * @var LoggerRenderer
	 */
	public function getDefaultRenderer() {
		return $this->defaultRenderer;
	}
	
	/**
	 * Finds the appropriate renderer for the given <var>input</var>, and 
	 * renders it (i.e. converts it to a string). 
	 *
	 * @param mixed $input Input to render.
	 * @return string The rendered contents.
	 */
	public function findAndRender($input) {
		if ($input === null) {
			return null;
		}
		
		// For objects, try to find a renderer in the map
		if(is_object($input)) {
			$renderer = $this->getByClassName(get_class($input));
			if (isset($renderer)) {
				return $renderer->render($input);
			}
		}
		
		// Fall back to the default renderer
		return $this->defaultRenderer->render($input);
	}

	/**
	 * Returns the appropriate renderer for a given object.
	 * 
	 * @param mixed $object
	 * @return LoggerRenderer Or null if none found.
	 */
	public function getByObject($object) {
		if (!is_object($object)) {
			return null;
		}
		return $this->getByClassName(get_class($object));
	}
	
	/**
	 * Returns the appropriate renderer for a given class name.
	 * 
	 * If no renderer could be found, returns NULL.
	 *
	 * @param string $class
	 * @return LoggerRendererObject Or null if not found.
	 */
	public function getByClassName($class) {
		for(; !empty($class); $class = get_parent_class($class)) {
			$class = strtolower($class);
			if(isset($this->map[$class])) {
				return $this->map[$class];
			}
		}
		return null;
	}

	/** Empties the renderer map. */
	public function clear() {
		$this->map = array();
	}
	
	/** Resets the renderer map to it's default configuration. */
	public function reset() {
		$this->defaultRenderer = new LoggerRendererDefault();
		$this->clear();
		$this->addRenderer('Exception', 'LoggerRendererException');
	}
}
api/log4php/main/php/renderers/LoggerRenderer.php0000644000004100000410000000235113466017021022360 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Implement this interface in order to render objects to strings.
 *
 * @version $Revision: 1394956 $
 * @package log4php
 * @subpackage renderers
 * @since 0.3
 */
interface LoggerRenderer {
	/**
	 * Renders the entity passed as <var>input</var> to a string.
	 * @param mixed $input The entity to render.
	 * @return string The rendered string.
	 */
	public function render($input);
}
api/log4php/main/php/LoggerHierarchy.php0000644000004100000410000001652413466017021020546 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * This class is specialized in retrieving loggers by name and also maintaining 
 * the logger hierarchy. The logger hierarchy is dealing with the several Log-Levels
 * Logger can have. From log4j website:
 * 
 * "A logger is said to be an ancestor of another logger if its name followed 
 * by a dot is a prefix of the descendant logger name. A logger is said to be
 * a parent of a child logger if there are no ancestors between itself and the 
 * descendant logger."
 * 
 * Child Loggers do inherit their Log-Levels from their Ancestors. They can
 * increase their Log-Level compared to their Ancestors, but they cannot decrease it.
 * 
 * <p>The casual user does not have to deal with this class directly.</p>
 *
 * <p>The structure of the logger hierarchy is maintained by the
 * getLogger method. The hierarchy is such that children link
 * to their parent but parents do not have any pointers to their
 * children. Moreover, loggers can be instantiated in any order, in
 * particular descendant before ancestor.</p>
 *
 * <p>In case a descendant is created before a particular ancestor,
 * then it creates a provision node for the ancestor and adds itself
 * to the provision node. Other descendants of the same ancestor add
 * themselves to the previously created provision node.</p>
 *
 * @version $Revision: 1394956 $
 * @package log4php
 */
class LoggerHierarchy {
	
	/** Array holding all Logger instances. */
	protected $loggers = array();
	
	/** 
	 * The root logger.
	 * @var RootLogger 
	 */
	protected $root;
	
	/** 
	 * The logger renderer map.
	 * @var LoggerRendererMap 
	 */
	protected $rendererMap;

	/** 
	 * Main level threshold. Events with lower level will not be logged by any 
	 * logger, regardless of it's configuration.
	 * @var LoggerLevel 
	 */
	protected $threshold;
	
	/**
	 * Creates a new logger hierarchy.
	 * @param LoggerRoot $root The root logger.
	 */
	public function __construct(LoggerRoot $root) {
		$this->root = $root;
		$this->setThreshold(LoggerLevel::getLevelAll());
		$this->rendererMap = new LoggerRendererMap();
	}
	 
	/**
	 * Clears all loggers.
	 */
	public function clear() {
		$this->loggers = array();
	}
	
	/**
	 * Check if the named logger exists in the hierarchy.
	 * @param string $name
	 * @return boolean
	 */
	public function exists($name) {
		return isset($this->loggers[$name]);
	}

	/**
	 * Returns all the currently defined loggers in this hierarchy as an array.
	 * @return array
	 */	 
	public function getCurrentLoggers() {
		return array_values($this->loggers);
	}
	
	/**
	 * Returns a named logger instance logger. If it doesn't exist, one is created.
	 * 
	 * @param string $name Logger name
	 * @return Logger Logger instance.
	 */
	public function getLogger($name) {
		if(!isset($this->loggers[$name])) {
			$logger = new Logger($name);

			$nodes = explode('.', $name);
			$firstNode = array_shift($nodes);
			
			// if name is not a first node but another first node is their
			if($firstNode != $name and isset($this->loggers[$firstNode])) {
				$logger->setParent($this->loggers[$firstNode]);
			} else {
				// if there is no father, set root logger as father
				$logger->setParent($this->root);
			} 
		
			// if there are more nodes than one
			if(count($nodes) > 0) {
				// find parent node
				foreach($nodes as $node) {
					$parentNode = "$firstNode.$node";
					if(isset($this->loggers[$parentNode]) and $parentNode != $name) {
						$logger->setParent($this->loggers[$parentNode]);
					}
					$firstNode .= ".$node";
				}
			}
			
			$this->loggers[$name] = $logger;
		}		
		
		return $this->loggers[$name];
	} 
	
	/**
	 * Returns the logger renderer map.
	 * @return LoggerRendererMap 
	 */
	public function getRendererMap() {
		return $this->rendererMap;
	}
	
	/**
	 * Returns the root logger.
	 * @return LoggerRoot
	 */ 
	public function getRootLogger() {
		return $this->root;
	}
	 
	/**
	 * Returns the main threshold level.
	 * @return LoggerLevel 
	 */
	public function getThreshold() {
		return $this->threshold;
	} 

	/**
	 * Returns true if the hierarchy is disabled for given log level and false
	 * otherwise.
	 * @return boolean
	 */
	public function isDisabled(LoggerLevel $level) {
		return ($this->threshold->toInt() > $level->toInt());
	}
	
	/**
	 * Reset all values contained in this hierarchy instance to their
	 * default. 
	 *
	 * This removes all appenders from all loggers, sets
	 * the level of all non-root loggers to <i>null</i>,
	 * sets their additivity flag to <i>true</i> and sets the level
	 * of the root logger to {@link LOGGER_LEVEL_DEBUG}.
	 * 
	 * <p>Existing loggers are not removed. They are just reset.
	 *
	 * <p>This method should be used sparingly and with care as it will
	 * block all logging until it is completed.</p>
	 */
	public function resetConfiguration() {
		$root = $this->getRootLogger();
		
		$root->setLevel(LoggerLevel::getLevelDebug());
		$this->setThreshold(LoggerLevel::getLevelAll());
		$this->shutDown();
		
		foreach($this->loggers as $logger) {
			$logger->setLevel(null);
			$logger->setAdditivity(true);
			$logger->removeAllAppenders();
		}
		
		$this->rendererMap->reset();
		LoggerAppenderPool::clear();
	}
	
	/**
	 * Sets the main threshold level.
	 * @param LoggerLevel $l
	 */
	public function setThreshold(LoggerLevel $threshold) {
		$this->threshold = $threshold;
	}
	
	/**
	 * Shutting down a hierarchy will <i>safely</i> close and remove
	 * all appenders in all loggers including the root logger.
	 * 
	 * The shutdown method is careful to close nested
	 * appenders before closing regular appenders. This is allows
	 * configurations where a regular appender is attached to a logger
	 * and again to a nested appender.
	 * 
	 * @todo Check if the last paragraph is correct.
	 */
	public function shutdown() {
		$this->root->removeAllAppenders();
		
		foreach($this->loggers as $logger) {
			$logger->removeAllAppenders();
		}
	}
	
	/**
	 * Prints the current Logger hierarchy tree. Useful for debugging.
	 */
	public function printHierarchy() {
		$this->printHierarchyInner($this->getRootLogger(), 0);
	}
	
	private function printHierarchyInner(Logger $current, $level) {
		for ($i = 0; $i < $level; $i++) {
			echo ($i == $level - 1) ? "|--" : "|  ";
		}
		echo $current->getName() . "\n";
		
		foreach($this->loggers as $logger) {
			if ($logger->getParent() == $current) {
				$this->printHierarchyInner($logger, $level + 1);
			}
		}
	}
} 
api/log4php/main/php/LoggerThrowableInformation.php0000644000004100000410000000337713466017021022767 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * The internal representation of throwables.
 *
 * @package log4php
 * @since 2.1
 */
class LoggerThrowableInformation {
	
	/** @var Exception Throwable to log */
	private $throwable;
	
	/** @var array Array of throwable messages */
	private $throwableArray;
	
	/**
	 * Create a new instance
	 * 
	 * @param $throwable - a throwable as a exception
	 * @param $logger - Logger reference
	 */
	public function __construct(Exception $throwable) {
		$this->throwable = $throwable;
	}
	
	/**
	* Return source exception
	* 
	* @return Exception
	*/
	public function getThrowable() {
		return $this->throwable;
	}
	
	/**
	 * @desc Returns string representation of throwable
	 * 
	 * @return array 
	 */
	public function getStringRepresentation() {
		if (!is_array($this->throwableArray)) {
			$renderer = new LoggerRendererException();
			
			$this->throwableArray = explode("\n", $renderer->render($this->throwable));
		}
		
		return $this->throwableArray;
	}
}
api/log4php/main/php/LoggerLoggingEvent.php0000644000004100000410000002333713466017021021220 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * The internal representation of logging event.
 *
 * @version $Revision: 1382273 $
 * @package log4php
 */
class LoggerLoggingEvent {

	private static $startTime;

	/** 
	* @var string Fully Qualified Class Name of the calling category class.
	*/
	private $fqcn;
	
	/**
	* @var Logger reference
	*/
	private $logger;
	
	/** 
	 * The category (logger) name.
	 * This field will be marked as private in future
	 * releases. Please do not access it directly. 
	 * Use the {@link getLoggerName()} method instead.
	 * @deprecated 
	 */
	private $categoryName;
	
	/** 
	 * Level of the logging event.
	 * @var LoggerLevel
	 */
	protected $level;
	
	/** 
	 * The nested diagnostic context (NDC) of logging event.
	 * @var string  
	 */
	private $ndc;
	
	/** 
	 * Have we tried to do an NDC lookup? If we did, there is no need
	 * to do it again.	Note that its value is always false when
	 * serialized. Thus, a receiving SocketNode will never use it's own
	 * (incorrect) NDC. See also writeObject method.
	 * @var boolean
	 */
	private $ndcLookupRequired = true;
	
	/** 
	 * @var mixed The application supplied message of logging event. 
	 */
	private $message;
	
	/** 
	 * The application supplied message rendered through the log4php
	 * objet rendering mechanism. At present renderedMessage == message.
	 * @var string
	 */
	private $renderedMessage;
	
	/** 
	 * The name of thread in which this logging event was generated.
	 * log4php saves here the process id via {@link PHP_MANUAL#getmypid getmypid()} 
	 * @var mixed
	 */
	private $threadName;
	
	/** 
	* The number of seconds elapsed from 1/1/1970 until logging event
	* was created plus microseconds if available.
	* @var float
	*/
	public $timeStamp;
	
	/** 
	* @var LoggerLocationInfo Location information for the caller. 
	*/
	private $locationInfo;
	
	/**
	 * @var LoggerThrowableInformation log4php internal representation of throwable
	 */
	private $throwableInfo;
	
	/**
	* Instantiate a LoggingEvent from the supplied parameters.
	*
	* Except {@link $timeStamp} all the other fields of
	* LoggerLoggingEvent are filled when actually needed.
	*
	* @param string $fqcn name of the caller class.
	* @param mixed $logger The {@link Logger} category of this event or the logger name.
	* @param LoggerLevel $level The level of this event.
	* @param mixed $message The message of this event.
	* @param integer $timeStamp the timestamp of this logging event.
	* @param Exception $throwable The throwable associated with logging event
	*/
	public function __construct($fqcn, $logger, LoggerLevel $level, $message, $timeStamp = null, $throwable = null) {
		$this->fqcn = $fqcn;
		if($logger instanceof Logger) {
			$this->logger = $logger;
			$this->categoryName = $logger->getName();
		} else {
			$this->categoryName = strval($logger);
		}
		$this->level = $level;
		$this->message = $message;
		if($timeStamp !== null && is_numeric($timeStamp)) {
			$this->timeStamp = $timeStamp;
		} else {
			$this->timeStamp = microtime(true);
		}
		
		if ($throwable !== null && $throwable instanceof Exception) {
			$this->throwableInfo = new LoggerThrowableInformation($throwable);
		}
	}

	/**
	 * Returns the full qualified classname.
	 * TODO: PHP does contain namespaces in 5.3. Those should be returned too, 
	 */
	 public function getFullQualifiedClassname() {
		 return $this->fqcn;
	 }
	 
	/**
	 * Set the location information for this logging event. The collected
	 * information is cached for future use.
	 *
	 * <p>This method uses {@link PHP_MANUAL#debug_backtrace debug_backtrace()} function (if exists)
	 * to collect informations about caller.</p>
	 * <p>It only recognize informations generated by {@link Logger} and its subclasses.</p>
	 * @return LoggerLocationInfo
	 */
	public function getLocationInformation() {
		if($this->locationInfo === null) {

			$locationInfo = array();
			$trace = debug_backtrace();
			$prevHop = null;
			// make a downsearch to identify the caller
			$hop = array_pop($trace);
			while($hop !== null) {
				if(isset($hop['class'])) {
					// we are sometimes in functions = no class available: avoid php warning here
					$className = strtolower($hop['class']);
					if(!empty($className) and ($className == 'logger' or 
						strtolower(get_parent_class($className)) == 'logger')) {
						$locationInfo['line'] = $hop['line'];
						$locationInfo['file'] = $hop['file'];
						break;
					}
				}
				$prevHop = $hop;
				$hop = array_pop($trace);
			}
			$locationInfo['class'] = isset($prevHop['class']) ? $prevHop['class'] : 'main';
			if(isset($prevHop['function']) and
				$prevHop['function'] !== 'include' and
				$prevHop['function'] !== 'include_once' and
				$prevHop['function'] !== 'require' and
				$prevHop['function'] !== 'require_once') {

				$locationInfo['function'] = $prevHop['function'];
			} else {
				$locationInfo['function'] = 'main';
			}
					 
			$this->locationInfo = new LoggerLocationInfo($locationInfo, $this->fqcn);
		}
		return $this->locationInfo;
	}

	/**
	 * Return the level of this event. Use this form instead of directly
	 * accessing the {@link $level} field.
	 * @return LoggerLevel	
	 */
	public function getLevel() {
		return $this->level;
	}

	/**
	 * Returns the logger which created the event.
	 * @return Logger
	 */
	public function getLogger() {
		return $this->logger;
	}
	
	/**
	 * Return the name of the logger. Use this form instead of directly
	 * accessing the {@link $categoryName} field.
	 * @return string  
	 */
	public function getLoggerName() {
		return $this->categoryName;
	}

	/**
	 * Return the message for this logging event.
	 * @return mixed
	 */
	public function getMessage() {
		return $this->message;
	}

	/**
	 * This method returns the NDC for this event. It will return the
	 * correct content even if the event was generated in a different
	 * thread or even on a different machine. The {@link LoggerNDC::get()} method
	 * should <b>never</b> be called directly.
	 * @return string  
	 */
	public function getNDC() {
		if($this->ndcLookupRequired) {
			$this->ndcLookupRequired = false;
			$this->ndc = LoggerNDC::get();
		}
		return $this->ndc;
	}

	/**
	 * Returns the the context corresponding to the <code>key</code>
	 * parameter.
	 * @return string
	 */
	public function getMDC($key) {
		return LoggerMDC::get($key);
	}
	
	/**
	 * Returns the entire MDC context.
	 * @return array
	 */
	public function getMDCMap () {
		return LoggerMDC::getMap();
	}

	/**
	 * Render message.
	 * @return string
	 */
	public function getRenderedMessage() {
		if($this->renderedMessage === null and $this->message !== null) {
			if(is_string($this->message)) {
				$this->renderedMessage = $this->message;
			} else {
				$rendererMap = Logger::getHierarchy()->getRendererMap();
				$this->renderedMessage= $rendererMap->findAndRender($this->message);
			}
		}
		return $this->renderedMessage;
	}

	/**
	 * Returns the time when the application started, as a UNIX timestamp 
	 * with microseconds.
	 * @return float
	 */
	public static function getStartTime() {
		if(!isset(self::$startTime)) {
			self::$startTime = microtime(true);
		}
		return self::$startTime; 
	}

	/**
	 * @return float
	 */
	public function getTimeStamp() {
		return $this->timeStamp;
	}
	
	/**
	 * Returns the time in seconds passed from the beginning of execution to 
	 * the time the event was constructed.
	 * 
	 * @return float Seconds with microseconds in decimals.
	 */
	public function getRelativeTime() {
		return $this->timeStamp - self::$startTime;
	}
	
	/**
	 * Returns the time in milliseconds passed from the beginning of execution
	 * to the time the event was constructed.
	 * 
	 * @deprecated This method has been replaced by getRelativeTime which 
	 * 		does not perform unneccesary multiplication and formatting.
	 * 
	 * @return integer 
	 */
	public function getTime() {
		$eventTime = $this->getTimeStamp();
		$eventStartTime = LoggerLoggingEvent::getStartTime();
		return number_format(($eventTime - $eventStartTime) * 1000, 0, '', '');
	}
	
	/**
	 * @return mixed
	 */
	public function getThreadName() {
		if ($this->threadName === null) {
			$this->threadName = (string)getmypid();
		}
		return $this->threadName;
	}

	/**
	 * @return mixed LoggerThrowableInformation
	 */
	public function getThrowableInformation() {
		return $this->throwableInfo;
	}
	
	/**
	 * Serialize this object
	 * @return string
	 */
	public function toString() {
		serialize($this);
	}
	
	/**
	 * Avoid serialization of the {@link $logger} object
	 */
	public function __sleep() {
		return array(
			'fqcn',
			'categoryName',
			'level',
			'ndc',
			'ndcLookupRequired',
			'message',
			'renderedMessage',
			'threadName',
			'timeStamp',
			'locationInfo',
		);
	}

}

LoggerLoggingEvent::getStartTime();
api/log4php/main/php/filters/0000755000004100000410000000000013466017021016417 5ustar  www-datawww-dataapi/log4php/main/php/filters/LoggerFilterLevelRange.php0000644000004100000410000001033013466017021023457 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * This is a very simple filter based on level matching, which can be
 * used to reject messages with priorities outside a certain range.
 *	
 * <p>The filter admits three options <b><var>LevelMin</var></b>, <b><var>LevelMax</var></b>
 * and <b><var>AcceptOnMatch</var></b>.</p>
 *
 * <p>If the level of the {@link LoggerLoggingEvent} is not between Min and Max
 * (inclusive), then {@link LoggerFilter::DENY} is returned.</p>
 *	
 * <p>If the Logging event level is within the specified range, then if
 * <b><var>AcceptOnMatch</var></b> is <i>true</i>, 
 * {@link LoggerFilter::ACCEPT} is returned, and if
 * <b><var>AcceptOnMatch</var></b> is <i>false</i>, 
 * {@link LoggerFilter::NEUTRAL} is returned.</p>
 *	
 * <p>If <b><var>LevelMin</var></b> is not defined, then there is no
 * minimum acceptable level (i.e. a level is never rejected for
 * being too "low"/unimportant).  If <b><var>LevelMax</var></b> is not
 * defined, then there is no maximum acceptable level (ie a
 * level is never rejected for being too "high"/important).</p>
 *
 * <p>Refer to the {@link LoggerAppender::setThreshold()} method
 * available to <b>all</b> appenders extending {@link LoggerAppender} 
 * for a more convenient way to filter out events by level.</p>
 *
 * <p>
 * An example for this filter:
 * 
 * {@example ../../examples/php/filter_levelrange.php 19}
 *
 * <p>
 * The corresponding XML file:
 * 
 * {@example ../../examples/resources/filter_levelrange.xml 18}
 *
 * @author Simon Kitching
 * @author based on the org.apache.log4j.varia.LevelRangeFilte Java code by Ceki G&uuml;lc&uuml; 
 *
 * @version $Revision: 1213283 $
 * @package log4php
 * @subpackage filters
 * @since 0.6
 */
class LoggerFilterLevelRange extends LoggerFilter {

	/**
	 * @var boolean
	 */
	protected $acceptOnMatch = true;

	/**
	 * @var LoggerLevel
	 */
	protected $levelMin;
  
	/**
	 * @var LoggerLevel
	 */
	protected $levelMax;

	/**
	 * @param boolean $acceptOnMatch
	 */
	public function setAcceptOnMatch($acceptOnMatch) {
		$this->setBoolean('acceptOnMatch', $acceptOnMatch); 
	}
	
	/**
	 * @param string $l the level min to match
	 */
	public function setLevelMin($level) {
		$this->setLevel('levelMin', $level);
	}

	/**
	 * @param string $l the level max to match
	 */
	public function setLevelMax($level) {
		$this->setLevel('levelMax', $level);
	}

	/**
	 * Return the decision of this filter.
	 *
	 * @param LoggerLoggingEvent $event
	 * @return integer
	 */
	public function decide(LoggerLoggingEvent $event) {
		$level = $event->getLevel();
		
		if($this->levelMin !== null) {
			if($level->isGreaterOrEqual($this->levelMin) == false) {
				// level of event is less than minimum
				return LoggerFilter::DENY;
			}
		}

		if($this->levelMax !== null) {
			if($level->toInt() > $this->levelMax->toInt()) {
				// level of event is greater than maximum
				// Alas, there is no Level.isGreater method. and using
				// a combo of isGreaterOrEqual && !Equal seems worse than
				// checking the int values of the level objects..
				return LoggerFilter::DENY;
			}
		}

		if($this->acceptOnMatch) {
			// this filter set up to bypass later filters and always return
			// accept if level in range
			return LoggerFilter::ACCEPT;
		} else {
			// event is ok for this filter; allow later filters to have a look..
			return LoggerFilter::NEUTRAL;
		}
	}
}
api/log4php/main/php/filters/LoggerFilterLevelMatch.php0000644000004100000410000000633213466017021023466 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * This is a very simple filter based on level matching.
 *
 * <p>The filter admits two options <b><var>LevelToMatch</var></b> and
 * <b><var>AcceptOnMatch</var></b>. If there is an exact match between the value
 * of the <b><var>LevelToMatch</var></b> option and the level of the 
 * {@link LoggerLoggingEvent}, then the {@link decide()} method returns 
 * {@link LoggerFilter::ACCEPT} in case the <b><var>AcceptOnMatch</var></b> 
 * option value is set to <i>true</i>, if it is <i>false</i> then 
 * {@link LoggerFilter::DENY} is returned. If there is no match, 
 * {@link LoggerFilter::NEUTRAL} is returned.</p>
 * 
 * <p>
 * An example for this filter:
 * 
 * {@example ../../examples/php/filter_levelmatch.php 19}
 *
 * <p>
 * The corresponding XML file:
 * 
 * {@example ../../examples/resources/filter_levelmatch.xml 18}
 * 
 * @version $Revision: 1213283 $
 * @package log4php
 * @subpackage filters
 * @since 0.6
 */
class LoggerFilterLevelMatch extends LoggerFilter {
  
	/** 
	 * Indicates if this event should be accepted or denied on match
	 * @var boolean
	 */
	protected $acceptOnMatch = true;

	/**
	 * The level, when to match
	 * @var LoggerLevel
	 */
	protected $levelToMatch;
  
	/**
	 * @param boolean $acceptOnMatch
	 */
	public function setAcceptOnMatch($acceptOnMatch) {
		$this->setBoolean('acceptOnMatch', $acceptOnMatch);
	}
	
	/**
	 * @param string $l the level to match
	 */
	public function setLevelToMatch($level) {
		$this->setLevel('levelToMatch', $level);
	}

	/**
	 * Return the decision of this filter.
	 * 
	 * Returns {@link LoggerFilter::NEUTRAL} if the <b><var>LevelToMatch</var></b>
	 * option is not set or if there is not match.	Otherwise, if there is a
	 * match, then the returned decision is {@link LoggerFilter::ACCEPT} if the
	 * <b><var>AcceptOnMatch</var></b> property is set to <i>true</i>. The
	 * returned decision is {@link LoggerFilter::DENY} if the
	 * <b><var>AcceptOnMatch</var></b> property is set to <i>false</i>.
	 *
	 * @param LoggerLoggingEvent $event
	 * @return integer
	 */
	public function decide(LoggerLoggingEvent $event) {
		if($this->levelToMatch === null) {
			return LoggerFilter::NEUTRAL;
		}
		
		if($this->levelToMatch->equals($event->getLevel())) {	
			return $this->acceptOnMatch ? LoggerFilter::ACCEPT : LoggerFilter::DENY;
		} else {
			return LoggerFilter::NEUTRAL;
		}
	}
}
api/log4php/main/php/filters/LoggerFilterDenyAll.php0000644000004100000410000000352613466017021022774 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * This filter drops all logging events. 
 * 
 * You can add this filter to the end of a filter chain to
 * switch from the default "accept all unless instructed otherwise"
 * filtering behaviour to a "deny all unless instructed otherwise"
 * behaviour.
 * 
 * <p>
 * An example for this filter:
 * 
 * {@example ../../examples/php/filter_denyall.php 19}
 *
 * <p>
 * The corresponding XML file:
 * 
 * {@example ../../examples/resources/filter_denyall.xml 18}
 *
 * @version $Revision: 883108 $
 * @package log4php
 * @subpackage filters
 * @since 0.3
 */
class LoggerFilterDenyAll extends LoggerFilter {

	/**
	 * Always returns the integer constant {@link LoggerFilter::DENY}
	 * regardless of the {@link LoggerLoggingEvent} parameter.
	 * 
	 * @param LoggerLoggingEvent $event The {@link LoggerLoggingEvent} to filter.
	 * @return LoggerFilter::DENY Always returns {@link LoggerFilter::DENY}
	 */
	public function decide(LoggerLoggingEvent $event) {
		return LoggerFilter::DENY;
	}
}
api/log4php/main/php/filters/LoggerFilterStringMatch.php0000644000004100000410000000533313466017021023665 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * This is a very simple filter based on string matching.
 * 
 * <p>The filter admits two options {@link $stringToMatch} and
 * {@link $acceptOnMatch}. If there is a match (using {@link PHP_MANUAL#strpos}
 * between the value of the {@link $stringToMatch} option and the message 
 * of the {@link LoggerLoggingEvent},
 * then the {@link decide()} method returns {@link LoggerFilter::ACCEPT} if
 * the <b>AcceptOnMatch</b> option value is true, if it is false then
 * {@link LoggerFilter::DENY} is returned. If there is no match, {@link LoggerFilter::NEUTRAL}
 * is returned.</p>
 * 
 * <p>
 * An example for this filter:
 * 
 * {@example ../../examples/php/filter_stringmatch.php 19}
 *
 * <p>
 * The corresponding XML file:
 * 
 * {@example ../../examples/resources/filter_stringmatch.xml 18}
 *
 * @version $Revision: 1213283 $
 * @package log4php
 * @subpackage filters
 * @since 0.3
 */
class LoggerFilterStringMatch extends LoggerFilter {

	/**
	 * @var boolean
	 */
	protected $acceptOnMatch = true;

	/**
	 * @var string
	 */
	protected $stringToMatch;

	/**
	 * @param mixed $acceptOnMatch a boolean or a string ('true' or 'false')
	 */
	public function setAcceptOnMatch($acceptOnMatch) {
		$this->setBoolean('acceptOnMatch', $acceptOnMatch);
	}
	
	/**
	 * @param string $s the string to match
	 */
	public function setStringToMatch($string) {
		$this->setString('stringToMatch', $string);
	}

	/**
	 * @return integer a {@link LOGGER_FILTER_NEUTRAL} is there is no string match.
	 */
	public function decide(LoggerLoggingEvent $event) {
		$msg = $event->getRenderedMessage();
		
		if($msg === null or $this->stringToMatch === null) {
			return LoggerFilter::NEUTRAL;
		}
		
		if(strpos($msg, $this->stringToMatch) !== false ) {
			return ($this->acceptOnMatch) ? LoggerFilter::ACCEPT : LoggerFilter::DENY;
		}
		return LoggerFilter::NEUTRAL;
	}
}
api/log4php/main/php/helpers/0000755000004100000410000000000013466017021016411 5ustar  www-datawww-dataapi/log4php/main/php/helpers/LoggerPatternParser.php0000644000004100000410000001651113466017021023060 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Most of the work of the {@link LoggerPatternLayout} class 
 * is delegated to the {@link LoggerPatternParser} class.
 * 
 * <p>It is this class that parses conversion patterns and creates
 * a chained list of {@link LoggerPatternConverter} converters.</p>
 * 
 * @version $Revision: 1395467 $ 
 * @package log4php
 * @subpackage helpers
 *
 * @since 0.3
 */
class LoggerPatternParser {

	/** Escape character for conversion words in the conversion pattern. */
	const ESCAPE_CHAR = '%';
	
	/** Maps conversion words to relevant converters. */
	private $converterMap;
	
	/** Conversion pattern used in layout. */
	private $pattern;
	
	/** Regex pattern used for parsing the conversion pattern. */
	private $regex;
	
	/** 
	 * First converter in the chain. 
	 * @var LoggerPatternConverter
	 */
	private $head;
	
	/** Last converter in the chain. */
	private $tail;
	
	public function __construct($pattern, $converterMap) {
		$this->pattern = $pattern;
		$this->converterMap = $converterMap;
		
		// Construct the regex pattern
		$this->regex = 
			'/' .                       // Starting regex pattern delimiter
			self::ESCAPE_CHAR .         // Character which marks the start of the conversion pattern
			'(?P<modifiers>[0-9.-]*)' . // Format modifiers (optional)
			'(?P<word>[a-zA-Z]+)' .     // The conversion word
			'(?P<option>{[^}]*})?' .    // Conversion option in braces (optional)
			'/';                        // Ending regex pattern delimiter
	}
	
	/** 
	 * Parses the conversion pattern string, converts it to a chain of pattern
	 * converters and returns the first converter in the chain.
	 * 
	 * @return LoggerPatternConverter
	 */
	public function parse() {
		
		// Skip parsing if the pattern is empty
		if (empty($this->pattern)) {
			$this->addLiteral('');
			return $this->head;
		}
		
		// Find all conversion words in the conversion pattern
		$count = preg_match_all($this->regex, $this->pattern, $matches, PREG_OFFSET_CAPTURE);
		if ($count === false) {
			$error = error_get_last();
			throw new LoggerException("Failed parsing layotut pattern: {$error['message']}");
		}
		
		$prevEnd = 0;
		
		foreach($matches[0] as $key => $item) {
			
			// Locate where the conversion command starts and ends
			$length = strlen($item[0]);
			$start = $item[1];
			$end = $item[1] + $length;
		
			// Find any literal expressions between matched commands
			if ($start > $prevEnd) {
				$literal = substr($this->pattern, $prevEnd, $start - $prevEnd);
				$this->addLiteral($literal);
			}
			
			// Extract the data from the matched command
			$word = !empty($matches['word'][$key]) ? $matches['word'][$key][0] : null;
			$modifiers = !empty($matches['modifiers'][$key]) ? $matches['modifiers'][$key][0] : null;
			$option = !empty($matches['option'][$key]) ? $matches['option'][$key][0] : null;
			
			// Create a converter and add it to the chain
			$this->addConverter($word, $modifiers, $option);
			
			$prevEnd = $end;
		}

		// Add any trailing literals
		if ($end < strlen($this->pattern)) {
			$literal = substr($this->pattern, $end);
			$this->addLiteral($literal);
		}
		
		return $this->head;
	}
	
	/** 
	 * Adds a literal converter to the converter chain. 
	 * @param string $string The string for the literal converter.
	 */
	private function addLiteral($string) {
		$converter = new LoggerPatternConverterLiteral($string);
		$this->addToChain($converter);
	}
	
	/**
	 * Adds a non-literal converter to the converter chain.
	 * 
	 * @param string $word The conversion word, used to determine which 
	 *  converter will be used.
	 * @param string $modifiers Formatting modifiers.
	 * @param string $option Option to pass to the converter.
	 */
	private function addConverter($word, $modifiers, $option) {
 		$formattingInfo = $this->parseModifiers($modifiers);
		$option = trim($option, "{} ");
		
		if (isset($this->converterMap[$word])) {
			$converter = $this->getConverter($word, $formattingInfo, $option);
			$this->addToChain($converter);	
		} else {
			trigger_error("log4php: Invalid keyword '%$word' in converison pattern. Ignoring keyword.", E_USER_WARNING);
		}
	}
	
	/**
	 * Determines which converter to use based on the conversion word. Creates 
	 * an instance of the converter using the provided formatting info and 
	 * option and returns it.
	 * 
	 * @param string $word The conversion word.
	 * @param LoggerFormattingInfo $info Formatting info.
	 * @param string $option Converter option.
	 * 
	 * @throws LoggerException 
	 * 
	 * @return LoggerPatternConverter
	 */
	private function getConverter($word, $info, $option) {
		if (!isset($this->converterMap[$word])) {
			throw new LoggerException("Invalid keyword '%$word' in converison pattern. Ignoring keyword.");
		}
		
		$converterClass = $this->converterMap[$word];
		if(!class_exists($converterClass)) {
			throw new LoggerException("Class '$converterClass' does not exist.");
		}
		
		$converter = new $converterClass($info, $option);
		if(!($converter instanceof LoggerPatternConverter)) {
			throw new LoggerException("Class '$converterClass' is not an instance of LoggerPatternConverter.");
		}
		
		return $converter;
	}
	
	/** Adds a converter to the chain and updates $head and $tail pointers. */
	private function addToChain(LoggerPatternConverter $converter) {
		if (!isset($this->head)) {
			$this->head = $converter;
			$this->tail = $this->head;
		} else {
			$this->tail->next = $converter;
			$this->tail = $this->tail->next;
		}
	}
	
	/**
	 * Parses the formatting modifiers and produces the corresponding 
	 * LoggerFormattingInfo object.
	 * 
	 * @param string $modifier
	 * @return LoggerFormattingInfo
	 * @throws LoggerException
	 */
	private function parseModifiers($modifiers) {
		$info = new LoggerFormattingInfo();
	
		// If no modifiers are given, return default values
		if (empty($modifiers)) {
			return $info;
		}
	
		// Validate
		$pattern = '/^(-?[0-9]+)?\.?-?[0-9]+$/';
		if (!preg_match($pattern, $modifiers)) {
			trigger_error("log4php: Invalid modifier in conversion pattern: [$modifiers]. Ignoring modifier.", E_USER_WARNING);
			return $info;
		}
	
		$parts = explode('.', $modifiers);
	
		if (!empty($parts[0])) {
			$minPart = (integer) $parts[0];
			$info->min = abs($minPart);
			$info->padLeft = ($minPart > 0);
		}
	
		if (!empty($parts[1])) {
			$maxPart = (integer) $parts[1];
			$info->max = abs($maxPart);
			$info->trimLeft = ($maxPart < 0);
		}
	
		return $info;
	}
}
api/log4php/main/php/helpers/LoggerFormattingInfo.php0000644000004100000410000000317013466017021023211 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * This class encapsulates the information obtained when parsing
 * formatting modifiers in conversion modifiers.
 * 
 * @package log4php
 * @subpackage helpers
 * @since 0.3
 */
class LoggerFormattingInfo {
	
	/** 
	 * Minimal output length. If output is shorter than this value, it will be
	 * padded with spaces. 
	 */
	public $min = 0;
	
	/** 
	 * Maximum output length. If output is longer than this value, it will be 
	 * trimmed.
	 */
	public $max = PHP_INT_MAX;
	
	/**
	 * Whether to pad the string from the left. If set to false, the string 
	 * will be padded from the right. 
	 */
	public $padLeft = true;
	
	/**
	 * Whether to trim the string from the left. If set to false, the string
	 * will be trimmed from the right.
	 */
	public $trimLeft = false;
}
api/log4php/main/php/helpers/LoggerUtils.php0000644000004100000410000000665713466017021021400 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Contains various helper methods.
 * 
 * @package log4php
 * @subpackage helpers
 * @since 2.3
 */
class LoggerUtils {
	
	/**
 	 * Splits a fully qualified class name into fragments delimited by the 
 	 * namespace separator (\). 
 	 * 
 	 * For backward compatibility, a dot (.) can be used as a delimiter as
 	 * well. 
	 * 
	 * @param string $name
	 * 
	 * @return array Class name split into fragments.
	 */
	public static function tokenizeClassName($name) {
		$name = str_replace('.', '\\', $name);
		$name = trim($name, ' \\');
		$fragments = explode('\\', $name);
		
		foreach($fragments as $key => $fragment) {
			if (trim($fragment) === '') {
				unset($fragments[$key]);
			}
		}
		
		return $fragments;
	}
	
	/**
	 * Attempts to shorten the given class name to the desired length.
	 * 
	 * This is done by separating the class name into fragments (delimited
	 * by \ or .) and trimming individual fragments, starting with the left,
	 * until desired length has been reached. 
	 * 
	 * The final fragment (i.e. class name) will never be shortened so the 
	 * result may still be longer than given length.
	 * 
	 * @param string $name The (qualified) class name.  
	 * @param integer $length The length to shorten to. If null or 0 is given,
	 * the name will be returned without shortening. 
	 */
	public static function shortenClassName($name, $length) {
		if ($length === null || $length < 0) {
			return $name;
		}
		
		$name = str_replace('.', '\\', $name);
		$name = trim($name, ' \\');
		
		// Check if any shortening is required
		$currentLength = strlen($name);
		if ($currentLength <= $length) {
			return $name;
		}
	
		// Split name into fragments
		$fragments = explode('\\', $name);

		// If zero length is specified, return only last fragment
		if ($length == 0) {
			return array_pop($fragments);
		}
		
		// If the name splits to only one fragment, then it cannot be shortened
		$count = count($fragments);
		if ($count == 1) {
			return $name;
		}
	
		foreach($fragments as $key => &$fragment) {
	
			// Never shorten last fragment
			if ($key == $count - 1) {
				break;
			}
	
			// Check for empty fragments (shouldn't happen but it's possible)
			$fragLen = strlen($fragment);
			if ($fragLen <= 1) {
				continue;
			}
	
			// Shorten fragment to one character and check if total length satisfactory
			$fragment = substr($fragment, 0, 1);
			$currentLength = $currentLength - $fragLen + 1;
	
			if ($currentLength <= $length) {
				break;
			}
		}
		unset($fragment);
	
		return implode('\\', $fragments);
	}
}

api/log4php/main/php/helpers/LoggerOptionConverter.php0000644000004100000410000001564713466017021023437 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * A convenience class to convert property values to specific types.
 *
 * @version $Revision: 1374617 $ 
 * @package log4php
 * @subpackage helpers
 * @since 0.5
 */
class LoggerOptionConverter {
	
	/** String values which are converted to boolean TRUE. */
	private static $trueValues = array('1', 'true', 'yes', 'on');
	
	/** 
	 * String values which are converted to boolean FALSE.
	 * 
	 * Note that an empty string must convert to false, because 
	 * parse_ini_file() which is used for parsing configuration 
	 * converts the value _false_ to an empty string.
	 */
	private static $falseValues = array('0', 'false', 'no', 'off', '');
	
	/**
	 * Read a predefined var.
	 *
	 * It returns a value referenced by <var>$key</var> using this search criteria:
	 * - if <var>$key</var> is a constant then return it. Else
	 * - if <var>$key</var> is set in <var>$_ENV</var> then return it. Else
	 * - return <var>$def</var>. 
	 *
	 * @param string $key The key to search for.
	 * @param string $def The default value to return.
	 * @return string	the string value of the system property, or the default
	 *					value if there is no property with that key.
	 */
	public static function getSystemProperty($key, $def) {
		if(defined($key)) {
			return (string)constant($key);
		} else if(isset($_SERVER[$key])) {
			return (string)$_SERVER[$key];
		} else if(isset($_ENV[$key])) {
			return (string)$_ENV[$key];
		} else {
			return $def;
		}
	}

	/** Converts $value to boolean, or throws an exception if not possible. */
	public static function toBooleanEx($value) {
		if (isset($value)) {
			if (is_bool($value)) {
				return $value;
			}
			$value = strtolower(trim($value));
			if (in_array($value, self::$trueValues)) {
				return true;
			}
			if (in_array($value, self::$falseValues)) {
				return false;
			}
		}
		
		throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to boolean.");
	}
	
	/** 
	 * Converts $value to integer, or throws an exception if not possible. 
	 * Floats cannot be converted to integer.
	 */
	public static function toIntegerEx($value) {
		if (is_integer($value)) {
			return $value;
		}
		if (is_numeric($value) && ($value == (integer) $value)) {
			return (integer) $value;
		}
	
		throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to integer.");
	}
	
	/**
	 * Converts $value to integer, or throws an exception if not possible.
	 * Floats cannot be converted to integer.
	 */
	public static function toPositiveIntegerEx($value) {
		if (is_integer($value) && $value > 0) {
			return $value;
		}
		if (is_numeric($value) && ($value == (integer) $value) && $value > 0) {
			return (integer) $value;
		}
	
		throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a positive integer.");
	}

	/** Converts the value to a level. Throws an exception if not possible. */
	public static function toLevelEx($value) {
		if ($value instanceof LoggerLevel) {
			return $value;
		}
		$level = LoggerLevel::toLevel($value);
		if ($level === null) {
			throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a logger level.");
		}
		return $level;
	}

	/**
	 * Converts a value to a valid file size (integer).
	 * 
	 * Supports 'KB', 'MB' and 'GB' suffixes, where KB = 1024 B etc. 
	 *
	 * The final value will be rounded to the nearest integer.
	 *
	 * Examples:
	 * - '100' => 100
	 * - '100.12' => 100
	 * - '100KB' => 102400
	 * - '1.5MB' => 1572864
	 * 
	 * @param mixed $value File size (optionally with suffix).
	 * @return integer Parsed file size.
	 */
	public static function toFileSizeEx($value) {
		
		if (empty($value)) {
			throw new LoggerException("Empty value cannot be converted to a file size.");
		}
		
		if (is_numeric($value)) {
			return (integer) $value;
		}
		
		if (!is_string($value)) {
			throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a file size.");
		}
		
		$str = strtoupper(trim($value));
		$count = preg_match('/^([0-9.]+)(KB|MB|GB)?$/', $str, $matches);
		
		if ($count > 0) {
			$size = $matches[1];
			$unit = $matches[2];
			
			switch($unit) {
				case 'KB': $size *= pow(1024, 1); break;
				case 'MB': $size *= pow(1024, 2); break;
				case 'GB': $size *= pow(1024, 3); break;
			}
			
			return (integer) $size;
		}
		
		throw new LoggerException("Given value [$value] cannot be converted to a file size.");
	}

	/** 
	 * Converts a value to string, or throws an exception if not possible. 
	 * 
	 * Objects can be converted to string if they implement the magic 
	 * __toString() method.
	 * 
	 */
	public static function toStringEx($value) {
		if (is_string($value)) {
			return $value;
		}
		if (is_numeric($value)) {
			return (string) $value;
		}
		if (is_object($value) && method_exists($value, '__toString')) {
			return (string) $value;
		}
	
		throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to string.");
	}
	
	/**
	 * Performs value substitution for string options.
	 * 
	 * An option can contain PHP constants delimited by '${' and '}'.
	 * 
	 * E.g. for input string "some ${FOO} value", the method will attempt 
	 * to substitute ${FOO} with the value of constant FOO if it exists.
	 * 
	 * Therefore, if FOO is a constant, and it has value "bar", the resulting 
	 * string will be "some bar value". 
	 * 
	 * If the constant is not defined, it will be replaced by an empty string, 
	 * and the resulting string will be "some  value". 
	 * 
	 * @param string $string String on which to perform substitution.
	 * @return string
	 */
	public static function substConstants($string) {
		preg_match_all('/\${([^}]+)}/', $string, $matches);
		
		foreach($matches[1] as $key => $match) {
			$match = trim($match);
			$search = $matches[0][$key];
			$replacement = defined($match) ? constant($match) : '';
			$string = str_replace($search, $replacement, $string);
		}
		return $string;
	}
}
api/log4php/main/php/LoggerAutoloader.php0000644000004100000410000001602013466017021020716 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 *		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @package log4php
 */

if (function_exists('__autoload')) {
	trigger_error("log4php: It looks like your code is using an __autoload() function. log4php uses spl_autoload_register() which will bypass your __autoload() function and may break autoloading.", E_USER_WARNING);
}

spl_autoload_register(array('LoggerAutoloader', 'autoload'));

/**
 * Class autoloader.
 * 
 * @package log4php
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @version $Revision: 1394956 $
 */
class LoggerAutoloader {
	
	/** Maps classnames to files containing the class. */
	private static $classes = array(
	
		// Base
		'LoggerAppender' => '/LoggerAppender.php',
		'LoggerAppenderPool' => '/LoggerAppenderPool.php',
		'LoggerConfigurable' => '/LoggerConfigurable.php',
		'LoggerConfigurator' => '/LoggerConfigurator.php',
		'LoggerException' => '/LoggerException.php',
		'LoggerFilter' => '/LoggerFilter.php',
		'LoggerHierarchy' => '/LoggerHierarchy.php',
		'LoggerLevel' => '/LoggerLevel.php',
		'LoggerLocationInfo' => '/LoggerLocationInfo.php',
		'LoggerLoggingEvent' => '/LoggerLoggingEvent.php',
		'LoggerMDC' => '/LoggerMDC.php',
		'LoggerNDC' => '/LoggerNDC.php',
		'LoggerLayout' => '/LoggerLayout.php',
		'LoggerReflectionUtils' => '/LoggerReflectionUtils.php',
		'LoggerRoot' => '/LoggerRoot.php',
		'LoggerThrowableInformation' => '/LoggerThrowableInformation.php',
		
		// Appenders
		'LoggerAppenderConsole' => '/appenders/LoggerAppenderConsole.php',
		'LoggerAppenderDailyFile' => '/appenders/LoggerAppenderDailyFile.php',
		'LoggerAppenderEcho' => '/appenders/LoggerAppenderEcho.php',
		'LoggerAppenderFile' => '/appenders/LoggerAppenderFile.php',
		'LoggerAppenderMail' => '/appenders/LoggerAppenderMail.php',
		'LoggerAppenderMailEvent' => '/appenders/LoggerAppenderMailEvent.php',
		'LoggerAppenderMongoDB' => '/appenders/LoggerAppenderMongoDB.php',
		'LoggerAppenderNull' => '/appenders/LoggerAppenderNull.php',
		'LoggerAppenderFirePHP' => '/appenders/LoggerAppenderFirePHP.php',
		'LoggerAppenderPDO' => '/appenders/LoggerAppenderPDO.php',
		'LoggerAppenderPhp' => '/appenders/LoggerAppenderPhp.php',
		'LoggerAppenderRollingFile' => '/appenders/LoggerAppenderRollingFile.php',
		'LoggerAppenderSocket' => '/appenders/LoggerAppenderSocket.php',
		'LoggerAppenderSyslog' => '/appenders/LoggerAppenderSyslog.php',
		
		// Configurators
		'LoggerConfigurationAdapter' => '/configurators/LoggerConfigurationAdapter.php',
		'LoggerConfigurationAdapterINI' => '/configurators/LoggerConfigurationAdapterINI.php',
		'LoggerConfigurationAdapterPHP' => '/configurators/LoggerConfigurationAdapterPHP.php',
		'LoggerConfigurationAdapterXML' => '/configurators/LoggerConfigurationAdapterXML.php',
		'LoggerConfiguratorDefault' => '/configurators/LoggerConfiguratorDefault.php',

		// Filters
		'LoggerFilterDenyAll' => '/filters/LoggerFilterDenyAll.php',
		'LoggerFilterLevelMatch' => '/filters/LoggerFilterLevelMatch.php',
		'LoggerFilterLevelRange' => '/filters/LoggerFilterLevelRange.php',
		'LoggerFilterStringMatch' => '/filters/LoggerFilterStringMatch.php',

		// Helpers
		'LoggerFormattingInfo' => '/helpers/LoggerFormattingInfo.php',
		'LoggerOptionConverter' => '/helpers/LoggerOptionConverter.php',
		'LoggerPatternParser' => '/helpers/LoggerPatternParser.php',
		'LoggerUtils' => '/helpers/LoggerUtils.php',
	
		// Pattern converters
		'LoggerPatternConverter' => '/pattern/LoggerPatternConverter.php',
		'LoggerPatternConverterClass' => '/pattern/LoggerPatternConverterClass.php',
		'LoggerPatternConverterCookie' => '/pattern/LoggerPatternConverterCookie.php',
		'LoggerPatternConverterDate' => '/pattern/LoggerPatternConverterDate.php',
		'LoggerPatternConverterEnvironment' => '/pattern/LoggerPatternConverterEnvironment.php',
		'LoggerPatternConverterFile' => '/pattern/LoggerPatternConverterFile.php',
		'LoggerPatternConverterLevel' => '/pattern/LoggerPatternConverterLevel.php',
		'LoggerPatternConverterLine' => '/pattern/LoggerPatternConverterLine.php',
		'LoggerPatternConverterLiteral' => '/pattern/LoggerPatternConverterLiteral.php',
		'LoggerPatternConverterLocation' => '/pattern/LoggerPatternConverterLocation.php',
		'LoggerPatternConverterLogger' => '/pattern/LoggerPatternConverterLogger.php',
		'LoggerPatternConverterMDC' => '/pattern/LoggerPatternConverterMDC.php',
		'LoggerPatternConverterMessage' => '/pattern/LoggerPatternConverterMessage.php',
		'LoggerPatternConverterMethod' => '/pattern/LoggerPatternConverterMethod.php',
		'LoggerPatternConverterNDC' => '/pattern/LoggerPatternConverterNDC.php',
		'LoggerPatternConverterNewLine' => '/pattern/LoggerPatternConverterNewLine.php',
		'LoggerPatternConverterProcess' => '/pattern/LoggerPatternConverterProcess.php',
		'LoggerPatternConverterRelative' => '/pattern/LoggerPatternConverterRelative.php',
		'LoggerPatternConverterRequest' => '/pattern/LoggerPatternConverterRequest.php',
		'LoggerPatternConverterServer' => '/pattern/LoggerPatternConverterServer.php',
		'LoggerPatternConverterSession' => '/pattern/LoggerPatternConverterSession.php',
		'LoggerPatternConverterSessionID' => '/pattern/LoggerPatternConverterSessionID.php',
		'LoggerPatternConverterSuperglobal' => '/pattern/LoggerPatternConverterSuperglobal.php',
		'LoggerPatternConverterThrowable' => '/pattern/LoggerPatternConverterThrowable.php',
		
		// Layouts
		'LoggerLayoutHtml' => '/layouts/LoggerLayoutHtml.php',
		'LoggerLayoutPattern' => '/layouts/LoggerLayoutPattern.php',
		'LoggerLayoutSerialized' => '/layouts/LoggerLayoutSerialized.php',
		'LoggerLayoutSimple' => '/layouts/LoggerLayoutSimple.php',
		'LoggerLayoutTTCC' => '/layouts/LoggerLayoutTTCC.php',
		'LoggerLayoutXml' => '/layouts/LoggerLayoutXml.php',
		
		// Renderers
		'LoggerRendererDefault' => '/renderers/LoggerRendererDefault.php',
		'LoggerRendererException' => '/renderers/LoggerRendererException.php',
		'LoggerRendererMap' => '/renderers/LoggerRendererMap.php',
		'LoggerRenderer' => '/renderers/LoggerRenderer.php',
	);
	
	/**
	 * Loads a class.
	 * @param string $className The name of the class to load.
	 */
	public static function autoload($className) {
		if(isset(self::$classes[$className])) {
			include dirname(__FILE__) . self::$classes[$className];
		}
	}
}
api/log4php/main/php/LoggerLayout.php0000644000004100000410000000403013466017021020072 0ustar  www-datawww-data<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *	   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package log4php
 */

/**
 * Extend this abstract class to create your own log layout format.
 *	
 * @version $Revision: 1213283 $
 * @package log4php
 */
abstract class LoggerLayout extends LoggerConfigurable {
	/**
	 * Activates options for this layout.
	 * Override this method if you have options to be activated.
	 */
	public function activateOptions() {
		return true;
	}

	/**
	 * Override this method to create your own layout format.
	 *
	 * @param LoggerLoggingEvent
	 * @return string
	 */
	public function format(LoggerLoggingEvent $event) {
		return $event->getRenderedMessage();
	} 
	
	/**
	 * Returns the content type output by this layout.
	 * @return string
	 */
	public function getContentType() {
		return "text/plain";
	} 
			
	/**
	 * Returns the footer for the layout format.
	 * @return string
	 */
	public function getFooter() {
		return null;
	} 

	/**
	 * Returns the header for the layout format.
	 * @return string
	 */
	public function getHeader() {
		return null;
	}
	
	/** Triggers a warning for this layout with the given message. */
	protected function warn($message) {
		trigger_error("log4php: [" . get_class($this) . "]: $message", E_USER_WARNING);
	}
}
api/voguepay_trans_verification_handler.php0000644000004100000410000000057313466017021021702 0ustar  www-datawww-data<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.     
 */





$url="https://voguepay.com/?" . http_build_query($_GET);
$response=  file_get_contents($url);
header("content-type: application/json");
echo $response;
exit;