}
// Get the results of the environment check.
-list($envstatus, $environment_results) = check_moodle_environment($version);
+list($envstatus, $environment_results) = check_moodle_environment($version, ENV_SELECT_NEWER);
// Display the page.
$output = $PAGE->get_renderer('core', 'admin');
* configuration and how it suits Moodle needs.
*
* @param boolean $result final result of the check (true/false)
- * @param array $environment_results array of results gathered
+ * @param environment_results[] $environment_results array of results gathered
* @return string HTML to output.
*/
public function environment_check_table($result, $environment_results) {
get_string('name'),
get_string('info'),
get_string('report'),
+ get_string('plugin'),
get_string('status'),
);
- $servertable->colclasses = array('centeralign name', 'centeralign info', 'leftalign report', 'centeralign status');
+ $servertable->colclasses = array('centeralign name', 'centeralign info', 'leftalign report', 'leftalign plugin', 'centeralign status');
$servertable->attributes['class'] = 'admintable environmenttable generaltable';
$servertable->id = 'serverstatus';
$othertable->head = array(
get_string('info'),
get_string('report'),
+ get_string('plugin'),
get_string('status'),
);
- $othertable->colclasses = array('aligncenter info', 'alignleft report', 'aligncenter status');
+ $othertable->colclasses = array('aligncenter info', 'alignleft report', 'alignleft plugin', 'aligncenter status');
$othertable->attributes['class'] = 'admintable environmenttable generaltable';
$othertable->id = 'otherserverstatus';
$type = $environment_result->getPart();
$info = $environment_result->getInfo();
$status = $environment_result->getStatus();
+ $plugin = $environment_result->getPluginName();
$error_code = $environment_result->getErrorCode();
// Process Report field
$rec = new stdClass();
if (!empty($info)){
$linkparts[] = $info;
}
- if (empty($CFG->docroot)) {
+ // Plugin environments do not have docs pages yet.
+ if (empty($CFG->docroot) or $environment_result->plugin) {
$report = get_string($stringtouse, 'admin', $rec);
} else {
$report = $this->doc_link(join($linkparts, '/'), get_string($stringtouse, 'admin', $rec));
// Add the row to the table
if ($environment_result->getPart() == 'custom_check'){
- $otherdata[$messagetype][] = array ($info, $report, $status);
+ $otherdata[$messagetype][] = array ($info, $report, $plugin, $status);
} else {
- $serverdata[$messagetype][] = array ($type, $info, $report, $status);
+ $serverdata[$messagetype][] = array ($type, $info, $report, $plugin, $status);
}
}
}
$temp->add(new admin_setting_configselect('defaultpreference_autosubscribe', new lang_string('autosubscribe'),
'', 1, $choices));
- if (!empty($CFG->forum_trackreadposts)) {
- $choices = array();
- $choices['0'] = new lang_string('trackforumsno');
- $choices['1'] = new lang_string('trackforumsyes');
- $temp->add(new admin_setting_configselect('defaultpreference_trackforums', new lang_string('trackforums'),
- '', 0, $choices));
- }
+ $choices = array();
+ $choices['0'] = new lang_string('trackforumsno');
+ $choices['1'] = new lang_string('trackforumsyes');
+ $temp->add(new admin_setting_configselect('defaultpreference_trackforums', new lang_string('trackforums'),
+ '', 0, $choices));
}
$ADMIN->add('accounts', $temp);
$cohort = $DB->get_record('cohort', array('id'=>$addcohort));
} else {
$cohort = $DB->get_record('cohort', array('idnumber'=>$addcohort));
+ if (empty($cohort) && has_capability('moodle/cohort:manage', context_system::instance())) {
+ // Cohort was not found. Create a new one.
+ $cohortid = cohort_add_cohort((object)array(
+ 'idnumber' => $addcohort,
+ 'name' => $addcohort,
+ 'contextid' => context_system::instance()->id
+ ));
+ $cohort = $DB->get_record('cohort', array('id'=>$cohortid));
+ }
}
if (empty($cohort)) {
/**
* phpCAS version. accessible for the user by phpCAS::getVersion().
*/
-define('PHPCAS_VERSION', '1.3.2');
+define('PHPCAS_VERSION', '1.3.3');
/**
* @addtogroup public
* CAS version 2.0
*/
define("CAS_VERSION_2_0", '2.0');
+/**
+ * CAS version 3.0
+ */
+define("CAS_VERSION_3_0", '3.0');
// ------------------------------------------------------------------------
// SAML defines
if (is_object(self::$_PHPCAS_CLIENT)) {
phpCAS :: error(self::$_PHPCAS_INIT_CALL['method'] . '() has already been called (at ' . self::$_PHPCAS_INIT_CALL['file'] . ':' . self::$_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 = debug_backtrace();
);
// initialize the object $_PHPCAS_CLIENT
- self::$_PHPCAS_CLIENT = new CAS_Client(
- $server_version, false, $server_hostname, $server_port, $server_uri,
- $changeSessionID
- );
+ try {
+ self::$_PHPCAS_CLIENT = new CAS_Client(
+ $server_version, false, $server_hostname, $server_port, $server_uri,
+ $changeSessionID
+ );
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
+ }
phpCAS :: traceEnd();
}
if (is_object(self::$_PHPCAS_CLIENT)) {
phpCAS :: error(self::$_PHPCAS_INIT_CALL['method'] . '() has already been called (at ' . self::$_PHPCAS_INIT_CALL['file'] . ':' . self::$_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 = debug_backtrace();
);
// initialize the object $_PHPCAS_CLIENT
- self::$_PHPCAS_CLIENT = new CAS_Client(
- $server_version, true, $server_hostname, $server_port, $server_uri,
- $changeSessionID
- );
+ try {
+ self::$_PHPCAS_CLIENT = new CAS_Client(
+ $server_version, true, $server_hostname, $server_port, $server_uri,
+ $changeSessionID
+ );
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
+ }
phpCAS :: traceEnd();
}
*/
public static function setLang($lang)
{
- if (!is_object(self::$_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::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setLang($lang);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setLang($lang);
}
/** @} */
*/
public static function setHTMLHeader($header)
{
- if (!is_object(self::$_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::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setHTMLHeader($header);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setHTMLHeader($header);
}
/**
*/
public static function setHTMLFooter($footer)
{
- if (!is_object(self::$_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::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setHTMLFooter($footer);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setHTMLFooter($footer);
}
/** @} */
public static function setPGTStorage($storage)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->isProxy()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- phpCAS :: error('this method should only be called before ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() (called at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ')');
- }
- if ( !($storage instanceof CAS_PGTStorage) ) {
- phpCAS :: error('type mismatched for parameter $storage (should be a CAS_PGTStorage `object\')');
+ phpCAS::_validateProxyExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setPGTStorage($storage);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setPGTStorage($storage);
phpCAS :: traceEnd();
}
$password='', $table='', $driver_options=null
) {
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->isProxy()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- phpCAS :: error('this method should only be called before ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() (called at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ')');
- }
- if (gettype($username) != 'string') {
- phpCAS :: error('type mismatched for parameter $username (should be `string\')');
- }
- if (gettype($password) != 'string') {
- phpCAS :: error('type mismatched for parameter $password (should be `string\')');
- }
- if (gettype($table) != 'string') {
- phpCAS :: error('type mismatched for parameter $table (should be `string\')');
+ phpCAS::_validateProxyExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setPGTStorageDb($dsn_or_pdo, $username, $password, $table, $driver_options);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setPGTStorageDb($dsn_or_pdo, $username, $password, $table, $driver_options);
phpCAS :: traceEnd();
}
public static function setPGTStorageFile($path = '')
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->isProxy()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- phpCAS :: error('this method should only be called before ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() (called at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ')');
- }
- if (gettype($path) != 'string') {
- phpCAS :: error('type mismatched for parameter $path (should be `string\')');
+ phpCAS::_validateProxyExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setPGTStorageFile($path);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setPGTStorageFile($path);
phpCAS :: traceEnd();
}
/** @} */
public static function getProxiedService ($type)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->isProxy()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- 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 (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
- }
- if (gettype($type) != 'string') {
- phpCAS :: error('type mismatched for parameter $type (should be `string\')');
- }
+ phpCAS::_validateProxyExists();
- $res = self::$_PHPCAS_CLIENT->getProxiedService($type);
+ try {
+ $res = self::$_PHPCAS_CLIENT->getProxiedService($type);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
+ }
phpCAS :: traceEnd();
return $res;
*/
public static function initializeProxiedService (CAS_ProxiedService $proxiedService)
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->isProxy()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- 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 (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
- }
+ phpCAS::_validateProxyExists();
- self::$_PHPCAS_CLIENT->initializeProxiedService($proxiedService);
+ try {
+ self::$_PHPCAS_CLIENT->initializeProxiedService($proxiedService);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
+ }
}
/**
public static function serviceWeb($url, & $err_code, & $output)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->isProxy()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- 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 (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
- }
- if (gettype($url) != 'string') {
- phpCAS :: error('type mismatched for parameter $url (should be `string\')');
- }
+ phpCAS::_validateProxyExists();
- $res = self::$_PHPCAS_CLIENT->serviceWeb($url, $err_code, $output);
+ try {
+ $res = self::$_PHPCAS_CLIENT->serviceWeb($url, $err_code, $output);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
+ }
phpCAS :: traceEnd($res);
return $res;
public static function serviceMail($url, $service, $flags, & $err_code, & $err_msg, & $pt)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->isProxy()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- 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 (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
- }
- if (gettype($url) != 'string') {
- phpCAS :: error('type mismatched for parameter $url (should be `string\')');
- }
+ phpCAS::_validateProxyExists();
- if (gettype($flags) != 'integer') {
- phpCAS :: error('type mismatched for parameter $flags (should be `integer\')');
+ try {
+ $res = self::$_PHPCAS_CLIENT->serviceMail($url, $service, $flags, $err_code, $err_msg, $pt);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- $res = self::$_PHPCAS_CLIENT->serviceMail($url, $service, $flags, $err_code, $err_msg, $pt);
-
phpCAS :: traceEnd($res);
return $res;
}
*/
public static function setCacheTimesForAuthRecheck($n)
{
- if (!is_object(self::$_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 $n (should be `integer\')');
+ phpCAS::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setCacheTimesForAuthRecheck($n);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setCacheTimesForAuthRecheck($n);
}
/**
*/
public static function setPostAuthenticateCallback ($function, array $additionalArgs = array())
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
self::$_PHPCAS_CLIENT->setPostAuthenticateCallback($function, $additionalArgs);
}
*/
public static function setSingleSignoutCallback ($function, array $additionalArgs = array())
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
self::$_PHPCAS_CLIENT->setSingleSignoutCallback($function, $additionalArgs);
}
public static function checkAuthentication()
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
$auth = self::$_PHPCAS_CLIENT->checkAuthentication();
public static function forceAuthentication()
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
-
+ phpCAS::_validateClientExists();
$auth = self::$_PHPCAS_CLIENT->forceAuthentication();
// store where the authentication has been checked and the result
self::$_PHPCAS_CLIENT->markAuthenticationCall($auth);
- /* if (!$auth) {
+ /* if (!$auth) {
phpCAS :: trace('user is not authenticated, redirecting to the CAS server');
self::$_PHPCAS_CLIENT->forceAuthentication();
} else {
public static function renewAuthentication()
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
$auth = self::$_PHPCAS_CLIENT->renewAuthentication();
// store where the authentication has been checked and the result
public static function isAuthenticated()
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
// call the isAuthenticated method of the $_PHPCAS_CLIENT object
$auth = self::$_PHPCAS_CLIENT->isAuthenticated();
*/
public static function isSessionAuthenticated()
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
return (self::$_PHPCAS_CLIENT->isSessionAuthenticated());
}
* This method returns the CAS user's login name.
*
* @return string the login name of the authenticated user
- * @warning should not be called only after phpCAS::forceAuthentication()
+ * @warning should only be called after phpCAS::forceAuthentication()
* or phpCAS::checkAuthentication().
* */
public static function getUser()
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::forceAuthentication() or ' . __CLASS__ . '::isAuthenticated()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
+ phpCAS::_validateClientExists();
+
+ try {
+ return self::$_PHPCAS_CLIENT->getUser();
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- return self::$_PHPCAS_CLIENT->getUser();
}
/**
* Answer attributes about the authenticated user.
*
- * @warning should not be called only after phpCAS::forceAuthentication()
+ * @warning should only be called after phpCAS::forceAuthentication()
* or phpCAS::checkAuthentication().
*
* @return array
*/
public static function getAttributes()
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::forceAuthentication() or ' . __CLASS__ . '::isAuthenticated()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
+ phpCAS::_validateClientExists();
+
+ try {
+ return self::$_PHPCAS_CLIENT->getAttributes();
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- return self::$_PHPCAS_CLIENT->getAttributes();
}
/**
* Answer true if there are attributes for the authenticated user.
*
- * @warning should not be called only after phpCAS::forceAuthentication()
+ * @warning should only be called after phpCAS::forceAuthentication()
* or phpCAS::checkAuthentication().
*
* @return bool
*/
public static function hasAttributes()
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::forceAuthentication() or ' . __CLASS__ . '::isAuthenticated()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
+ phpCAS::_validateClientExists();
+
+ try {
+ return self::$_PHPCAS_CLIENT->hasAttributes();
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- return self::$_PHPCAS_CLIENT->hasAttributes();
}
/**
* @param string $key attribute name
*
* @return bool
- * @warning should not be called only after phpCAS::forceAuthentication()
+ * @warning should only be called after phpCAS::forceAuthentication()
* or phpCAS::checkAuthentication().
*/
public static function hasAttribute($key)
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::forceAuthentication() or ' . __CLASS__ . '::isAuthenticated()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
+ phpCAS::_validateClientExists();
+
+ try {
+ return self::$_PHPCAS_CLIENT->hasAttribute($key);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- return self::$_PHPCAS_CLIENT->hasAttribute($key);
}
/**
* @param string $key attribute name
*
* @return mixed string for a single value or an array if multiple values exist.
- * @warning should not be called only after phpCAS::forceAuthentication()
+ * @warning should only be called after phpCAS::forceAuthentication()
* or phpCAS::checkAuthentication().
*/
public static function getAttribute($key)
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCalled()) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::forceAuthentication() or ' . __CLASS__ . '::isAuthenticated()');
- }
- if (!self::$_PHPCAS_CLIENT->wasAuthenticationCallSuccessful()) {
- phpCAS :: error('authentication was checked (by ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerMethod() . '() at ' . self::$_PHPCAS_CLIENT->getAuthenticationCallerFile() . ':' . self::$_PHPCAS_CLIENT->getAuthenticationCallerLine() . ') but the method returned false');
+ phpCAS::_validateClientExists();
+
+ try {
+ return self::$_PHPCAS_CLIENT->getAttribute($key);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- return self::$_PHPCAS_CLIENT->getAttribute($key);
}
/**
*/
public static function handleLogoutRequests($check_client = true, $allowed_clients = false)
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
return (self::$_PHPCAS_CLIENT->handleLogoutRequests($check_client, $allowed_clients));
}
*/
public static function getServerLoginURL()
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
return self::$_PHPCAS_CLIENT->getServerLoginURL();
}
public static function setServerLoginURL($url = '')
{
phpCAS :: traceBegin();
- if (!is_object(self::$_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::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setServerLoginURL($url);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setServerLoginURL($url);
+
phpCAS :: traceEnd();
}
public static function setServerServiceValidateURL($url = '')
{
phpCAS :: traceBegin();
- if (!is_object(self::$_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::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setServerServiceValidateURL($url);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setServerServiceValidateURL($url);
+
phpCAS :: traceEnd();
}
public static function setServerProxyValidateURL($url = '')
{
phpCAS :: traceBegin();
- if (!is_object(self::$_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::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setServerProxyValidateURL($url);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setServerProxyValidateURL($url);
+
phpCAS :: traceEnd();
}
public static function setServerSamlValidateURL($url = '')
{
phpCAS :: traceBegin();
- if (!is_object(self::$_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::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setServerSamlValidateURL($url);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setServerSamlValidateURL($url);
+
phpCAS :: traceEnd();
}
*/
public static function getServerLogoutURL()
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should not be called before ' . __CLASS__ . '::client() or ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
return self::$_PHPCAS_CLIENT->getServerLogoutURL();
}
public static function setServerLogoutURL($url = '')
{
phpCAS :: traceBegin();
- if (!is_object(self::$_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::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setServerLogoutURL($url);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setServerLogoutURL($url);
+
phpCAS :: traceEnd();
}
public static function logout($params = "")
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
$parsedParams = array ();
if ($params != "") {
if (is_string($params)) {
public static function logoutWithRedirectService($service)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
if (!is_string($service)) {
phpCAS :: error('type mismatched for parameter $service (should be `string\')');
}
{
trigger_error('Function deprecated for cas servers >= 3.3.5.1', E_USER_DEPRECATED);
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
if (!is_string($service)) {
phpCAS :: error('type mismatched for parameter $service (should be `string\')');
}
public static function setFixedCallbackURL($url = '')
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
- if (!self::$_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::_validateProxyExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setCallbackURL($url);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setCallbackURL($url);
+
phpCAS :: traceEnd();
}
public static function setFixedServiceURL($url)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_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::_validateProxyExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setURL($url);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setURL($url);
+
phpCAS :: traceEnd();
}
*/
public static function getServiceURL()
{
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateProxyExists();
return (self::$_PHPCAS_CLIENT->getURL());
}
*/
public static function retrievePT($target_service, & $err_code, & $err_msg)
{
- if (!is_object(self::$_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\')');
+ phpCAS::_validateProxyExists();
+
+ try {
+ return (self::$_PHPCAS_CLIENT->retrievePT($target_service, $err_code, $err_msg));
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- return (self::$_PHPCAS_CLIENT->retrievePT($target_service, $err_code, $err_msg));
}
/**
public static function setCasServerCACert($cert, $validate_cn = true)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_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\')');
- }
- if (gettype($validate_cn) != 'boolean') {\r
- phpCAS :: error('type mismatched for parameter $validate_cn (should be `boolean\')');\r
+ phpCAS::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->setCasServerCACert($cert, $validate_cn);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->setCasServerCACert($cert, $validate_cn);
+
phpCAS :: traceEnd();
}
public static function setNoCasServerValidation()
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
phpCAS :: trace('You have configured no validation of the legitimacy of the cas server. This is not recommended for production use.');
self::$_PHPCAS_CLIENT->setNoCasServerValidation();
phpCAS :: traceEnd();
public static function setNoClearTicketsFromUrl()
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
self::$_PHPCAS_CLIENT->setNoClearTicketsFromUrl();
phpCAS :: traceEnd();
}
public static function setExtraCurlOption($key, $value)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
- }
+ phpCAS::_validateClientExists();
+
self::$_PHPCAS_CLIENT->setExtraCurlOption($key, $value);
phpCAS :: traceEnd();
}
public static function allowProxyChain(CAS_ProxyChain_Interface $proxy_chain)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
- }
- if (self::$_PHPCAS_CLIENT->getServerVersion() !== CAS_VERSION_2_0) {
- phpCAS :: error('this method can only be used with the cas 2.0 protool');
+ phpCAS::_validateClientExists();
+
+ if (self::$_PHPCAS_CLIENT->getServerVersion() !== CAS_VERSION_2_0
+ && self::$_PHPCAS_CLIENT->getServerVersion() !== CAS_VERSION_3_0) {
+ phpCAS :: error('this method can only be used with the cas 2.0/3.0 protocols');
}
self::$_PHPCAS_CLIENT->getAllowedProxyChains()->allowProxyChain($proxy_chain);
phpCAS :: traceEnd();
*/
public static function getProxies ()
{
- if ( !is_object(self::$_PHPCAS_CLIENT) ) {
- phpCAS::error('this method should only be called after '.__CLASS__.'::client()');
- }
+ phpCAS::_validateProxyExists();
return(self::$_PHPCAS_CLIENT->getProxies());
}
{
phpCAS::traceBegin();
phpCAS::log('rebroadcastNodeUrl:'.$rebroadcastNodeUrl);
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
- }
- if ( !(bool)preg_match("/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i", $rebroadcastNodeUrl)) {
- phpCAS::error('type mismatched for parameter $rebroadcastNodeUrl (should be `url\')');
+ phpCAS::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->addRebroadcastNode($rebroadcastNodeUrl);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->addRebroadcastNode($rebroadcastNodeUrl);
+
phpCAS::traceEnd();
}
public static function addRebroadcastHeader($header)
{
phpCAS :: traceBegin();
- if (!is_object(self::$_PHPCAS_CLIENT)) {
- phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()');
+ phpCAS::_validateClientExists();
+
+ try {
+ self::$_PHPCAS_CLIENT->addRebroadcastHeader($header);
+ } catch (Exception $e) {
+ phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
}
- self::$_PHPCAS_CLIENT->addRebroadcastHeader($header);
+
phpCAS :: traceEnd();
}
-}
+ /**
+ * Checks if a client already exists
+ *
+ * @throws CAS_OutOfSequenceBeforeClientException
+ *
+ * @return void
+ */
+ private static function _validateClientExists()
+ {
+ if (!is_object(self::$_PHPCAS_CLIENT)) {
+ throw new CAS_OutOfSequenceBeforeClientException();
+ }
+ }
+
+ /**
+ * Checks of a proxy client aready exists
+ *
+ * @throws CAS_OutOfSequenceBeforeProxyException
+ *
+ * @return void
+ */
+ private static function _validateProxyExists()
+ {
+ if (!is_object(self::$_PHPCAS_CLIENT)) {
+ throw new CAS_OutOfSequenceBeforeProxyException();
+ }
+ }
+}
// ########################################################################
// DOCUMENTATION
// ########################################################################
printf(
$lang->getYouWereNotAuthenticated(),
htmlentities($client->getURL()),
- $_SERVER['SERVER_ADMIN']
+ isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN']:''
);
phpCAS::trace('CAS URL: '.$cas_url);
phpCAS::trace('Authentication failure: '.$failure);
phpCAS::trace('Reason: CAS error');
break;
case CAS_VERSION_2_0:
+ case CAS_VERSION_3_0:
if ( empty($err_code) ) {
phpCAS::trace('Reason: no CAS error');
} else {
{
// Static to hold the Include Path to CAS
static $include_path;
- // Setup the include path if it's not already set from a previous call
- if (!$include_path) {
- $include_path = dirname(dirname(__FILE__));
- }
+ // Check only for CAS classes
if (substr($class, 0, 4) !== 'CAS_') {
return false;
}
+ // Setup the include path if it's not already set from a previous call
+ if (empty($include_path)) {
+ $include_path = array(dirname(dirname(__FILE__)), dirname(dirname(__FILE__)) . '/../test/' );
+ }
+
// Declare local variable to store the expected full path to the file
- $file_path = $include_path . '/' . str_replace('_', '/', $class) . '.php';
- $fp = @fopen($file_path, 'r', true);
- if ($fp) {
- fclose($fp);
- include $file_path;
- if (!class_exists($class, false) && !interface_exists($class, false)) {
- die(
- new Exception(
- 'Class ' . $class . ' was not present in ' .
- $file_path .
- ' [CAS_autoload]'
- )
- );
+ foreach ($include_path as $path) {
+ $file_path = $path . '/' . str_replace('_', '/', $class) . '.php';
+ $fp = @fopen($file_path, 'r', true);
+ if ($fp) {
+ fclose($fp);
+ include $file_path;
+ if (!class_exists($class, false) && !interface_exists($class, false)) {
+ die(
+ new Exception(
+ 'Class ' . $class . ' was not present in ' .
+ $file_path .
+ ' [CAS_autoload]'
+ )
+ );
+ }
+ return true;
}
- return true;
}
$e = new Exception(
'Class ' . $class . ' could not be loaded from ' .
$file_path . ', file does not exist (Path="'
- . $include_path .'") [CAS_autoload]'
+ . implode(':', $include_path) .'") [CAS_autoload]'
);
$trace = $e->getTrace();
if (isset($trace[2]) && isset($trace[2]['function'])
// set up __autoload
if (function_exists('spl_autoload_register')) {
- if (!(spl_autoload_functions()) || !in_array('CAS_autoload', spl_autoload_functions())) {
+ if (!(spl_autoload_functions())
+ || !in_array('CAS_autoload', spl_autoload_functions())
+ ) {
spl_autoload_register('CAS_autoload');
- if (function_exists('__autoload') && !in_array('__autoload', spl_autoload_functions())) {
+ if (function_exists('__autoload')
+ && !in_array('__autoload', spl_autoload_functions())
+ ) {
// __autoload() was being used, but now would be ignored, add
// it to the autoload stack
spl_autoload_register('__autoload');
*/
public function setHTMLHeader($header)
{
+ // Argument Validation
+ if (gettype($header) != 'string')
+ throw new CAS_TypeMismatchException($header, '$header', 'string');
+
$this->_output_header = $header;
}
*/
public function setHTMLFooter($footer)
{
+ // Argument Validation
+ if (gettype($footer) != 'string')
+ throw new CAS_TypeMismatchException($footer, '$footer', 'string');
+
$this->_output_footer = $footer;
}
*/
public function setLang($lang)
{
+ // Argument Validation
+ if (gettype($lang) != 'string')
+ throw new CAS_TypeMismatchException($lang, '$lang', 'string');
+
phpCAS::traceBegin();
$obj = new $lang();
if (!($obj instanceof CAS_Languages_LanguageInterface)) {
- throw new CAS_InvalidArgumentException('$className must implement the CAS_Languages_LanguageInterface');
+ throw new CAS_InvalidArgumentException(
+ '$className must implement the CAS_Languages_LanguageInterface'
+ );
}
$this->_lang = $lang;
phpCAS::traceEnd();
*/
public function setServerLoginURL($url)
{
+ // Argument Validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+
return $this->_server['login_url'] = $url;
}
*/
public function setServerServiceValidateURL($url)
{
+ // Argument Validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+
return $this->_server['service_validate_url'] = $url;
}
*/
public function setServerProxyValidateURL($url)
{
+ // Argument Validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+
return $this->_server['proxy_validate_url'] = $url;
}
*/
public function setServerSamlValidateURL($url)
{
+ // Argument Validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+
return $this->_server['saml_validate_url'] = $url;
}
$this->_server['service_validate_url'] = $this->_getServerBaseURL()
.'serviceValidate';
break;
+ case CAS_VERSION_3_0:
+ $this->_server['service_validate_url'] = $this->_getServerBaseURL()
+ .'p3/serviceValidate';
+ break;
}
}
- $url = $this->_buildQueryUrl($this->_server['service_validate_url'], 'service='.urlencode($this->getURL()));
+ $url = $this->_buildQueryUrl(
+ $this->_server['service_validate_url'],
+ 'service='.urlencode($this->getURL())
+ );
phpCAS::traceEnd($url);
return $url;
}
}
}
- $url = $this->_buildQueryUrl($this->_server['saml_validate_url'], 'TARGET='.urlencode($this->getURL()));
+ $url = $this->_buildQueryUrl(
+ $this->_server['saml_validate_url'],
+ 'TARGET='.urlencode($this->getURL())
+ );
phpCAS::traceEnd($url);
return $url;
}
case CAS_VERSION_2_0:
$this->_server['proxy_validate_url'] = $this->_getServerBaseURL().'proxyValidate';
break;
+ case CAS_VERSION_3_0:
+ $this->_server['proxy_validate_url'] = $this->_getServerBaseURL().'p3/proxyValidate';
+ break;
}
}
- $url = $this->_buildQueryUrl($this->_server['proxy_validate_url'], 'service='.urlencode($this->getURL()));
+ $url = $this->_buildQueryUrl(
+ $this->_server['proxy_validate_url'],
+ 'service='.urlencode($this->getURL())
+ );
phpCAS::traceEnd($url);
return $url;
}
$this->_server['proxy_url'] = '';
break;
case CAS_VERSION_2_0:
+ case CAS_VERSION_3_0:
$this->_server['proxy_url'] = $this->_getServerBaseURL().'proxy';
break;
}
*/
public function setServerLogoutURL($url)
{
+ // Argument Validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+
return $this->_server['logout_url'] = $url;
}
{
$obj = new $className;
if (!($obj instanceof CAS_Request_RequestInterface)) {
- throw new CAS_InvalidArgumentException('$className must implement the CAS_Request_RequestInterface');
+ throw new CAS_InvalidArgumentException(
+ '$className must implement the CAS_Request_RequestInterface'
+ );
}
$this->_requestImplementation = $className;
}
// Methods for supplying code-flow feedback to integrators.
// ########################################################################
+ /**
+ * Ensure that this is actually a proxy object or fail with an exception
+ *
+ * @throws CAS_OutOfSequenceProxyException
+ *
+ * @return void
+ */
+ public function ensureIsProxy()
+ {
+ if (!$this->isProxy()) {
+ throw new CAS_OutOfSequenceProxyException();
+ }
+ }
+
/**
* Mark the caller of authentication. This will help client integraters determine
* problems with their code flow if they call a function such as getUser() before
return !empty($this->_authentication_caller);
}
+ /**
+ * Ensure that authentication was checked. Terminate with exception if no
+ * authentication was performed
+ *
+ * @throws CAS_OutOfSequenceBeforeAuthenticationCallException
+ *
+ * @return void
+ */
+ private function _ensureAuthenticationCalled()
+ {
+ if (!$this->wasAuthenticationCalled()) {
+ throw new CAS_OutOfSequenceBeforeAuthenticationCallException();
+ }
+ }
+
/**
* Answer the result of the authentication call.
*
*/
public function wasAuthenticationCallSuccessful ()
{
- if (empty($this->_authentication_caller)) {
- throw new CAS_OutOfSequenceException('markAuthenticationCall() hasn\'t happened.');
- }
+ $this->_ensureAuthenticationCalled();
return $this->_authentication_caller['result'];
}
+
+ /**
+ * Ensure that authentication was checked. Terminate with exception if no
+ * authentication was performed
+ *
+ * @throws CAS_OutOfSequenceBeforeAuthenticationCallException
+ *
+ * @return void
+ */
+ public function ensureAuthenticationCallSuccessful()
+ {
+ $this->_ensureAuthenticationCalled();
+ if (!$this->_authentication_caller['result']) {
+ throw new CAS_OutOfSequenceException(
+ 'authentication was checked (by '
+ . $this->getAuthenticationCallerMethod()
+ . '() at ' . $this->getAuthenticationCallerFile()
+ . ':' . $this->getAuthenticationCallerLine()
+ . ') but the method returned false'
+ );
+ }
+ }
+
/**
* Answer information about the authentication caller.
*
*/
public function getAuthenticationCallerFile ()
{
- if (empty($this->_authentication_caller)) {
- throw new CAS_OutOfSequenceException('markAuthenticationCall() hasn\'t happened.');
- }
+ $this->_ensureAuthenticationCalled();
return $this->_authentication_caller['file'];
}
*/
public function getAuthenticationCallerLine ()
{
- if (empty($this->_authentication_caller)) {
- throw new CAS_OutOfSequenceException('markAuthenticationCall() hasn\'t happened.');
- }
+ $this->_ensureAuthenticationCalled();
return $this->_authentication_caller['line'];
}
*/
public function getAuthenticationCallerMethod ()
{
- if (empty($this->_authentication_caller)) {
- throw new CAS_OutOfSequenceException('markAuthenticationCall() hasn\'t happened.');
- }
+ $this->_ensureAuthenticationCalled();
return $this->_authentication_caller['method'];
}
* @param string $server_hostname the hostname of the CAS server
* @param int $server_port the port the CAS server is running on
* @param string $server_uri the URI the CAS server is responding on
- * @param bool $changeSessionID Allow phpCAS to change the session_id (Single Sign Out/handleLogoutRequests is based on that change)
+ * @param bool $changeSessionID Allow phpCAS to change the session_id
+ * (Single Sign Out/handleLogoutRequests
+ * is based on that change)
*
* @return a newly created CAS_Client object
*/
$server_uri,
$changeSessionID = true
) {
+ // Argument validation
+ if (gettype($server_version) != 'string')
+ throw new CAS_TypeMismatchException($server_version, '$server_version', 'string');
+ if (gettype($proxy) != 'boolean')
+ throw new CAS_TypeMismatchException($proxy, '$proxy', 'boolean');
+ if (gettype($server_hostname) != 'string')
+ throw new CAS_TypeMismatchException($server_hostname, '$server_hostname', 'string');
+ if (gettype($server_port) != 'integer')
+ throw new CAS_raTypeMismatchException($server_port, '$server_port', 'integer');
+ if (gettype($server_uri) != 'string')
+ throw new CAS_TypeMismatchException($server_uri, '$server_uri', 'string');
+ if (gettype($changeSessionID) != 'boolean')
+ throw new CAS_TypeMismatchException($changeSessionID, '$changeSessionID', 'boolean');
phpCAS::traceBegin();
-
- $this->_setChangeSessionID($changeSessionID); // true : allow to change the session_id(), false session_id won't be change and logout won't be handle because of that
+ // true : allow to change the session_id(), false session_id won't be
+ // change and logout won't be handle because of that
+ $this->_setChangeSessionID($changeSessionID);
// skip Session Handling for logout requests and if don't want it'
if (session_id()=="" && !$this->_isLogoutRequest()) {
- phpCAS :: trace("Starting a new session");
session_start();
+ phpCAS :: trace("Starting a new session " . session_id());
}
// are we in proxy mode ?
if (!isset($_SESSION['phpCAS']['service_cookies'])) {
$_SESSION['phpCAS']['service_cookies'] = array();
}
- $this->_serviceCookieJar = new CAS_CookieJar($_SESSION['phpCAS']['service_cookies']);
+ $this->_serviceCookieJar = new CAS_CookieJar(
+ $_SESSION['phpCAS']['service_cookies']
+ );
}
//check version
}
break;
case CAS_VERSION_2_0:
+ case CAS_VERSION_3_0:
break;
case SAML_VERSION_1_1:
break;
if ( $this->_isCallbackMode() ) {
//callback mode: check that phpCAS is secured
if ( !$this->_isHttps() ) {
- phpCAS::error('CAS proxies must be secured to use phpCAS; PGT\'s will not be received from the CAS server');
+ phpCAS::error(
+ 'CAS proxies must be secured to use phpCAS; PGT\'s will not be received from the CAS server'
+ );
}
} else {
//normal mode: get ticket and remove it from CGI parameters for
unset($_GET['ticket']);
} else if ( !empty($ticket) ) {
//ill-formed ticket, halt
- phpCAS::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')');
+ phpCAS::error(
+ 'ill-formed ticket found in the URL (ticket=`'
+ .htmlentities($ticket).'\')'
+ );
}
}
*/
public function getUser()
{
+ // Sequence validation
+ $this->ensureAuthenticationCallSuccessful();
+
+ return $this->_getUser();
+ }
+
+ /**
+ * This method returns the CAS user's login name.
+ *
+ * @return string the login name of the authenticated user
+ *
+ * @warning should be called only after CAS_Client::forceAuthentication() or
+ * CAS_Client::isAuthenticated(), otherwise halt with an error.
+ */
+ private function _getUser()
+ {
+ // This is likely a duplicate check that could be removed....
if ( empty($this->_user) ) {
phpCAS::error(
'this method should be used only after '.__CLASS__
*/
public function getAttributes()
{
+ // Sequence validation
+ $this->ensureAuthenticationCallSuccessful();
+ // This is likely a duplicate check that could be removed....
if ( empty($this->_user) ) {
// if no user is set, there shouldn't be any attributes also...
phpCAS::error(
*/
public function hasAttributes()
{
+ // Sequence validation
+ $this->ensureAuthenticationCallSuccessful();
+
return !empty($this->_attributes);
}
/**
* @return bool is attribute available
*/
public function hasAttribute($key)
+ {
+ // Sequence validation
+ $this->ensureAuthenticationCallSuccessful();
+
+ return $this->_hasAttribute($key);
+ }
+
+ /**
+ * Check whether a specific attribute with a name is available
+ *
+ * @param string $key name of attribute
+ *
+ * @return bool is attribute available
+ */
+ private function _hasAttribute($key)
{
return (is_array($this->_attributes)
&& array_key_exists($key, $this->_attributes));
*/
public function getAttribute($key)
{
- if ($this->hasAttribute($key)) {
+ // Sequence validation
+ $this->ensureAuthenticationCallSuccessful();
+
+ if ($this->_hasAttribute($key)) {
return $this->_attributes[$key];
}
}
*/
public function setCacheTimesForAuthRecheck($n)
{
+ if (gettype($n) != 'integer')
+ throw new CAS_TypeMismatchException($n, '$n', 'string');
+
$this->_cache_times_for_auth_recheck = $n;
}
.$this->_cache_times_for_auth_recheck.')'
);
} else {
- phpCAS::trace('user is not authenticated (cached for until login pressed)');
+ phpCAS::trace(
+ 'user is not authenticated (cached for until login pressed)'
+ );
}
} else {
$_SESSION['phpCAS']['unauth_count'] = 0;
if ( $this->_wasPreviouslyAuthenticated() ) {
if ($this->hasTicket()) {
// User has a additional ticket but was already authenticated
- phpCAS::trace('ticket was present and will be discarded, use renewAuthenticate()');
+ phpCAS::trace(
+ 'ticket was present and will be discarded, use renewAuthenticate()'
+ );
if ($this->_clearTicketsFromUrl) {
phpCAS::trace("Prepare redirect to : ".$this->getURL());
+ session_write_close();
header('Location: '.$this->getURL());
flush();
phpCAS::traceExit();
throw new CAS_GracefullTerminationException();
} else {
- phpCAS::trace('Already authenticated, but skipping ticket clearing since setNoClearTicketsFromUrl() was used.');
+ phpCAS::trace(
+ 'Already authenticated, but skipping ticket clearing since setNoClearTicketsFromUrl() was used.'
+ );
$res = true;
}
} else {
// the user has already (previously during the session) been
// authenticated, nothing to be done.
- phpCAS::trace('user was already authenticated, no need to look for tickets');
+ phpCAS::trace(
+ 'user was already authenticated, no need to look for tickets'
+ );
$res = true;
}
} else {
switch ($this->getServerVersion()) {
case CAS_VERSION_1_0:
// if a Service Ticket was given, validate it
- phpCAS::trace('CAS 1.0 ticket `'.$this->getTicket().'\' is present');
- $this->validateCAS10($validate_url, $text_response, $tree_response); // if it fails, it halts
- phpCAS::trace('CAS 1.0 ticket `'.$this->getTicket().'\' was validated');
- $_SESSION['phpCAS']['user'] = $this->getUser();
+ phpCAS::trace(
+ 'CAS 1.0 ticket `'.$this->getTicket().'\' is present'
+ );
+ $this->validateCAS10(
+ $validate_url, $text_response, $tree_response
+ ); // if it fails, it halts
+ phpCAS::trace(
+ 'CAS 1.0 ticket `'.$this->getTicket().'\' was validated'
+ );
+ $_SESSION['phpCAS']['user'] = $this->_getUser();
$res = true;
$logoutTicket = $this->getTicket();
break;
case CAS_VERSION_2_0:
+ case CAS_VERSION_3_0:
// if a Proxy Ticket was given, validate it
- phpCAS::trace('CAS 2.0 ticket `'.$this->getTicket().'\' is present');
- $this->validateCAS20($validate_url, $text_response, $tree_response); // note: if it fails, it halts
- phpCAS::trace('CAS 2.0 ticket `'.$this->getTicket().'\' was validated');
+ phpCAS::trace(
+ 'CAS '.$this->getServerVersion().' ticket `'.$this->getTicket().'\' is present'
+ );
+ $this->validateCAS20(
+ $validate_url, $text_response, $tree_response
+ ); // note: if it fails, it halts
+ phpCAS::trace(
+ 'CAS '.$this->getServerVersion().' ticket `'.$this->getTicket().'\' was validated'
+ );
if ( $this->isProxy() ) {
- $this->_validatePGT($validate_url, $text_response, $tree_response); // idem
+ $this->_validatePGT(
+ $validate_url, $text_response, $tree_response
+ ); // idem
phpCAS::trace('PGT `'.$this->_getPGT().'\' was validated');
$_SESSION['phpCAS']['pgt'] = $this->_getPGT();
}
- $_SESSION['phpCAS']['user'] = $this->getUser();
- if ($this->hasAttributes()) {
- $_SESSION['phpCAS']['attributes'] = $this->getAttributes();
+ $_SESSION['phpCAS']['user'] = $this->_getUser();
+ if (!empty($this->_attributes)) {
+ $_SESSION['phpCAS']['attributes'] = $this->_attributes;
}
$proxies = $this->getProxies();
if (!empty($proxies)) {
break;
case SAML_VERSION_1_1:
// if we have a SAML ticket, validate it.
- phpCAS::trace('SAML 1.1 ticket `'.$this->getTicket().'\' is present');
- $this->validateSA($validate_url, $text_response, $tree_response); // if it fails, it halts
- phpCAS::trace('SAML 1.1 ticket `'.$this->getTicket().'\' was validated');
- $_SESSION['phpCAS']['user'] = $this->getUser();
- $_SESSION['phpCAS']['attributes'] = $this->getAttributes();
+ phpCAS::trace(
+ 'SAML 1.1 ticket `'.$this->getTicket().'\' is present'
+ );
+ $this->validateSA(
+ $validate_url, $text_response, $tree_response
+ ); // if it fails, it halts
+ phpCAS::trace(
+ 'SAML 1.1 ticket `'.$this->getTicket().'\' was validated'
+ );
+ $_SESSION['phpCAS']['user'] = $this->_getUser();
+ $_SESSION['phpCAS']['attributes'] = $this->_attributes;
$res = true;
$logoutTicket = $this->getTicket();
break;
phpCAS::trace('no ticket found');
}
if ($res) {
- // Mark the auth-check as complete to allow post-authentication
- // callbacks to make use of phpCAS::getUser() and similar methods
- $this->markAuthenticationCall($res);
-
// call the post-authenticate callback if registered.
if ($this->_postAuthenticateCallbackFunction) {
$args = $this->_postAuthenticateCallbackArgs;
array_unshift($args, $logoutTicket);
- call_user_func_array($this->_postAuthenticateCallbackFunction, $args);
+ call_user_func_array(
+ $this->_postAuthenticateCallbackFunction, $args
+ );
}
// if called with a ticket parameter, we need to redirect to the
// security precaution to prevent a ticket in the HTTP_REFERRER
if ($this->_clearTicketsFromUrl) {
phpCAS::trace("Prepare redirect to : ".$this->getURL());
+ session_write_close();
header('Location: '.$this->getURL());
flush();
phpCAS::traceExit();
}
}
}
-
+ // Mark the auth-check as complete to allow post-authentication
+ // callbacks to make use of phpCAS::getUser() and similar methods
+ $this->markAuthenticationCall($res);
phpCAS::traceEnd($res);
return $res;
}
if ( $this->isProxy() ) {
// CAS proxy: username and PGT must be present
- if ( $this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) {
+ if ( $this->isSessionAuthenticated()
+ && !empty($_SESSION['phpCAS']['pgt'])
+ ) {
// authentication already done
$this->_setUser($_SESSION['phpCAS']['user']);
if (isset($_SESSION['phpCAS']['attributes'])) {
$this->setAttributes($_SESSION['phpCAS']['attributes']);
}
$this->_setPGT($_SESSION['phpCAS']['pgt']);
- phpCAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\', PGT = `'.$_SESSION['phpCAS']['pgt'].'\'');
+ phpCAS::trace(
+ 'user = `'.$_SESSION['phpCAS']['user'].'\', PGT = `'
+ .$_SESSION['phpCAS']['pgt'].'\''
+ );
// Include the list of proxies
if (isset($_SESSION['phpCAS']['proxies'])) {
$this->_setProxies($_SESSION['phpCAS']['proxies']);
- phpCAS::trace('proxies = "'.implode('", "', $_SESSION['phpCAS']['proxies']).'"');
+ phpCAS::trace(
+ 'proxies = "'
+ .implode('", "', $_SESSION['phpCAS']['proxies']).'"'
+ );
}
$auth = true;
- } elseif ( $this->isSessionAuthenticated() && empty($_SESSION['phpCAS']['pgt']) ) {
+ } elseif ( $this->isSessionAuthenticated()
+ && empty($_SESSION['phpCAS']['pgt'])
+ ) {
// these two variables should be empty or not empty at the same time
- phpCAS::trace('username found (`'.$_SESSION['phpCAS']['user'].'\') but PGT is empty');
+ phpCAS::trace(
+ 'username found (`'.$_SESSION['phpCAS']['user']
+ .'\') but PGT is empty'
+ );
// unset all tickets to enforce authentication
unset($_SESSION['phpCAS']);
$this->setTicket('');
- } elseif ( !$this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) {
+ } elseif ( !$this->isSessionAuthenticated()
+ && !empty($_SESSION['phpCAS']['pgt'])
+ ) {
// these two variables should be empty or not empty at the same time
- phpCAS::trace('PGT found (`'.$_SESSION['phpCAS']['pgt'].'\') but username is empty');
+ phpCAS::trace(
+ 'PGT found (`'.$_SESSION['phpCAS']['pgt']
+ .'\') but username is empty'
+ );
// unset all tickets to enforce authentication
unset($_SESSION['phpCAS']);
$this->setTicket('');
// Include the list of proxies
if (isset($_SESSION['phpCAS']['proxies'])) {
$this->_setProxies($_SESSION['phpCAS']['proxies']);
- phpCAS::trace('proxies = "'.implode('", "', $_SESSION['phpCAS']['proxies']).'"');
+ phpCAS::trace(
+ 'proxies = "'
+ .implode('", "', $_SESSION['phpCAS']['proxies']).'"'
+ );
}
$auth = true;
{
phpCAS::traceBegin();
$cas_url = $this->getServerLoginURL($gateway, $renew);
+ session_write_close();
if (php_sapi_name() === 'cli') {
@header('Location: '.$cas_url);
} else {
$cas_url = $this->getServerLogoutURL();
$paramSeparator = '?';
if (isset($params['url'])) {
- $cas_url = $cas_url . $paramSeparator . "url=" . urlencode($params['url']);
+ $cas_url = $cas_url . $paramSeparator . "url="
+ . urlencode($params['url']);
$paramSeparator = '&';
}
if (isset($params['service'])) {
- $cas_url = $cas_url . $paramSeparator . "service=" . urlencode($params['service']);
+ $cas_url = $cas_url . $paramSeparator . "service="
+ . urlencode($params['service']);
}
header('Location: '.$cas_url);
phpCAS::trace("Prepare redirect to : ".$cas_url);
phpCAS::traceEnd();
return;
}
- if (!$this->getChangeSessionID() && is_null($this->_signoutCallbackFunction)) {
- phpCAS::trace("phpCAS can't handle logout requests if it is not allowed to change session_id.");
+ if (!$this->getChangeSessionID()
+ && is_null($this->_signoutCallbackFunction)
+ ) {
+ phpCAS::trace(
+ "phpCAS can't handle logout requests if it is not allowed to change session_id."
+ );
}
phpCAS::trace("Logout requested");
$decoded_logout_rq = urldecode($_POST['logoutRequest']);
$client = gethostbyaddr($client_ip);
phpCAS::trace("Client: ".$client."/".$client_ip);
foreach ($allowed_clients as $allowed_client) {
- if (($client == $allowed_client) or ($client_ip == $allowed_client)) {
- phpCAS::trace("Allowed client '".$allowed_client."' matches, logout request is allowed");
+ if (($client == $allowed_client)
+ || ($client_ip == $allowed_client)
+ ) {
+ phpCAS::trace(
+ "Allowed client '".$allowed_client
+ ."' matches, logout request is allowed"
+ );
$allowed = true;
break;
} else {
- phpCAS::trace("Allowed client '".$allowed_client."' does not match");
+ phpCAS::trace(
+ "Allowed client '".$allowed_client."' does not match"
+ );
}
}
} else {
$this->_rebroadcast(self::LOGOUT);
}
// Extract the ticket from the SAML Request
- preg_match("|<samlp:SessionIndex>(.*)</samlp:SessionIndex>|", $decoded_logout_rq, $tick, PREG_OFFSET_CAPTURE, 3);
- $wrappedSamlSessionIndex = preg_replace('|<samlp:SessionIndex>|', '', $tick[0][0]);
- $ticket2logout = preg_replace('|</samlp:SessionIndex>|', '', $wrappedSamlSessionIndex);
+ preg_match(
+ "|<samlp:SessionIndex>(.*)</samlp:SessionIndex>|",
+ $decoded_logout_rq, $tick, PREG_OFFSET_CAPTURE, 3
+ );
+ $wrappedSamlSessionIndex = preg_replace(
+ '|<samlp:SessionIndex>|', '', $tick[0][0]
+ );
+ $ticket2logout = preg_replace(
+ '|</samlp:SessionIndex>|', '', $wrappedSamlSessionIndex
+ );
phpCAS::trace("Ticket to logout: ".$ticket2logout);
// call the post-authenticate callback if registered.
call_user_func_array($this->_signoutCallbackFunction, $args);
}
- // If phpCAS is managing the session_id, destroy session thanks to session_id.
+ // If phpCAS is managing the session_id, destroy session thanks to
+ // session_id.
if ($this->getChangeSessionID()) {
$session_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $ticket2logout);
phpCAS::trace("Session id: ".$session_id);
private $_cas_server_ca_cert = null;
- /**\r
- * validate CN of the CAS server certificate\r
- *\r
- * @hideinitializer\r
- */\r
+ /**
+
+ * validate CN of the CAS server certificate
+
+ *
+
+ * @hideinitializer
+
+ */
+
private $_cas_server_cn_validate = true;
/**
*/
public function setCasServerCACert($cert, $validate_cn)
{
+ // Argument validation
+ if (gettype($cert) != 'string')
+ throw new CAS_TypeMismatchException($cert, '$cert', 'string');
+ if (gettype($validate_cn) != 'boolean')
+ throw new CAS_TypeMismatchException($validate_cn, '$validate_cn', 'boolean');
+
$this->_cas_server_ca_cert = $cert;
$this->_cas_server_cn_validate = $validate_cn;
}
phpCAS::traceBegin();
$result = false;
// build the URL to validate the ticket
- $validate_url = $this->getServerServiceValidateURL().'&ticket='.$this->getTicket();
+ $validate_url = $this->getServerServiceValidateURL()
+ .'&ticket='.urlencode($this->getTicket());
// open and read the URL
if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) {
- phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
+ phpCAS::trace(
+ 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')'
+ );
throw new CAS_AuthenticationException(
$this, 'CAS 1.0 ticket not validated', $validate_url,
true/*$no_response*/
// open and read the URL
if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) {
- phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
- throw new CAS_AuthenticationException($this, 'SA not validated', $validate_url, true/*$no_response*/);
+ phpCAS::trace(
+ 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')'
+ );
+ throw new CAS_AuthenticationException(
+ $this, 'SA not validated', $validate_url, true/*$no_response*/
+ );
}
phpCAS::trace('server version: '.$this->getServerVersion());
$result = false;
} else if ( $tree_response->localName != 'Envelope' ) {
// insure that tag name is 'Envelope'
- phpCAS::trace('bad XML root node (should be `Envelope\' instead of `'.$tree_response->localName.'\'');
+ phpCAS::trace(
+ 'bad XML root node (should be `Envelope\' instead of `'
+ .$tree_response->localName.'\''
+ );
throw new CAS_AuthenticationException(
$this, 'SA not validated', $validate_url,
false/*$no_response*/, true/*$bad_response*/,
foreach ($attr_array as $attr_key => $attr_value) {
if (count($attr_value) > 1) {
$this->_attributes[$attr_key] = $attr_value;
- phpCAS::trace("* " . $attr_key . "=" . $attr_value);
+ phpCAS::trace("* " . $attr_key . "=" . print_r($attr_value, true));
} else {
$this->_attributes[$attr_key] = $attr_value[0];
phpCAS::trace("* " . $attr_key . "=" . $attr_value[0]);
$final_uri = '';
// remove the ticket if present in the URL
$final_uri = 'https://';
- $final_uri .= $this->_getServerUrl();
+ $final_uri .= $this->_getClientUrl();
$request_uri = $_SERVER['REQUEST_URI'];
$request_uri = preg_replace('/\?.*$/', '', $request_uri);
$final_uri .= $request_uri;
- $this->setCallbackURL($final_uri);
+ $this->_callback_url = $final_uri;
}
return $this->_callback_url;
}
*/
public function setCallbackURL($url)
{
+ // Sequence validation
+ $this->ensureIsProxy();
+ // Argument Validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+
return $this->_callback_url = $url;
}
*/
public function setPGTStorage($storage)
{
+ // Sequence validation
+ $this->ensureIsProxy();
+
// check that the storage has not already been set
if ( is_object($this->_pgt_storage) ) {
phpCAS::error('PGT storage already defined');
}
// check to make sure a valid storage object was specified
- if ( !($storage instanceof CAS_PGTStorage_AbstractStorage) ) {
- phpCAS::error('Invalid PGT storage object');
- }
+ if ( !($storage instanceof CAS_PGTStorage_AbstractStorage) )
+ throw new CAS_TypeMismatchException($storage, '$storage', 'CAS_PGTStorage_AbstractStorage object');
// store the PGTStorage object
$this->_pgt_storage = $storage;
*
* @return void
*/
- public function setPGTStorageDb($dsn_or_pdo, $username='', $password='', $table='', $driver_options=null)
- {
+ public function setPGTStorageDb(
+ $dsn_or_pdo, $username='', $password='', $table='', $driver_options=null
+ ) {
+ // Sequence validation
+ $this->ensureIsProxy();
+
+ // Argument validation
+ if ((is_object($dsn_or_pdo) && !($dsn_or_pdo instanceof PDO)) || gettype($dsn_or_pdo) != 'string')
+ throw new CAS_TypeMismatchException($dsn_or_pdo, '$dsn_or_pdo', 'string or PDO object');
+ if (gettype($username) != 'string')
+ throw new CAS_TypeMismatchException($username, '$username', 'string');
+ if (gettype($password) != 'string')
+ throw new CAS_TypeMismatchException($password, '$password', 'string');
+ if (gettype($table) != 'string')
+ throw new CAS_TypeMismatchException($table, '$password', 'string');
+
// create the storage object
- $this->setPGTStorage(new CAS_PGTStorage_Db($this, $dsn_or_pdo, $username, $password, $table, $driver_options));
+ $this->setPGTStorage(
+ new CAS_PGTStorage_Db(
+ $this, $dsn_or_pdo, $username, $password, $table, $driver_options
+ )
+ );
}
/**
*/
public function setPGTStorageFile($path='')
{
+ // Sequence validation
+ $this->ensureIsProxy();
+
+ // Argument validation
+ if (gettype($path) != 'string')
+ throw new CAS_TypeMismatchException($path, '$path', 'string');
+
// create the storage object
$this->setPGTStorage(new CAS_PGTStorage_File($this, $path));
}
*
* @param string &$validate_url the URL of the request to the CAS server.
* @param string $text_response the response of the CAS server, as is
- * (XML text); result of CAS_Client::validateCAS10() or CAS_Client::validateCAS20().
+ * (XML text); result of
+ * CAS_Client::validateCAS10() or
+ * CAS_Client::validateCAS20().
* @param string $tree_response the response of the CAS server, as a DOM XML
* tree; result of CAS_Client::validateCAS10() or CAS_Client::validateCAS20().
*
);
} else {
// PGT Iou transmitted, extract it
- $pgt_iou = trim($tree_response->getElementsByTagName("proxyGrantingTicket")->item(0)->nodeValue);
+ $pgt_iou = trim(
+ $tree_response->getElementsByTagName("proxyGrantingTicket")->item(0)->nodeValue
+ );
if (preg_match('/PGTIOU-[\.\-\w]/', $pgt_iou)) {
$pgt = $this->_loadPGT($pgt_iou);
if ( $pgt == false ) {
phpCAS::trace('could not load PGT');
throw new CAS_AuthenticationException(
- $this, 'PGT Iou was transmitted but PGT could not be retrieved',
+ $this,
+ 'PGT Iou was transmitted but PGT could not be retrieved',
$validate_url, false/*$no_response*/,
false/*$bad_response*/, $text_response
);
*/
public function retrievePT($target_service,&$err_code,&$err_msg)
{
+ // Argument validation
+ if (gettype($target_service) != 'string')
+ throw new CAS_TypeMismatchException($target_service, '$target_service', 'string');
+
phpCAS::traceBegin();
// by default, $err_msg is set empty and $pt to true. On error, $pt is
$err_msg = '';
// build the URL to retrieve the PT
- $cas_url = $this->getServerProxyURL().'?targetService='.urlencode($target_service).'&pgt='.$this->_getPGT();
+ $cas_url = $this->getServerProxyURL().'?targetService='
+ .urlencode($target_service).'&pgt='.$this->_getPGT();
// open and read the URL
if ( !$this->_readURL($cas_url, $headers, $cas_response, $err_msg) ) {
- phpCAS::trace('could not open URL \''.$cas_url.'\' to validate ('.$err_msg.')');
+ phpCAS::trace(
+ 'could not open URL \''.$cas_url.'\' to validate ('.$err_msg.')'
+ );
$err_code = PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE;
$err_msg = 'could not retrieve PT (no response from the CAS server)';
phpCAS::traceEnd(false);
if ( $proxy_success_list->item(0)->getElementsByTagName("proxyTicket")->length != 0) {
$err_code = PHPCAS_SERVICE_OK;
$err_msg = '';
- $pt = trim($proxy_success_list->item(0)->getElementsByTagName("proxyTicket")->item(0)->nodeValue);
+ $pt = trim(
+ $proxy_success_list->item(0)->getElementsByTagName("proxyTicket")->item(0)->nodeValue
+ );
phpCAS::trace('original PT: '.trim($pt));
phpCAS::traceEnd($pt);
return $pt;
// at this step, we are sure that the response of the CAS server was
// illformed
$err_code = PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE;
- $err_msg = 'Invalid response from the CAS server (response=`'.$cas_response.'\')';
+ $err_msg = 'Invalid response from the CAS server (response=`'
+ .$cas_response.'\')';
phpCAS::traceEnd(false);
return false;
$request->setUrl($url);
if (empty($this->_cas_server_ca_cert) && !$this->_no_cas_server_validation) {
- phpCAS::error('one of the methods phpCAS::setCasServerCACert() or phpCAS::setNoCasServerValidation() must be called.');
+ phpCAS::error(
+ 'one of the methods phpCAS::setCasServerCACert() or phpCAS::setNoCasServerValidation() must be called.'
+ );
}
if ($this->_cas_server_ca_cert != '') {
- $request->setSslCaCert($this->_cas_server_ca_cert, $this->_cas_server_cn_validate);
+ $request->setSslCaCert(
+ $this->_cas_server_ca_cert, $this->_cas_server_cn_validate
+ );
}
// add extra stuff if SAML
phpCAS::traceBegin();
//get the ticket
- $sa = $this->getTicket();
+ $sa = urlencode($this->getTicket());
- $body=SAML_SOAP_ENV.SAML_SOAP_BODY.SAMLP_REQUEST.SAML_ASSERTION_ARTIFACT.$sa.SAML_ASSERTION_ARTIFACT_CLOSE.SAMLP_REQUEST_CLOSE.SAML_SOAP_BODY_CLOSE.SAML_SOAP_ENV_CLOSE;
+ $body = SAML_SOAP_ENV.SAML_SOAP_BODY.SAMLP_REQUEST
+ .SAML_ASSERTION_ARTIFACT.$sa.SAML_ASSERTION_ARTIFACT_CLOSE
+ .SAMLP_REQUEST_CLOSE.SAML_SOAP_BODY_CLOSE.SAML_SOAP_ENV_CLOSE;
phpCAS::traceEnd($body);
return ($body);
*/
public function getProxiedService ($type)
{
+ // Sequence validation
+ $this->ensureIsProxy();
+ $this->ensureAuthenticationCallSuccessful();
+
+ // Argument validation
+ if (gettype($type) != 'string')
+ throw new CAS_TypeMismatchException($type, '$type', 'string');
+
switch ($type) {
case PHPCAS_PROXIED_SERVICE_HTTP_GET:
case PHPCAS_PROXIED_SERVICE_HTTP_POST:
}
return $proxiedService;
case PHPCAS_PROXIED_SERVICE_IMAP;
- $proxiedService = new CAS_ProxiedService_Imap($this->getUser());
+ $proxiedService = new CAS_ProxiedService_Imap($this->_getUser());
if ($proxiedService instanceof CAS_ProxiedService_Testable) {
$proxiedService->setCasClient($this);
}
return $proxiedService;
default:
- throw new CAS_InvalidArgumentException("Unknown proxied-service type, $type.");
+ throw new CAS_InvalidArgumentException(
+ "Unknown proxied-service type, $type."
+ );
}
}
*/
public function initializeProxiedService (CAS_ProxiedService $proxiedService)
{
+ // Sequence validation
+ $this->ensureIsProxy();
+ $this->ensureAuthenticationCallSuccessful();
+
$url = $proxiedService->getServiceUrl();
if (!is_string($url)) {
- throw new CAS_ProxiedService_Exception("Proxied Service ".get_class($proxiedService)."->getServiceUrl() should have returned a string, returned a ".gettype($url)." instead.");
+ throw new CAS_ProxiedService_Exception(
+ "Proxied Service ".get_class($proxiedService)
+ ."->getServiceUrl() should have returned a string, returned a "
+ .gettype($url)." instead."
+ );
}
$pt = $this->retrievePT($url, $err_code, $err_msg);
if (!$pt) {
*/
public function serviceWeb($url,&$err_code,&$output)
{
+ // Sequence validation
+ $this->ensureIsProxy();
+ $this->ensureAuthenticationCallSuccessful();
+
+ // Argument validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+
try {
$service = $this->getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET);
$service->setUrl($url);
return false;
} catch (CAS_ProxiedService_Exception $e) {
$lang = $this->getLangObj();
- $output = sprintf($lang->getServiceUnavailable(), $url, $e->getMessage());
+ $output = sprintf(
+ $lang->getServiceUnavailable(), $url, $e->getMessage()
+ );
$err_code = PHPCAS_SERVICE_NOT_AVAILABLE;
return false;
}
*/
public function serviceMail($url,$serviceUrl,$flags,&$err_code,&$err_msg,&$pt)
{
+ // Sequence validation
+ $this->ensureIsProxy();
+ $this->ensureAuthenticationCallSuccessful();
+
+ // Argument validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+ if (gettype($serviceUrl) != 'string')
+ throw new CAS_TypeMismatchException($serviceUrl, '$serviceUrl', 'string');
+ if (gettype($flags) != 'integer')
+ throw new CAS_TypeMismatchException($flags, '$flags', 'string');
+
try {
$service = $this->getProxiedService(PHPCAS_PROXIED_SERVICE_IMAP);
$service->setServiceUrl($serviceUrl);
$result = false;
// build the URL to validate the ticket
if ($this->getAllowedProxyChains()->isProxyingAllowed()) {
- $validate_url = $this->getServerProxyValidateURL().'&ticket='.$this->getTicket();
+ $validate_url = $this->getServerProxyValidateURL().'&ticket='
+ .urlencode($this->getTicket());
} else {
- $validate_url = $this->getServerServiceValidateURL().'&ticket='.$this->getTicket();
+ $validate_url = $this->getServerServiceValidateURL().'&ticket='
+ .urlencode($this->getTicket());
}
if ( $this->isProxy() ) {
// open and read the URL
if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) {
- phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
+ phpCAS::trace(
+ 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')'
+ );
throw new CAS_AuthenticationException(
$this, 'Ticket not validated', $validate_url,
true/*$no_response*/
$result = false;
} else if ($tree_response->getElementsByTagName("authenticationSuccess")->length != 0) {
// authentication succeded, extract the user name
- $success_elements = $tree_response->getElementsByTagName("authenticationSuccess");
+ $success_elements = $tree_response
+ ->getElementsByTagName("authenticationSuccess");
if ( $success_elements->item(0)->getElementsByTagName("user")->length == 0) {
// no user specified => error
throw new CAS_AuthenticationException(
);
$result = false;
} else {
- $this->_setUser(trim($success_elements->item(0)->getElementsByTagName("user")->item(0)->nodeValue));
+ $this->_setUser(
+ trim(
+ $success_elements->item(0)->getElementsByTagName("user")->item(0)->nodeValue
+ )
+ );
$this->_readExtraAttributesCas20($success_elements);
// Store the proxies we are sitting behind for authorization checking
$proxyList = array();
}
} else if ( $tree_response->getElementsByTagName("authenticationFailure")->length != 0) {
// authentication succeded, extract the error code and message
- $auth_fail_list = $tree_response->getElementsByTagName("authenticationFailure");
+ $auth_fail_list = $tree_response
+ ->getElementsByTagName("authenticationFailure");
throw new CAS_AuthenticationException(
$this, 'Ticket not validated', $validate_url,
false/*$no_response*/, false/*$bad_response*/,
// </cas:serviceResponse>
//
if ( $success_elements->item(0)->getElementsByTagName("attributes")->length != 0) {
- $attr_nodes = $success_elements->item(0)->getElementsByTagName("attributes");
+ $attr_nodes = $success_elements->item(0)
+ ->getElementsByTagName("attributes");
phpCas :: trace("Found nested jasig style attributes");
if ($attr_nodes->item(0)->hasChildNodes()) {
// Nested Attributes
foreach ($attr_nodes->item(0)->childNodes as $attr_child) {
- phpCas :: trace("Attribute [".$attr_child->localName."] = ".$attr_child->nodeValue);
- $this->_addAttributeToArray($extra_attributes, $attr_child->localName, $attr_child->nodeValue);
+ phpCas :: trace(
+ "Attribute [".$attr_child->localName."] = "
+ .$attr_child->nodeValue
+ );
+ $this->_addAttributeToArray(
+ $extra_attributes, $attr_child->localName,
+ $attr_child->nodeValue
+ );
}
}
} else {
continue;
default:
if (strlen(trim($attr_node->nodeValue))) {
- phpCas :: trace("Attribute [".$attr_node->localName."] = ".$attr_node->nodeValue);
- $this->_addAttributeToArray($extra_attributes, $attr_node->localName, $attr_node->nodeValue);
+ phpCas :: trace(
+ "Attribute [".$attr_node->localName."] = ".$attr_node->nodeValue
+ );
+ $this->_addAttributeToArray(
+ $extra_attributes, $attr_node->localName,
+ $attr_node->nodeValue
+ );
}
}
}
// </cas:authenticationSuccess>
// </cas:serviceResponse>
//
- if (!count($extra_attributes) && $success_elements->item(0)->getElementsByTagName("attribute")->length != 0) {
- $attr_nodes = $success_elements->item(0)->getElementsByTagName("attribute");
+ if (!count($extra_attributes)
+ && $success_elements->item(0)->getElementsByTagName("attribute")->length != 0
+ ) {
+ $attr_nodes = $success_elements->item(0)
+ ->getElementsByTagName("attribute");
$firstAttr = $attr_nodes->item(0);
- if (!$firstAttr->hasChildNodes() && $firstAttr->hasAttribute('name') && $firstAttr->hasAttribute('value')) {
+ if (!$firstAttr->hasChildNodes()
+ && $firstAttr->hasAttribute('name')
+ && $firstAttr->hasAttribute('value')
+ ) {
phpCas :: trace("Found Name-Value style attributes");
// Nested Attributes
foreach ($attr_nodes as $attr_node) {
- if ($attr_node->hasAttribute('name') && $attr_node->hasAttribute('value')) {
- phpCas :: trace("Attribute [".$attr_node->getAttribute('name')."] = ".$attr_node->getAttribute('value'));
- $this->_addAttributeToArray($extra_attributes, $attr_node->getAttribute('name'), $attr_node->getAttribute('value'));
+ if ($attr_node->hasAttribute('name')
+ && $attr_node->hasAttribute('value')
+ ) {
+ phpCas :: trace(
+ "Attribute [".$attr_node->getAttribute('name')
+ ."] = ".$attr_node->getAttribute('value')
+ );
+ $this->_addAttributeToArray(
+ $extra_attributes, $attr_node->getAttribute('name'),
+ $attr_node->getAttribute('value')
+ );
}
}
}
*/
public function setURL($url)
{
+ // Argument Validation
+ if (gettype($url) != 'string')
+ throw new CAS_TypeMismatchException($url, '$url', 'string');
+
$this->_url = $url;
}
$final_uri = ($this->_isHttps()) ? 'https' : 'http';
$final_uri .= '://';
- $final_uri .= $this->_getServerUrl();
+ $final_uri .= $this->_getClientUrl();
$request_uri = explode('?', $_SERVER['REQUEST_URI'], 2);
$final_uri .= $request_uri[0];
if (isset($request_uri[1]) && $request_uri[1]) {
$query_string= $this->_removeParameterFromQueryString('ticket', $request_uri[1]);
- // If the query string still has anything left, append it to the final URI
+ // If the query string still has anything left,
+ // append it to the final URI
if ($query_string !== '') {
$final_uri .= "?$query_string";
}
/**
- * Try to figure out the server URL with possible Proxys / Ports etc.
+ * Try to figure out the phpCas client URL with possible Proxys / Ports etc.
*
* @return string Server URL with domain:port
*/
- private function _getServerUrl()
+ private function _getClientUrl()
{
$server_url = '';
if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
if (empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
$server_port = $_SERVER['SERVER_PORT'];
} else {
- $server_port = $_SERVER['HTTP_X_FORWARDED_PORT'];
+ $ports = explode(',', $_SERVER['HTTP_X_FORWARDED_PORT']);
+ $server_port = $ports[0];
}
if ( ($this->_isHttps() && $server_port!=443)
*/
private function _isHttps()
{
- if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
+ if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
+ return ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
+ }
+ if ( isset($_SERVER['HTTPS'])
+ && !empty($_SERVER['HTTPS'])
+ && $_SERVER['HTTPS'] != 'off'
+ ) {
return true;
} else {
return false;
private function _removeParameterFromQueryString($parameterName, $queryString)
{
$parameterName = preg_quote($parameterName);
- return preg_replace("/&$parameterName(=[^&]*)?|^$parameterName(=[^&]*)?&?/", '', $queryString);
+ return preg_replace(
+ "/&$parameterName(=[^&]*)?|^$parameterName(=[^&]*)?&?/",
+ '', $queryString
+ );
}
/**
if ($this->getChangeSessionID()) {
if (!empty($this->_user)) {
$old_session = $_SESSION;
+ phpCAS :: trace("Killing session: ". session_id());
session_destroy();
// set up a new session, of name based on the ticket
$session_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $ticket);
- phpCAS :: trace("Session ID: ".$session_id);
+ phpCAS :: trace("Starting session: ". $session_id);
session_id($session_id);
session_start();
phpCAS :: trace("Restoring old session vars");
$_SESSION = $old_session;
} else {
- phpCAS :: error('Session should only be renamed after successfull authentication');
+ phpCAS :: error(
+ 'Session should only be renamed after successfull authentication'
+ );
}
} else {
- phpCAS :: trace("Skipping session rename since phpCAS is not handling the session.");
+ phpCAS :: trace(
+ "Skipping session rename since phpCAS is not handling the session."
+ );
}
phpCAS::traceEnd();
}
phpCAS::traceBegin();
$lang = $this->getLangObj();
$this->printHTMLHeader($lang->getAuthenticationFailed());
- printf($lang->getYouWereNotAuthenticated(), htmlentities($this->getURL()), $_SERVER['SERVER_ADMIN']);
+ printf(
+ $lang->getYouWereNotAuthenticated(), htmlentities($this->getURL()),
+ $_SERVER['SERVER_ADMIN']
+ );
phpCAS::trace('CAS URL: '.$cas_url);
phpCAS::trace('Authentication failure: '.$failure);
if ( $no_response ) {
phpCAS::trace('Reason: CAS error');
break;
case CAS_VERSION_2_0:
+ case CAS_VERSION_3_0:
if ( empty($err_code) ) {
phpCAS::trace('Reason: no CAS error');
} else {
- phpCAS::trace('Reason: ['.$err_code.'] CAS error: '.$err_msg);
+ phpCAS::trace(
+ 'Reason: ['.$err_code.'] CAS error: '.$err_msg
+ );
}
break;
}
*/
public function addRebroadcastNode($rebroadcastNodeUrl)
{
+ // Argument validation
+ if ( !(bool)preg_match("/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i", $rebroadcastNodeUrl))
+ throw new CAS_TypeMismatchException($rebroadcastNodeUrl, '$rebroadcastNodeUrl', 'url');
+
// Store the rebroadcast node and set flag
$this->_rebroadcast = true;
$this->_rebroadcast_nodes[] = $rebroadcastNodeUrl;
*/
public function addRebroadcastHeader($header)
{
+ if (gettype($header) != 'string')
+ throw new CAS_TypeMismatchException($header, '$header', 'string');
+
$this->_rebroadcast_headers[] = $header;
}
$multiRequest = new $multiClassName();
for ($i = 0; $i < sizeof($this->_rebroadcast_nodes); $i++) {
- if ((($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::HOSTNAME) && !empty($dns) && (stripos($this->_rebroadcast_nodes[$i], $dns) === false)) || (($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::IP) && !empty($ip) && (stripos($this->_rebroadcast_nodes[$i], $ip) === false))) {
- phpCAS::trace('Rebroadcast target URL: '.$this->_rebroadcast_nodes[$i].$_SERVER['REQUEST_URI']);
+ if ((($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::HOSTNAME) && !empty($dns) && (stripos($this->_rebroadcast_nodes[$i], $dns) === false))
+ || (($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::IP) && !empty($ip) && (stripos($this->_rebroadcast_nodes[$i], $ip) === false))
+ ) {
+ phpCAS::trace(
+ 'Rebroadcast target URL: '.$this->_rebroadcast_nodes[$i]
+ .$_SERVER['REQUEST_URI']
+ );
$className = $this->_requestImplementation;
$request = new $className();
$request->makePost();
if ($type == self::LOGOUT) {
// Logout request
- $request->setPostBody('rebroadcast=false&logoutRequest='.$_POST['logoutRequest']);
+ $request->setPostBody(
+ 'rebroadcast=false&logoutRequest='.$_POST['logoutRequest']
+ );
} else if ($type == self::PGTIOU) {
// pgtIou/pgtId rebroadcast
$request->setPostBody('rebroadcast=false');
$multiRequest->addRequest($request);
} else {
- phpCAS::trace('Rebroadcast not sent to self: '.$this->_rebroadcast_nodes[$i].' == '.(!empty($ip)?$ip:'').'/'.(!empty($dns)?$dns:''));
+ phpCAS::trace(
+ 'Rebroadcast not sent to self: '
+ .$this->_rebroadcast_nodes[$i].' == '.(!empty($ip)?$ip:'')
+ .'/'.(!empty($dns)?$dns:'')
+ );
}
}
// We need at least 1 request
protected function parseCookieHeader ($line, $defaultDomain)
{
if (!$defaultDomain) {
- throw new CAS_InvalidArgumentException('$defaultDomain was not provided.');
+ throw new CAS_InvalidArgumentException(
+ '$defaultDomain was not provided.'
+ );
}
// Set our default values
protected function cookieMatchesTarget ($cookie, $target)
{
if (!is_array($target)) {
- throw new CAS_InvalidArgumentException('$target must be an array of URL attributes as generated by parse_url().');
+ throw new CAS_InvalidArgumentException(
+ '$target must be an array of URL attributes as generated by parse_url().'
+ );
}
if (!isset($target['host'])) {
- throw new CAS_InvalidArgumentException('$target must be an array of URL attributes as generated by parse_url().');
+ throw new CAS_InvalidArgumentException(
+ '$target must be an array of URL attributes as generated by parse_url().'
+ );
}
// Verify that the scheme matches
}
}
} else {
- // If the cookie host doesn't begin with '.', the host must case-insensitive
- // match exactly
+ // If the cookie host doesn't begin with '.',
+ // the host must case-insensitive match exactly
if (strcasecmp($target['host'], $cookie['domain']) !== 0) {
return false;
}
}
// Verify that the port matches
- if (isset($cookie['ports']) && !in_array($target['port'], $cookie['ports'])) {
+ if (isset($cookie['ports'])
+ && !in_array($target['port'], $cookie['ports'])
+ ) {
return false;
}
*/
public function getYouWereNotAuthenticated()
{
- return '<p>Sie wurden nicht angemeldet.</p><p>Um es erneut zu versuchen klicken Sie <a href="%s">hier</a>.</p><p>Wenn das Problem bestehen bleibt, kontkatieren Sie den <a href="mailto:%s">Administrator</a> dieser Seite.</p>';
+ return '<p>Sie wurden nicht angemeldet.</p><p>Um es erneut zu versuchen klicken Sie <a href="%s">hier</a>.</p><p>Wenn das Problem bestehen bleibt, kontaktieren Sie den <a href="mailto:%s">Administrator</a> dieser Seite.</p>';
}
/**
}
}
-?>
\ No newline at end of file
+?>
--- /dev/null
+<?php
+
+/**
+ * Licensed to Jasig under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * Jasig 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.
+ *
+ *
+ * PHP Version 5
+ *
+ * @file CAS/OutOfSequenceBeforeAuthenticationCallException.php
+ * @category Authentication
+ * @package PhpCAS
+ * @author Joachim Fritschi <jfritschi@freenet.de>
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
+ * @link https://wiki.jasig.org/display/CASC/phpCAS
+ */
+
+/**
+ * This class defines Exceptions that should be thrown when the sequence of
+ * operations is invalid. In this case it should be thrown when an
+ * authentication call has not yet happened.
+ *
+ * @class CAS_OutOfSequenceBeforeAuthenticationCallException
+ * @category Authentication
+ * @package PhpCAS
+ * @author Joachim Fritschi <jfritschi@freenet.de>
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
+ * @link https://wiki.jasig.org/display/CASC/phpCAS
+ */
+class CAS_OutOfSequenceBeforeAuthenticationCallException
+extends CAS_OutOfSequenceException
+implements CAS_Exception
+{
+ /**
+ * Return standard error meessage
+ *
+ * @return void
+ */
+ public function __construct ()
+ {
+ parent::__construct('An authentication call hasn\'t happened yet.');
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Licensed to Jasig under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * Jasig 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.
+ *
+ *
+ * PHP Version 5
+ *
+ * @file CAS/OutOfSequenceBeforeClientException.php
+ * @category Authentication
+ * @package PhpCAS
+ * @author Joachim Fritschi <jfritschi@freenet.de>
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
+ * @link https://wiki.jasig.org/display/CASC/phpCAS
+ */
+
+/**
+ * This class defines Exceptions that should be thrown when the sequence of
+ * operations is invalid. In this case it should be thrown when the client() or
+ * proxy() call has not yet happened and no client or proxy object exists.
+ *
+ * @class CAS_OutOfSequenceBeforeClientException
+ * @category Authentication
+ * @package PhpCAS
+ * @author Joachim Fritschi <jfritschi@freenet.de>
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
+ * @link https://wiki.jasig.org/display/CASC/phpCAS
+ */
+class CAS_OutOfSequenceBeforeClientException
+extends CAS_OutOfSequenceException
+implements CAS_Exception
+{
+ /**
+ * Return standard error message
+ *
+ * @return void
+ */
+ public function __construct ()
+ {
+ parent::__construct(
+ 'this method cannot be called before phpCAS::client() or phpCAS::proxy()'
+ );
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Licensed to Jasig under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * Jasig 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.
+ *
+ *
+ * PHP Version 5
+ *
+ * @file CAS/OutOfSequenceBeforeProxyException.php
+ * @category Authentication
+ * @package PhpCAS
+ * @author Joachim Fritschi <jfritschi@freenet.de>
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
+ * @link https://wiki.jasig.org/display/CASC/phpCAS
+ */
+
+/**
+ * This class defines Exceptions that should be thrown when the sequence of
+ * operations is invalid. In this case it should be thrown when the proxy() call
+ * has not yet happened and no proxy object exists.
+ *
+ * @class CAS_OutOfSequenceBeforeProxyException
+ * @category Authentication
+ * @package PhpCAS
+ * @author Joachim Fritschi <jfritschi@freenet.de>
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
+ * @link https://wiki.jasig.org/display/CASC/phpCAS
+ */
+class CAS_OutOfSequenceBeforeProxyException
+extends CAS_OutOfSequenceException
+implements CAS_Exception
+{
+
+ /**
+ * Return standard error message
+ *
+ * @return void
+ */
+ public function __construct ()
+ {
+ parent::__construct(
+ 'this method cannot be called before phpCAS::proxy()'
+ );
+ }
+}
{
phpCAS::traceBegin();
if ( !$cas_parent->isProxy() ) {
- phpCAS::error('defining PGT storage makes no sense when not using a CAS proxy');
+ phpCAS::error(
+ 'defining PGT storage makes no sense when not using a CAS proxy'
+ );
}
phpCAS::traceEnd();
}
* @param string $driver_options any driver options to use when
* connecting to the database
*/
- public function __construct($cas_parent, $dsn_or_pdo, $username='', $password='', $table='', $driver_options=null)
- {
+ public function __construct(
+ $cas_parent, $dsn_or_pdo, $username='', $password='', $table='',
+ $driver_options=null
+ ) {
phpCAS::traceBegin();
// call the ancestor's constructor
parent::__construct($cas_parent);
// create the PDO object if it doesn't exist already
if (!($this->_pdo instanceof PDO)) {
try {
- $this->_pdo = new PDO($this->_dsn, $this->_username, $this->_password, $this->_driver_options);
+ $this->_pdo = new PDO(
+ $this->_dsn, $this->_username, $this->_password,
+ $this->_driver_options
+ );
}
catch(PDOException $e) {
phpCAS::error('Database connection error: ' . $e->getMessage());
*/
protected function createTableSql()
{
- return 'CREATE TABLE ' . $this->_getTable() . ' (pgt_iou VARCHAR(255) NOT NULL PRIMARY KEY, pgt VARCHAR(255) NOT NULL)';
+ return 'CREATE TABLE ' . $this->_getTable()
+ . ' (pgt_iou VARCHAR(255) NOT NULL PRIMARY KEY, pgt VARCHAR(255) NOT NULL)';
}
/**
* This method returns the query used to store a pgt
*
- * @return the store PGT SQL, :pgt and :pgt_iou are the bind params contained in the query
+ * @return the store PGT SQL, :pgt and :pgt_iou are the bind params contained
+ * in the query
*/
protected function storePgtSql()
{
- return 'INSERT INTO ' . $this->_getTable() . ' (pgt_iou, pgt) VALUES (:pgt_iou, :pgt)';
+ return 'INSERT INTO ' . $this->_getTable()
+ . ' (pgt_iou, pgt) VALUES (:pgt_iou, :pgt)';
}
/**
- * This method returns the query used to retrieve a pgt. the first column of the first row should contain the pgt
+ * This method returns the query used to retrieve a pgt. the first column
+ * of the first row should contain the pgt
*
- * @return the retrieve PGT SQL, :pgt_iou is the only bind param contained in the query
+ * @return the retrieve PGT SQL, :pgt_iou is the only bind param contained
+ * in the query
*/
protected function retrievePgtSql()
{
/**
* This method returns the query used to delete a pgt.
*
- * @return the delete PGT SQL, :pgt_iou is the only bind param contained in the query
+ * @return the delete PGT SQL, :pgt_iou is the only bind param contained in
+ * the query
*/
protected function deletePgtSql()
{
*
* @return void
* @throws InvalidArgumentException If the $proxyTicket is invalid.
- * @throws CAS_OutOfSequenceException If called after a proxy ticket has already been initialized/set.
+ * @throws CAS_OutOfSequenceException If called after a proxy ticket has
+ * already been initialized/set.
*/
public function setProxyTicket ($proxyTicket)
{
if (empty($proxyTicket)) {
- throw new CAS_InvalidArgumentException("Trying to initialize with an empty proxy ticket.");
+ throw new CAS_InvalidArgumentException(
+ 'Trying to initialize with an empty proxy ticket.'
+ );
}
if (!empty($this->_proxyTicket)) {
- throw new CAS_OutOfSequenceException('Already initialized, cannot change the proxy ticket.');
+ throw new CAS_OutOfSequenceException(
+ 'Already initialized, cannot change the proxy ticket.'
+ );
}
$this->_proxyTicket = $proxyTicket;
}
protected function getProxyTicket ()
{
if (empty($this->_proxyTicket)) {
- throw new CAS_OutOfSequenceException('No proxy ticket yet. Call $this->initializeProxyTicket() to aquire the proxy ticket.');
+ throw new CAS_OutOfSequenceException(
+ 'No proxy ticket yet. Call $this->initializeProxyTicket() to aquire the proxy ticket.'
+ );
}
return $this->_proxyTicket;
public function setCasClient (CAS_Client $casClient)
{
if (!empty($this->_proxyTicket)) {
- throw new CAS_OutOfSequenceException('Already initialized, cannot change the CAS_Client.');
+ throw new CAS_OutOfSequenceException(
+ 'Already initialized, cannot change the CAS_Client.'
+ );
}
$this->_casClient = $casClient;
protected function initializeProxyTicket()
{
if (!empty($this->_proxyTicket)) {
- throw new CAS_OutOfSequenceException('Already initialized, cannot initialize again.');
+ throw new CAS_OutOfSequenceException(
+ 'Already initialized, cannot initialize again.'
+ );
}
// Allow usage of a particular CAS_Client for unit testing.
if (empty($this->_casClient)) {
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://wiki.jasig.org/display/CASC/phpCAS
*/
-abstract class CAS_ProxiedService_Http_Abstract
-extends CAS_ProxiedService_Abstract
-implements CAS_ProxiedService_Http
+abstract class CAS_ProxiedService_Http_Abstract extends
+CAS_ProxiedService_Abstract implements CAS_ProxiedService_Http
{
/**
* The HTTP request mechanism talking to the target service.
*
* @return void
*/
- public function __construct (CAS_Request_RequestInterface $requestHandler, CAS_CookieJar $cookieJar)
- {
+ public function __construct(CAS_Request_RequestInterface $requestHandler,
+ CAS_CookieJar $cookieJar
+ ) {
$this->requestHandler = $requestHandler;
$this->_cookieJar = $cookieJar;
}
* @return string
* @throws Exception If no service url is available.
*/
- public function getServiceUrl ()
+ public function getServiceUrl()
{
if (empty($this->_url)) {
- throw new CAS_ProxiedService_Exception('No URL set via '.get_class($this).'->setUrl($url).');
+ throw new CAS_ProxiedService_Exception(
+ 'No URL set via ' . get_class($this) . '->setUrl($url).'
+ );
}
return $this->_url;
/*********************************************************
* Configure the Request
- *********************************************************/
+ *********************************************************/
/**
* Set the URL of the Request
* @return void
* @throws CAS_OutOfSequenceException If called after the Request has been sent.
*/
- public function setUrl ($url)
+ public function setUrl($url)
{
if ($this->hasBeenSent()) {
- throw new CAS_OutOfSequenceException('Cannot set the URL, request already sent.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot set the URL, request already sent.'
+ );
}
if (!is_string($url)) {
throw new CAS_InvalidArgumentException('$url must be a string.');
/*********************************************************
* 2. Send the Request
- *********************************************************/
+ *********************************************************/
/**
* Perform the request.
* @throws CAS_ProxiedService_Exception If there is a failure sending the
* request to the target service.
*/
- public function send ()
+ public function send()
{
if ($this->hasBeenSent()) {
- throw new CAS_OutOfSequenceException('Cannot send, request already sent.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot send, request already sent.'
+ );
}
phpCAS::traceBegin();
$this->initializeProxyTicket();
$url = $this->getServiceUrl();
if (strstr($url, '?') === false) {
- $url = $url.'?ticket='.$this->getProxyTicket();
+ $url = $url . '?ticket=' . $this->getProxyTicket();
} else {
- $url = $url.'&ticket='.$this->getProxyTicket();
+ $url = $url . '&ticket=' . $this->getProxyTicket();
}
try {
* @throws CAS_ProxiedService_Exception If there is a failure sending the
* request to the target service.
*/
- protected function makeRequest ($url)
+ protected function makeRequest($url)
{
// Verify that we are not in a redirect loop
$this->_numRequests++;
$this->populateRequest($request);
// Perform the request.
- phpCAS::trace('Performing proxied service request to \''.$url.'\'');
+ phpCAS::trace('Performing proxied service request to \'' . $url . '\'');
if (!$request->send()) {
- $message = 'Could not perform proxied service request to URL`'.$url.'\'. '.$request->getErrorMessage();
+ $message = 'Could not perform proxied service request to URL`'
+ . $url . '\'. ' . $request->getErrorMessage();
phpCAS::trace($message);
throw new CAS_ProxiedService_Exception($message);
}
$this->_cookieJar->storeCookies($url, $request->getResponseHeaders());
// Follow any redirects
- if ($redirectUrl = $this->getRedirectUrl($request->getResponseHeaders())) {
- phpCAS :: trace('Found redirect:'.$redirectUrl);
+ if ($redirectUrl = $this->getRedirectUrl($request->getResponseHeaders())
+ ) {
+ phpCAS::trace('Found redirect:' . $redirectUrl);
$this->makeRequest($redirectUrl);
} else {
*
* @return void
*/
- abstract protected function populateRequest (CAS_Request_RequestInterface $request);
+ abstract protected function populateRequest(
+ CAS_Request_RequestInterface $request
+ );
/**
* Answer a redirect URL if a redirect header is found, otherwise null.
*
* @return string or null
*/
- protected function getRedirectUrl (array $responseHeaders)
+ protected function getRedirectUrl(array $responseHeaders)
{
// Check for the redirect after authentication
foreach ($responseHeaders as $header) {
- if (preg_match('/^(Location:|URI:)\s*([^\s]+.*)$/', $header, $matches)) {
+ if ( preg_match('/^(Location:|URI:)\s*([^\s]+.*)$/', $header, $matches)
+ ) {
return trim(array_pop($matches));
}
}
/*********************************************************
* 3. Access the response
- *********************************************************/
+ *********************************************************/
/**
* Answer true if our request has been sent yet.
*
* @return bool
*/
- protected function hasBeenSent ()
+ protected function hasBeenSent()
{
return ($this->_numRequests > 0);
}
* @return array An array of header strings.
* @throws CAS_OutOfSequenceException If called before the Request has been sent.
*/
- public function getResponseHeaders ()
+ public function getResponseHeaders()
{
if (!$this->hasBeenSent()) {
- throw new CAS_OutOfSequenceException('Cannot access response, request not sent yet.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot access response, request not sent yet.'
+ );
}
return $this->_responseHeaders;
* @return int
* @throws CAS_OutOfSequenceException If called before the Request has been sent.
*/
- public function getResponseStatusCode ()
+ public function getResponseStatusCode()
{
if (!$this->hasBeenSent()) {
- throw new CAS_OutOfSequenceException('Cannot access response, request not sent yet.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot access response, request not sent yet.'
+ );
}
return $this->_responseStatusCode;
* @return string
* @throws CAS_OutOfSequenceException If called before the Request has been sent.
*/
- public function getResponseBody ()
+ public function getResponseBody()
{
if (!$this->hasBeenSent()) {
- throw new CAS_OutOfSequenceException('Cannot access response, request not sent yet.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot access response, request not sent yet.'
+ );
}
return $this->_responseBody;
*
* @return array An array containing cookies. E.g. array('name' => 'val');
*/
- public function getCookies ()
+ public function getCookies()
{
return $this->_cookieJar->getCookies($this->getServiceUrl());
}
*
* Usage Example:
*
- * try {
- * $service = phpCAS::getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET);
- * $service->setUrl('http://www.example.com/path/');
- * $service->send();
- * if ($service->getResponseStatusCode() == 200)
- * return $service->getResponseBody();
- * else
- * // The service responded with an error code 404, 500, etc.
- * throw new Exception('The service responded with an error.');
+ * try {
+ * $service = phpCAS::getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET);
+ * $service->setUrl('http://www.example.com/path/');
+ * $service->send();
+ * if ($service->getResponseStatusCode() == 200)
+ * return $service->getResponseBody();
+ * else
+ * // The service responded with an error code 404, 500, etc.
+ * throw new Exception('The service responded with an error.');
*
- * } catch (CAS_ProxyTicketException $e) {
- * if ($e->getCode() == PHPCAS_SERVICE_PT_FAILURE)
- * return "Your login has timed out. You need to log in again.";
- * else
- * // Other proxy ticket errors are from bad request format (shouldn't happen)
- * // or CAS server failure (unlikely) so lets just stop if we hit those.
- * throw $e;
- * } catch (CAS_ProxiedService_Exception $e) {
- * // Something prevented the service request from being sent or received.
- * // We didn't even get a valid error response (404, 500, etc), so this
- * // might be caused by a network error or a DNS resolution failure.
- * // We could handle it in some way, but for now we will just stop.
- * throw $e;
- * }
+ * } catch (CAS_ProxyTicketException $e) {
+ * if ($e->getCode() == PHPCAS_SERVICE_PT_FAILURE)
+ * return "Your login has timed out. You need to log in again.";
+ * else
+ * // Other proxy ticket errors are from bad request format
+ * // (shouldn't happen) or CAS server failure (unlikely)
+ * // so lets just stop if we hit those.
+ * throw $e;
+ * } catch (CAS_ProxiedService_Exception $e) {
+ * // Something prevented the service request from being sent or received.
+ * // We didn't even get a valid error response (404, 500, etc), so this
+ * // might be caused by a network error or a DNS resolution failure.
+ * // We could handle it in some way, but for now we will just stop.
+ * throw $e;
+ * }
*
* @class CAS_ProxiedService_Http_Get
* @category Authentication
*
* Usage Example:
*
- * try {
- * $service = phpCAS::getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_POST);
- * $service->setUrl('http://www.example.com/path/');
- * $service->setContentType('text/xml');
- * $service->setBody(''<?xml version="1.0"?'.'><methodCall><methodName>example.search</methodName></methodCall>');
- * $service->send();
- * if ($service->getResponseStatusCode() == 200)
- * return $service->getResponseBody();
- * else
- * // The service responded with an error code 404, 500, etc.
- * throw new Exception('The service responded with an error.');
+ * try {
+ * $service = phpCAS::getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_POST);
+ * $service->setUrl('http://www.example.com/path/');
+ * $service->setContentType('text/xml');
+ * $service->setBody('<?xml version="1.0"?'.'><methodCall><methodName>example.search</methodName></methodCall>');
+ * $service->send();
+ * if ($service->getResponseStatusCode() == 200)
+ * return $service->getResponseBody();
+ * else
+ * // The service responded with an error code 404, 500, etc.
+ * throw new Exception('The service responded with an error.');
*
- * } catch (CAS_ProxyTicketException $e) {
- * if ($e->getCode() == PHPCAS_SERVICE_PT_FAILURE)
- * return "Your login has timed out. You need to log in again.";
- * else
- * // Other proxy ticket errors are from bad request format (shouldn't happen)
- * // or CAS server failure (unlikely) so lets just stop if we hit those.
- * throw $e;
- * } catch (CAS_ProxiedService_Exception $e) {
- * // Something prevented the service request from being sent or received.
- * // We didn't even get a valid error response (404, 500, etc), so this
- * // might be caused by a network error or a DNS resolution failure.
- * // We could handle it in some way, but for now we will just stop.
- * throw $e;
- * }
+ * } catch (CAS_ProxyTicketException $e) {
+ * if ($e->getCode() == PHPCAS_SERVICE_PT_FAILURE)
+ * return "Your login has timed out. You need to log in again.";
+ * else
+ * // Other proxy ticket errors are from bad request format
+ * // (shouldn't happen) or CAS server failure (unlikely) so lets just
+ * // stop if we hit those.
+ * throw $e;
+ * } catch (CAS_ProxiedService_Exception $e) {
+ * // Something prevented the service request from being sent or received.
+ * // We didn't even get a valid error response (404, 500, etc), so this
+ * // might be caused by a network error or a DNS resolution failure.
+ * // We could handle it in some way, but for now we will just stop.
+ * throw $e;
+ * }
*
* @class CAS_ProxiedService_Http_Post
* @category Authentication
public function setContentType ($contentType)
{
if ($this->hasBeenSent()) {
- throw new CAS_OutOfSequenceException('Cannot set the content type, request already sent.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot set the content type, request already sent.'
+ );
}
$this->_contentType = $contentType;
public function setBody ($body)
{
if ($this->hasBeenSent()) {
- throw new CAS_OutOfSequenceException('Cannot set the body, request already sent.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot set the body, request already sent.'
+ );
}
$this->_body = $body;
protected function populateRequest (CAS_Request_RequestInterface $request)
{
if (empty($this->_contentType) && !empty($this->_body)) {
- throw new CAS_ProxiedService_Exception("If you pass a POST body, you must specify a content type via ".get_class($this).'->setContentType($contentType).');
+ throw new CAS_ProxiedService_Exception(
+ "If you pass a POST body, you must specify a content type via "
+ .get_class($this).'->setContentType($contentType).'
+ );
}
$request->makePost();
public function getServiceUrl ()
{
if (empty($this->_url)) {
- throw new CAS_ProxiedService_Exception('No URL set via '.get_class($this).'->getServiceUrl($url).');
+ throw new CAS_ProxiedService_Exception(
+ 'No URL set via '.get_class($this).'->getServiceUrl($url).'
+ );
}
return $this->_url;
public function setServiceUrl ($url)
{
if ($this->hasBeenOpened()) {
- throw new CAS_OutOfSequenceException('Cannot set the URL, stream already opened.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot set the URL, stream already opened.'
+ );
}
if (!is_string($url) || !strlen($url)) {
throw new CAS_InvalidArgumentException('Invalid url.');
public function setMailbox ($mailbox)
{
if ($this->hasBeenOpened()) {
- throw new CAS_OutOfSequenceException('Cannot set the mailbox, stream already opened.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot set the mailbox, stream already opened.'
+ );
}
if (!is_string($mailbox) || !strlen($mailbox)) {
throw new CAS_InvalidArgumentException('Invalid mailbox.');
public function setOptions ($options)
{
if ($this->hasBeenOpened()) {
- throw new CAS_OutOfSequenceException('Cannot set options, stream already opened.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot set options, stream already opened.'
+ );
}
if (!is_int($options)) {
throw new CAS_InvalidArgumentException('Invalid options.');
* PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE
* PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE
* PHPCAS_SERVICE_PT_FAILURE
- * @throws CAS_ProxiedService_Exception If there is a failure sending the request to the target service. */
+ * @throws CAS_ProxiedService_Exception If there is a failure sending the
+ * request to the target service.
+ */
public function open ()
{
if ($this->hasBeenOpened()) {
throw new CAS_OutOfSequenceException('Stream already opened.');
}
if (empty($this->_mailbox)) {
- throw new CAS_ProxiedService_Exception('You must specify a mailbox via '.get_class($this).'->setMailbox($mailbox)');
+ throw new CAS_ProxiedService_Exception(
+ 'You must specify a mailbox via '.get_class($this)
+ .'->setMailbox($mailbox)'
+ );
}
phpCAS::traceBegin();
// Get our proxy ticket and append it to our URL.
$this->initializeProxyTicket();
phpCAS::trace('opening IMAP mailbox `'.$this->_mailbox.'\'...');
- $this->_stream = @imap_open($this->_mailbox, $this->_username, $this->getProxyTicket(), $this->_options);
+ $this->_stream = @imap_open(
+ $this->_mailbox, $this->_username, $this->getProxyTicket(),
+ $this->_options
+ );
if ($this->_stream) {
phpCAS::trace('ok');
} else {
phpCAS::trace('could not open mailbox');
// @todo add localization integration.
- $message = 'IMAP Error: '.$url.' '. var_export(imap_errors(), true);
+ $message = 'IMAP Error: '.$this->_url.' '. var_export(imap_errors(), true);
phpCAS::trace($message);
throw new CAS_ProxiedService_Exception($message);
}
public function getStream ()
{
if (!$this->hasBeenOpened()) {
- throw new CAS_OutOfSequenceException('Cannot access stream, not opened yet.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot access stream, not opened yet.'
+ );
}
return $this->_stream;
}
public function getImapProxyTicket ()
{
if (!$this->hasBeenOpened()) {
- throw new CAS_OutOfSequenceException('Cannot access errors, stream not opened yet.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot access errors, stream not opened yet.'
+ );
}
return $this->getProxyTicket();
}
* This interface defines methods that allow proxy-authenticated service handlers
* to be tested in unit tests.
*
- * Classes implementing this interface SHOULD store the CAS_Client passed and initialize
- * themselves with that client rather than via the static phpCAS method. For example:
+ * Classes implementing this interface SHOULD store the CAS_Client passed and
+ * initialize themselves with that client rather than via the static phpCAS
+ * method. For example:
*
* / **
* * Fetch our proxy ticket.
* @param CAS_Client $casClient Cas client object
*
* @return void
- * @throws CAS_OutOfSequenceException If called after a proxy ticket has already been initialized/set.
+ * @throws CAS_OutOfSequenceException If called after a proxy ticket has
+ * already been initialized/set.
*/
public function setCasClient (CAS_Client $casClient);
*/
public function __construct(array $chain)
{
- $this->chain = array_values($chain); // Ensure that we have an indexed array
+ // Ensure that we have an indexed array
+ $this->chain = array_values($chain);
}
/**
$proxy_url = $list[$i];
if (preg_match('/^\/.*\/[ixASUXu]*$/s', $search)) {
if (preg_match($search, $proxy_url)) {
- phpCAS::trace("Found regexp " . $search . " matching " . $proxy_url);
+ phpCAS::trace(
+ "Found regexp " . $search . " matching " . $proxy_url
+ );
} else {
- phpCAS::trace("No regexp match " . $search . " != " . $proxy_url);
+ phpCAS::trace(
+ "No regexp match " . $search . " != " . $proxy_url
+ );
$mismatch = true;
break;
}
} else {
if (strncasecmp($search, $proxy_url, strlen($search)) == 0) {
- phpCAS::trace("Found string " . $search . " matching " . $proxy_url);
+ phpCAS::trace(
+ "Found string " . $search . " matching " . $proxy_url
+ );
} else {
- phpCAS::trace("No match " . $search . " != " . $proxy_url);
+ phpCAS::trace(
+ "No match " . $search . " != " . $proxy_url
+ );
$mismatch = true;
break;
}
PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
);
if (!in_array($code, $ptCodes)) {
- trigger_error('Invalid code '.$code.' passed. Must be one of PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, or PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE.');
+ trigger_error(
+ 'Invalid code '.$code
+ .' passed. Must be one of PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, or PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE.'
+ );
}
parent::__construct($message, $code);
public function setUrl ($url)
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
$this->url = $url;
public function addCookie ($name, $value)
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
$this->cookies[$name] = $value;
public function addCookies (array $cookies)
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
$this->cookies = array_merge($this->cookies, $cookies);
public function addHeader ($header)
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
$this->headers[] = $header;
public function addHeaders (array $headers)
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
$this->headers = array_merge($this->headers, $headers);
public function makePost ()
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
$this->isPost = true;
public function setPostBody ($body)
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
if (!$this->isPost) {
- throw new CAS_OutOfSequenceException('Cannot add a POST body to a GET request, use makePost() first.');
+ throw new CAS_OutOfSequenceException(
+ 'Cannot add a POST body to a GET request, use makePost() first.'
+ );
}
$this->postBody = $body;
public function setSslCaCert ($caCertPath,$validate_cn=true)
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
$this->caCertPath = $caCertPath;
$this->validateCN = $validate_cn;
public function send ()
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot send again.');
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot send again.'
+ );
}
if (is_null($this->url) || !$this->url) {
- throw new CAS_OutOfSequenceException('A url must be specified via setUrl() before the request can be sent.');
+ throw new CAS_OutOfSequenceException(
+ 'A url must be specified via setUrl() before the request can be sent.'
+ );
}
$this->_sent = true;
return $this->sendRequest();
public function getResponseHeaders ()
{
if (!$this->_sent) {
- throw new CAS_OutOfSequenceException('Request has not been sent yet. Cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has not been sent yet. Cannot '.__METHOD__
+ );
}
return $this->_responseHeaders;
}
public function getResponseStatusCode ()
{
if (!$this->_sent) {
- throw new CAS_OutOfSequenceException('Request has not been sent yet. Cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has not been sent yet. Cannot '.__METHOD__
+ );
}
- if (!preg_match('/HTTP\/[0-9.]+\s+([0-9]+)\s*(.*)/', $this->_responseHeaders[0], $matches)) {
- throw new CAS_Request_Exception("Bad response, no status code was found in the first line.");
+ if (!preg_match(
+ '/HTTP\/[0-9.]+\s+([0-9]+)\s*(.*)/',
+ $this->_responseHeaders[0], $matches
+ )
+ ) {
+ throw new CAS_Request_Exception(
+ 'Bad response, no status code was found in the first line.'
+ );
}
return intval($matches[1]);
public function getResponseBody ()
{
if (!$this->_sent) {
- throw new CAS_OutOfSequenceException('Request has not been sent yet. Cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has not been sent yet. Cannot '.__METHOD__
+ );
}
return $this->_responseBody;
public function getErrorMessage ()
{
if (!$this->_sent) {
- throw new CAS_OutOfSequenceException('Request has not been sent yet. Cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has not been sent yet. Cannot '.__METHOD__
+ );
}
return $this->_errorMessage;
}
public function addRequest (CAS_Request_RequestInterface $request)
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
if (!$request instanceof CAS_Request_CurlRequest) {
- throw new CAS_InvalidArgumentException('As a CAS_Request_CurlMultiRequest, I can only work with CAS_Request_CurlRequest objects.');
+ throw new CAS_InvalidArgumentException(
+ 'As a CAS_Request_CurlMultiRequest, I can only work with CAS_Request_CurlRequest objects.'
+ );
}
$this->_requests[] = $request;
public function getNumRequests()
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot '.__METHOD__);
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot '.__METHOD__
+ );
}
return count($this->_requests);
}
public function send ()
{
if ($this->_sent) {
- throw new CAS_OutOfSequenceException('Request has already been sent cannot send again.');
+ throw new CAS_OutOfSequenceException(
+ 'Request has already been sent cannot send again.'
+ );
}
if (!count($this->_requests)) {
- throw new CAS_OutOfSequenceException('At least one request must be added via addRequest() before the multi-request can be sent.');
+ throw new CAS_OutOfSequenceException(
+ 'At least one request must be added via addRequest() before the multi-request can be sent.'
+ );
}
$this->_sent = true;
$buf = curl_exec($ch);
if ( $buf === false ) {
phpCAS::trace('curl_exec() failed');
- $this->storeErrorMessage('CURL error #'.curl_errno($ch).': '.curl_error($ch));
+ $this->storeErrorMessage(
+ 'CURL error #'.curl_errno($ch).': '.curl_error($ch)
+ );
$res = false;
} else {
$this->storeResponseBody($buf);
if ($this->validateCN) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
} else {
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_CAINFO, $this->caCertPath);
--- /dev/null
+<?php
+
+/**
+ * Licensed to Jasig under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * Jasig 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.
+ *
+ * PHP Version 5
+ *
+ * @file CAS/InvalidArgumentException.php
+ * @category Authentication
+ * @package PhpCAS
+ * @author Adam Franco <afranco@middlebury.edu>
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
+ * @link https://wiki.jasig.org/display/CASC/phpCAS
+ */
+
+/**
+ * Exception that denotes invalid arguments were passed.
+ *
+ * @class CAS_InvalidArgumentException
+ * @category Authentication
+ * @package PhpCAS
+ * @author Adam Franco <afranco@middlebury.edu>
+ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
+ * @link https://wiki.jasig.org/display/CASC/phpCAS
+ */
+class CAS_TypeMismatchException
+extends CAS_InvalidArgumentException
+{
+ /**
+ * Constructor, provides a nice message.
+ *
+ * @param mixed $argument Argument
+ * @param string $argumentName Argument Name
+ * @param string $type Type
+ * @param string $message Error Message
+ * @param integer $code Code
+ *
+ * @return void
+ */
+ public function __construct (
+ $argument, $argumentName, $type, $message = '', $code = 0
+ ) {
+ if (is_object($argument)) {
+ $foundType = get_class($argument).' object';
+ } else {
+ $foundType = gettype($argument);
+ }
+
+ parent::__construct(
+ 'type mismatched for parameter '
+ . $argumentName . ' (should be \'' . $type .' \'), '
+ . $foundType . ' given. ' . $message, $code
+ );
+ }
+}
+?>
-Description of phpCAS 1.3.2 library import
+Description of phpCAS 1.3.3 library import
* downloaded from http://downloads.jasig.org/cas-clients/php/current/
-iarenaza
+merrill
<location>CAS</location>
<name>CAS</name>
<license>BSD</license>
- <version>1.3.2</version>
+ <version>1.3.3</version>
<licenseversion></licenseversion>
</library>
</libraries>
This files describes API changes in /auth/* - plugins,
information provided here is intended especially for developers.
+=== 2.8 ===
+
+* \core\session\manager::session_exists() now verifies the session is active
+ instead of only checking the session data is present in low level session handler
+
=== 2.7 ===
* If you are returning a url in method change_password_url() from config, please make sure it is set before trying to use it.
// Set initial values.
if (json.cm !== undefined &&
node.one('select[name=cm] > option[value=' + json.cm + ']')) {
- node.one('select[name=cm]').set('value', json.cm);
+ node.one('select[name=cm]').set('value', '' + json.cm);
}
if (json.e !== undefined) {
- node.one('select[name=e]').set('value', json.e);
+ node.one('select[name=e]').set('value', '' + json.e);
}
// Add event handlers (first time only).
var fields = Y.JSON.parse(response.responseText);
for (var field in fields) {
var select = node.one('select[name=x\\[' + field + '\\]]');
- select.set('value', fields[field]);
+ select.set('value', '' + fields[field]);
select.set('disabled', false);
}
},
// Set initial values.
if (json.id !== undefined &&
node.one('select[name=id] > option[value=' + json.id + ']')) {
- node.one('select[name=id]').set('value', json.id);
+ node.one('select[name=id]').set('value', '' + json.id);
}
if (json.min !== undefined) {
node.one('input[name=min]').set('checked', true);
if (json.creating === undefined) {
if (json.id !== undefined &&
node.one('select[name=id] > option[value=' + json.id + ']')) {
- node.one('select[name=id]').set('value', json.id);
+ node.one('select[name=id]').set('value', '' + json.id);
} else if (json.id === undefined) {
node.one('select[name=id]').set('value', 'any');
}
// Set initial value if specified.
if (json.id !== undefined &&
node.one('select[name=id] > option[value=' + json.id + ']')) {
- node.one('select[name=id]').set('value', json.id);
+ node.one('select[name=id]').set('value', '' + json.id);
}
// Add event handlers (first time only).
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This file keeps track of upgrades to the badges block
+ *
+ * Sometimes, changes between versions involve alterations to database structures
+ * and other major things that may break installations.
+ *
+ * The upgrade function in this file will attempt to perform all the necessary
+ * actions to upgrade your older installation to the current version.
+ *
+ * If there's something it cannot do itself, it will tell you what you need to do.
+ *
+ * The commands in here will all be database-neutral, using the methods of
+ * database_manager class
+ *
+ * Please do not forget to use upgrade_set_timeout()
+ * before any action that may take longer time to finish.
+ *
+ * @since Moodle 2.8
+ * @package block_badges
+ * @copyright 2014 Andrew Davis
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+/**
+ * Upgrade the badges block
+ * @param int $oldversion
+ * @param object $block
+ */
+function xmldb_block_badges_upgrade($oldversion, $block) {
+ global $DB;
+
+ if ($oldversion < 2014062600) {
+ // Add this block the default blocks on /my.
+ $blockname = 'badges';
+
+ $page = new moodle_page();
+ $page->set_context(context_system::instance());
+
+ // Check to see if this block is already on the default /my page.
+ $criteria = array(
+ 'blockname' => $blockname,
+ 'parentcontextid' => $page->context->id,
+ 'pagetypepattern' => 'my-index'
+ );
+
+ if (!$DB->record_exists('block_instances', $criteria)) {
+ // Add the block to the default /my.
+ $page->blocks->add_region(BLOCK_POS_RIGHT);
+ $page->blocks->add_block($blockname, BLOCK_POS_RIGHT, 0, false, 'my-index');
+ }
+
+ upgrade_block_savepoint(true, 2014062600, $blockname);
+ }
+
+ return true;
+}
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2014051200; // The current plugin version (Date: YYYYMMDDXX).
+$plugin->version = 2014062600; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2014050800; // Requires this Moodle version.
-$plugin->component = 'block_badges';
\ No newline at end of file
+$plugin->component = 'block_badges';
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This file keeps track of upgrades to the calendar_month block
+ *
+ * Sometimes, changes between versions involve alterations to database structures
+ * and other major things that may break installations.
+ *
+ * The upgrade function in this file will attempt to perform all the necessary
+ * actions to upgrade your older installation to the current version.
+ *
+ * If there's something it cannot do itself, it will tell you what you need to do.
+ *
+ * The commands in here will all be database-neutral, using the methods of
+ * database_manager class
+ *
+ * Please do not forget to use upgrade_set_timeout()
+ * before any action that may take longer time to finish.
+ *
+ * @since Moodle 2.8
+ * @package block_calendar_month
+ * @copyright 2014 Andrew Davis
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+/**
+ * Upgrade the calendar_month block
+ * @param int $oldversion
+ * @param object $block
+ */
+function xmldb_block_calendar_month_upgrade($oldversion, $block) {
+ global $DB;
+
+ if ($oldversion < 2014062600) {
+ // Add this block the default blocks on /my.
+ $blockname = 'calendar_month';
+
+ $page = new moodle_page();
+ $page->set_context(context_system::instance());
+
+ // Check to see if this block is already on the default /my page.
+ $criteria = array(
+ 'blockname' => $blockname,
+ 'parentcontextid' => $page->context->id,
+ 'pagetypepattern' => 'my-index'
+ );
+
+ if (!$DB->record_exists('block_instances', $criteria)) {
+ // Add the block to the default /my.
+ $page->blocks->add_region(BLOCK_POS_RIGHT);
+ $page->blocks->add_block($blockname, BLOCK_POS_RIGHT, 0, false, 'my-index');
+ }
+
+ upgrade_block_savepoint(true, 2014062600, $blockname);
+ }
+
+ return true;
+}
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2014051200; // The current plugin version (Date: YYYYMMDDXX)
+$plugin->version = 2014062600; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2014050800; // Requires this Moodle version
$plugin->component = 'block_calendar_month'; // Full name of the plugin (used for diagnostics)
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This file keeps track of upgrades to the calendar_upcoming block
+ *
+ * Sometimes, changes between versions involve alterations to database structures
+ * and other major things that may break installations.
+ *
+ * The upgrade function in this file will attempt to perform all the necessary
+ * actions to upgrade your older installation to the current version.
+ *
+ * If there's something it cannot do itself, it will tell you what you need to do.
+ *
+ * The commands in here will all be database-neutral, using the methods of
+ * database_manager class
+ *
+ * Please do not forget to use upgrade_set_timeout()
+ * before any action that may take longer time to finish.
+ *
+ * @since Moodle 2.8
+ * @package block_calendar_upcoming
+ * @copyright 2014 Andrew Davis
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+/**
+ * Upgrade the calendar_upcoming block
+ * @param int $oldversion
+ * @param object $block
+ */
+function xmldb_block_calendar_upcoming_upgrade($oldversion, $block) {
+ global $DB;
+
+ if ($oldversion < 2014062600) {
+ // Add this block the default blocks on /my.
+ $blockname = 'calendar_upcoming';
+
+ $page = new moodle_page();
+ $page->set_context(context_system::instance());
+
+ // Check to see if this block is already on the default /my page.
+ $criteria = array(
+ 'blockname' => $blockname,
+ 'parentcontextid' => $page->context->id,
+ 'pagetypepattern' => 'my-index'
+ );
+
+ if (!$DB->record_exists('block_instances', $criteria)) {
+ // Add the block to the default /my.
+ $page->blocks->add_region(BLOCK_POS_RIGHT);
+ $page->blocks->add_block($blockname, BLOCK_POS_RIGHT, 0, false, 'my-index');
+ }
+
+ upgrade_block_savepoint(true, 2014062600, $blockname);
+ }
+
+ return true;
+}
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2014051200; // The current plugin version (Date: YYYYMMDDXX)
+$plugin->version = 2014062600; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2014050800; // Requires this Moodle version
$plugin->component = 'block_calendar_upcoming'; // Full name of the plugin (used for diagnostics)
*/
var $content = NULL;
- /**
- * A string generated by {@link _add_edit_controls()} to display block manipulation links when the user is in editing mode.
- * @var string $edit_controls
- */
- var $edit_controls = NULL;
-
/**
* The initialized instance of this block object.
* @var block $instance
return false;
}
- /**
- * Default behavior: print the config_instance.html file
- * You don't need to override this if you're satisfied with the above
- *
- * @deprecated since Moodle 2.0.
- * @return boolean whether anything was done. Blocks should use edit_form.php.
- */
- function instance_config_print() {
- global $CFG, $DB, $OUTPUT;
- // Default behavior: print the config_instance.html file
- // You don't need to override this if you're satisfied with the above
- if (!$this->instance_allow_multiple() && !$this->instance_allow_config()) {
- return false;
- }
-
- if (is_file($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html')) {
- echo $OUTPUT->box_start('generalbox boxaligncenter blockconfiginstance');
- include($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html');
- echo $OUTPUT->box_end();
- } else {
- notice(get_string('blockconfigbad'), str_replace('blockaction=', 'dummy=', qualified_me()));
- }
-
- return true;
- }
-
/**
* Serialize and store config data
*/
return 180;
}
- /** @deprecated since Moodle 2.0. */
- function _print_block() {
- throw new coding_exception('_print_block is no longer used. It was a private ' .
- 'method of the block class, only for use by the blocks system. You ' .
- 'should not have been calling it anyway.');
- }
-
- /** @deprecated since Moodle 2.0. */
- function _print_shadow() {
- throw new coding_exception('_print_shadow is no longer used. It was a private ' .
- 'method of the block class, only for use by the blocks system. You ' .
- 'should not have been calling it anyway.');
- }
-
- /** @deprecated since Moodle 2.0. */
- function _title_html() {
- throw new coding_exception('_title_html is no longer used. It was a private ' .
- 'method of the block class, only for use by the blocks system. You ' .
- 'should not have been calling it anyway.');
- }
-
- /** @deprecated since Moodle 2.0. */
- function _add_edit_controls() {
- throw new coding_exception('_add_edit_controls is no longer used. It was a private ' .
- 'method of the block class, only for use by the blocks system. You ' .
- 'should not have been calling it anyway.');
- }
-
- /** @deprecated since Moodle 2.0. */
- function config_print() {
- throw new coding_exception('config_print() can no longer be used. Blocks should use a settings.php file.');
- }
-
/**
* Can be overridden by the block to prevent the block from being dockable.
*
public function specialization() {
}
- /**
- * displays instance configuration form
- *
- * @return boolean
- */
- function instance_config_print() {
- return false;
-
- /*
- global $CFG;
-
- $form = new block_myprofile.phpConfigForm(null, array($this->config));
- $form->display();
-
- return true;
- */
- }
-
/**
* locations where block can be displayed
*
This files describes API changes in /blocks/* - activity modules,
information provided here is intended especially for developers.
+=== 2.8 ===
+
+* The instance_config_print() function was removed. It was deprecated in
+ Moodle 2.0, but without debugging notices. Since it was no longer a part
+ of the code path, debugging notices would not have been displayed.
+* Deprecated functions were removed from the block_base class:
+** _print_block()
+** _print_shadow()
+** _title_html()
+** _add_edit_controls()
+** config_print()
+
=== 2.6 ===
* Deprecated /admin/block.php was removed, make sure blocks are using settings.php instead.
$events = calendar_get_upcoming($calendar->courses, $calendar->groups, $calendar->users, 1, 100, $calendar->timestamp_today());
$output = html_writer::start_tag('div', array('class'=>'header'));
+ $output .= $this->course_filter_selector($returnurl, get_string('dayviewfor', 'calendar'));
if (calendar_user_can_add_event($calendar->course)) {
$output .= $this->add_event_button($calendar->course->id, 0, 0, 0, $calendar->time);
}
- $output .= $this->course_filter_selector($returnurl, get_string('dayviewfor', 'calendar'));
$output .= html_writer::end_tag('div');
// Controls
$output .= html_writer::tag('div', calendar_top_controls('day', array('id' => $calendar->courseid, 'time' => $calendar->time)), array('class'=>'controls'));
calendar_events_by_day($events, $date['mon'], $date['year'], $eventsbyday, $durationbyday, $typesbyday, $calendar->courses);
$output = html_writer::start_tag('div', array('class'=>'header'));
+ $output .= $this->course_filter_selector($returnurl, get_string('detailedmonthviewfor', 'calendar'));
if (calendar_user_can_add_event($calendar->course)) {
$output .= $this->add_event_button($calendar->course->id, 0, 0, 0, $calendar->time);
}
- $output .= $this->course_filter_selector($returnurl, get_string('detailedmonthviewfor', 'calendar'));
$output .= html_writer::end_tag('div', array('class'=>'header'));
// Controls
$output .= html_writer::tag('div', calendar_top_controls('month', array('id' => $calendar->courseid, 'time' => $calendar->time)), array('class' => 'controls'));
$events = calendar_get_upcoming($calendar->courses, $calendar->groups, $calendar->users, $futuredays, $maxevents);
$output = html_writer::start_tag('div', array('class'=>'header'));
+ $output .= $this->course_filter_selector($returnurl, get_string('upcomingeventsfor', 'calendar'));
if (calendar_user_can_add_event($calendar->course)) {
$output .= $this->add_event_button($calendar->course->id);
}
- $output .= $this->course_filter_selector($returnurl, get_string('upcomingeventsfor', 'calendar'));
$output .= html_writer::end_tag('div');
if ($events) {
* @return Given[]
*/
public function i_delete_activity($activityname) {
-
- $deletestring = get_string('delete');
-
- $steps = array(
- new Given('I click on "' . $this->escape($deletestring) . '" "link" in the "' . $this->escape($activityname) . '" activity')
- );
+ $steps = array();
+ $activity = $this->escape($activityname);
+ if ($this->running_javascript()) {
+ $steps[] = new Given('I open "' . $activity . '" actions menu');
+ }
+ $steps[] = new Given('I click on "' . get_string('delete') . '" "link" in the "' . $activity . '" activity');
// JS enabled.
// Not using chain steps here because the exceptions catcher have problems detecting
| Cat 1 | 0 | CAT1 |
And the following "courses" exist:
| category | fullname | shortname | idnumber | sortorder | timecreated |
- | CAT1 | Social studies | Senior school | Ext003 | 1 | 10000000001 |
- | CAT1 | Applied sciences | Middle school | Sci001 | 2 | 10000000002 |
- | CAT1 | Extended social studies | Junior school | Ext002 | 3 | 10000000003 |
+ | CAT1 | Social studies | Senior school | Ext003 | 1 | 1000000001 |
+ | CAT1 | Applied sciences | Middle school | Sci001 | 2 | 1000000002 |
+ | CAT1 | Extended social studies | Junior school | Ext002 | 3 | 1000000003 |
And I log in as "admin"
And I go to the courses management page
And I open "Test forum name 1" actions menu
And I click on "Hide" "link" in the "Test forum name 1" activity
And "#section-2" "css_element" <should_see_other_sections> exist
- And I open "Test forum name 1" actions menu
And I delete "Test forum name 1" activity
And I should not see "Test forum name 1" in the "#region-main" "css_element"
And I duplicate "Test forum name 2" activity editing the new copy with:
| Cat 1 | 0 | CAT1 |
And the following "courses" exist:
| category | fullname | shortname | idnumber | sortorder | timecreated |
- | CAT1 | Social studies | Senior school | Ext003 | 1 | 10000000001 |
- | CAT1 | Applied sciences | Middle school | Sci001 | 2 | 10000000002 |
- | CAT1 | Extended social studies | Junior school | Ext002 | 3 | 10000000003 |
+ | CAT1 | Social studies | Senior school | Ext003 | 1 | 1000000001 |
+ | CAT1 | Applied sciences | Middle school | Sci001 | 2 | 1000000002 |
+ | CAT1 | Extended social studies | Junior school | Ext002 | 3 | 1000000003 |
And I log in as "admin"
And I go to the courses management page
| Cat 1 | 0 | CAT1 |
And the following "courses" exist:
| category | fullname | shortname | idnumber | sortorder | timecreated |
- | CAT1 | Social studies | Senior school | Ext003 | 1 | 10000000001 |
- | CAT1 | Applied sciences | Middle school | Sci001 | 2 | 10000000002 |
- | CAT1 | Extended social studies | Junior school | Ext002 | 3 | 10000000003 |
+ | CAT1 | Social studies | Senior school | Ext003 | 1 | 1000000001 |
+ | CAT1 | Applied sciences | Middle school | Sci001 | 2 | 1000000002 |
+ | CAT1 | Extended social studies | Junior school | Ext002 | 3 | 1000000003 |
And I log in as "admin"
And I go to the courses management page
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle 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 General Public License for more details.
+//
+// You should have received a copy