<?php

/**
 *  OpenID v1.1
 *  Copyright 2010 (c) R Woodgate
 *  All Rights Reserved
 *
 **/
if (!defined('INCLUDED_AMEMBER_CONFIG')) {
    die("Direct access to this location is not allowed");
}
$notebook_page = 'openid';
config_set_notebook_comment($notebook_page, 'OpenID');
if (file_exists($rm = dirname(__FILE__) . "/readme.txt")) {
    config_set_readme($notebook_page, $rm);
}
add_config_field("protect.{$notebook_page}.testmode", 'Test Mode?', 'checkbox', "Debug statements will be written to the log file.", $notebook_page);
add_config_field("protect.{$notebook_page}.sqlupdated", 'SQL Field installed?', 'checkbox', "The plugin will attempt to add a 'openid'<br/>\n\t\t\t\t\tfield automatically. Uncheck if you need to reinstall.", $notebook_page);
add_config_field("protect.{$notebook_page}.ax_optional", "Request Profile Information", 'multi_select', "Profile information you would like from the<br/>\n\t\t\t\t\tOpenID provider. You will need <a href='{$config['root_url']}/admin/fields.php'>aMember fields</a><br/>\n\t\t\t\t\twith the same name for any selected items.<br/>\n\t\t\t\t\tNB: Not all information may be available.", $notebook_page, '', '', '', array('options' => array('' => '*** None') + openid_ax2field(), 'store_type' => 1));
add_config_field("oidfd.##3", 'New Member Settings', 'header', '', $notebook_page);
add_config_field("protect.{$notebook_page}.newaccount", "Create aMember account?", 'checkbox', "Creates new aMember account automatically<br/>\n\t\t\t\t\t if OpenID user doesn't have one.", $notebook_page);
global $db;
$plist = array();
foreach ($db->get_products_list() as $pr) {
    $plist[$pr['product_id']] = $pr['title'] . " ({$pr['expire_days']})";
}
add_config_field("protect.{$notebook_page}.newaccountproduct", "OpenID Product Subscription", 'select', "New aMember account will be automatically<br/>\n\t\t\t\t\t subscribed to selected product when created<br/>\n\t\t\t\t\t via OpenID. Only works if 'Create aMember<br/>\n\t\t\t\t\t account' is selected above.", $notebook_page, '', '', '', array('options' => array('' => '*** None') + $plist));
add_config_field("protect.{$notebook_page}.ax_required", "Required Signup Information", 'multi_select', "Information you require to create an account<br/>\n\t\t\t\t\tautomatically. If any selected item is not<br/>\n\t\t\t\t\tavailable, member will be required to use the<br/>\n\t\t\t\t\tsignup form. NB: You will need <a href='{$config['root_url']}/admin/fields.php'>aMember fields</a> with<br/>\n\t\t\t\t\tthe same name for any selected items.", $notebook_page, '', '', '', array('options' => array('' => '*** None') + openid_ax2field(), 'store_type' => 1));
function openid_create_account()
{
    global $config, $db, $plugin_config;
    $this_config = $plugin_config['protect']['openid'];
    $testmode = $this_config['testmode'];
    // Check create account is allowed
    if (!$this_config['newaccount']) {
        header("Location: " . $config['root_url'] . "/signup.php");
        exit;
    }
    // Check login to OpenID
    if (!$_SESSION['openid']['identity']) {
        header("Location: " . $config['root_url'] . "/signup.php");
        exit;
    }
    // Check there is not already a linked account
    list($l, $p) = openid_check_logged_in();
    if (strlen($l) && strlen($p)) {
        header("Location: " . $config['root_url'] . "/login.php");
        exit;
    }
    // Check OpenID email is available, that it is not too long, and not already exists in aMember
    $email = $_SESSION['openid']['data']['contact/email'];
    if (!$email || strlen($email) > 64 || $config['unique_email'] && $db->users_find_by_string($email, 'email', 1)) {
        if ($testmode == 1) {
            $db->log_error("openid: Create account aborted: Email address too long, not provided, or already exists ({$email})");
        }
        header("Location: " . $config['root_url'] . "/signup.php");
        exit;
    }
    // Check all required information has been supplied
    $ax_required = array_filter((array) $this_config['ax_required']);
    $ax_missing = array();
    foreach ($ax_required as $ax) {
        if (!$_SESSION['openid']['data'][$ax]) {
            $ax_missing[] = $ax;
        }
    }
    if (count($ax_missing) > 0) {
        $ax_missing = implode(", ", $ax_missing);
        if ($testmode == 1) {
            $db->log_error("openid: Auto-create account aborted: The following required items were missing ({$ax_missing})");
        }
        header("Location: " . $config['root_url'] . "/signup.php");
        exit;
    }
    // Ok, now we can create the account
    $vars = array();
    if ($_SESSION['openid']['data']['namePerson/first'] && $_SESSION['openid']['data']['namePerson/last']) {
        $vars['name_f'] = $_SESSION['openid']['data']['namePerson/first'];
        $vars['name_l'] = $_SESSION['openid']['data']['namePerson/last'];
    } else {
        if ($_SESSION['openid']['data']['namePerson']) {
            list($vars['name_f'], $vars['name_l']) = explode(" ", $_SESSION['openid']['data']['namePerson']);
        }
    }
    foreach ($ax_required as $ax) {
        $vars[openid_ax2field($ax)] = $_SESSION['openid']['data'][$ax];
        if ($ax == 'person/gender') {
            $vars['is_male'] = $_SESSION['openid']['data'][$ax] == "M" ? 1 : 0;
        }
    }
    $vars['pass'] = $vars['pass0'] = $vars['pass1'] = generate_password($vars);
    $vars['email'] = $email;
    $vars['login'] = generate_login($vars);
    if ($GLOBALS['_LANG_SELECTED'] != get_default_lang()) {
        $vars['selected_lang'] = $GLOBALS['_LANG_SELECTED'];
    }
    $member_id = $db->add_pending_user($vars);
    $openid = $db->escape($_SESSION['openid']['identity']);
    $db->query("UPDATE {$db->config['prefix']}members SET openid = '{$openid}' WHERE member_id = '{$member_id}' LIMIT 1");
    $db->log_error("openid: Created aMember account for OpenID user ({$openid}) - " . print_r($vars, 1));
    $is_affiliate = '0';
    //only member newsletters
    if ($db->get_signup_threads_c($is_affiliate)) {
        $db->subscribe_member($member_id, $is_affiliate);
    }
    // Now add OpenID product subscripton, if set
    if ($this_config['newaccountproduct']) {
        $openid_product =& get_product($this_config['newaccountproduct']);
        $openid_payment = array('member_id' => $member_id, 'product_id' => $openid_product->config['product_id'], 'completed' => 0, 'paysys_id' => 'free', 'begin_date' => $begin_date = date('Y-m-d'), 'expire_date' => $openid_product->get_expire($begin_date));
        $db->add_payment($openid_payment);
        if ($testmode == 1) {
            $db->log_error("openid: Added subscription (product #{$this_config['newaccountproduct']} ) for OpenID user ({$openid}), login = {$vars['login']}");
        }
        // Now go to thanks page...
        $payment_id = $GLOBALS['_amember_added_payment_id'];
        $vcode = md5($payment_id . $begin_date . $member_id);
        header("Location: " . $config['root_url'] . "/plugins/protect/openid/thanks.php?payment_id={$payment_id}&vcode={$vcode}");
        exit;
    }
    // Account only - go to member page...
    header("Location: " . $config['root_url'] . "/member.php");
    exit;
}