code:
# Translation of StatusNet - CacheLog to Dutch (Nederlands)
# Exported from translatewiki.net
#
# Author: Siebrand
# --
# This file is distributed under the same license as the StatusNet package.
#
msgid ""
msgstr ""
"Project-Id-Version: StatusNet - CacheLog\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-06-30 11:07+0000\n"
"PO-Revision-Date: 2012-06-30 11:07:59+0000\n"
"Language-Team: Dutch <https://translatewiki.net/wiki/Portal:nl>\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-POT-Import-Date: 2011-06-05 21:49:51+0000\n"
"X-Generator: MediaWiki 1.20alpha (233fc08); Translate 2012-06-21\n"
"X-Translation-Project: translatewiki.net <https://translatewiki.net>\n"
"X-Language-Code: nl\n"
"X-Message-Group: #out-statusnet-plugin-cachelog\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#. TRANS: Plugin description.
msgid "Log reads and writes to the cache."
msgstr "Lezen en schrijven naar de cache in het logboek opnemen."


code:
# Translation of StatusNet - CacheLog to Portuguese (português)
# Exported from translatewiki.net
#
# Author: Waldir
# --
# This file is distributed under the same license as the StatusNet package.
#
msgid ""
msgstr ""
"Project-Id-Version: StatusNet - CacheLog\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-06-30 11:07+0000\n"
"PO-Revision-Date: 2012-06-30 11:07:59+0000\n"
"Language-Team: Portuguese <https://translatewiki.net/wiki/Portal:pt>\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-POT-Import-Date: 2011-06-05 21:49:51+0000\n"
"X-Generator: MediaWiki 1.20alpha (233fc08); Translate 2012-06-21\n"
"X-Translation-Project: translatewiki.net <https://translatewiki.net>\n"
"X-Language-Code: pt\n"
"X-Message-Group: #out-statusnet-plugin-cachelog\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#. TRANS: Plugin description.
msgid "Log reads and writes to the cache."
msgstr "Regista leituras e escritas na cache."

license: mit


code:
# Translation of StatusNet - CacheLog to Russian (русский)
# Exported from translatewiki.net
#
# Author: Александр Сигачёв
# --
# This file is distributed under the same license as the StatusNet package.
#
msgid ""
msgstr ""
"Project-Id-Version: StatusNet - CacheLog\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-06-30 11:07+0000\n"
"PO-Revision-Date: 2012-06-30 11:07:59+0000\n"
"Language-Team: Russian <https://translatewiki.net/wiki/Portal:ru>\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-POT-Import-Date: 2011-06-05 21:49:51+0000\n"
"X-Generator: MediaWiki 1.20alpha (233fc08); Translate 2012-06-21\n"
"X-Translation-Project: translatewiki.net <https://translatewiki.net>\n"
"X-Language-Code: ru\n"
"X-Message-Group: #out-statusnet-plugin-cachelog\n"
"Plural-Forms: nplurals=3; plural=(n%10 == 1 && n%100 != 11) ? 0 : ( (n%10 >= "
"2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20)) ? 1 : 2 );\n"

#. TRANS: Plugin description.
msgid "Log reads and writes to the cache."
msgstr "Журнал читает и пишет в кеш."


code:
# Translation of StatusNet - CacheLog to Tagalog (Tagalog)
# Exported from translatewiki.net
#
# Author: AnakngAraw
# --
# This file is distributed under the same license as the StatusNet package.
#
msgid ""
msgstr ""
"Project-Id-Version: StatusNet - CacheLog\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-06-30 11:07+0000\n"
"PO-Revision-Date: 2012-06-30 11:07:59+0000\n"
"Language-Team: Tagalog <https://translatewiki.net/wiki/Portal:tl>\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-POT-Import-Date: 2011-06-05 21:49:51+0000\n"
"X-Generator: MediaWiki 1.20alpha (233fc08); Translate 2012-06-21\n"
"X-Translation-Project: translatewiki.net <https://translatewiki.net>\n"
"X-Language-Code: tl\n"
"X-Message-Group: #out-statusnet-plugin-cachelog\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#. TRANS: Plugin description.
msgid "Log reads and writes to the cache."
msgstr "Ang tala ay nagbabasa at nagsusulat sa taguan."


code:
# Translation of StatusNet - CacheLog to Ukrainian (українська)
# Exported from translatewiki.net
#
# Author: Boogie
# --
# This file is distributed under the same license as the StatusNet package.
#
msgid ""
msgstr ""
"Project-Id-Version: StatusNet - CacheLog\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-06-30 11:07+0000\n"
"PO-Revision-Date: 2012-06-30 11:07:59+0000\n"
"Language-Team: Ukrainian <https://translatewiki.net/wiki/Portal:uk>\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-POT-Import-Date: 2011-06-05 21:49:51+0000\n"
"X-Generator: MediaWiki 1.20alpha (233fc08); Translate 2012-06-21\n"
"X-Translation-Project: translatewiki.net <https://translatewiki.net>\n"
"X-Language-Code: uk\n"
"X-Message-Group: #out-statusnet-plugin-cachelog\n"
"Plural-Forms: nplurals=3; plural=(n%10 == 1 && n%100 != 11) ? 0 : ( (n%10 >= "
"2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20)) ? 1 : 2 );\n"

#. TRANS: Plugin description.
msgid "Log reads and writes to the cache."
msgstr "Лоґ переглядів та записів у кеші."


code:
# Translation of StatusNet - CacheLog to Simplified Chinese (中文（简体）)
# Exported from translatewiki.net
#
# Author: ZhengYiFeng
# --
# This file is distributed under the same license as the StatusNet package.
#
msgid ""
msgstr ""
"Project-Id-Version: StatusNet - CacheLog\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-06-30 11:07+0000\n"
"PO-Revision-Date: 2012-06-30 11:08:00+0000\n"
"Language-Team: Simplified Chinese <https://translatewiki.net/wiki/Portal:zh-"
"hans>\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-POT-Import-Date: 2011-06-05 21:49:51+0000\n"
"X-Generator: MediaWiki 1.20alpha (233fc08); Translate 2012-06-21\n"
"X-Translation-Project: translatewiki.net <https://translatewiki.net>\n"
"X-Language-Code: zh-hans\n"
"X-Message-Group: #out-statusnet-plugin-cachelog\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#. TRANS: Plugin description.
msgid "Log reads and writes to the cache."
msgstr "将读写日志到缓存。"


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Plugin to enable Single Sign On via CAS (Central Authentication Service)
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Plugin
 * @package   StatusNet
 * @author    Craig Andrews <candrews@integralblue.com>
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET') && !defined('LACONICA')) {
    exit(1);
}

// We bundle the phpCAS library...
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/CAS');

class CasAuthenticationPlugin extends AuthenticationPlugin
{
    public $server;
    public $port = 443;
    public $path = '';
    public $takeOverLogin = false;

    function checkPassword($username, $password)
    {
        global $casTempPassword;
        return ($casTempPassword == $password);
    }

    function onAutoload($cls)
    {
        switch ($cls)
        {
         case 'phpCAS':
            require_once(INSTALLDIR.'/plugins/CasAuthentication/extlib/CAS.php');
            return false;
        }

        // if it's not our exception, try standard places
        return parent::onAutoload($cls);
    }

    function onArgsInitialize(&$args)
    {
        if($this->takeOverLogin && $args['action'] == 'login')
        {
            $args['action'] = 'caslogin';
        }
    }

    function onStartInitializeRouter($m)
    {
        $m->connect('main/cas', array('action' => 'caslogin'));
        return true;
    }

    function onEndLoginGroupNav($action)
    {
        $action_name = $action->trimmed('action');

        $action->menuItem(common_local_url('caslogin'),
                          // TRANS: Menu item. CAS is Central Authentication Service.
                          _m('CAS'),
                          // TRANS: Tooltip for menu item. CAS is Central Authentication Service.
                          _m('Login or register with CAS.'),
                          $action_name === 'caslogin');

        return true;
    }

    function onEndShowPageNotice($action)
    {
        $name = $action->trimmed('action');

        switch ($name)
        {
         case 'login':
            // TRANS: Invitation to users with a CAS account to log in using the service.
            // TRANS: "[CAS login]" is a link description. (%%action.caslogin%%) is the URL.
            // TRANS: These two elements may not be separated.
            $instr = _m('(Have an account with CAS? ' .
              'Try our [CAS login](%%action.caslogin%%)!)');
            break;
         default:
            return true;
        }

        $output = common_markup_to_html($instr);
        $action->raw($output);
        return true;
    }

    function onLoginAction($action, &$login)
    {
        switch ($action)
        {
         case 'caslogin':
            $login = true;
            return false;
         default:
            return true;
        }
    }

    function onInitializePlugin(){
        parent::onInitializePlugin();
        if(!isset($this->server)){
            // TRANS: Exception thrown when the CAS Authentication plugin has been configured incorrectly.
            throw new Exception(_m("Specifying a server is required."));
        }
        if(!isset($this->port)){
            // TRANS: Exception thrown when the CAS Authentication plugin has been configured incorrectly.
            throw new Exception(_m("Specifying a port is required."));
        }
        if(!isset($this->path)){
            // TRANS: Exception thrown when the CAS Authentication plugin has been configured incorrectly.
            throw new Exception(_m("Specifying a path is required."));
        }
        //These values need to be accessible to a action object
        //I can't think of any other way than global variables
        //to allow the action instance to be able to see values :-(
        global $casSettings;
        $casSettings = array();
        $casSettings['server']=$this->server;
        $casSettings['port']=$this->port;
        $casSettings['path']=$this->path;
        $casSettings['takeOverLogin']=$this->takeOverLogin;
    }

    function onPluginVersion(&$versions)
    {
        $versions[] = array('name' => 'CAS Authentication',
                            'version' => GNUSOCIAL_VERSION,
                            'author' => 'Craig Andrews',
                            'homepage' => 'http://status.net/wiki/Plugin:CasAuthentication',
                            // TRANS: Plugin description. CAS is Central Authentication Service.
                            'rawdescription' => _m('The CAS Authentication plugin allows for StatusNet to handle authentication through CAS (Central Authentication Service).'));
        return true;
    }
}


code:
The CAS Authentication plugin allows for StatusNet to handle authentication
through CAS (Central Authentication Service).

Installation
============
add "addPlugin('casAuthentication',
    array('setting'=>'value', 'setting2'=>'value2', ...);"
to the bottom of your config.php

Settings
========
provider_name*: a unique name for this authentication provider.
authoritative (false): Set to true if CAS's responses are authoritative
    (if authorative and CAS fails, no other password checking will be done).
autoregistration (false): Set to true if users should be automatically created
    when they attempt to login.
email_changeable (true): Are users allowed to change their email address?
    (true or false)
password_changeable*: must be set to false. This plugin does not support changing passwords.

server*: CAS server to authentication against
port (443): Port the CAS server listens on. Almost always 443
path (): Path on the server to CAS. Usually blank.
takeOverLogin (false): Take over the main login action. If takeOverLogin is
    set, anytime the standard username/password login form would be shown,
    a CAS login will be done instead.

* required
default values are in (parenthesis)

Example
=======
addPlugin('casAuthentication', array(
    'provider_name'=>'Example',
    'authoritative'=>true,
    'autoregistration'=>true,
    'server'=>'sso-cas.univ-rennes1.fr',
    'port'=>443,
    'path'=>'',
    'takeOverLogin'=>true
));

path: plugins/CasAuthentication/README


code:
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }

class CasloginAction extends Action
{
    function handle($args)
    {
        parent::handle($args);
        if (common_is_real_login()) {
            // TRANS: Client error displayed when trying to log in while already logged on.
            $this->clientError(_m('Already logged in.'));
        } else {
            global $casSettings;
            phpCAS::client(CAS_VERSION_2_0,$casSettings['server'],$casSettings['port'],$casSettings['path'],false);
            phpCAS::setNoCasServerValidation();
            phpCAS::handleLogoutRequests();
            phpCAS::forceAuthentication();
            global $casTempPassword;
            $casTempPassword = common_random_hexstr(16);
            $user = common_check_user(phpCAS::getUser(), $casTempPassword);
            if (!$user) {
                // TRANS: Server error displayed when trying to log in with incorrect username or password.
                $this->serverError(_m('Incorrect username or password.'));
            }

            // success!
            if (!common_set_user($user)) {
                // TRANS: Server error displayed when login fails in CAS authentication plugin.
                $this->serverError(_m('Error setting user. You are probably not authorized.'));
            }

            common_real_login(true);

            $url = common_get_returnto();

            if ($url) {
                // We don't have to return to it again
                common_set_returnto(null);
            } else {
                if(common_config('site', 'private') && $casSettings['takeOverLogin']) {
                    //SSO users expect to just go to the URL they entered
                    //if we don't have a returnto set, the user entered the
                    //main StatusNet url, so send them there.
                    $url = common_local_url('public');
                } else {
                    //With normal logins (regular form-based username/password),
                    //the user would expect to go to their home after logging in.
                    $url = common_local_url('public',
                                        array('nickname' =>
                                              $user->nickname));
                }
            }

            common_redirect($url, 303);
        }
    }
}


code:
<?php

/*
 * Copyright © 2003-2010, The ESUP-Portail consortium & the JA-SIG Collaborative.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of the ESUP-Portail consortium & the JA-SIG
 *       Collaborative nor the names of its contributors may be used to endorse or
 *       promote products derived from this software without specific prior
 *       written permission.

 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

//
// hack by Vangelis Haniotakis to handle the absence of $_SERVER['REQUEST_URI'] in IIS
//
if (!$_SERVER['REQUEST_URI']) {
	$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
}

//
// another one by Vangelis Haniotakis also to make phpCAS work with PHP5
//
if (version_compare(PHP_VERSION, '5', '>=') && !(function_exists('domxml_new_doc'))) {
	require_once (dirname(__FILE__) . '/CAS/domxml-php4-to-php5.php');
}

/**
 * @file CAS/CAS.php
 * Interface class of the phpCAS library
 *
 * @ingroup public
 */

// ########################################################################
//  CONSTANTS
// ########################################################################

// ------------------------------------------------------------------------
//  CAS VERSIONS
// ------------------------------------------------------------------------

/**
 * phpCAS version. accessible for the user by phpCAS::getVersion().
 */
define('PHPCAS_VERSION', '1.1.2');

// ------------------------------------------------------------------------
//  CAS VERSIONS
// ------------------------------------------------------------------------
/**
 * @addtogroup public
 * @{
 */

/**
 * CAS version 1.0
 */
define("CAS_VERSION_1_0", '1.0');
/*!
 * CAS version 2.0
 */
define("CAS_VERSION_2_0", '2.0');

// ------------------------------------------------------------------------
//  SAML defines
// ------------------------------------------------------------------------

/**
 * SAML protocol
 */
define("SAML_VERSION_1_1", 'S1');

/**
 * XML header for SAML POST
 */
define("SAML_XML_HEADER", '<?xml version="1.0" encoding="UTF-8"?>');

/**
 * SOAP envelope for SAML POST
 */
define("SAML_SOAP_ENV", '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/>');

/**
 * SOAP body for SAML POST
 */
define("SAML_SOAP_BODY", '<SOAP-ENV:Body>');

/**
 * SAMLP request
 */
define("SAMLP_REQUEST", '<samlp:Request xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol"  MajorVersion="1" MinorVersion="1" RequestID="_192.168.16.51.1024506224022" IssueInstant="2002-06-19T17:03:44.022Z">');
define("SAMLP_REQUEST_CLOSE", '</samlp:Request>');

/**
 * SAMLP artifact tag (for the ticket)
 */
define("SAML_ASSERTION_ARTIFACT", '<samlp:AssertionArtifact>');

/**
 * SAMLP close
 */
define("SAML_ASSERTION_ARTIFACT_CLOSE", '</samlp:AssertionArtifact>');

/**
 * SOAP body close
 */
define("SAML_SOAP_BODY_CLOSE", '</SOAP-ENV:Body>');

/**
 * SOAP envelope close
 */
define("SAML_SOAP_ENV_CLOSE", '</SOAP-ENV:Envelope>');

/**
 * SAML Attributes
 */
define("SAML_ATTRIBUTES", 'SAMLATTRIBS');

/** @} */
/**
 * @addtogroup publicPGTStorage
 * @{
 */
// ------------------------------------------------------------------------
//  FILE PGT STORAGE
// ------------------------------------------------------------------------
/**
 * Default path used when storing PGT's to file
 */
define("CAS_PGT_STORAGE_FILE_DEFAULT_PATH", '/tmp');
/**
 * phpCAS::setPGTStorageFile()'s 2nd parameter to write plain text files
 */
define("CAS_PGT_STORAGE_FILE_FORMAT_PLAIN", 'plain');
/**
 * phpCAS::setPGTStorageFile()'s 2nd parameter to write xml files
 */
define("CAS_PGT_STORAGE_FILE_FORMAT_XML", 'xml');
/**
 * Default format used when storing PGT's to file
 */
define("CAS_PGT_STORAGE_FILE_DEFAULT_FORMAT", CAS_PGT_STORAGE_FILE_FORMAT_PLAIN);
// ------------------------------------------------------------------------
//  DATABASE PGT STORAGE
// ------------------------------------------------------------------------
/**
 * default database type when storing PGT's to database
 */
define("CAS_PGT_STORAGE_DB_DEFAULT_DATABASE_TYPE", 'mysql');
/**
 * default host when storing PGT's to database
 */
define("CAS_PGT_STORAGE_DB_DEFAULT_HOSTNAME", 'localhost');
/**
 * default port when storing PGT's to database
 */
define("CAS_PGT_STORAGE_DB_DEFAULT_PORT", '');
/**
 * default database when storing PGT's to database
 */
define("CAS_PGT_STORAGE_DB_DEFAULT_DATABASE", 'phpCAS');
/**
 * default table when storing PGT's to database
 */
define("CAS_PGT_STORAGE_DB_DEFAULT_TABLE", 'pgt');

/** @} */
// ------------------------------------------------------------------------
// SERVICE ACCESS ERRORS
// ------------------------------------------------------------------------
/**
 * @addtogroup publicServices
 * @{
 */

/**
 * phpCAS::service() error code on success
 */
define("PHPCAS_SERVICE_OK", 0);
/**
 * phpCAS::service() error code when the PT could not retrieve because
 * the CAS server did not respond.
 */
define("PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE", 1);
/**
 * phpCAS::service() error code when the PT could not retrieve because
 * the response of the CAS server was ill-formed.
 */
define("PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE", 2);
/**
 * phpCAS::service() error code when the PT could not retrieve because
 * the CAS server did not want to.
 */
define("PHPCAS_SERVICE_PT_FAILURE", 3);
/**
 * phpCAS::service() error code when the service was not available.
 */
define("PHPCAS_SERVICE_NOT AVAILABLE", 4);

/** @} */
// ------------------------------------------------------------------------
//  LANGUAGES
// ------------------------------------------------------------------------
/**
 * @addtogroup publicLang
 * @{
 */

define("PHPCAS_LANG_ENGLISH", 'english');
define("PHPCAS_LANG_FRENCH", 'french');
define("PHPCAS_LANG_GREEK", 'greek');
define("PHPCAS_LANG_GERMAN", 'german');
define("PHPCAS_LANG_JAPANESE", 'japanese');
define("PHPCAS_LANG_SPANISH", 'spanish');
define("PHPCAS_LANG_CATALAN", 'catalan');

/** @} */

/**
 * @addtogroup internalLang
 * @{
 */

/**
 * phpCAS default language (when phpCAS::setLang() is not used)
 */
define("PHPCAS_LANG_DEFAULT", PHPCAS_LANG_ENGLISH);

/** @} */
// ------------------------------------------------------------------------
//  DEBUG
// ------------------------------------------------------------------------
/**
 * @addtogroup publicDebug
 * @{
 */

/**
 * The default directory for the debug file under Unix.
 */
define('DEFAULT_DEBUG_DIR', '/tmp/');

/** @} */
// ------------------------------------------------------------------------
//  MISC
// ------------------------------------------------------------------------
/**
 * @addtogroup internalMisc
 * @{
 */

/**
 * This global variable is used by the interface class phpCAS.
 *
 * @hideinitializer
 */
$GLOBALS['PHPCAS_CLIENT'] = null;

/**
 * This global variable is used to store where the initializer is called from
 * (to print a comprehensive error in case of multiple calls).
 *
 * @hideinitializer
 */
$GLOBALS['PHPCAS_INIT_CALL'] = array (
	'done' => FALSE,
	'file' => '?',
	'line' => -1,
	'method' => '?'
);

/**
 * This global variable is used to store where the method checking
 * the authentication is called from (to print comprehensive errors)
 *
 * @hideinitializer
 */
$GLOBALS['PHPCAS_AUTH_CHECK_CALL'] = array (
	'done' => FALSE,
	'file' => '?',
	'line' => -1,
	'method' => '?',
	'result' => FALSE
);

/**
 * This global variable is used to store phpCAS debug mode.
 *
 * @hideinitializer
 */
$GLOBALS['PHPCAS_DEBUG'] = array (
	'filename' => FALSE,
	'indent' => 0,
	'unique_id' => ''
);

/** @} */

// ########################################################################
//  CLIENT CLASS
// ########################################################################

// include client class
include_once (dirname(__FILE__) . '/CAS/client.php');

// ########################################################################
//  INTERFACE CLASS
// ########################################################################

/**
 * @class phpCAS
 * The phpCAS class is a simple container for the phpCAS library. It provides CAS
 * authentication for web applications written in PHP.
 *
 * @ingroup public
 * @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
 *
 * \internal All its methods access the same object ($PHPCAS_CLIENT, declared
 * at the end of CAS/client.php).
 */

class phpCAS {

	// ########################################################################
	//  INITIALIZATION
	// ########################################################################

	/**
	 * @addtogroup publicInit
	 * @{
	 */

	/**
	 * phpCAS client initializer.
	 * @note Only one of the phpCAS::client() and phpCAS::proxy functions should be
	 * called, only once, and before all other methods (except phpCAS::getVersion()
	 * and phpCAS::setDebug()).
	 *
	 * @param $server_version the version of the CAS server
	 * @param $server_hostname the hostname of the CAS server
	 * @param $server_port the port the CAS server is running on
	 * @param $server_uri the URI the CAS server is responding on
	 * @param $start_session Have phpCAS start PHP sessions (default true)
	 *
	 * @return a newly created CASClient object
	 */
	function client($server_version, $server_hostname, $server_port, $server_uri, $start_session = true) {
		global $PHPCAS_CLIENT, $PHPCAS_INIT_CALL;

		phpCAS :: traceBegin();
		if (is_object($PHPCAS_CLIENT)) {
			phpCAS :: error($PHPCAS_INIT_CALL['method'] . '() has already been called (at ' . $PHPCAS_INIT_CALL['file'] . ':' . $PHPCAS_INIT_CALL['line'] . ')');
		}
		if (gettype($server_version) != 'string') {
			phpCAS :: error('type mismatched for parameter $server_version (should be `string\')');
		}
		if (gettype($server_hostname) != 'string') {
			phpCAS :: error('type mismatched for parameter $server_hostname (should be `string\')');
		}
		if (gettype($server_port) != 'integer') {
			phpCAS :: error('type mismatched for parameter $server_port (should be `integer\')');
		}
		if (gettype($server_uri) != 'string') {
			phpCAS :: error('type mismatched for parameter $server_uri (should be `string\')');
		}

		// store where the initializer is called from
		$dbg = phpCAS :: backtrace();
		$PHPCAS_INIT_CALL = array (
			'done' => TRUE,
			'file' => $dbg[0]['file'],
			'line' => $dbg[0]['line'],
			'method' => __CLASS__ . '::' . __FUNCTION__
		);

		// initialize the global object $PHPCAS_CLIENT
		$PHPCAS_CLIENT = new CASClient($server_version, FALSE /*proxy*/
		, $server_hostname, $server_port, $server_uri, $start_session);
		phpCAS :: traceEnd();
	}

	/**
	 * phpCAS proxy initializer.
	 * @note Only one of the phpCAS::client() and phpCAS::proxy functions should be
	 * called, only once, and before all other methods (except phpCAS::getVersion()
	 * and phpCAS::setDebug()).
	 *
	 * @param $server_version the version of the CAS server
	 * @param $server_hostname the hostname of the CAS server
	 * @param $server_port the port the CAS server is running on
	 * @param $server_uri the URI the CAS server is responding on
	 * @param $start_session Have phpCAS start PHP sessions (default true)
	 *
	 * @return a newly created CASClient object
	 */
	function proxy($server_version, $server_hostname, $server_port, $server_uri, $start_session = true) {
		global $PHPCAS_CLIENT, $PHPCAS_INIT_CALL;

		phpCAS :: traceBegin();
		if (is_object($PHPCAS_CLIENT)) {
			phpCAS :: error($PHPCAS_INIT_CALL['method'] . '() has already been called (at ' . $PHPCAS_INIT_CALL['file'] . ':' . $PHPCAS_INIT_CALL['line'] . ')');
		}
		if (gettype($server_version) != 'string') {
			phpCAS :: error('type mismatched for parameter $server_version (should be `string\')');
		}
		if (gettype($server_hostname) != 'string') {
			phpCAS :: error('type mismatched for parameter $server_hostname (should be `string\')');
		}
		if (gettype($server_port) != 'integer') {
			phpCAS :: error('type mismatched for parameter $server_port (should be `integer\')');
		}
		if (gettype($server_uri) != 'string') {
			phpCAS :: error('type mismatched for parameter $server_uri (should be `string\')');
		}

		// store where the initialzer is called from
		$dbg = phpCAS :: backtrace();
		$PHPCAS_INIT_CALL = array (
			'done' => TRUE,
			'file' => $dbg[0]['file'],
			'line' => $dbg[0]['line'],
			'method' => __CLASS__ . '::' . __FUNCTION__
		);

		// initialize the global object $PHPCAS_CLIENT
		$PHPCAS_CLIENT = new CASClient($server_version, TRUE /*proxy*/
		, $server_hostname, $server_port, $server_uri, $start_session);
		phpCAS :: traceEnd();
	}

	/** @} */
	// ########################################################################
	//  DEBUGGING
	// ########################################################################

	/**
	 * @addtogroup publicDebug
	 * @{
	 */

	/**
	 * Set/unset debug mode
	 *
	 * @param $filename the name of the file used for logging, or FALSE to stop debugging.
	 */
	function setDebug($filename = '') {
		global $PHPCAS_DEBUG;

		if ($filename != FALSE && gettype($filename) != 'string') {
			phpCAS :: error('type mismatched for parameter $dbg (should be FALSE or the name of the log file)');
		}

		if (empty ($filename)) {
			if (preg_match('/^Win.*/', getenv('OS'))) {
				if (isset ($_ENV['TMP'])) {
					$debugDir = $_ENV['TMP'] . '/';
				} else
					if (isset ($_ENV['TEMP'])) {
						$debugDir = $_ENV['TEMP'] . '/';
					} else {
						$debugDir = '';
					}
			} else {
				$debugDir = DEFAULT_DEBUG_DIR;
			}
			$filename = $debugDir . 'phpCAS.log';
		}

		if (empty ($PHPCAS_DEBUG['unique_id'])) {
			$PHPCAS_DEBUG['unique_id'] = substr(strtoupper(md5(uniqid(''))), 0, 4);
		}

		$PHPCAS_DEBUG['filename'] = $filename;

		phpCAS :: trace('START phpCAS-' . PHPCAS_VERSION . ' ******************');
	}

	/** @} */
	/**
	 * @addtogroup internalDebug
	 * @{
	 */

	/**
	 * This method is a wrapper for debug_backtrace() that is not available
	 * in all PHP versions (>= 4.3.0 only)
	 */
	function backtrace() {
		if (function_exists('debug_backtrace')) {
			return debug_backtrace();
		} else {
			// poor man's hack ... but it does work ...
			return array ();
		}
	}

	/**
	 * Logs a string in debug mode.
	 *
	 * @param $str the string to write
	 *
	 * @private
	 */
	function log($str) {
		$indent_str = ".";
		global $PHPCAS_DEBUG;

		if ($PHPCAS_DEBUG['filename']) {
			for ($i = 0; $i < $PHPCAS_DEBUG['indent']; $i++) {
				$indent_str .= '|    ';
			}
			error_log($PHPCAS_DEBUG['unique_id'] . ' ' . $indent_str . $str . "\n", 3, $PHPCAS_DEBUG['filename']);
		}

	}

	/**
	 * This method is used by interface methods to print an error and where the function
	 * was originally called from.
	 *
	 * @param $msg the message to print
	 *
	 * @private
	 */
	function error($msg) {
		$dbg = phpCAS :: backtrace();
		$function = '?';
		$file = '?';
		$line = '?';
		if (is_array($dbg)) {
			for ($i = 1; $i < sizeof($dbg); $i++) {
				if (is_array($dbg[$i])) {
					if ($dbg[$i]['class'] == __CLASS__) {
						$function = $dbg[$i]['function'];
						$file = $dbg[$i]['file'];
						$line = $dbg[$i]['line'];
					}
				}
			}
		}
		echo "
\nphpCAS error: " . __CLASS__ . "::" . $function . '(): ' . htmlentities($msg) . " in " . $file . " on line " . $line . "
\n";
		phpCAS :: trace($msg);
		phpCAS :: traceExit();
		exit ();
	}

	/**
	 * This method is used to log something in debug mode.
	 */
	function trace($str) {
		$dbg = phpCAS :: backtrace();
		phpCAS :: log($str . ' [' . basename($dbg[1]['file']) . ':' . $dbg[1]['line'] . ']');
	}

	/**
	 * This method is used to indicate the start of the execution of a function in debug mode.
	 */
	function traceBegin() {
		global $PHPCAS_DEBUG;

		$dbg = phpCAS :: backtrace();
		$str = '=> ';
		if (!empty ($dbg[2]['class'])) {
			$str .= $dbg[2]['class'] . '::';
		}
		$str .= $dbg[2]['function'] . '(';
		if (is_array($dbg[2]['args'])) {
			foreach ($dbg[2]['args'] as $index => $arg) {
				if ($index != 0) {
					$str .= ', ';
				}
				$str .= str_replace("\n", "", var_export($arg, TRUE));
			}
		}
		$str .= ') [' . basename($dbg[2]['file']) . ':' . $dbg[2]['line'] . ']';
		phpCAS :: log($str);
		$PHPCAS_DEBUG['indent']++;
	}

	/**
	 * This method is used to indicate the end of the execution of a function in debug mode.
	 *
	 * @param $res the result of the function
	 */
	function traceEnd($res = '') {
		global $PHPCAS_DEBUG;

		$PHPCAS_DEBUG['indent']--;
		$dbg = phpCAS :: backtrace();
		$str = '';
		$str .= '<= ' . str_replace("\n", "", var_export($res, TRUE));
		phpCAS :: log($str);
	}

	/**
	 * This method is used to indicate the end of the execution of the program
	 */
	function traceExit() {
		global $PHPCAS_DEBUG;

		phpCAS :: log('exit()');
		while ($PHPCAS_DEBUG['indent'] > 0) {
			phpCAS :: log('-');
			$PHPCAS_DEBUG['indent']--;
		}
	}

	/** @} */
	// ########################################################################
	//  INTERNATIONALIZATION
	// ########################################################################
	/**
	 * @addtogroup publicLang
	 * @{
	 */

	/**
	 * This method is used to set the language used by phpCAS.
	 * @note Can be called only once.
	 *
	 * @param $lang a string representing the language.
	 *
	 * @sa PHPCAS_LANG_FRENCH, PHPCAS_LANG_ENGLISH
	 */
	function setLang($lang) {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		if (gettype($lang) != 'string') {
			phpCAS :: error('type mismatched for parameter $lang (should be `string\')');
		}
		$PHPCAS_CLIENT->setLang($lang);
	}

	/** @} */
	// ########################################################################
	//  VERSION
	// ########################################################################
	/**
	 * @addtogroup public
	 * @{
	 */

	/**
	 * This method returns the phpCAS version.
	 *
	 * @return the phpCAS version.
	 */
	function getVersion() {
		return PHPCAS_VERSION;
	}

	/** @} */
	// ########################################################################
	//  HTML OUTPUT
	// ########################################################################
	/**
	 * @addtogroup publicOutput
	 * @{
	 */

	/**
	 * This method sets the HTML header used for all outputs.
	 *
	 * @param $header the HTML header.
	 */
	function setHTMLHeader($header) {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		if (gettype($header) != 'string') {
			phpCAS :: error('type mismatched for parameter $header (should be `string\')');
		}
		$PHPCAS_CLIENT->setHTMLHeader($header);
	}

	/**
	 * This method sets the HTML footer used for all outputs.
	 *
	 * @param $footer the HTML footer.
	 */
	function setHTMLFooter($footer) {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		if (gettype($footer) != 'string') {
			phpCAS :: error('type mismatched for parameter $footer (should be `string\')');
		}
		$PHPCAS_CLIENT->setHTMLFooter($footer);
	}

	/** @} */
	// ########################################################################
	//  PGT STORAGE
	// ########################################################################
	/**
	 * @addtogroup publicPGTStorage
	 * @{
	 */

	/**
	 * This method is used to tell phpCAS to store the response of the
	 * CAS server to PGT requests onto the filesystem.
	 *
	 * @param $format the format used to store the PGT's (`plain' and `xml' allowed)
	 * @param $path the path where the PGT's should be stored
	 */
	function setPGTStorageFile($format = '', $path = '') {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;

		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_CLIENT->isProxy()) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if ($PHPCAS_AUTH_CHECK_CALL['done']) {
			phpCAS :: error('this method should only be called before ' . $PHPCAS_AUTH_CHECK_CALL['method'] . '() (called at ' . $PHPCAS_AUTH_CHECK_CALL['file'] . ':' . $PHPCAS_AUTH_CHECK_CALL['line'] . ')');
		}
		if (gettype($format) != 'string') {
			phpCAS :: error('type mismatched for parameter $format (should be `string\')');
		}
		if (gettype($path) != 'string') {
			phpCAS :: error('type mismatched for parameter $format (should be `string\')');
		}
		$PHPCAS_CLIENT->setPGTStorageFile($format, $path);
		phpCAS :: traceEnd();
	}

	/**
	 * This method is used to tell phpCAS to store the response of the
	 * CAS server to PGT requests into a database.
	 * @note The connection to the database is done only when needed.
	 * As a consequence, bad parameters are detected only when
	 * initializing PGT storage, except in debug mode.
	 *
	 * @param $user the user to access the data with
	 * @param $password the user's password
	 * @param $database_type the type of the database hosting the data
	 * @param $hostname the server hosting the database
	 * @param $port the port the server is listening on
	 * @param $database the name of the database
	 * @param $table the name of the table storing the data
	 */
	function setPGTStorageDB($user, $password, $database_type = '', $hostname = '', $port = 0, $database = '', $table = '') {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;

		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_CLIENT->isProxy()) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if ($PHPCAS_AUTH_CHECK_CALL['done']) {
			phpCAS :: error('this method should only be called before ' . $PHPCAS_AUTH_CHECK_CALL['method'] . '() (called at ' . $PHPCAS_AUTH_CHECK_CALL['file'] . ':' . $PHPCAS_AUTH_CHECK_CALL['line'] . ')');
		}
		if (gettype($user) != 'string') {
			phpCAS :: error('type mismatched for parameter $user (should be `string\')');
		}
		if (gettype($password) != 'string') {
			phpCAS :: error('type mismatched for parameter $password (should be `string\')');
		}
		if (gettype($database_type) != 'string') {
			phpCAS :: error('type mismatched for parameter $database_type (should be `string\')');
		}
		if (gettype($hostname) != 'string') {
			phpCAS :: error('type mismatched for parameter $hostname (should be `string\')');
		}
		if (gettype($port) != 'integer') {
			phpCAS :: error('type mismatched for parameter $port (should be `integer\')');
		}
		if (gettype($database) != 'string') {
			phpCAS :: error('type mismatched for parameter $database (should be `string\')');
		}
		if (gettype($table) != 'string') {
			phpCAS :: error('type mismatched for parameter $table (should be `string\')');
		}
		$PHPCAS_CLIENT->setPGTStorageDB($user, $password, $database_type, $hostname, $port, $database, $table);
		phpCAS :: traceEnd();
	}

	/** @} */
	// ########################################################################
	// ACCESS TO EXTERNAL SERVICES
	// ########################################################################
	/**
	 * @addtogroup publicServices
	 * @{
	 */

	/**
	 * This method is used to access an HTTP[S] service.
	 *
	 * @param $url the service to access.
	 * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on
	 * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
	 * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE.
	 * @param $output the output of the service (also used to give an error
	 * message on failure).
	 *
	 * @return TRUE on success, FALSE otherwise (in this later case, $err_code
	 * gives the reason why it failed and $output contains an error message).
	 */
	function serviceWeb($url, & $err_code, & $output) {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;

		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_CLIENT->isProxy()) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_AUTH_CHECK_CALL['done']) {
			phpCAS :: error('this method should only be called after the programmer is sure the user has been authenticated (by calling ' . __CLASS__ . '::checkAuthentication() or ' . __CLASS__ . '::forceAuthentication()');
		}
		if (!$PHPCAS_AUTH_CHECK_CALL['result']) {
			phpCAS :: error('authentication was checked (by ' . $PHPCAS_AUTH_CHECK_CALL['method'] . '() at ' . $PHPCAS_AUTH_CHECK_CALL['file'] . ':' . $PHPCAS_AUTH_CHECK_CALL['line'] . ') but the method returned FALSE');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be `string\')');
		}

		$res = $PHPCAS_CLIENT->serviceWeb($url, $err_code, $output);

		phpCAS :: traceEnd($res);
		return $res;
	}

	/**
	 * This method is used to access an IMAP/POP3/NNTP service.
	 *
	 * @param $url a string giving the URL of the service, including the mailing box
	 * for IMAP URLs, as accepted by imap_open().
	 * @param $service a string giving for CAS retrieve Proxy ticket
	 * @param $flags options given to imap_open().
	 * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on
	 * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
	 * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE.
	 * @param $err_msg an error message on failure
	 * @param $pt the Proxy Ticket (PT) retrieved from the CAS server to access the URL
	 * on success, FALSE on error).
	 *
	 * @return an IMAP stream on success, FALSE otherwise (in this later case, $err_code
	 * gives the reason why it failed and $err_msg contains an error message).
	 */
	function serviceMail($url, $service, $flags, & $err_code, & $err_msg, & $pt) {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;

		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_CLIENT->isProxy()) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_AUTH_CHECK_CALL['done']) {
			phpCAS :: error('this method should only be called after the programmer is sure the user has been authenticated (by calling ' . __CLASS__ . '::checkAuthentication() or ' . __CLASS__ . '::forceAuthentication()');
		}
		if (!$PHPCAS_AUTH_CHECK_CALL['result']) {
			phpCAS :: error('authentication was checked (by ' . $PHPCAS_AUTH_CHECK_CALL['method'] . '() at ' . $PHPCAS_AUTH_CHECK_CALL['file'] . ':' . $PHPCAS_AUTH_CHECK_CALL['line'] . ') but the method returned FALSE');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be `string\')');
		}

		if (gettype($flags) != 'integer') {
			phpCAS :: error('type mismatched for parameter $flags (should be `integer\')');
		}

		$res = $PHPCAS_CLIENT->serviceMail($url, $service, $flags, $err_code, $err_msg, $pt);

		phpCAS :: traceEnd($res);
		return $res;
	}

	/** @} */
	// ########################################################################
	//  AUTHENTICATION
	// ########################################################################
	/**
	 * @addtogroup publicAuth
	 * @{
	 */

	/**
	 * Set the times authentication will be cached before really accessing the CAS server in gateway mode:
	 * - -1: check only once, and then never again (until you pree login)
	 * - 0: always check
	 * - n: check every "n" time
	 *
	 * @param $n an integer.
	 */
	function setCacheTimesForAuthRecheck($n) {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		if (gettype($n) != 'integer') {
			phpCAS :: error('type mismatched for parameter $header (should be `string\')');
		}
		$PHPCAS_CLIENT->setCacheTimesForAuthRecheck($n);
	}

	/**
	 * This method is called to check if the user is authenticated (use the gateway feature).
	 * @return TRUE when the user is authenticated; otherwise FALSE.
	 */
	function checkAuthentication() {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;

		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}

		$auth = $PHPCAS_CLIENT->checkAuthentication();

		// store where the authentication has been checked and the result
		$dbg = phpCAS :: backtrace();
		$PHPCAS_AUTH_CHECK_CALL = array (
			'done' => TRUE,
			'file' => $dbg[0]['file'],
			'line' => $dbg[0]['line'],
			'method' => __CLASS__ . '::' . __FUNCTION__,
			'result' => $auth
		);
		phpCAS :: traceEnd($auth);
		return $auth;
	}

	/**
	 * This method is called to force authentication if the user was not already
	 * authenticated. If the user is not authenticated, halt by redirecting to
	 * the CAS server.
	 */
	function forceAuthentication() {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;

		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}

		$auth = $PHPCAS_CLIENT->forceAuthentication();

		// store where the authentication has been checked and the result
		$dbg = phpCAS :: backtrace();
		$PHPCAS_AUTH_CHECK_CALL = array (
			'done' => TRUE,
			'file' => $dbg[0]['file'],
			'line' => $dbg[0]['line'],
			'method' => __CLASS__ . '::' . __FUNCTION__,
			'result' => $auth
		);

		if (!$auth) {
			phpCAS :: trace('user is not authenticated, redirecting to the CAS server');
			$PHPCAS_CLIENT->forceAuthentication();
		} else {
			phpCAS :: trace('no need to authenticate (user `' . phpCAS :: getUser() . '\' is already authenticated)');
		}

		phpCAS :: traceEnd();
		return $auth;
	}

	/**
	 * This method is called to renew the authentication.
	 **/
	function renewAuthentication() {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;

		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}

		// store where the authentication has been checked and the result
		$dbg = phpCAS :: backtrace();
		$PHPCAS_AUTH_CHECK_CALL = array (
			'done' => TRUE,
			'file' => $dbg[0]['file'],
			'line' => $dbg[0]['line'],
			'method' => __CLASS__ . '::' . __FUNCTION__,
			'result' => $auth
		);

		$PHPCAS_CLIENT->renewAuthentication();
		phpCAS :: traceEnd();
	}

	/**
	 * This method has been left from version 0.4.1 for compatibility reasons.
	 */
	function authenticate() {
		phpCAS :: error('this method is deprecated. You should use ' . __CLASS__ . '::forceAuthentication() instead');
	}

	/**
	 * This method is called to check if the user is authenticated (previously or by
	 * tickets given in the URL).
	 *
	 * @return TRUE when the user is authenticated.
	 */
	function isAuthenticated() {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;

		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}

		// call the isAuthenticated method of the global $PHPCAS_CLIENT object
		$auth = $PHPCAS_CLIENT->isAuthenticated();

		// store where the authentication has been checked and the result
		$dbg = phpCAS :: backtrace();
		$PHPCAS_AUTH_CHECK_CALL = array (
			'done' => TRUE,
			'file' => $dbg[0]['file'],
			'line' => $dbg[0]['line'],
			'method' => __CLASS__ . '::' . __FUNCTION__,
			'result' => $auth
		);
		phpCAS :: traceEnd($auth);
		return $auth;
	}

	/**
	 * Checks whether authenticated based on $_SESSION. Useful to avoid
	 * server calls.
	 * @return true if authenticated, false otherwise.
	 * @since 0.4.22 by Brendan Arnold
	 */
	function isSessionAuthenticated() {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		return ($PHPCAS_CLIENT->isSessionAuthenticated());
	}

	/**
	 * This method returns the CAS user's login name.
	 * @warning should not be called only after phpCAS::forceAuthentication()
	 * or phpCAS::checkAuthentication().
	 *
	 * @return the login name of the authenticated user
	 */
	function getUser() {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_AUTH_CHECK_CALL['done']) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::forceAuthentication() or ' . __CLASS__ . '::isAuthenticated()');
		}
		if (!$PHPCAS_AUTH_CHECK_CALL['result']) {
			phpCAS :: error('authentication was checked (by ' . $PHPCAS_AUTH_CHECK_CALL['method'] . '() at ' . $PHPCAS_AUTH_CHECK_CALL['file'] . ':' . $PHPCAS_AUTH_CHECK_CALL['line'] . ') but the method returned FALSE');
		}
		return $PHPCAS_CLIENT->getUser();
	}

	/**
	 * This method returns the CAS user's login name.
	 * @warning should not be called only after phpCAS::forceAuthentication()
	 * or phpCAS::checkAuthentication().
	 *
	 * @return the login name of the authenticated user
	 */
	function getAttributes() {
		global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_AUTH_CHECK_CALL['done']) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::forceAuthentication() or ' . __CLASS__ . '::isAuthenticated()');
		}
		if (!$PHPCAS_AUTH_CHECK_CALL['result']) {
			phpCAS :: error('authentication was checked (by ' . $PHPCAS_AUTH_CHECK_CALL['method'] . '() at ' . $PHPCAS_AUTH_CHECK_CALL['file'] . ':' . $PHPCAS_AUTH_CHECK_CALL['line'] . ') but the method returned FALSE');
		}
		return $PHPCAS_CLIENT->getAttributes();
	}
	/**
	 * Handle logout requests.
	 */
	function handleLogoutRequests($check_client = true, $allowed_clients = false) {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		return ($PHPCAS_CLIENT->handleLogoutRequests($check_client, $allowed_clients));
	}

	/**
	 * This method returns the URL to be used to login.
	 * or phpCAS::isAuthenticated().
	 *
	 * @return the login name of the authenticated user
	 */
	function getServerLoginURL() {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		return $PHPCAS_CLIENT->getServerLoginURL();
	}

	/**
	 * Set the login URL of the CAS server.
	 * @param $url the login URL
	 * @since 0.4.21 by Wyman Chan
	 */
	function setServerLoginURL($url = '') {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after
							' . __CLASS__ . '::client()');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be
						`string\')');
		}
		$PHPCAS_CLIENT->setServerLoginURL($url);
		phpCAS :: traceEnd();
	}

	/**
	 * Set the serviceValidate URL of the CAS server.
	 * Used only in CAS 1.0 validations
	 * @param $url the serviceValidate URL
	 * @since 1.1.0 by Joachim Fritschi
	 */
	function setServerServiceValidateURL($url = '') {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after
							' . __CLASS__ . '::client()');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be
						`string\')');
		}
		$PHPCAS_CLIENT->setServerServiceValidateURL($url);
		phpCAS :: traceEnd();
	}

	/**
	 * Set the proxyValidate URL of the CAS server.
	 * Used for all CAS 2.0 validations
	 * @param $url the proxyValidate URL
	 * @since 1.1.0 by Joachim Fritschi
	 */
	function setServerProxyValidateURL($url = '') {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after
							' . __CLASS__ . '::client()');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be
						`string\')');
		}
		$PHPCAS_CLIENT->setServerProxyValidateURL($url);
		phpCAS :: traceEnd();
	}

	/**
	 * Set the samlValidate URL of the CAS server.
	 * @param $url the samlValidate URL
	 * @since 1.1.0 by Joachim Fritschi
	 */
	function setServerSamlValidateURL($url = '') {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after
							' . __CLASS__ . '::client()');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be
						`string\')');
		}
		$PHPCAS_CLIENT->setServerSamlValidateURL($url);
		phpCAS :: traceEnd();
	}

	/**
	 * This method returns the URL to be used to login.
	 * or phpCAS::isAuthenticated().
	 *
	 * @return the login name of the authenticated user
	 */
	function getServerLogoutURL() {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
		}
		return $PHPCAS_CLIENT->getServerLogoutURL();
	}

	/**
	 * Set the logout URL of the CAS server.
	 * @param $url the logout URL
	 * @since 0.4.21 by Wyman Chan
	 */
	function setServerLogoutURL($url = '') {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after
							' . __CLASS__ . '::client()');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be
						`string\')');
		}
		$PHPCAS_CLIENT->setServerLogoutURL($url);
		phpCAS :: traceEnd();
	}

	/**
	 * This method is used to logout from CAS.
	 * @params $params an array that contains the optional url and service parameters that will be passed to the CAS server
	 * @public
	 */
	function logout($params = "") {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
		}
		$parsedParams = array ();
		if ($params != "") {
			if (is_string($params)) {
				phpCAS :: error('method `phpCAS::logout($url)\' is now deprecated, use `phpCAS::logoutWithUrl($url)\' instead');
			}
			if (!is_array($params)) {
				phpCAS :: error('type mismatched for parameter $params (should be `array\')');
			}
			foreach ($params as $key => $value) {
				if ($key != "service" && $key != "url") {
					phpCAS :: error('only `url\' and `service\' parameters are allowed for method `phpCAS::logout($params)\'');
				}
				$parsedParams[$key] = $value;
			}
		}
		$PHPCAS_CLIENT->logout($parsedParams);
		// never reached
		phpCAS :: traceEnd();
	}

	/**
	 * This method is used to logout from CAS. Halts by redirecting to the CAS server.
	 * @param $service a URL that will be transmitted to the CAS server
	 */
	function logoutWithRedirectService($service) {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
		}
		if (!is_string($service)) {
			phpCAS :: error('type mismatched for parameter $service (should be `string\')');
		}
		$PHPCAS_CLIENT->logout(array (
			"service" => $service
		));
		// never reached
		phpCAS :: traceEnd();
	}

	/**
	 * This method is used to logout from CAS. Halts by redirecting to the CAS server.
	 * @param $url a URL that will be transmitted to the CAS server
	 */
	function logoutWithUrl($url) {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
		}
		if (!is_string($url)) {
			phpCAS :: error('type mismatched for parameter $url (should be `string\')');
		}
		$PHPCAS_CLIENT->logout(array (
			"url" => $url
		));
		// never reached
		phpCAS :: traceEnd();
	}

	/**
	 * This method is used to logout from CAS. Halts by redirecting to the CAS server.
	 * @param $service a URL that will be transmitted to the CAS server
	 * @param $url a URL that will be transmitted to the CAS server
	 */
	function logoutWithRedirectServiceAndUrl($service, $url) {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
		}
		if (!is_string($service)) {
			phpCAS :: error('type mismatched for parameter $service (should be `string\')');
		}
		if (!is_string($url)) {
			phpCAS :: error('type mismatched for parameter $url (should be `string\')');
		}
		$PHPCAS_CLIENT->logout(array (
			"service" => $service,
			"url" => $url
		));
		// never reached
		phpCAS :: traceEnd();
	}

	/**
	 * Set the fixed URL that will be used by the CAS server to transmit the PGT.
	 * When this method is not called, a phpCAS script uses its own URL for the callback.
	 *
	 * @param $url the URL
	 */
	function setFixedCallbackURL($url = '') {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (!$PHPCAS_CLIENT->isProxy()) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be `string\')');
		}
		$PHPCAS_CLIENT->setCallbackURL($url);
		phpCAS :: traceEnd();
	}

	/**
	 * Set the fixed URL that will be set as the CAS service parameter. When this
	 * method is not called, a phpCAS script uses its own URL.
	 *
	 * @param $url the URL
	 */
	function setFixedServiceURL($url) {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (gettype($url) != 'string') {
			phpCAS :: error('type mismatched for parameter $url (should be `string\')');
		}
		$PHPCAS_CLIENT->setURL($url);
		phpCAS :: traceEnd();
	}

	/**
	 * Get the URL that is set as the CAS service parameter.
	 */
	function getServiceURL() {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		return ($PHPCAS_CLIENT->getURL());
	}

	/**
	 * Retrieve a Proxy Ticket from the CAS server.
	 */
	function retrievePT($target_service, & $err_code, & $err_msg) {
		global $PHPCAS_CLIENT;
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
		}
		if (gettype($target_service) != 'string') {
			phpCAS :: error('type mismatched for parameter $target_service(should be `string\')');
		}
		return ($PHPCAS_CLIENT->retrievePT($target_service, $err_code, $err_msg));
	}

	/**
	 * Set the certificate of the CAS server.
	 *
	 * @param $cert the PEM certificate
	 */
	function setCasServerCert($cert) {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
		}
		if (gettype($cert) != 'string') {
			phpCAS :: error('type mismatched for parameter $cert (should be `string\')');
		}
		$PHPCAS_CLIENT->setCasServerCert($cert);
		phpCAS :: traceEnd();
	}

	/**
	 * Set the certificate of the CAS server CA.
	 *
	 * @param $cert the CA certificate
	 */
	function setCasServerCACert($cert) {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
		}
		if (gettype($cert) != 'string') {
			phpCAS :: error('type mismatched for parameter $cert (should be `string\')');
		}
		$PHPCAS_CLIENT->setCasServerCACert($cert);
		phpCAS :: traceEnd();
	}

	/**
	 * Set no SSL validation for the CAS server.
	 */
	function setNoCasServerValidation() {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
		}
		$PHPCAS_CLIENT->setNoCasServerValidation();
		phpCAS :: traceEnd();
	}

	/** @} */

	/**
	 * Change CURL options.
	 * CURL is used to connect through HTTPS to CAS server
	 * @param $key the option key
	 * @param $value the value to set
	 */
	function setExtraCurlOption($key, $value) {
		global $PHPCAS_CLIENT;
		phpCAS :: traceBegin();
		if (!is_object($PHPCAS_CLIENT)) {
			phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
		}
		$PHPCAS_CLIENT->setExtraCurlOption($key, $value);
		phpCAS :: traceEnd();
	}

}

// ########################################################################
// DOCUMENTATION
// ########################################################################

// ########################################################################
//  MAIN PAGE

/**
 * @mainpage
 *
 * The following pages only show the source documentation.
 *
 */

// ########################################################################
//  MODULES DEFINITION

/** @defgroup public User interface */

/** @defgroup publicInit Initialization
 *  @ingroup public */

/** @defgroup publicAuth Authentication
 *  @ingroup public */

/** @defgroup publicServices Access to external services
 *  @ingroup public */

/** @defgroup publicConfig Configuration
 *  @ingroup public */

/** @defgroup publicLang Internationalization
 *  @ingroup publicConfig */

/** @defgroup publicOutput HTML output
 *  @ingroup publicConfig */

/** @defgroup publicPGTStorage PGT storage
 *  @ingroup publicConfig */

/** @defgroup publicDebug Debugging
 *  @ingroup public */

/** @defgroup internal Implementation */

/** @defgroup internalAuthentication Authentication
 *  @ingroup internal */

/** @defgroup internalBasic CAS Basic client features (CAS 1.0, Service Tickets)
 *  @ingroup internal */

/** @defgroup internalProxy CAS Proxy features (CAS 2.0, Proxy Granting Tickets)
 *  @ingroup internal */

/** @defgroup internalPGTStorage PGT storage
 *  @ingroup internalProxy */

/** @defgroup internalPGTStorageDB PGT storage in a database
 *  @ingroup internalPGTStorage */

/** @defgroup internalPGTStorageFile PGT storage on the filesystem
 *  @ingroup internalPGTStorage */

/** @defgroup internalCallback Callback from the CAS server
 *  @ingroup internalProxy */

/** @defgroup internalProxied CAS proxied client features (CAS 2.0, Proxy Tickets)
 *  @ingroup internal */

/** @defgroup internalConfig Configuration
 *  @ingroup internal */

/** @defgroup internalOutput HTML output
 *  @ingroup internalConfig */

/** @defgroup internalLang Internationalization
 *  @ingroup internalConfig
 *
 * To add a new language:
 * - 1. define a new constant PHPCAS_LANG_XXXXXX in CAS/CAS.php
 * - 2. copy any file from CAS/languages to CAS/languages/XXXXXX.php
 * - 3. Make the translations
 */

/** @defgroup internalDebug Debugging
 *  @ingroup internal */

/** @defgroup internalMisc Miscellaneous
 *  @ingroup internal */

// ########################################################################
//  EXAMPLES

/**
 * @example example_simple.php
 */
/**
 * @example example_proxy.php
 */
/**
 * @example example_proxy2.php
 */
/**
 * @example example_lang.php
 */
/**
 * @example example_html.php
 */
/**
 * @example example_file.php
 */
/**
 * @example example_db.php
 */
/**
 * @example example_service.php
 */
/**
 * @example example_session_proxy.php
 */
/**
 * @example example_session_service.php
 */
/**
 * @example example_gateway.php
 */
/**
 * @example example_custom_urls.php
 */
?>


code:
<?php
/*
 * Copyright © 2003-2010, The ESUP-Portail consortium & the JA-SIG Collaborative.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of the ESUP-Portail consortium & the JA-SIG
 *       Collaborative nor the names of its contributors may be used to endorse or
 *       promote products derived from this software without specific prior
 *       written permission.

 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @file CAS/PGTStorage/pgt-db.php
 * Basic class for PGT database storage
 */

/**
 * @class PGTStorageDB
 * The PGTStorageDB class is a class for PGT database storage. An instance of
 * this class is returned by CASClient::SetPGTStorageDB().
 *
 * @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
 *
 * @ingroup internalPGTStorageDB
 */

class PGTStorageDB extends PGTStorage
{
  /**
   * @addtogroup internalPGTStorageDB
   * @{
   */

  /**
   * a string representing a PEAR DB URL to connect to the database. Written by
   * PGTStorageDB::PGTStorageDB(), read by getURL().
   *
   * @hideinitializer
   * @private
   */
  var $_url='';

  /**
   * This method returns the PEAR DB URL to use to connect to the database.
   *
   * @return a PEAR DB URL
   *
   * @private
   */
  function getURL()
    {
      return $this->_url;
    }

  /**
   * The handle of the connection to the database where PGT's are stored. Written by
   * PGTStorageDB::init(), read by getLink().
   *
   * @hideinitializer
   * @private
   */
  var $_link = null;

  /**
   * This method returns the handle of the connection to the database where PGT's are
   * stored.
   *
   * @return a handle of connection.
   *
   * @private
   */
  function getLink()
    {
      return $this->_link;
    }

  /**
   * The name of the table where PGT's are stored. Written by
   * PGTStorageDB::PGTStorageDB(), read by getTable().
   *
   * @hideinitializer
   * @private
   */
  var $_table = '';

  /**
   * This method returns the name of the table where PGT's are stored.
   *
   * @return the name of a table.
   *
   * @private
   */
  function getTable()
    {
      return $this->_table;
    }

  // ########################################################################
  //  DEBUGGING
  // ########################################################################

  /**
   * This method returns an informational string giving the type of storage
   * used by the object (used for debugging purposes).
   *
   * @return an informational string.
   * @public
   */
  function getStorageType()
    {
      return "database";
    }

  /**
   * This method returns an informational string giving informations on the
   * parameters of the storage.(used for debugging purposes).
   *
   * @public
   */
  function getStorageInfo()
    {
      return 'url=`'.$this->getURL().'\', table=`'.$this->getTable().'\'';
    }

  // ########################################################################
  //  CONSTRUCTOR
  // ########################################################################

  /**
   * The class constructor, called by CASClient::SetPGTStorageDB().
   *
   * @param $cas_parent the CASClient instance that creates the object.
   * @param $user the user to access the data with
   * @param $password the user's password
   * @param $database_type the type of the database hosting the data
   * @param $hostname the server hosting the database
   * @param $port the port the server is listening on
   * @param $database the name of the database
   * @param $table the name of the table storing the data
   *
   * @public
   */
  function PGTStorageDB($cas_parent,$user,$password,$database_type,$hostname,$port,$database,$table)
    {
      phpCAS::traceBegin();

      // call the ancestor's constructor
      $this->PGTStorage($cas_parent);

      if ( empty($database_type) ) $database_type = CAS_PGT_STORAGE_DB_DEFAULT_DATABASE_TYPE;
      if ( empty($hostname) ) $hostname = CAS_PGT_STORAGE_DB_DEFAULT_HOSTNAME;
      if ( $port==0 ) $port = CAS_PGT_STORAGE_DB_DEFAULT_PORT;
      if ( empty($database) ) $database = CAS_PGT_STORAGE_DB_DEFAULT_DATABASE;
      if ( empty($table) ) $table = CAS_PGT_STORAGE_DB_DEFAULT_TABLE;

      // build and store the PEAR DB URL
      $this->_url = $database_type.':'.'//'.$user.':'.$password.'@'.$hostname.':'.$port.'/'.$database;

      // XXX should use setURL and setTable
      phpCAS::traceEnd();
    }

  // ########################################################################
  //  INITIALIZATION
  // ########################################################################

  /**
   * This method is used to initialize the storage. Halts on error.
   *
   * @public
   */
  function init()
    {
      phpCAS::traceBegin();
      // if the storage has already been initialized, return immediatly
      if ( $this->isInitialized() )
		return;
      // call the ancestor's method (mark as initialized)
      parent::init();

	  //include phpDB library (the test was introduced in release 0.4.8 for
	  //the integration into Tikiwiki).
	  if (!class_exists('DB')) {
		include_once('DB.php');
	  }

      // try to connect to the database
      $this->_link = DB::connect($this->getURL());
      if ( DB::isError($this->_link) ) {
	phpCAS::error('could not connect to database ('.DB::errorMessage($this->_link).')');
      }
      var_dump($this->_link);
      phpCAS::traceBEnd();
    }

  /** @} */
}

?>


code:
<?php
/*
 * Copyright © 2003-2010, The ESUP-Portail consortium & the JA-SIG Collaborative.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of the ESUP-Portail consortium & the JA-SIG
 *       Collaborative nor the names of its contributors may be used to endorse or
 *       promote products derived from this software without specific prior
 *       written permission.

 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * @file CAS/PGTStorage/pgt-file.php
 * Basic class for PGT file storage
 */

/**
 * @class PGTStorageFile
 * The PGTStorageFile class is a class for PGT file storage. An instance of
 * this class is returned by CASClient::SetPGTStorageFile().
 *
 * @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
 *
 * @ingroup internalPGTStorageFile
 */

class PGTStorageFile extends PGTStorage
{
  /**
   * @addtogroup internalPGTStorageFile
   * @{
   */

  /**
   * a string telling where PGT's should be stored on the filesystem. Written by
   * PGTStorageFile::PGTStorageFile(), read by getPath().
   *
   * @private
   */
  var $_path;

  /**
   * This method returns the name of the directory where PGT's should be stored
   * on the filesystem.
   *
   * @return the name of a directory (with leading and trailing '/')
   *
   * @private
   */
  function getPath()
    {
      return $this->_path;
    }

  /**
   * a string telling the format to use to store PGT's (plain or xml). Written by
   * PGTStorageFile::PGTStorageFile(), read by getFormat().
   *
   * @private
   */
  var $_format;

  /**
   * This method returns the format to use when storing PGT's on the filesystem.
   *
   * @return a string corresponding to the format used (plain or xml).
   *
   * @private
   */
  function getFormat()
    {
      return $this->_format;
    }

  // ########################################################################
  //  DEBUGGING
  // ########################################################################

  /**
   * This method returns an informational string giving the type of storage
   * used by the object (used for debugging purposes).
   *
   * @return an informational string.
   * @public
   */
  function getStorageType()
    {
      return "file";
    }

  /**
   * This method returns an informational string giving informations on the
   * parameters of the storage.(used for debugging purposes).
   *
   * @return an informational string.
   * @public
   */
  function getStorageInfo()
    {
      return 'path=`'.$this->getPath().'\', format=`'.$this->getFormat().'\'';
    }

  // ########################################################################
  //  CONSTRUCTOR
  // ########################################################################

  /**
   * The class constructor, called by CASClient::SetPGTStorageFile().
   *
   * @param $cas_parent the CASClient instance that creates the object.
   * @param $format the format used to store the PGT's (`plain' and `xml' allowed).
   * @param $path the path where the PGT's should be stored
   *
   * @public
   */
  function PGTStorageFile($cas_parent,$format,$path)
    {
      phpCAS::traceBegin();
      // call the ancestor's constructor
      $this->PGTStorage($cas_parent);

      if (empty($format) ) $format = CAS_PGT_STORAGE_FILE_DEFAULT_FORMAT;
      if (empty($path) ) $path = CAS_PGT_STORAGE_FILE_DEFAULT_PATH;

      // check that the path is an absolute path
      if (getenv("OS")=="Windows_NT"){

      	 if (!preg_match('`^[a-zA-Z]:`', $path)) {
	     	phpCAS::error('an absolute path is needed for PGT storage to file');
      	}

      }
      else
      {

      	if ( $path[0] != '/' ) {
			phpCAS::error('an absolute path is needed for PGT storage to file');
      	}

      	// store the path (with a leading and trailing '/')
      	$path = preg_replace('|[/]*$|','/',$path);
      	$path = preg_replace('|^[/]*|','/',$path);
      }

      $this->_path = $path;
      // check the format and store it
      switch ($format) {
      case CAS_PGT_STORAGE_FILE_FORMAT_PLAIN:
      case CAS_PGT_STORAGE_FILE_FORMAT_XML:
	$this->_format = $format;
	break;
      default:
	phpCAS::error('unknown PGT file storage format (`'.CAS_PGT_STORAGE_FILE_FORMAT_PLAIN.'\' and `'.CAS_PGT_STORAGE_FILE_FORMAT_XML.'\' allowed)');
      }
      phpCAS::traceEnd();
    }

  // ########################################################################
  //  INITIALIZATION
  // ########################################################################

  /**
   * This method is used to initialize the storage. Halts on error.
   *
   * @public
   */
  function init()
    {
      phpCAS::traceBegin();
      // if the storage has already been initialized, return immediatly
      if ( $this->isInitialized() )
	return;
      // call the ancestor's method (mark as initialized)
      parent::init();
      phpCAS::traceEnd();
    }

  // ########################################################################
  //  PGT I/O
  // ########################################################################

  /**
   * This method returns the filename corresponding to a PGT Iou.
   *
   * @param $pgt_iou the PGT iou.
   *
   * @return a filename
   * @private
   */
  function getPGTIouFilename($pgt_iou)
    {
      phpCAS::traceBegin();
      $filename = $this->getPath().$pgt_iou.'.'.$this->getFormat();
      phpCAS::traceEnd($filename);
      return $filename;
    }

  /**
   * This method stores a PGT and its corresponding PGT Iou into a file. Echoes a
   * warning on error.
   *
   * @param $pgt the PGT
   * @param $pgt_iou the PGT iou
   *
   * @public
   */
  function write($pgt,$pgt_iou)
    {
      phpCAS::traceBegin();
      $fname = $this->getPGTIouFilename($pgt_iou);
      if ( $f=fopen($fname,"w") ) {
	if ( fputs($f,$pgt) === FALSE ) {
	  phpCAS::error('could not write PGT to `'.$fname.'\'');
	}
	fclose($f);
      } else {
	phpCAS::error('could not open `'.$fname.'\'');
      }
      phpCAS::traceEnd();
    }

  /**
   * This method reads a PGT corresponding to a PGT Iou and deletes the
   * corresponding file.
   *
   * @param $pgt_iou the PGT iou
   *
   * @return the corresponding PGT, or FALSE on error
   *
   * @public
   */
  function read($pgt_iou)
    {
      phpCAS::traceBegin();
      $pgt = FALSE;
      $fname = $this->getPGTIouFilename($pgt_iou);
      if ( !($f=fopen($fname,"r")) ) {
	phpCAS::trace('could not open `'.$fname.'\'');
      } else {
	if ( ($pgt=fgets($f)) === FALSE ) {
	  phpCAS::trace('could not read PGT from `'.$fname.'\'');
	}
	fclose($f);
      }

      // delete the PGT file
      @unlink($fname);

      phpCAS::traceEnd($pgt);
      return $pgt;
    }

  /** @} */

}

?>


code:
<?php
/*
 * Copyright © 2003-2010, The ESUP-Portail consortium & the JA-SIG Collaborative.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of the ESUP-Portail consortium & the JA-SIG
 *       Collaborative nor the names of its contributors may be used to endorse or
 *       promote products derived from this software without specific prior
 *       written permission.

 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * @file CAS/PGTStorage/pgt-main.php
 * Basic class for PGT storage
 */

/**
 * @class PGTStorage
 * The PGTStorage class is a generic class for PGT storage. This class should
 * not be instanciated itself but inherited by specific PGT storage classes.
 *
 * @author   Pascal Aubry <pascal.aubry at univ-rennes1.fr>
 *
 * @ingroup internalPGTStorage
 */

class PGTStorage
{
  /**
   * @addtogroup internalPGTStorage
   * @{
   */

  // ########################################################################
  //  CONSTRUCTOR
  // ########################################################################

  /**
   * The constructor of the class, should be called only by inherited classes.
   *
   * @param $cas_parent the CASclient instance that creates the current object.
   *
   * @protected
   */
  function PGTStorage($cas_parent)
    {
      phpCAS::traceBegin();
      if ( !$cas_parent->isProxy() ) {
	phpCAS::error('defining PGT storage makes no sense when not using a CAS proxy');
      }
      phpCAS::traceEnd();
    }

  // ########################################################################
  //  DEBUGGING
  // ########################################################################

  /**
   * This virtual method returns an informational string giving the type of storage
   * used by the object (used for debugging purposes).
   *
   * @public
   */
  function getStorageType()
    {
      phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called');
    }

  /**
   * This virtual method returns an informational string giving informations on the
   * parameters of the storage.(used for debugging purposes).
   *
   * @public
   */
  function getStorageInfo()
    {
      phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called');
    }

  // ########################################################################
  //  ERROR HANDLING
  // ########################################################################

  /**
   * string used to store an error message. Written by PGTStorage::setErrorMessage(),
   * read by PGTStorage::getErrorMessage().
   *
   * @hideinitializer
   * @private
   * @deprecated not used.
   */
  var $_error_message=FALSE;

  /**
   * This method sets en error message, which can be read later by
   * PGTStorage::getErrorMessage().
   *
   * @param $error_message an error message
   *
   * @protected
   * @deprecated not used.
   */
  function setErrorMessage($error_message)
    {
      $this->_error_message = $error_message;
    }

  /**
   * This method returns an error message set by PGTStorage::setErrorMessage().
   *
   * @return an error message when set by PGTStorage::setErrorMessage(), FALSE
   * otherwise.
   *
   * @public
   * @deprecated not used.
   */
  function getErrorMessage()
    {
      return $this->_error_message;
    }

  // ########################################################################
  //  INITIALIZATION
  // ########################################################################

  /**
   * a boolean telling if the storage has already been initialized. Written by
   * PGTStorage::init(), read by PGTStorage::isInitialized().
   *
   * @hideinitializer
   * @private
   */
  var $_initialized = FALSE;

  /**
   * This method tells if the storage has already been intialized.
   *
   * @return a boolean
   *
   * @protected
   */
  function isInitialized()
    {
      return $this->_initialized;
    }

  /**
   * This virtual method initializes the object.
   *
   * @protected
   */
  function init()
    {
      $this->_initialized = TRUE;
    }

  // ########################################################################
  //  PGT I/O
  // ########################################################################

  /**
   * This virtual method stores a PGT and its corresponding PGT Iuo.
   * @note Should never be called.
   *
   * @param $pgt the PGT
   * @param $pgt_iou the PGT iou
   *
   * @protected
   */
  function write($pgt,$pgt_iou)
    {
      phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called');
    }

  /**
   * This virtual method reads a PGT corresponding to a PGT Iou and deletes
   * the corresponding storage entry.
   * @note Should never be called.
   *
   * @param $pgt_iou the PGT iou
   *
   * @protected
   */
  function read($pgt_iou)
    {
      phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called');
    }

  /** @} */

}

// include specific PGT storage classes
include_once(dirname(__FILE__).'/pgt-file.php');
include_once(dirname(__FILE__).'/pgt-db.php');

?>