function validate_avatar($avatar_url)
{
    validate_url($avatar_url);

    if(!preg_match('/.+\.jpg/', $avatar_url))
        throw new invalid_avatar_exception();

    $image_size = @getimagesize($avatar_url);

    if($image_size === false)
        throw new invalid_avatar_exception();

    if($image_size[0] != 100 || $image_size[1] != 100)
        throw new invalid_avatar_exception();
}
    function index()
    {
        if(!isset($_SESSION['active_user']))
            redirect_to(make_url("users"));

        $usr = instance_model('users');
        $user = $usr->get_user_by_id($_SESSION['active_user']['id']);

        if($user == array())
            throw new no_such_user_exception();

        if(!isset($_POST['Submit']))
        {
            $form_vals = array(
                $user[0]['E-mail'],
                $user[0]['Full_name'],
                $user[0]['Location'],
                $user[0]['Web'],
                $user[0]['Bio']);

        // Display main
            $view = instance_view("settings_main");
            $view = $view->parse_to_variable(array(
                'form_vals' => $form_vals));
        }
        else
        {
            $form_vals = $_POST;

        // Validate email
            try {
                validate_email($form_vals[0]);
            } catch(exception $e) {
                new_flash('Email address is invalid', 1);
                $form_vals[0] = $user[0]['E-mail'];
            }

        // Validate full name
            try {
                validate_50($form_vals[1]);
            } catch(exception $e) {
                new_flash('Full name is too long, max 50 chars', 1);
                $form_vals[1] = $user[0]['User_name'];
            }
            
        // Validate location
            try {
                validate_50($form_vals[2]);
            } catch(exception $e) {
                new_flash('Location is too long, max 50 chars', 1);
                $form_vals[2] = $user[0]['Location'];
            }

        // Validate web
            try {
                validate_url($form_vals[3]);
            } catch(exception $e) {
                new_flash('Website URL is invalid', 1);
                $form_vals[3] = $user[0]['Web'];
            }

        // Validate bio
            try {
                validate_bio($form_vals[4]);
            } catch(exception $e) {
                new_flash('Bio is invalid', 1);
                $form_vals[4] = $user[0]['Bio'];
            }

            if(count(get_errors()) == 0)
            {
            // Everything was vald, save updated user options
                $usr->update_user(
                    $user[0]['ID'],
                    $form_vals[0],
                    $form_vals[1],
                    $form_vals[2],
                    $form_vals[3],
                    $form_vals[4]);

                redirect_to(make_url('settings'));
            }
            else
            {
            // Something was invalid, redisplay main
                $view = instance_view("settings_main");
                $view = $view->parse_to_variable(array(
                    'form_vals' => $form_vals));
            }
        }

    // Display sidebar
        $sb_view = instance_view("settings_sidebar");
        $sb_view = $sb_view->parse_to_variable(array(
            'uid'   => $_SESSION['active_user']['id'],
            'uname' => $_SESSION['active_user']['name']));

        $this->set_template_paramiters(
            array('main_content' => $view,
                  'sidebar'      => $sb_view));
    }
Пример #3
1
function create_user($arr)
{
    // Required: { username, nickname, email } or { openid_url }
    $a = get_app();
    $result = array('success' => false, 'user' => null, 'password' => '', 'message' => '');
    $using_invites = get_config('system', 'invitation_only');
    $num_invites = get_config('system', 'number_invites');
    $invite_id = x($arr, 'invite_id') ? notags(trim($arr['invite_id'])) : '';
    $username = x($arr, 'username') ? notags(trim($arr['username'])) : '';
    $nickname = x($arr, 'nickname') ? notags(trim($arr['nickname'])) : '';
    $email = x($arr, 'email') ? notags(trim($arr['email'])) : '';
    $openid_url = x($arr, 'openid_url') ? notags(trim($arr['openid_url'])) : '';
    $photo = x($arr, 'photo') ? notags(trim($arr['photo'])) : '';
    $password = x($arr, 'password') ? trim($arr['password']) : '';
    $blocked = x($arr, 'blocked') ? intval($arr['blocked']) : 0;
    $verified = x($arr, 'verified') ? intval($arr['verified']) : 0;
    $publish = x($arr, 'profile_publish_reg') && intval($arr['profile_publish_reg']) ? 1 : 0;
    $netpublish = strlen(get_config('system', 'directory_submit_url')) ? $publish : 0;
    $tmp_str = $openid_url;
    if ($using_invites) {
        if (!$invite_id) {
            $result['message'] .= t('An invitation is required.') . EOL;
            return $result;
        }
        $r = q("select * from register where `hash` = '%s' limit 1", dbesc($invite_id));
        if (!results($r)) {
            $result['message'] .= t('Invitation could not be verified.') . EOL;
            return $result;
        }
    }
    if (!x($username) || !x($email) || !x($nickname)) {
        if ($openid_url) {
            if (!validate_url($tmp_str)) {
                $result['message'] .= t('Invalid OpenID url') . EOL;
                return $result;
            }
            $_SESSION['register'] = 1;
            $_SESSION['openid'] = $openid_url;
            require_once 'library/openid.php';
            $openid = new LightOpenID();
            $openid->identity = $openid_url;
            $openid->returnUrl = $a->get_baseurl() . '/openid';
            $openid->required = array('namePerson/friendly', 'contact/email', 'namePerson');
            $openid->optional = array('namePerson/first', 'media/image/aspect11', 'media/image/default');
            try {
                $authurl = $openid->authUrl();
            } catch (Exception $e) {
                $result['message'] .= t("We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.") . EOL . EOL . t("The error message was:") . $e->getMessage() . EOL;
                return $result;
            }
            goaway($authurl);
            // NOTREACHED
        }
        notice(t('Please enter the required information.') . EOL);
        return;
    }
    if (!validate_url($tmp_str)) {
        $openid_url = '';
    }
    $err = '';
    // collapse multiple spaces in name
    $username = preg_replace('/ +/', ' ', $username);
    if (mb_strlen($username) > 48) {
        $result['message'] .= t('Please use a shorter name.') . EOL;
    }
    if (mb_strlen($username) < 3) {
        $result['message'] .= t('Name too short.') . EOL;
    }
    // I don't really like having this rule, but it cuts down
    // on the number of auto-registrations by Russian spammers
    //  Using preg_match was completely unreliable, due to mixed UTF-8 regex support
    //	$no_utf = get_config('system','no_utf');
    //	$pat = (($no_utf) ? '/^[a-zA-Z]* [a-zA-Z]*$/' : '/^\p{L}* \p{L}*$/u' );
    // So now we are just looking for a space in the full name.
    $loose_reg = get_config('system', 'no_regfullname');
    if (!$loose_reg) {
        $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
        if (!strpos($username, ' ')) {
            $result['message'] .= t("That doesn't appear to be your full (First Last) name.") . EOL;
        }
    }
    if (!allowed_email($email)) {
        $result['message'] .= t('Your email domain is not among those allowed on this site.') . EOL;
    }
    if (!valid_email($email) || !validate_email($email)) {
        $result['message'] .= t('Not a valid email address.') . EOL;
    }
    // Disallow somebody creating an account using openid that uses the admin email address,
    // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
    $adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email'])));
    //if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0) && strlen($openid_url)) {
    if (x($a->config, 'admin_email') && in_array(strtolower($email), $adminlist) && strlen($openid_url)) {
        $r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1", dbesc($email));
        if (count($r)) {
            $result['message'] .= t('Cannot use that email.') . EOL;
        }
    }
    $nickname = $arr['nickname'] = strtolower($nickname);
    if (!preg_match("/^[a-z][a-z0-9\\-\\_]*\$/", $nickname)) {
        $result['message'] .= t('Your "nickname" can only contain "a-z", "0-9", "-", and "_", and must also begin with a letter.') . EOL;
    }
    $r = q("SELECT `uid` FROM `user`\n               \tWHERE `nickname` = '%s' LIMIT 1", dbesc($nickname));
    if (count($r)) {
        $result['message'] .= t('Nickname is already registered. Please choose another.') . EOL;
    }
    // Check deleted accounts that had this nickname. Doesn't matter to us,
    // but could be a security issue for federated platforms.
    $r = q("SELECT * FROM `userd`\n               \tWHERE `username` = '%s' LIMIT 1", dbesc($nickname));
    if (count($r)) {
        $result['message'] .= t('Nickname was once registered here and may not be re-used. Please choose another.') . EOL;
    }
    if (strlen($result['message'])) {
        return $result;
    }
    $new_password = strlen($password) ? $password : autoname(6) . mt_rand(100, 9999);
    $new_password_encoded = hash('whirlpool', $new_password);
    $result['password'] = $new_password;
    require_once 'include/crypto.php';
    $keys = new_keypair(4096);
    if ($keys === false) {
        $result['message'] .= t('SERIOUS ERROR: Generation of security keys failed.') . EOL;
        return $result;
    }
    $default_service_class = get_config('system', 'default_service_class');
    if (!$default_service_class) {
        $default_service_class = '';
    }
    $prvkey = $keys['prvkey'];
    $pubkey = $keys['pubkey'];
    /**
     *
     * Create another keypair for signing/verifying
     * salmon protocol messages. We have to use a slightly
     * less robust key because this won't be using openssl
     * but the phpseclib. Since it is PHP interpreted code
     * it is not nearly as efficient, and the larger keys
     * will take several minutes each to process.
     *
     */
    $sres = new_keypair(512);
    $sprvkey = $sres['prvkey'];
    $spubkey = $sres['pubkey'];
    $r = q("INSERT INTO `user` ( `guid`, `username`, `password`, `email`, `openid`, `nickname`,\n\t\t`pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked`, `timezone`, `service_class`, `default-location` )\n\t\tVALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 'UTC', '%s', '' )", dbesc(generate_user_guid()), dbesc($username), dbesc($new_password_encoded), dbesc($email), dbesc($openid_url), dbesc($nickname), dbesc($pubkey), dbesc($prvkey), dbesc($spubkey), dbesc($sprvkey), dbesc(datetime_convert()), intval($verified), intval($blocked), dbesc($default_service_class));
    if ($r) {
        $r = q("SELECT * FROM `user`\n\t\t\tWHERE `username` = '%s' AND `password` = '%s' LIMIT 1", dbesc($username), dbesc($new_password_encoded));
        if ($r !== false && count($r)) {
            $u = $r[0];
            $newuid = intval($r[0]['uid']);
        }
    } else {
        $result['message'] .= t('An error occurred during registration. Please try again.') . EOL;
        return $result;
    }
    /**
     * if somebody clicked submit twice very quickly, they could end up with two accounts
     * due to race condition. Remove this one.
     */
    $r = q("SELECT `uid` FROM `user`\n               \tWHERE `nickname` = '%s' ", dbesc($nickname));
    if (count($r) > 1 && $newuid) {
        $result['message'] .= t('Nickname is already registered. Please choose another.') . EOL;
        q("DELETE FROM `user` WHERE `uid` = %d", intval($newuid));
        return $result;
    }
    if (x($newuid) !== false) {
        $r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` )\n\t\t\tVALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ", intval($newuid), t('default'), 1, dbesc($username), dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"), dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"), intval($publish), intval($netpublish));
        if ($r === false) {
            $result['message'] .= t('An error occurred creating your default profile. Please try again.') . EOL;
            // Start fresh next time.
            $r = q("DELETE FROM `user` WHERE `uid` = %d", intval($newuid));
            return $result;
        }
        $r = q("INSERT INTO `contact` ( `uid`, `created`, `self`, `name`, `nick`, `photo`, `thumb`, `micro`, `blocked`, `pending`, `url`, `nurl`,\n\t\t\t`request`, `notify`, `poll`, `confirm`, `poco`, `name-date`, `uri-date`, `avatar-date`, `closeness` )\n\t\t\tVALUES ( %d, '%s', 1, '%s', '%s', '%s', '%s', '%s', 0, 0, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', 0 ) ", intval($newuid), datetime_convert(), dbesc($username), dbesc($nickname), dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"), dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"), dbesc($a->get_baseurl() . "/photo/micro/{$newuid}.jpg"), dbesc($a->get_baseurl() . "/profile/{$nickname}"), dbesc(normalise_link($a->get_baseurl() . "/profile/{$nickname}")), dbesc($a->get_baseurl() . "/dfrn_request/{$nickname}"), dbesc($a->get_baseurl() . "/dfrn_notify/{$nickname}"), dbesc($a->get_baseurl() . "/dfrn_poll/{$nickname}"), dbesc($a->get_baseurl() . "/dfrn_confirm/{$nickname}"), dbesc($a->get_baseurl() . "/poco/{$nickname}"), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc(datetime_convert()));
        // Create a group with no members. This allows somebody to use it
        // right away as a default group for new contacts.
        require_once 'include/group.php';
        group_add($newuid, t('Friends'));
        $r = q("SELECT id FROM `group` WHERE uid = %d AND name = '%s'", intval($newuid), dbesc(t('Friends')));
        if ($r && count($r)) {
            $def_gid = $r[0]['id'];
            q("UPDATE user SET def_gid = %d WHERE uid = %d", intval($r[0]['id']), intval($newuid));
        }
        if (get_config('system', 'newuser_private') && $def_gid) {
            q("UPDATE user SET allow_gid = '%s' WHERE uid = %d", dbesc("<" . $def_gid . ">"), intval($newuid));
        }
    }
    // if we have no OpenID photo try to look up an avatar
    if (!strlen($photo)) {
        $photo = avatar_img($email);
    }
    // unless there is no avatar-plugin loaded
    if (strlen($photo)) {
        require_once 'include/Photo.php';
        $photo_failure = false;
        $filename = basename($photo);
        $img_str = fetch_url($photo, true);
        // guess mimetype from headers or filename
        $type = guess_image_type($photo, true);
        $img = new Photo($img_str, $type);
        if ($img->is_valid()) {
            $img->scaleImageSquare(175);
            $hash = photo_new_resource();
            $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 4);
            if ($r === false) {
                $photo_failure = true;
            }
            $img->scaleImage(80);
            $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 5);
            if ($r === false) {
                $photo_failure = true;
            }
            $img->scaleImage(48);
            $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 6);
            if ($r === false) {
                $photo_failure = true;
            }
            if (!$photo_failure) {
                q("UPDATE `photo` SET `profile` = 1 WHERE `resource-id` = '%s' ", dbesc($hash));
            }
        }
    }
    call_hooks('register_account', $newuid);
    $result['success'] = true;
    $result['user'] = $u;
    return $result;
}
Пример #4
0
function parse($url)
{
    //parse $url.  Essentially we are going to take what is given and remove any extension
    $url_array = explode(".", $url);
    //define paths
    $url_name = substr($url_array[0], 1);
    $url_html = "templates" . $url_array[0] . ".html";
    $url_php = "scripts/pages" . $url_array[0] . ".php";
    if ($url_array[0] == "/login") {
        serve_login_page();
        return;
    }
    if ($url_array[0] == "/signup") {
        serve_signup_page();
        return;
    }
    if ($_SESSION["logged_in"] !== true) {
        serve_login_page();
        return;
    }
    //validate url
    if (!validate_url($url_html, $url_php)) {
        $url_name = "home";
        $url_html = "templates/home.html";
        $url_php = "scripts/pages/home.php";
    }
    //load generic template file
    $html = file_get_contents("templates/HTMLTemplate");
    //load body file
    $body = file_get_contents($url_html);
    $has_permission = true;
    //clear out permission variable
    //execute page specific php, if it exists
    file_exists($url_php);
    include $url_php;
    //check permission variable against user account.
    //If permission variable not set, die loudly
    if (!$has_permission) {
        return;
    }
    $html = str_replace("==active==", $url_name, $html);
    //push body content into $html
    $html = str_replace("==body==", $body, $html);
    $growl = get_growl();
    $html = str_replace("==growl==", $growl, $html);
    //echo out resulting webpage
    echo $html;
}
Пример #5
0
    function update_user($id, $email, $full_name, $location, $web, $bio)
    {
        $this->verify_user_id($id);
        validate_email($email);
        validate_50($full_name);
        validate_50($location);
        validate_url($web);
        validate_bio($bio);

        $query = "UPDATE `users` SET
            `E-mail` = '@v',
            `Full_name` = '@v',
            `Location` = '@v',
            `Web` = '@v',
            `Bio` = '@v'
            WHERE `ID` = '@v' LIMIT 1";

        $this->query($query, $email, $full_name, $location, $web, $bio, $id);
    }
    function new_dm($user_id, $type, $remote_name, $remote_profile,
        $remote_avatar, $remote_message, $remote_time)
    {
        $users = instance_model('users');
        $users->verify_user_id($user_id);

        if(!($type == "public" || $type == 'private'))
            throw new invalid_dm_type_exception();

        validate_username($remote_name);
        validate_url($remote_profile);
        validate_avatar($remote_avatar);
        validate_message($remote_message);

        $query = "INSERT INTO `direct-message`
            (`User_ID`, `Type`, `Remote_name`, `Remote_profile`,
                `Remote_avatar`, `Remote_message`, `Remote_time`)
            VALUES ('@v','@v','@v','@v','@v', '@v', '@v')";

        $this->query($query, $user_id, $type, $remote_name,
            $remote_profile, $remote_avatar, $remote_message, $remote_time);
    }
Пример #7
0
 function test_validate_url()
 {
     $this->change_global('evo_charset', 'latin1');
     // valid:
     foreach (array('http://b2evolution.net', 'https://demo.b2evolution.net', 'http://user@example.com/path', 'http://*****:*****@example.com/path', 'mailto:example@example.org', 'mailto:example@example.org?subject=TEST', 'http://lдu.de/', 'http://lдu.de/foo bar') as $url) {
         $r = validate_url($url, 'commenting', false);
         // True means validation ok
         $this->assertFalse($r, $url . ' NOT allowed in comments');
     }
     foreach (array('http://b2evolution.net', 'https://demo.b2evolution.net', 'http://user@example.com/path', 'http://*****:*****@example.com/path', 'mailto:example@example.org', 'mailto:example@example.org?subject=TEST', 'http://lдu.de/', '/foobar', '/foobar#anchor', '#anchor') as $url) {
         $r = validate_url($url, 'posting', false);
         $this->assertFalse($r, $url . ' NOT allowed in posts');
     }
     // invalid:
     foreach (array('http://', 'http://&amp;', 'http://<script>...</script>', 'mailto:www.example.com', 'foobar') as $url) {
         $r = validate_url($url, 'commenting', false);
         // True means validation rejected
         $this->assertTrue($r, $url . ' allowed in comments');
         $r = validate_url($url, 'posting', false);
         $this->assertTrue($r, $url . ' allowed in posts');
     }
 }
Пример #8
0
        authenticate_success($r[0]);
    }
} else {
    if (isset($_SESSION)) {
        nuke_session();
    }
    if (x($_POST, 'password') && strlen($_POST['password'])) {
        $encrypted = hash('whirlpool', trim($_POST['password']));
    } else {
        if (x($_POST, 'openid_url') && strlen($_POST['openid_url']) || x($_POST, 'username') && strlen($_POST['username'])) {
            $noid = get_config('system', 'no_openid');
            $openid_url = trim(strlen($_POST['openid_url']) ? $_POST['openid_url'] : $_POST['username']);
            // validate_url alters the calling parameter
            $temp_string = $openid_url;
            // if it's an email address or doesn't resolve to a URL, fail.
            if ($noid || strpos($temp_string, '@') || !validate_url($temp_string)) {
                $a = get_app();
                notice(t('Login failed.') . EOL);
                goaway(z_root());
                // NOTREACHED
            }
            // Otherwise it's probably an openid.
            try {
                require_once 'library/openid.php';
                $openid = new LightOpenID();
                $openid->identity = $openid_url;
                $_SESSION['openid'] = $openid_url;
                $a = get_app();
                $openid->returnUrl = $a->get_baseurl(true) . '/openid';
                goaway($openid->authUrl());
            } catch (Exception $e) {
Пример #9
0
/**
 * Checks if the url is valid
 *
 * @param string url to check
 * @return boolean true if OK
 */
function is_url($url)
{
    if (validate_url($url, 'posting', false)) {
        return false;
    }
    return true;
}
Пример #10
0
                ";
                die ('');
            }       
            error_reporting(E_ALL);
            session_destroy();    
        }
        
		// 	clean input			
		$url 		= 	cleaninput(cleanup_text(trim(substr ($url, 0,100))));
		$title 		= 	cleaninput(cleanup_text(trim(substr ($title, 0,100))));
		$description = 	cleaninput(cleanup_text(nl2br(trim(substr ($description, 0,250)))));
		$email 		= 	cleaninput(cleanup_text(trim(substr ($email, 0,100))));
		
		//	check Url
		$input  = $url;        
		validate_url($input);
        $url = $input;
			
		//	check Title
		if(!preg_match('/^[[:print:]]{5,100}$/', $title)) {
            echo "<h1>$mytitle</h1><br />
                <p class='em cntr warnadmin'> 
                ".$sph_messages['InvTitle']."
                <br />               
                </p>
                <br />
                <a class='bkbtn' href='addurl.php' title='Go back to Suggest form'>".$sph_messages['BackToSubForm']."</a>                
                </body>
                </html>
            ";
            die ('');
Пример #11
0
/**
 * Create a new Comment and return an XML-RPC response
 *
 * @param array of params
 *			- Item (object)
 *			- User (object) Can be NULL for anonymous comments
 *			- password (string)
 *			- username (string)
 *			- comment_parent (int)
 *			- content (string)
 *			- author (string)
 *			- author_url (string)
 *			- author_email (string)
 * @return xmlrpcmsg
 */
function xmlrpcs_new_comment($params = array(), &$commented_Item)
{
    global $DB, $Plugins, $Messages, $Hit, $localtimenow, $require_name_email, $minimum_comment_interval;
    $params = array_merge(array('password' => '', 'username' => '', 'content' => '', 'comment_parent' => 0, 'author' => '', 'author_url' => '', 'author_email' => ''), $params);
    $comment = $params['content'] = trim($params['content']);
    if (!$commented_Item->can_comment(NULL)) {
        return xmlrpcs_resperror(5, T_('You cannot leave comments on this post!'));
    }
    $commented_Item->load_Blog();
    // Make sure Blog is loaded (will be needed whether logged in or not)
    if (empty($params['username']) && empty($params['password'])) {
        // Anonymous comment
        // NO permission to edit!
        $perm_comment_edit = false;
        $User = NULL;
        $author = trim($params['author']);
        $email = trim($params['author_email']);
        if ($commented_Item->Blog->get_setting('allow_anon_url')) {
            $url = trim($params['author_url']);
        } else {
            $url = NULL;
        }
        // we need some id info from the anonymous user:
        if ($require_name_email) {
            // We want Name and EMail with comments
            if (empty($author)) {
                return xmlrpcs_resperror(5, T_('Please fill in your name.'));
            }
            if (empty($email)) {
                return xmlrpcs_resperror(5, T_('Please fill in your email.'));
            }
        }
        if (!empty($author) && antispam_check($author)) {
            return xmlrpcs_resperror(5, T_('Supplied name is invalid.'));
        }
        if (!empty($email) && (!is_email($email) || antispam_check($email))) {
            return xmlrpcs_resperror(5, T_('Supplied email address is invalid.'));
        }
        if (!stristr($url, '://') && !stristr($url, '@')) {
            // add 'http://' if no protocol defined for URL; but not if the user seems to be entering an email address alone
            $url = 'http://' . $url;
        }
        if (strlen($url) <= 8) {
            // ex: https:// is 8 chars
            $url = '';
        }
        // Note: as part of the validation we require the url to be absolute; otherwise we cannot detect bozos typing in
        // a title for their comment or whatever...
        if ($error = validate_url($url, 'commenting')) {
            return xmlrpcs_resperror(5, T_('Supplied website address is invalid: ') . $error);
        }
    } else {
        $User =& $params['User'];
        $perm_comment_edit = $User->check_perm('blog_comment!published', 'edit', false, $commented_Item->Blog->ID);
        $author = $User->ID;
        $url = $User->url;
        $email = $User->email;
    }
    // Following call says "WARNING: this does *NOT* (necessarilly) make the HTML code safe.":
    $comment = check_html_sanity($comment, $perm_comment_edit ? 'posting' : 'commenting', $User);
    if ($comment === false) {
        // ERROR! Restore original comment for further editing:
        $comment = $params['content'];
    }
    if (empty($comment)) {
        // comment should not be empty!
        return xmlrpcs_resperror(5, T_('Please do not send empty comments.'));
    }
    $now = date2mysql($localtimenow);
    /*
     * Flood-protection
     * NOTE: devs can override the flood protection delay in /conf/_overrides_TEST.php
     * TODO: Put time check into query?
     * TODO: move that as far !!UP!! as possible! We want to waste minimum resources on Floods
     * TODO: have several thresholds. For example:
     * 1 comment max every 30 sec + 5 comments max every 10 minutes + 15 comments max every 24 hours
     * TODO: factorize with trackback
     */
    $query = 'SELECT MAX(comment_date)
				FROM T_comments
				WHERE comment_author_IP = ' . $DB->quote($Hit->IP) . '
				OR comment_author_email = ' . $DB->quote($email);
    $ok = 1;
    if ($then = $DB->get_var($query)) {
        $time_lastcomment = mysql2date("U", $then);
        $time_newcomment = mysql2date("U", $now);
        if ($time_newcomment - $time_lastcomment < $minimum_comment_interval) {
            $ok = 0;
        }
    }
    if (!$ok) {
        return xmlrpcs_resperror(5, sprintf(T_('You can only post a new comment every %d seconds.'), $minimum_comment_interval));
    }
    /* end flood-protection */
    /**
     * Create comment object. Gets validated, before recording it into DB:
     */
    $Comment = new Comment();
    $Comment->set('type', 'comment');
    $Comment->set_Item($commented_Item);
    if ($User) {
        // User is logged in, we'll use his ID
        $Comment->set_author_User($User);
    } else {
        // User is not logged in:
        $Comment->set('author', $author);
        $Comment->set('author_email', $email);
        $Comment->set('author_url', $url);
    }
    if (!empty($params['comment_parent'])) {
        $Comment->set('in_reply_to_cmt_ID', intval($params['comment_parent']));
    }
    $Comment->set('author_IP', $Hit->IP);
    $Comment->set('date', $now);
    $Comment->set('content', $comment);
    if ($perm_comment_edit) {
        // User has perm to moderate comments, publish automatically:
        $Comment->set('status', 'published');
    } else {
        // Assign default status for new comments:
        $Comment->set('status', $commented_Item->Blog->get_setting('new_feedback_status'));
    }
    $action = 'submit_comment_post_' . $commented_Item->ID;
    // Trigger event: a Plugin could add a $category="error" message here..
    $Plugins->trigger_event('BeforeCommentFormInsert', array('Comment' => &$Comment, 'original_comment' => $params['content'], 'is_preview' => false, 'action' => &$action));
    if ($Messages->has_errors()) {
        return xmlrpcs_resperror(5, $Messages->get_string('Cannot create comment, please correct these errors:' . "\n", '', "  //  \n", 'xmlrpc'));
    }
    $Comment->dbinsert();
    if ($Comment->ID) {
        // comment has not been deleted
        // Trigger event: a Plugin should cleanup any temporary data here..
        $Plugins->trigger_event('AfterCommentFormInsert', array('Comment' => &$Comment, 'original_comment' => $params['content']));
        /*
         * --------------------------
         * New comment notifications:
         * --------------------------
         */
        // TODO: dh> this should only send published feedback probably and should also use "outbound_notifications_mode"
        // fp> yes for general users, but comment moderators need to receive notifications for new unpublished comments
        // asimo> this handle moderators and general users as well and use "outbound_notifications_mode" in case of general users
        // Moderators will get emails about every new comment
        // Subscribed user will only get emails about new published comments
        $executed_by_userid = empty($User) ? NULL : $User->ID;
        $Comment->handle_notifications(true, $executed_by_userid);
    } else {
        return xmlrpcs_resperror(99, 'Error while inserting comment: ' . $DB->last_error);
    }
    return new xmlrpcresp(new xmlrpcval($Comment->ID, 'int'));
}
Пример #12
0
 function register_post(&$a)
 {
     global $lang;
     $verified = 0;
     $blocked = 1;
     switch ($a->config['register_policy']) {
         case REGISTER_OPEN:
             $blocked = 0;
             $verified = 1;
             break;
         case REGISTER_APPROVE:
             $blocked = 1;
             $verified = 0;
             break;
         default:
         case REGISTER_CLOSED:
             if (!x($_SESSION, 'authenticated') && !x($_SESSION, 'administrator')) {
                 notice(t('Permission denied.') . EOL);
                 return;
             }
             $blocked = 1;
             $verified = 0;
             break;
     }
     $using_invites = get_config('system', 'invitation_only');
     $num_invites = get_config('system', 'number_invites');
     $invite_id = x($_POST, 'invite_id') ? notags(trim($_POST['invite_id'])) : '';
     $username = x($_POST, 'username') ? notags(trim($_POST['username'])) : '';
     $nickname = x($_POST, 'nickname') ? notags(trim($_POST['nickname'])) : '';
     $email = x($_POST, 'email') ? notags(trim($_POST['email'])) : '';
     $openid_url = x($_POST, 'openid_url') ? notags(trim($_POST['openid_url'])) : '';
     $photo = x($_POST, 'photo') ? notags(trim($_POST['photo'])) : '';
     $publish = x($_POST, 'profile_publish_reg') && intval($_POST['profile_publish_reg']) ? 1 : 0;
     $netpublish = strlen(get_config('system', 'directory_submit_url')) ? $publish : 0;
     $tmp_str = $openid_url;
     if ($using_invites) {
         if (!$invite_id) {
             notice(t('An invitation is required.') . EOL);
             return;
         }
         $r = q("select * from register where `hash` = '%s' limit 1", dbesc($invite_id));
         if (!results($r)) {
             notice(t('Invitation could not be verified.') . EOL);
             return;
         }
     }
     if (!x($username) || !x($email) || !x($nickname)) {
         if ($openid_url) {
             if (!validate_url($tmp_str)) {
                 notice(t('Invalid OpenID url') . EOL);
                 return;
             }
             $_SESSION['register'] = 1;
             $_SESSION['openid'] = $openid_url;
             require_once 'library/openid.php';
             $openid = new LightOpenID();
             $openid->identity = $openid_url;
             $openid->returnUrl = $a->get_baseurl() . '/openid';
             $openid->required = array('namePerson/friendly', 'contact/email', 'namePerson');
             $openid->optional = array('namePerson/first', 'media/image/aspect11', 'media/image/default');
             goaway($openid->authUrl());
             // NOTREACHED
         }
         notice(t('Please enter the required information.') . EOL);
         return;
     }
     if (!validate_url($tmp_str)) {
         $openid_url = '';
     }
     $err = '';
     // collapse multiple spaces in name
     $username = preg_replace('/ +/', ' ', $username);
     if (mb_strlen($username) > 48) {
         $err .= t('Please use a shorter name.') . EOL;
     }
     if (mb_strlen($username) < 3) {
         $err .= t('Name too short.') . EOL;
     }
     // I don't really like having this rule, but it cuts down
     // on the number of auto-registrations by Russian spammers
     //  Using preg_match was completely unreliable, due to mixed UTF-8 regex support
     //	$no_utf = get_config('system','no_utf');
     //	$pat = (($no_utf) ? '/^[a-zA-Z]* [a-zA-Z]*$/' : '/^\p{L}* \p{L}*$/u' );
     // So now we are just looking for a space in the full name.
     $loose_reg = get_config('system', 'no_regfullname');
     if (!$loose_reg) {
         $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
         if (!strpos($username, ' ')) {
             $err .= t("That doesn't appear to be your full (First Last) name.") . EOL;
         }
     }
     if (!allowed_email($email)) {
         $err .= t('Your email domain is not among those allowed on this site.') . EOL;
     }
     if (!valid_email($email) || !validate_email($email)) {
         $err .= t('Not a valid email address.') . EOL;
     }
     // Disallow somebody creating an account using openid that uses the admin email address,
     // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
     if (x($a->config, 'admin_email') && strcasecmp($email, $a->config['admin_email']) == 0 && strlen($openid_url)) {
         $r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1", dbesc($email));
         if (count($r)) {
             $err .= t('Cannot use that email.') . EOL;
         }
     }
     $nickname = $_POST['nickname'] = strtolower($nickname);
     if (!preg_match("/^[a-z][a-z0-9\\-\\_]*\$/", $nickname)) {
         $err .= t('Your "nickname" can only contain "a-z", "0-9", "-", and "_", and must also begin with a letter.') . EOL;
     }
     $r = q("SELECT `uid` FROM `user`\n               \tWHERE `nickname` = '%s' LIMIT 1", dbesc($nickname));
     if (count($r)) {
         $err .= t('Nickname is already registered. Please choose another.') . EOL;
     }
     if (strlen($err)) {
         notice($err);
         return;
     }
     $new_password = autoname(6) . mt_rand(100, 9999);
     $new_password_encoded = hash('whirlpool', $new_password);
     $res = openssl_pkey_new(array('digest_alg' => 'sha1', 'private_key_bits' => 4096, 'encrypt_key' => false));
     // Get private key
     if (empty($res)) {
         notice(t('SERIOUS ERROR: Generation of security keys failed.') . EOL);
         return;
     }
     $prvkey = '';
     openssl_pkey_export($res, $prvkey);
     // Get public key
     $pkey = openssl_pkey_get_details($res);
     $pubkey = $pkey["key"];
     /**
      *
      * Create another keypair for signing/verifying
      * salmon protocol messages. We have to use a slightly
      * less robust key because this won't be using openssl
      * but the phpseclib. Since it is PHP interpreted code
      * it is not nearly as efficient, and the larger keys
      * will take several minutes each to process.
      *
      */
     $sres = openssl_pkey_new(array('digest_alg' => 'sha1', 'private_key_bits' => 512, 'encrypt_key' => false));
     // Get private key
     $sprvkey = '';
     openssl_pkey_export($sres, $sprvkey);
     // Get public key
     $spkey = openssl_pkey_get_details($sres);
     $spubkey = $spkey["key"];
     $r = q("INSERT INTO `user` ( `guid`, `username`, `password`, `email`, `openid`, `nickname`,\n\t\t`pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked` )\n\t\tVALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )", dbesc(generate_user_guid()), dbesc($username), dbesc($new_password_encoded), dbesc($email), dbesc($openid_url), dbesc($nickname), dbesc($pubkey), dbesc($prvkey), dbesc($spubkey), dbesc($sprvkey), dbesc(datetime_convert()), intval($verified), intval($blocked));
     if ($r) {
         $r = q("SELECT `uid` FROM `user` \n\t\t\tWHERE `username` = '%s' AND `password` = '%s' LIMIT 1", dbesc($username), dbesc($new_password_encoded));
         if ($r !== false && count($r)) {
             $newuid = intval($r[0]['uid']);
         }
     } else {
         notice(t('An error occurred during registration. Please try again.') . EOL);
         return;
     }
     /**
      * if somebody clicked submit twice very quickly, they could end up with two accounts 
      * due to race condition. Remove this one.
      */
     $r = q("SELECT `uid` FROM `user`\n               \tWHERE `nickname` = '%s' ", dbesc($nickname));
     if (count($r) > 1 && $newuid) {
         $err .= t('Nickname is already registered. Please choose another.') . EOL;
         q("DELETE FROM `user` WHERE `uid` = %d LIMIT 1", intval($newuid));
         notice($err);
         return;
     }
     if (x($newuid) !== false) {
         $r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` )\n\t\t\tVALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ", intval($newuid), 'default', 1, dbesc($username), dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"), dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"), intval($publish), intval($netpublish));
         if ($r === false) {
             notice(t('An error occurred creating your default profile. Please try again.') . EOL);
             // Start fresh next time.
             $r = q("DELETE FROM `user` WHERE `uid` = %d", intval($newuid));
             return;
         }
         $r = q("INSERT INTO `contact` ( `uid`, `created`, `self`, `name`, `nick`, `photo`, `thumb`, `micro`, `blocked`, `pending`, `url`, `nurl`,\n\t\t\t`request`, `notify`, `poll`, `confirm`, `poco`, `name-date`, `uri-date`, `avatar-date` )\n\t\t\tVALUES ( %d, '%s', 1, '%s', '%s', '%s', '%s', '%s', 0, 0, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($newuid), datetime_convert(), dbesc($username), dbesc($nickname), dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"), dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"), dbesc($a->get_baseurl() . "/photo/micro/{$newuid}.jpg"), dbesc($a->get_baseurl() . "/profile/{$nickname}"), dbesc(normalise_link($a->get_baseurl() . "/profile/{$nickname}")), dbesc($a->get_baseurl() . "/dfrn_request/{$nickname}"), dbesc($a->get_baseurl() . "/dfrn_notify/{$nickname}"), dbesc($a->get_baseurl() . "/dfrn_poll/{$nickname}"), dbesc($a->get_baseurl() . "/dfrn_confirm/{$nickname}"), dbesc($a->get_baseurl() . "/poco/{$nickname}"), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc(datetime_convert()));
     }
     $use_gravatar = get_config('system', 'no_gravatar') ? false : true;
     // if we have an openid photo use it.
     // otherwise unless it is disabled, use gravatar
     if ($use_gravatar || strlen($photo)) {
         require_once 'include/Photo.php';
         if ($use_gravatar && !strlen($photo)) {
             $photo = gravatar_img($email);
         }
         $photo_failure = false;
         $filename = basename($photo);
         $img_str = fetch_url($photo, true);
         $img = new Photo($img_str);
         if ($img->is_valid()) {
             $img->scaleImageSquare(175);
             $hash = photo_new_resource();
             $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 4);
             if ($r === false) {
                 $photo_failure = true;
             }
             $img->scaleImage(80);
             $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 5);
             if ($r === false) {
                 $photo_failure = true;
             }
             $img->scaleImage(48);
             $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 6);
             if ($r === false) {
                 $photo_failure = true;
             }
             if (!$photo_failure) {
                 q("UPDATE `photo` SET `profile` = 1 WHERE `resource-id` = '%s' ", dbesc($hash));
             }
         }
     }
     if ($netpublish && $a->config['register_policy'] != REGISTER_APPROVE) {
         $url = $a->get_baseurl() . "/profile/{$nickname}";
         proc_run('php', "include/directory.php", "{$url}");
     }
     call_hooks('register_account', $newuid);
     if ($a->config['register_policy'] == REGISTER_OPEN) {
         if ($using_invites && $invite_id) {
             q("delete * from register where hash = '%s' limit 1", dbesc($invite_id));
             set_pconfig($newuid, 'system', 'invites_remaining', $num_invites);
         }
         $email_tpl = get_intltext_template("register_open_eml.tpl");
         $email_tpl = replace_macros($email_tpl, array('$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$username' => $username, '$email' => $email, '$password' => $new_password, '$uid' => $newuid));
         $res = mail($email, sprintf(t('Registration details for %s'), $a->config['sitename']), $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n" . 'Content-type: text/plain; charset=UTF-8' . "\n" . 'Content-transfer-encoding: 8bit');
         if ($res) {
             info(t('Registration successful. Please check your email for further instructions.') . EOL);
             goaway(z_root());
         } else {
             notice(t('Failed to send email message. Here is the message that failed.') . $email_tpl . EOL);
         }
     } elseif ($a->config['register_policy'] == REGISTER_APPROVE) {
         if (!strlen($a->config['admin_email'])) {
             notice(t('Your registration can not be processed.') . EOL);
             goaway(z_root());
         }
         $hash = random_string();
         $r = q("INSERT INTO `register` ( `hash`, `created`, `uid`, `password`, `language` ) VALUES ( '%s', '%s', %d, '%s', '%s' ) ", dbesc($hash), dbesc(datetime_convert()), intval($newuid), dbesc($new_password), dbesc($lang));
         $r = q("SELECT `language` FROM `user` WHERE `email` = '%s' LIMIT 1", dbesc($a->config['admin_email']));
         if (count($r)) {
             push_lang($r[0]['language']);
         } else {
             push_lang('en');
         }
         if ($using_invites && $invite_id) {
             q("delete * from register where hash = '%s' limit 1", dbesc($invite_id));
             set_pconfig($newuid, 'system', 'invites_remaining', $num_invites);
         }
         $email_tpl = get_intltext_template("register_verify_eml.tpl");
         $email_tpl = replace_macros($email_tpl, array('$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$username' => $username, '$email' => $email, '$password' => $new_password, '$uid' => $newuid, '$hash' => $hash));
         $res = mail($a->config['admin_email'], sprintf(t('Registration request at %s'), $a->config['sitename']), $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n" . 'Content-type: text/plain; charset=UTF-8' . "\n" . 'Content-transfer-encoding: 8bit');
         pop_lang();
         if ($res) {
             info(t('Your registration is pending approval by the site owner.') . EOL);
             goaway(z_root());
         }
     }
     return;
 }
Пример #13
0
 function dfrn_request_post(&$a)
 {
     if ($a->argc != 2 || !count($a->profile)) {
         return;
     }
     if ($_POST['cancel']) {
         goaway(z_root());
     }
     /**
      *
      * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
      * to confirm the request, and then we've clicked submit (perhaps after logging in). 
      * That brings us here:
      *
      */
     if (x($_POST, 'localconfirm') && $_POST['localconfirm'] == 1) {
         /**
          * Ensure this is a valid request
          */
         if (local_user() && $a->user['nickname'] == $a->argv[1] && x($_POST, 'dfrn_url')) {
             $dfrn_url = notags(trim($_POST['dfrn_url']));
             $aes_allow = x($_POST, 'aes_allow') && $_POST['aes_allow'] == 1 ? 1 : 0;
             $confirm_key = x($_POST, 'confirm_key') ? $_POST['confirm_key'] : "";
             $contact_record = null;
             if (x($dfrn_url)) {
                 /**
                  * Lookup the contact based on their URL (which is the only unique thing we have at the moment)
                  */
                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1", intval(local_user()), dbesc($dfrn_url));
                 if (count($r)) {
                     if (strlen($r[0]['dfrn-id'])) {
                         /**
                          * We don't need to be here. It has already happened.
                          */
                         notice(t("This introduction has already been accepted.") . EOL);
                         return;
                     } else {
                         $contact_record = $r[0];
                     }
                 }
                 if (is_array($contact_record)) {
                     $r = q("UPDATE `contact` SET `ret-aes` = %d WHERE `id` = %d LIMIT 1", intval($aes_allow), intval($contact_record['id']));
                 } else {
                     /**
                      * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
                      */
                     require_once 'Scrape.php';
                     $parms = scrape_dfrn($dfrn_url);
                     if (!count($parms)) {
                         notice(t('Profile location is not valid or does not contain profile information.') . EOL);
                         return;
                     } else {
                         if (!x($parms, 'fn')) {
                             notice(t('Warning: profile location has no identifiable owner name.') . EOL);
                         }
                         if (!x($parms, 'photo')) {
                             notice(t('Warning: profile location has no profile photo.') . EOL);
                         }
                         $invalid = validate_dfrn($parms);
                         if ($invalid) {
                             notice(sprintf(tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid), $invalid) . EOL);
                             return;
                         }
                     }
                     $dfrn_request = $parms['dfrn-request'];
                     /********* Escape the entire array ********/
                     dbesc_array($parms);
                     /******************************************/
                     /**
                      * Create a contact record on our site for the other person
                      */
                     $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `name`, `nick`, `photo`, `site-pubkey`,\n\t\t\t\t\t\t`request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`) \n\t\t\t\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)", intval(local_user()), datetime_convert(), dbesc($dfrn_url), dbesc(normalise_link($dfrn_url)), $parms['fn'], $parms['nick'], $parms['photo'], $parms['key'], $parms['dfrn-request'], $parms['dfrn-confirm'], $parms['dfrn-notify'], $parms['dfrn-poll'], $parms['dfrn-poco'], dbesc(NETWORK_DFRN), intval($aes_allow));
                 }
                 if ($r) {
                     info(t("Introduction complete.") . EOL);
                 }
                 /**
                  * Allow the blocked remote notification to complete
                  */
                 if (is_array($contact_record)) {
                     $dfrn_request = $contact_record['request'];
                 }
                 if (strlen($dfrn_request) && strlen($confirm_key)) {
                     $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
                 }
                 // (ignore reply, nothing we can do it failed)
                 goaway($dfrn_url);
                 return;
                 // NOTREACHED
             }
         }
         // invalid/bogus request
         notice(t('Unrecoverable protocol error.') . EOL);
         goaway(z_root());
         return;
         // NOTREACHED
     }
     /**
      * Otherwise:
      * 
      * Scenario 1:
      * We are the requestee. A person from a remote cell has made an introduction 
      * on our profile web page and clicked submit. We will use their DFRN-URL to 
      * figure out how to contact their cell.  
      *
      * Scrape the originating DFRN-URL for everything we need. Create a contact record
      * and an introduction to show our user next time he/she logs in.
      * Finally redirect back to the requestor so that their site can record the request.
      * If our user (the requestee) later confirms this request, a record of it will need 
      * to exist on the requestor's cell in order for the confirmation process to complete.. 
      *
      * It's possible that neither the requestor or the requestee are logged in at the moment,
      * and the requestor does not yet have any credentials to the requestee profile.
      *
      * Who is the requestee? We've already loaded their profile which means their nickname should be
      * in $a->argv[1] and we should have their complete info in $a->profile.
      *
      */
     if (!(is_array($a->profile) && count($a->profile))) {
         notice(t('Profile unavailable.') . EOL);
         return;
     }
     $nickname = $a->profile['nickname'];
     $notify_flags = $a->profile['notify-flags'];
     $uid = $a->profile['uid'];
     $maxreq = intval($a->profile['maxreq']);
     $contact_record = null;
     $failed = false;
     $parms = null;
     if (x($_POST, 'dfrn_url')) {
         /**
          * Block friend request spam
          */
         if ($maxreq) {
             $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d", dbesc(datetime_convert('UTC', 'UTC', 'now - 24 hours')), intval($uid));
             if (count($r) > $maxreq) {
                 notice(sprintf(t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
                 notice(t('Spam protection measures have been invoked.') . EOL);
                 notice(t('Friends are advised to please try again in 24 hours.') . EOL);
                 return;
             }
         }
         /**
          *
          * Cleanup old introductions that remain blocked. 
          * Also remove the contact record, but only if there is no existing relationship
          * Do not remove email contacts as these may be awaiting email verification
          */
         $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel` \n\t\t\tFROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`\n\t\t\tWHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0 \n\t\t\tAND `contact`.`network` != '%s'\n\t\t\tAND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ", dbesc(NETWORK_MAIL));
         if (count($r)) {
             foreach ($r as $rr) {
                 if (!$rr['rel']) {
                     q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1", intval($rr['cid']));
                 }
                 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1", intval($rr['iid']));
             }
         }
         /**
          *
          * Cleanup any old email intros - which will have a greater lifetime
          */
         $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel` \n\t\t\tFROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`\n\t\t\tWHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0 \n\t\t\tAND `contact`.`network` = '%s'\n\t\t\tAND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ", dbesc(NETWORK_MAIL));
         if (count($r)) {
             foreach ($r as $rr) {
                 if (!$rr['rel']) {
                     q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1", intval($rr['cid']));
                 }
                 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1", intval($rr['iid']));
             }
         }
         $url = trim($_POST['dfrn_url']);
         if (!strlen($url)) {
             notice(t("Invalid locator") . EOL);
             return;
         }
         // Canonicalise email-style profile locator
         $hcard = '';
         $url = webfinger_dfrn($url, $hcard);
         if (substr($url, 0, 5) === 'stat:') {
             $network = NETWORK_OSTATUS;
             $url = substr($url, 5);
         } else {
             $network = NETWORK_DFRN;
         }
         logger('dfrn_request: url: ' . $url);
         if (!strlen($url)) {
             notice(t("Unable to resolve your name at the provided location.") . EOL);
             return;
         }
         if ($network === NETWORK_DFRN) {
             $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1", intval($uid), dbesc($url));
             if (count($ret)) {
                 if (strlen($ret[0]['issued-id'])) {
                     notice(t('You have already introduced yourself here.') . EOL);
                     return;
                 } elseif ($ret[0]['rel'] == CONTACT_IS_FRIEND) {
                     notice(sprintf(t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
                     return;
                 } else {
                     $contact_record = $ret[0];
                     $parms = array('dfrn-request' => $ret[0]['request']);
                 }
             }
             $issued_id = random_string();
             if (is_array($contact_record)) {
                 // There is a contact record but no issued-id, so this
                 // is a reciprocal introduction from a known contact
                 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1", dbesc($issued_id), intval($contact_record['id']));
             } else {
                 if (!validate_url($url)) {
                     notice(t('Invalid profile URL.') . EOL);
                     goaway($a->get_baseurl() . '/' . $a->cmd);
                     return;
                     // NOTREACHED
                 }
                 if (!allowed_url($url)) {
                     notice(t('Disallowed profile URL.') . EOL);
                     goaway($a->get_baseurl() . '/' . $a->cmd);
                     return;
                     // NOTREACHED
                 }
                 require_once 'Scrape.php';
                 $parms = scrape_dfrn($hcard ? $hcard : $url);
                 if (!count($parms)) {
                     notice(t('Profile location is not valid or does not contain profile information.') . EOL);
                     goaway($a->get_baseurl() . '/' . $a->cmd);
                 } else {
                     if (!x($parms, 'fn')) {
                         notice(t('Warning: profile location has no identifiable owner name.') . EOL);
                     }
                     if (!x($parms, 'photo')) {
                         notice(t('Warning: profile location has no profile photo.') . EOL);
                     }
                     $invalid = validate_dfrn($parms);
                     if ($invalid) {
                         notice(sprintf(tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid), $invalid) . EOL);
                         return;
                     }
                 }
                 $parms['url'] = $url;
                 $parms['issued-id'] = $issued_id;
                 dbesc_array($parms);
                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,\n\t\t\t\t\t`request`, `confirm`, `notify`, `poll`, `poco`, `network` )\n\t\t\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )", intval($uid), dbesc(datetime_convert()), $parms['url'], dbesc(normalise_link($parms['url'])), $parms['fn'], $parms['nick'], $parms['issued-id'], $parms['photo'], $parms['key'], $parms['dfrn-request'], $parms['dfrn-confirm'], $parms['dfrn-notify'], $parms['dfrn-poll'], $parms['dfrn-poco'], dbesc(NETWORK_DFRN));
                 // find the contact record we just created
                 if ($r) {
                     $r = q("SELECT `id` FROM `contact` \n\t\t\t\t\t\tWHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1", intval($uid), $parms['url'], $parms['issued-id']);
                     if (count($r)) {
                         $contact_record = $r[0];
                     }
                 }
             }
             if ($r === false) {
                 notice(t('Failed to update contact record.') . EOL);
                 return;
             }
             $hash = random_string() . (string) time();
             // Generate a confirm_key
             if (is_array($contact_record)) {
                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)\n\t\t\t\t\tVALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )", intval($uid), intval($contact_record['id']), x($_POST, 'knowyou') && $_POST['knowyou'] == 1 ? 1 : 0, dbesc(notags(trim($_POST['dfrn-request-message']))), dbesc($hash), dbesc(datetime_convert()));
             }
             // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
             if (!$failed) {
                 info(t('Your introduction has been sent.') . EOL);
             }
             // "Homecoming" - send the requestor back to their site to record the introduction.
             $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
             $aes_allow = function_exists('openssl_encrypt') ? 1 : 0;
             goaway($parms['dfrn-request'] . "?dfrn_url={$dfrn_url}" . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&confirm_key=' . $hash . ($aes_allow ? "&aes_allow=1" : ""));
             // NOTREACHED
             // END $network === NETWORK_DFRN
         } elseif ($network === NETWORK_OSTATUS) {
             /**
              *
              * OStatus network
              * Check contact existence
              * Try and scrape together enough information to create a contact record, 
              * with us as CONTACT_IS_FOLLOWER
              * Substitute our user's feed URL into $url template
              * Send the subscriber home to subscribe
              *
              */
             $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
             goaway($url);
             // NOTREACHED
             // END $network === NETWORK_OSTATUS
         }
     }
     return;
 }
Пример #14
0
function redirect($url, $absolute = false)
{
    if (strpos($url, '/actions/') !== false) {
        $url = CONFIG_INDEX_REDIRECT_TO;
    }
    if (!$absolute) {
        $url = CONFIG_SITE_URL . trim($url, '/');
    }
    validate_url($url);
    header('location: ' . $url);
    exit;
}
Пример #15
0
function innovation_show()
{
    global $services, $innovation_file, $innovation_data, $thisfile_innov;
    $success = $error = null;
    // submitted form
    if (isset($_POST['submit'])) {
        foreach ($services as $var) {
            if ($_POST[$var] != '') {
                if (validate_url($_POST[$var])) {
                    $resp[$var] = $_POST[$var];
                } else {
                    $error .= i18n_r($thisfile_innov . '/' . strtoupper($var) . '_ERROR') . ' ';
                }
            }
        }
        # if there are no errors, save data
        if (!$error) {
            $xml = @new SimpleXMLElement('<item></item>');
            foreach ($services as $var) {
                if (isset($resp[$var])) {
                    $xml->addChild($var, $resp[$var]);
                }
            }
            if (!$xml->asXML($innovation_file)) {
                $error = i18n_r('CHMOD_ERROR');
            } else {
                $innovation_data = getXML($innovation_file);
                $success = i18n_r('SETTINGS_UPDATED');
            }
        }
    }
    ?>
	<h3><?php 
    i18n($thisfile_innov . '/INNOVATION_TITLE');
    ?>
</h3>
	
	<?php 
    if ($success) {
        echo '<p style="color:#669933;"><b>' . $success . '</b></p>';
    }
    if ($error) {
        echo '<p style="color:#cc0000;"><b>' . $error . '</b></p>';
    }
    ?>
	
	<form method="post" action="<?php 
    echo $_SERVER['REQUEST_URI'];
    ?>
">
		
		<?php 
    foreach ($services as $var) {
        $value = '';
        if (isset($innovation_data->{$var})) {
            $value = $innovation_data->{$var};
        }
        echo '<p><label for="inn_' . $var . '" >' . i18n($thisfile_innov . '/' . strtoupper($var) . '_URL') . '</label><input id="inn_' . $var . '" name="' . $var . '" class="text" value="' . $value . '" type="url" /></p>';
    }
    ?>

		<p><input type="submit" id="submit" class="submit" value="<?php 
    i18n('BTN_SAVESETTINGS');
    ?>
" name="submit" /></p>
	</form>
	
	<?php 
}
Пример #16
0
function settings_post(&$a)
{
    if (!local_user()) {
        return;
    }
    if (x($_SESSION, 'submanage') && intval($_SESSION['submanage'])) {
        return;
    }
    if (count($a->user) && x($a->user, 'uid') && $a->user['uid'] != local_user()) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    $old_page_flags = $a->user['page-flags'];
    if ($a->argc > 1 && $a->argv[1] === 'oauth' && x($_POST, 'remove')) {
        check_form_security_token_redirectOnErr('/settings/oauth', 'settings_oauth');
        $key = $_POST['remove'];
        q("DELETE FROM tokens WHERE id='%s' AND uid=%d", dbesc($key), local_user());
        goaway($a->get_baseurl(true) . "/settings/oauth/");
        return;
    }
    if ($a->argc > 2 && $a->argv[1] === 'oauth' && ($a->argv[2] === 'edit' || $a->argv[2] === 'add') && x($_POST, 'submit')) {
        check_form_security_token_redirectOnErr('/settings/oauth', 'settings_oauth');
        $name = x($_POST, 'name') ? $_POST['name'] : '';
        $key = x($_POST, 'key') ? $_POST['key'] : '';
        $secret = x($_POST, 'secret') ? $_POST['secret'] : '';
        $redirect = x($_POST, 'redirect') ? $_POST['redirect'] : '';
        $icon = x($_POST, 'icon') ? $_POST['icon'] : '';
        if ($name == "" || $key == "" || $secret == "") {
            notice(t("Missing some important data!"));
        } else {
            if ($_POST['submit'] == t("Update")) {
                $r = q("UPDATE clients SET\n\t\t\t\t\t\t\tclient_id='%s',\n\t\t\t\t\t\t\tpw='%s',\n\t\t\t\t\t\t\tname='%s',\n\t\t\t\t\t\t\tredirect_uri='%s',\n\t\t\t\t\t\t\ticon='%s',\n\t\t\t\t\t\t\tuid=%d\n\t\t\t\t\t\tWHERE client_id='%s'", dbesc($key), dbesc($secret), dbesc($name), dbesc($redirect), dbesc($icon), local_user(), dbesc($key));
            } else {
                $r = q("INSERT INTO clients\n\t\t\t\t\t\t\t(client_id, pw, name, redirect_uri, icon, uid)\n\t\t\t\t\t\tVALUES ('%s','%s','%s','%s','%s',%d)", dbesc($key), dbesc($secret), dbesc($name), dbesc($redirect), dbesc($icon), local_user());
            }
        }
        goaway($a->get_baseurl(true) . "/settings/oauth/");
        return;
    }
    if ($a->argc > 1 && $a->argv[1] == 'addon') {
        check_form_security_token_redirectOnErr('/settings/addon', 'settings_addon');
        call_hooks('plugin_settings_post', $_POST);
        return;
    }
    if ($a->argc > 1 && $a->argv[1] == 'connectors') {
        check_form_security_token_redirectOnErr('/settings/connectors', 'settings_connectors');
        if (x($_POST, 'imap-submit')) {
            $mail_server = x($_POST, 'mail_server') ? $_POST['mail_server'] : '';
            $mail_port = x($_POST, 'mail_port') ? $_POST['mail_port'] : '';
            $mail_ssl = x($_POST, 'mail_ssl') ? strtolower(trim($_POST['mail_ssl'])) : '';
            $mail_user = x($_POST, 'mail_user') ? $_POST['mail_user'] : '';
            $mail_pass = x($_POST, 'mail_pass') ? trim($_POST['mail_pass']) : '';
            $mail_action = x($_POST, 'mail_action') ? trim($_POST['mail_action']) : '';
            $mail_movetofolder = x($_POST, 'mail_movetofolder') ? trim($_POST['mail_movetofolder']) : '';
            $mail_replyto = x($_POST, 'mail_replyto') ? $_POST['mail_replyto'] : '';
            $mail_pubmail = x($_POST, 'mail_pubmail') ? $_POST['mail_pubmail'] : '';
            $mail_disabled = function_exists('imap_open') && !get_config('system', 'imap_disabled') ? 0 : 1;
            if (get_config('system', 'dfrn_only')) {
                $mail_disabled = 1;
            }
            if (!$mail_disabled) {
                $failed = false;
                $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval(local_user()));
                if (!count($r)) {
                    q("INSERT INTO `mailacct` (`uid`) VALUES (%d)", intval(local_user()));
                }
                if (strlen($mail_pass)) {
                    $pass = '';
                    openssl_public_encrypt($mail_pass, $pass, $a->user['pubkey']);
                    q("UPDATE `mailacct` SET `pass` = '%s' WHERE `uid` = %d", dbesc(bin2hex($pass)), intval(local_user()));
                }
                $r = q("UPDATE `mailacct` SET `server` = '%s', `port` = %d, `ssltype` = '%s', `user` = '%s',\n\t\t\t\t\t`action` = %d, `movetofolder` = '%s',\n\t\t\t\t\t`mailbox` = 'INBOX', `reply_to` = '%s', `pubmail` = %d WHERE `uid` = %d", dbesc($mail_server), intval($mail_port), dbesc($mail_ssl), dbesc($mail_user), intval($mail_action), dbesc($mail_movetofolder), dbesc($mail_replyto), intval($mail_pubmail), intval(local_user()));
                logger("mail: updating mailaccount. Response: " . print_r($r, true));
                $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval(local_user()));
                if (count($r)) {
                    $eacct = $r[0];
                    require_once 'include/email.php';
                    $mb = construct_mailbox_name($eacct);
                    if (strlen($eacct['server'])) {
                        $dcrpass = '';
                        openssl_private_decrypt(hex2bin($eacct['pass']), $dcrpass, $a->user['prvkey']);
                        $mbox = email_connect($mb, $mail_user, $dcrpass);
                        unset($dcrpass);
                        if (!$mbox) {
                            $failed = true;
                            notice(t('Failed to connect with email account using the settings provided.') . EOL);
                        }
                    }
                }
                if (!$failed) {
                    info(t('Email settings updated.') . EOL);
                }
            }
        }
        call_hooks('connector_settings_post', $_POST);
        return;
    }
    if ($a->argc > 1 && $a->argv[1] === 'features') {
        check_form_security_token_redirectOnErr('/settings/features', 'settings_features');
        foreach ($_POST as $k => $v) {
            if (strpos($k, 'feature_') === 0) {
                set_pconfig(local_user(), 'feature', substr($k, 8), intval($v) ? 1 : 0);
            }
        }
        info(t('Features updated') . EOL);
        return;
    }
    if ($a->argc > 1 && $a->argv[1] === 'display') {
        check_form_security_token_redirectOnErr('/settings/display', 'settings_display');
        $theme = x($_POST, 'theme') ? notags(trim($_POST['theme'])) : $a->user['theme'];
        $mobile_theme = x($_POST, 'mobile_theme') ? notags(trim($_POST['mobile_theme'])) : '';
        $nosmile = x($_POST, 'nosmile') ? intval($_POST['nosmile']) : 0;
        $noinfo = x($_POST, 'noinfo') ? intval($_POST['noinfo']) : 0;
        $infinite_scroll = x($_POST, 'infinite_scroll') ? intval($_POST['infinite_scroll']) : 0;
        $no_auto_update = x($_POST, 'no_auto_update') ? intval($_POST['no_auto_update']) : 0;
        $browser_update = x($_POST, 'browser_update') ? intval($_POST['browser_update']) : 0;
        $browser_update = $browser_update * 1000;
        if ($browser_update < 10000) {
            $browser_update = 10000;
        }
        $itemspage_network = x($_POST, 'itemspage_network') ? intval($_POST['itemspage_network']) : 40;
        if ($itemspage_network > 100) {
            $itemspage_network = 100;
        }
        $itemspage_mobile_network = x($_POST, 'itemspage_mobile_network') ? intval($_POST['itemspage_mobile_network']) : 20;
        if ($itemspage_mobile_network > 100) {
            $itemspage_mobile_network = 100;
        }
        if ($mobile_theme !== '') {
            set_pconfig(local_user(), 'system', 'mobile_theme', $mobile_theme);
        }
        set_pconfig(local_user(), 'system', 'update_interval', $browser_update);
        set_pconfig(local_user(), 'system', 'itemspage_network', $itemspage_network);
        set_pconfig(local_user(), 'system', 'itemspage_mobile_network', $itemspage_mobile_network);
        set_pconfig(local_user(), 'system', 'no_smilies', $nosmile);
        set_pconfig(local_user(), 'system', 'ignore_info', $noinfo);
        set_pconfig(local_user(), 'system', 'infinite_scroll', $infinite_scroll);
        set_pconfig(local_user(), 'system', 'no_auto_update', $no_auto_update);
        if ($theme == $a->user['theme']) {
            // call theme_post only if theme has not been changed
            if (($themeconfigfile = get_theme_config_file($theme)) != null) {
                require_once $themeconfigfile;
                theme_post($a);
            }
        }
        $r = q("UPDATE `user` SET `theme` = '%s' WHERE `uid` = %d", dbesc($theme), intval(local_user()));
        call_hooks('display_settings_post', $_POST);
        goaway($a->get_baseurl(true) . '/settings/display');
        return;
        // NOTREACHED
    }
    check_form_security_token_redirectOnErr('/settings', 'settings');
    if (x($_POST, 'resend_relocate')) {
        proc_run('php', 'include/notifier.php', 'relocate', local_user());
        info(t("Relocate message has been send to your contacts"));
        goaway($a->get_baseurl(true) . '/settings');
    }
    call_hooks('settings_post', $_POST);
    if (x($_POST, 'password') || x($_POST, 'confirm')) {
        $newpass = $_POST['password'];
        $confirm = $_POST['confirm'];
        $oldpass = hash('whirlpool', $_POST['opassword']);
        $err = false;
        if ($newpass != $confirm) {
            notice(t('Passwords do not match. Password unchanged.') . EOL);
            $err = true;
        }
        if (!x($newpass) || !x($confirm)) {
            notice(t('Empty passwords are not allowed. Password unchanged.') . EOL);
            $err = true;
        }
        //  check if the old password was supplied correctly before
        //  changing it to the new value
        $r = q("SELECT `password` FROM `user`WHERE `uid` = %d LIMIT 1", intval(local_user()));
        if ($oldpass != $r[0]['password']) {
            notice(t('Wrong password.') . EOL);
            $err = true;
        }
        if (!$err) {
            $password = hash('whirlpool', $newpass);
            $r = q("UPDATE `user` SET `password` = '%s' WHERE `uid` = %d", dbesc($password), intval(local_user()));
            if ($r) {
                info(t('Password changed.') . EOL);
            } else {
                notice(t('Password update failed. Please try again.') . EOL);
            }
        }
    }
    $username = x($_POST, 'username') ? notags(trim($_POST['username'])) : '';
    $email = x($_POST, 'email') ? notags(trim($_POST['email'])) : '';
    $timezone = x($_POST, 'timezone') ? notags(trim($_POST['timezone'])) : '';
    $defloc = x($_POST, 'defloc') ? notags(trim($_POST['defloc'])) : '';
    $openid = x($_POST, 'openid_url') ? notags(trim($_POST['openid_url'])) : '';
    $maxreq = x($_POST, 'maxreq') ? intval($_POST['maxreq']) : 0;
    $expire = x($_POST, 'expire') ? intval($_POST['expire']) : 0;
    $def_gid = x($_POST, 'group-selection') ? intval($_POST['group-selection']) : 0;
    $expire_items = x($_POST, 'expire_items') ? intval($_POST['expire_items']) : 0;
    $expire_notes = x($_POST, 'expire_notes') ? intval($_POST['expire_notes']) : 0;
    $expire_starred = x($_POST, 'expire_starred') ? intval($_POST['expire_starred']) : 0;
    $expire_photos = x($_POST, 'expire_photos') ? intval($_POST['expire_photos']) : 0;
    $expire_network_only = x($_POST, 'expire_network_only') ? intval($_POST['expire_network_only']) : 0;
    $allow_location = x($_POST, 'allow_location') && intval($_POST['allow_location']) == 1 ? 1 : 0;
    $publish = x($_POST, 'profile_in_directory') && intval($_POST['profile_in_directory']) == 1 ? 1 : 0;
    $net_publish = x($_POST, 'profile_in_netdirectory') && intval($_POST['profile_in_netdirectory']) == 1 ? 1 : 0;
    $old_visibility = x($_POST, 'visibility') && intval($_POST['visibility']) == 1 ? 1 : 0;
    $page_flags = x($_POST, 'page-flags') && intval($_POST['page-flags']) ? intval($_POST['page-flags']) : 0;
    $blockwall = x($_POST, 'blockwall') && intval($_POST['blockwall']) == 1 ? 0 : 1;
    // this setting is inverted!
    $blocktags = x($_POST, 'blocktags') && intval($_POST['blocktags']) == 1 ? 0 : 1;
    // this setting is inverted!
    $unkmail = x($_POST, 'unkmail') && intval($_POST['unkmail']) == 1 ? 1 : 0;
    $cntunkmail = x($_POST, 'cntunkmail') ? intval($_POST['cntunkmail']) : 0;
    $suggestme = x($_POST, 'suggestme') ? intval($_POST['suggestme']) : 0;
    $hide_friends = $_POST['hide-friends'] == 1 ? 1 : 0;
    $hidewall = $_POST['hidewall'] == 1 ? 1 : 0;
    $post_newfriend = $_POST['post_newfriend'] == 1 ? 1 : 0;
    $post_joingroup = $_POST['post_joingroup'] == 1 ? 1 : 0;
    $post_profilechange = $_POST['post_profilechange'] == 1 ? 1 : 0;
    $email_textonly = $_POST['email_textonly'] == 1 ? 1 : 0;
    $notify = 0;
    if (x($_POST, 'notify1')) {
        $notify += intval($_POST['notify1']);
    }
    if (x($_POST, 'notify2')) {
        $notify += intval($_POST['notify2']);
    }
    if (x($_POST, 'notify3')) {
        $notify += intval($_POST['notify3']);
    }
    if (x($_POST, 'notify4')) {
        $notify += intval($_POST['notify4']);
    }
    if (x($_POST, 'notify5')) {
        $notify += intval($_POST['notify5']);
    }
    if (x($_POST, 'notify6')) {
        $notify += intval($_POST['notify6']);
    }
    if (x($_POST, 'notify7')) {
        $notify += intval($_POST['notify7']);
    }
    if (x($_POST, 'notify8')) {
        $notify += intval($_POST['notify8']);
    }
    $email_changed = false;
    $err = '';
    $name_change = false;
    if ($username != $a->user['username']) {
        $name_change = true;
        if (strlen($username) > 40) {
            $err .= t(' Please use a shorter name.');
        }
        if (strlen($username) < 3) {
            $err .= t(' Name too short.');
        }
    }
    if ($email != $a->user['email']) {
        $email_changed = true;
        //  check for the correct password
        $r = q("SELECT `password` FROM `user`WHERE `uid` = %d LIMIT 1", intval(local_user()));
        $password = hash('whirlpool', $_POST['mpassword']);
        if ($password != $r[0]['password']) {
            $err .= t('Wrong Password') . EOL;
            $email = $a->user['email'];
        }
        //  check the email is valid
        if (!valid_email($email)) {
            $err .= t(' Not valid email.');
        }
        //  ensure new email is not the admin mail
        //if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0)) {
        if (x($a->config, 'admin_email')) {
            $adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email'])));
            if (in_array(strtolower($email), $adminlist)) {
                $err .= t(' Cannot change to that email.');
                $email = $a->user['email'];
            }
        }
    }
    if (strlen($err)) {
        notice($err . EOL);
        return;
    }
    if ($timezone != $a->user['timezone']) {
        if (strlen($timezone)) {
            date_default_timezone_set($timezone);
        }
    }
    $str_group_allow = perms2str($_POST['group_allow']);
    $str_contact_allow = perms2str($_POST['contact_allow']);
    $str_group_deny = perms2str($_POST['group_deny']);
    $str_contact_deny = perms2str($_POST['contact_deny']);
    $openidserver = $a->user['openidserver'];
    $openid = normalise_openid($openid);
    // If openid has changed or if there's an openid but no openidserver, try and discover it.
    if ($openid != $a->user['openid'] || strlen($openid) && !strlen($openidserver)) {
        $tmp_str = $openid;
        if (strlen($tmp_str) && validate_url($tmp_str)) {
            logger('updating openidserver');
            require_once 'library/openid.php';
            $open_id_obj = new LightOpenID();
            $open_id_obj->identity = $openid;
            $openidserver = $open_id_obj->discover($open_id_obj->identity);
        } else {
            $openidserver = '';
        }
    }
    set_pconfig(local_user(), 'expire', 'items', $expire_items);
    set_pconfig(local_user(), 'expire', 'notes', $expire_notes);
    set_pconfig(local_user(), 'expire', 'starred', $expire_starred);
    set_pconfig(local_user(), 'expire', 'photos', $expire_photos);
    set_pconfig(local_user(), 'expire', 'network_only', $expire_network_only);
    set_pconfig(local_user(), 'system', 'suggestme', $suggestme);
    set_pconfig(local_user(), 'system', 'post_newfriend', $post_newfriend);
    set_pconfig(local_user(), 'system', 'post_joingroup', $post_joingroup);
    set_pconfig(local_user(), 'system', 'post_profilechange', $post_profilechange);
    set_pconfig(local_user(), 'system', 'email_textonly', $email_textonly);
    if ($page_flags == PAGE_PRVGROUP) {
        $hidewall = 1;
        if (!$str_contact_allow && !$str_group_allow && !$str_contact_deny && !$str_group_deny) {
            if ($def_gid) {
                info(t('Private forum has no privacy permissions. Using default privacy group.') . EOL);
                $str_group_allow = '<' . $def_gid . '>';
            } else {
                notice(t('Private forum has no privacy permissions and no default privacy group.') . EOL);
            }
        }
    }
    $r = q("UPDATE `user` SET `username` = '%s', `email` = '%s', `openid` = '%s', `timezone` = '%s',  `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `notify-flags` = %d, `page-flags` = %d, `default-location` = '%s', `allow_location` = %d, `maxreq` = %d, `expire` = %d, `openidserver` = '%s', `def_gid` = %d, `blockwall` = %d, `hidewall` = %d, `blocktags` = %d, `unkmail` = %d, `cntunkmail` = %d  WHERE `uid` = %d", dbesc($username), dbesc($email), dbesc($openid), dbesc($timezone), dbesc($str_contact_allow), dbesc($str_group_allow), dbesc($str_contact_deny), dbesc($str_group_deny), intval($notify), intval($page_flags), dbesc($defloc), intval($allow_location), intval($maxreq), intval($expire), dbesc($openidserver), intval($def_gid), intval($blockwall), intval($hidewall), intval($blocktags), intval($unkmail), intval($cntunkmail), intval(local_user()));
    if ($r) {
        info(t('Settings updated.') . EOL);
    }
    $r = q("UPDATE `profile`\n\t\tSET `publish` = %d,\n\t\t`name` = '%s',\n\t\t`net-publish` = %d,\n\t\t`hide-friends` = %d\n\t\tWHERE `is-default` = 1 AND `uid` = %d", intval($publish), dbesc($username), intval($net_publish), intval($hide_friends), intval(local_user()));
    if ($name_change) {
        q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `self` = 1", dbesc($username), dbesc(datetime_convert()), intval(local_user()));
    }
    if ($old_visibility != $net_publish || $page_flags != $old_page_flags) {
        // Update global directory in background
        $url = $_SESSION['my_url'];
        if ($url && strlen(get_config('system', 'directory_submit_url'))) {
            proc_run('php', "include/directory.php", "{$url}");
        }
    }
    require_once 'include/profile_update.php';
    profile_change();
    //$_SESSION['theme'] = $theme;
    if ($email_changed && $a->config['register_policy'] == REGISTER_VERIFY) {
        // FIXME - set to un-verified, blocked and redirect to logout
        // Why? Are we verifying people or email addresses?
    }
    goaway($a->get_baseurl(true) . '/settings');
    return;
    // NOTREACHED
}
Пример #17
0
 /**
  * Validates the comment.
  */
 private function validate()
 {
     $this->errors = array();
     // Validate values.
     if (!validate_name($this->user)) {
         $this->errors['name'] = TRUE;
     }
     if (!validate_url($this->website)) {
         $this->errors['website'] = TRUE;
     }
     if (!validate_email($this->email)) {
         $this->errors['email'] = TRUE;
     }
     if (count($this->errors) == 0) {
         $this->is_valid = TRUE;
     }
 }
Пример #18
0
function zrl_init(&$a)
{
    $tmp_str = get_my_url();
    if (validate_url($tmp_str)) {
        proc_run('php', 'include/gprobe.php', bin2hex($tmp_str));
        $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
        call_hooks('zrl_init', $arr);
    }
}
Пример #19
0
 /**
  * Creates and return one formatted HTML A element
  *
  * @param 	FTL_Binding
  * @param	string
  *
  * @return 	string
  *
  */
 public static function create_href(FTL_Binding $tag, $url)
 {
     if ($tag->getAttribute('href') === TRUE) {
         if (validate_url($url)) {
             $title = $url;
             $title_key = $tag->getAttribute('display', 'title');
             $attributes = $tag->getAttribute('attributes');
             if (!is_null($tag->getValue($title_key))) {
                 $title = $tag->getValue($title_key);
             }
             if ($tag->getAttribute('popup') === TRUE) {
                 $url = anchor_popup($url, $title, $attributes);
             } else {
                 $url = anchor($url, $title, $attributes);
             }
         }
     }
     return $url;
 }
Пример #20
0
 public static function isValidGitRepoURL($url)
 {
     if (validate_url($url) && strrpos(parse_url($url, PHP_URL_PATH), '.')) {
         return true;
     } else {
         return false;
     }
 }
Пример #21
0
/**
 *
 * @global array $allowedSites
 * @param string $src
 * @return string
 */
function check_external($src)
{
    global $allowedSites;
    // work out file details
    $fileDetails = pathinfo($src);
    $filename = 'external_' . md5($src);
    $local_filepath = DIRECTORY_CACHE . '/' . $filename . '.' . strtolower($fileDetails['extension']);
    // only do this stuff the file doesn't already exist
    if (!file_exists($local_filepath)) {
        if (strpos(strtolower($src), 'http://') !== false || strpos(strtolower($src), 'https://') !== false) {
            if (!validate_url($src)) {
                display_error('invalid url');
            }
            $url_info = parse_url($src);
            // convert youtube video urls
            // need to tidy up the code
            if ($url_info['host'] == 'www.youtube.com' || $url_info['host'] == 'youtube.com') {
                parse_str($url_info['query']);
                if (isset($v)) {
                    $src = 'http://img.youtube.com/vi/' . $v . '/0.jpg';
                    $url_info['host'] = 'img.youtube.com';
                }
            }
            // check allowed sites (if required)
            if (ALLOW_EXTERNAL) {
                $isAllowedSite = true;
            } else {
                $isAllowedSite = false;
                foreach ($allowedSites as $site) {
                    if (strpos(strtolower($url_info['host']), $site) !== false) {
                        $isAllowedSite = true;
                    }
                }
            }
            // if allowed
            if ($isAllowedSite) {
                if (function_exists('curl_init')) {
                    global $fh;
                    $fh = fopen($local_filepath, 'w');
                    $ch = curl_init($src);
                    curl_setopt($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT);
                    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
                    curl_setopt($ch, CURLOPT_URL, $src);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                    curl_setopt($ch, CURLOPT_FILE, $fh);
                    curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curl_write');
                    // error so die
                    if (curl_exec($ch) === FALSE) {
                        unlink($local_filepath);
                        touch($local_filepath);
                        display_error('error reading file ' . $src . ' from remote host: ' . curl_error($ch));
                    }
                    curl_close($ch);
                    fclose($fh);
                } else {
                    if (!($img = file_get_contents($src))) {
                        display_error('remote file for ' . $src . ' can not be accessed. It is likely that the file permissions are restricted');
                    }
                    if (file_put_contents($local_filepath, $img) == FALSE) {
                        display_error('error writing temporary file');
                    }
                }
                if (!file_exists($local_filepath)) {
                    display_error('local file for ' . $src . ' can not be created');
                }
                $src = $local_filepath;
            } else {
                display_error('remote host "' . $url_info['host'] . '" not allowed');
            }
        }
    } else {
        $src = $local_filepath;
    }
    return $src;
}
Пример #22
0
if (!($Blog =& $commented_Item->get_Blog())) {
    trackback_response(1, 'Sorry, could not get the post\'s weblog.');
    // exits
}
if (!$commented_Item->can_receive_pings()) {
    trackback_response(1, 'Sorry, this weblog does not allow you to trackback its posts.');
    // exits
}
// Commented out again, because it's comment specific: if( ! $commented_Item->can_comment( NULL ) )
// "BeforeTrackbackInsert" should be hooked instead!
if ($commented_Item->comment_status != 'open') {
    trackback_response(1, 'Sorry, this item does not accept trackbacks.');
    // exits
}
// CHECK content
if ($error = validate_url($url, 'commenting')) {
    $Messages->add(T_('Supplied URL is invalid: ') . $error, 'error');
}
if ($Messages->has_errors()) {
    trackback_response(1, $Messages->get_string('', '', "\n"));
    // exits
}
// TODO: dh> title and excerpt should be htmlbody, too, no?
$title = strmaxlen(strip_tags($title), 255, '...', 'raw');
$excerpt = strmaxlen(strip_tags($excerpt), 255, '...', 'raw');
$blog_name = strmaxlen($blog_name, 255, '...', 'htmlbody');
$comment = '';
if (!empty($title)) {
    $comment .= '<strong>' . $title . '</strong>';
    if (!empty($excerpt)) {
        $comment .= '<br />';
Пример #23
0
 $comment->content_id = $id;
 $comment->subject = '';
 $comment->comment = trim($_POST['comment']);
 if ($_SESSION['user']['id']) {
     $user = new User();
     $user->load((int) $_SESSION['user']['id']);
     $comment->user_id = $user->user_id;
     $comment->name = '';
     $comment->email = '';
     $comment->homepage = '';
     unset($_GET['err']);
 } else {
     $comment->name = trim($_POST['name']);
     $comment->email = trim($_POST['email']);
     if (!empty($_POST['homepage'])) {
         $comment->homepage = validate_url(trim($_POST['homepage']));
     } else {
         $comment->homepage = "";
     }
 }
 // In old method
 $comment->parent_type = TYPE_CONTENT;
 $comment->parent_id = $id;
 if ($comment->spam_check()) {
     $error_message = "Sorry, your comment cannot be posted as it looks like spam.  Try removing any links to possibly suspect sites, and re-submitting.";
     Logger::log("Comment rejected by spam filter", LOGGER_ACTION);
 } else {
     $error_message = 'Your comment has been posted successfully';
     $comment->save();
     if ($comment->spam_state != SPAM_STATE_OK) {
         $error_message = "Sorry, your comment cannot be posted as it was classified as spam by Akismet, or contained links to blacklisted sites.  Please check the links in your post, and that your name and e-mail address are correct.";
 public function validate()
 {
     if (!is_string($this->code)) {
         throw new InvalidPackage("Invalid code value.");
     }
     if (!is_string($this->classname)) {
         throw new InvalidPackage("Invalid classname value.");
     }
     if (preg_match("/^[a-zA-Z0-9_\\-]+\$/", $this->name) == 0) {
         throw new InvalidPackage("Invalid name value (must be at least 1 character, accepted chars: a-z A-Z 0-9 - _).");
     }
     if (!is_string($this->author)) {
         throw new InvalidPackage("Invalid author value.");
     }
     if (!is_string($this->versiontext)) {
         throw new InvalidPackage("Invalid versiontext value.");
     }
     if (!is_numeric($this->versioncount)) {
         throw new InvalidPackage("Invalid versioncount value. Must be a number.");
     }
     if (!is_numeric($this->api)) {
         throw new InvalidPackage("Invalid api value. Must be a number.");
     }
     if (!is_string($this->short_description)) {
         throw new InvalidPackage("Invalid short_description value.");
     }
     if (!empty($this->updatepath) and !validate_url($this->updatepath)) {
         throw new InvalidPackage("Invalid updatepath value. Must be an URL. " . $this->updatepath);
     }
     if (!empty($this->web) and !validate_url($this->web)) {
         throw new InvalidPackage("Invalid web value. Must be an URL.");
     }
     if ($this->license !== NULL and !is_string($this->license)) {
         throw new InvalidPackage("Invalid license value.");
     }
     if ($this->help !== NULL and !is_string($this->help)) {
         throw new InvalidPackage("Invalid help value.");
     }
     if ($this->custompub !== NULL and !validate_arraydir($this->custompub)) {
         throw new InvalidPackage("Invalid custompub value.");
     }
     if ($this->custompriv !== NULL and !validate_arraydir($this->custompriv)) {
         throw new InvalidPackage("Invalid custompriv value.");
     }
     if ($this->tpls !== NULL and !validate_arraydir($this->tpls)) {
         throw new InvalidPackage("Invalid tpls value.");
     }
     return True;
 }
Пример #25
0
 /**
  * Get & Analyze referer
  *
  * Due to potential non-thread safety with getenv() (fallback), we'd better do this early.
  *
  * referer_type: enum('search', 'blacklist', 'referer', 'direct'); 'spam' gets used internally
  */
 function detect_referer($referer = NULL)
 {
     global $Debuglog, $debug;
     global $self_referer_list, $SpecialList;
     // used to detect $referer_type
     global $skins_path, $siteskins_path;
     global $Settings;
     if (isset($referer)) {
         $this->referer = $referer;
     } else {
         // Get referer from HTTP request
         $this->referer = $this->get_referer();
     }
     if (empty($this->referer)) {
         // NO referer
         // This type may be superseeded and set to 'admin'
         if (!$this->detect_admin_page()) {
             // Not an admin page:
             $this->referer_type = 'direct';
         } else {
             if (empty($this->hit_type)) {
                 $this->hit_type = 'admin';
             }
             $this->referer_type = 'direct';
         }
         return;
     }
     // ANALYZE referer...
     // Check self referer list, see {@link $self_referer_list}
     // fplanque: we log these (again), because if we didn't we woudln't detect
     // reloads on these... and that would be a problem!
     foreach ($self_referer_list as $self_referer) {
         $pos = strpos($this->referer, $self_referer);
         // If not starting within in the first 12 chars it's probably an url param as in &url=http://this_blog.com
         if ($pos !== false && $pos <= 12 && !($debug && strpos($this->referer, '/search.html'))) {
             // This type may be superseeded by admin page
             if (!$this->detect_admin_page()) {
                 // Not an admin page:
                 $Debuglog->add('Hit: detect_referer(): self referer (' . $self_referer . ')', 'request');
                 $this->referer_type = 'self';
             } else {
                 if (empty($this->hit_type)) {
                     $this->hit_type = 'admin';
                 }
                 $this->referer_type = 'self';
             }
             return;
         }
     }
     // Check Special list, see {@link $SpecialList}
     // NOTE: This is NOT the antispam!!
     // fplanque: we log these (again), because if we didn't we woudln't detect
     // reloads on these... and that would be a problem!
     foreach ($SpecialList as $lSpeciallist) {
         $pos = strpos($this->referer, $lSpeciallist);
         // If not starting within in the first 12 chars it's probably an url param as in &url=http://this_blog.com
         if ($pos !== false && $pos <= 12) {
             // Not an admin page:
             $Debuglog->add('Hit: detect_referer(): blacklist (' . $lSpeciallist . ')', 'request');
             $this->referer_type = 'special';
             return;
         }
     }
     // Check if the referer is valid and does not match the antispam blacklist:
     // NOTE: requests to admin pages should not arrive here, because they should be matched above through $self_referer_list!
     load_funcs('_core/_url.funcs.php');
     if ($error = validate_url($this->referer, 'commenting')) {
         // This is most probably referer spam!!
         $Debuglog->add('Hit: detect_referer(): ' . $error . ' (SPAM)', 'hit');
         $this->referer_type = 'spam';
         if ($Settings->get('antispam_block_spam_referers')) {
             // In order to preserve server resources, we're going to stop processing immediatly (no logging)!!
             require $siteskins_path . '_403_referer_spam.main.php';
             // error & exit
             exit(0);
             // just in case.
             // THIS IS THE END!!
         }
         return;
         // type "spam"
     }
     // Is the referer a search engine?
     if ($this->is_search_referer($this->referer)) {
         $Debuglog->add('Hit: detect_referer(): search engine', 'request');
         $this->referer_type = 'search';
         return;
     }
     $this->referer_type = 'referer';
 }
Пример #26
0
         $hours = $hours . ' Hours ago';
         $minutes = "";
     } elseif ($minutes != 0) {
         $days = "";
         $hours = "";
         $minutes = $minutes . ' Minutes ago';
     }
 }
 $dcounttime = $now . $days . $hours . $minutes;
 /************************************/
 if (validate_email($ds['email'])) {
     $email = '<a href="mailto:' . mail_protect($ds['email']) . '"><img src="images/icons/email.gif" border="0" alt="' . $_language->module['email'] . '" /></a>';
 } else {
     $email = '';
 }
 if (validate_url($ds['hp'])) {
     $hp = '<a href="' . $ds['hp'] . '" target="_blank"><img src="images/icons/hp.gif" border="0" alt="' . $_language->module['homepage'] . '" /></a>';
 } else {
     $hp = '';
 }
 $sem = '/[0-9]{6,11}/si';
 $icq_number = str_replace('-', '', $ds['icq']);
 if (preg_match($sem, $icq_number)) {
     $icq = '<a href="http://www.icq.com/people/about_me.php?uin=' . $icq_number . '" target="_blank"><img src="http://online.mirabilis.com/scripts/online.dll?icq=' . $icq_number . '&amp;img=5" border="0" alt="icq" /></a>';
 } else {
     $icq = "";
 }
 $name = strip_tags($ds['name']);
 $message = cleartext($ds['comment']);
 $quotemessage = strip_tags($ds['comment']);
 $quotemessage = str_replace("'", "`", $quotemessage);
Пример #27
0
 * This php script validates URL passed in POST, and 
 * retrieves its associated short URL from the database.
 */
// Imports
if (!function_exists(db_connect)) {
    include 'db_connect.php';
}
if (!function_exists(base62_encode)) {
    include 'base62.php';
}
include 'get_id_hash.php';
// Get URL from POST, remove http(s) from beginning
$url = $_POST['url'];
$url = preg_replace('#[h|H][t|T][t|T][p|P][s|S]?://#', '', $url);
// Main body
if (validate_url($url)) {
    // Connect to database
    $mysqli = db_connect();
    // Query to see if URL is in database
    // Prepare statement
    if (!($stmt = $mysqli->prepare("SELECT shorturl from urls where url=?"))) {
        die('Query failed.');
    }
    // Bind params, execute query, bind/fetch result, close stmt
    $stmt->bind_param('s', $url);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($surl);
    $stmt->fetch();
    // If URL not in database, add it. Otherwise, get the existing short URL.
    if ($stmt->num_rows == 0) {
Пример #28
0
                }
            }
        }
    }
} else {
    if (!empty($_POST['btn_save_link'])) {
        if (empty($_POST['link_categories'])) {
            $error_array[] = "Please select a category";
        }
        if (empty($_POST['title'])) {
            $error_array[] = "Please enter a title for the link";
        }
        if (empty($_POST['url'])) {
            $error_array[] = "Please enter the URL for the link";
        }
        $_POST['url'] = validate_url($_POST['url']);
        if (!Validation::isValidURL($_POST['url'])) {
            $error_array[] = "Please enter a valid URL for the link";
        }
        if (count($error_array) == 0) {
            //$tmp_array = explode(':', $_POST['link_categories']);
            //$_POST['category_id'] = $tmp_array[0];
            try {
                if ($_POST['form_action'] == "update") {
                    $id_array = $_POST['link_id'];
                    $temp = explode(':', $id_array[0]);
                    $link_id = $temp[1];
                    $param_array = array('user_id' => $_SESSION['user']['id'], 'category_id' => $tmp_array[0], 'title' => $_POST['title'], 'url' => $_POST['url'], 'changed' => time(), 'link_id' => $link_id);
                    $Links = new Links();
                    $Links->set_params($param_array);
                    $Links->update_link();
Пример #29
-1
function redirect($url, $absolute = false)
{
    if (!$absolute) {
        $url = CONFIG_SITE_URL . trim($url, '/');
    }
    validate_url($url);
    header('location: ' . $url);
    exit;
}
Пример #30
-1
function settings_post(&$a)
{
    if (!local_user()) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    if (count($a->user) && x($a->user, 'uid') && $a->user['uid'] != local_user()) {
        notice(t('Permission denied.') . EOL);
        return;
    }
    if ($a->argc > 1 && $a->argv[1] === 'oauth' && x($_POST, 'remove')) {
        $key = $_POST['remove'];
        q("DELETE FROM tokens WHERE id='%s' AND uid=%d", dbesc($key), local_user());
        goaway($a->get_baseurl() . "/settings/oauth/");
        return;
    }
    if ($a->argc > 2 && $a->argv[1] === 'oauth' && ($a->argv[2] === 'edit' || $a->argv[2] === 'add') && x($_POST, 'submit')) {
        $name = x($_POST, 'name') ? $_POST['name'] : '';
        $key = x($_POST, 'key') ? $_POST['key'] : '';
        $secret = x($_POST, 'secret') ? $_POST['secret'] : '';
        $redirect = x($_POST, 'redirect') ? $_POST['redirect'] : '';
        $icon = x($_POST, 'icon') ? $_POST['icon'] : '';
        if ($name == "" || $key == "" || $secret == "") {
            notice(t("Missing some important data!"));
        } else {
            if ($_POST['submit'] == t("Update")) {
                $r = q("UPDATE clients SET\n\t\t\t\t\t\t\tclient_id='%s',\n\t\t\t\t\t\t\tpw='%s',\n\t\t\t\t\t\t\tname='%s',\n\t\t\t\t\t\t\tredirect_uri='%s',\n\t\t\t\t\t\t\ticon='%s',\n\t\t\t\t\t\t\tuid=%d\n\t\t\t\t\t\tWHERE client_id='%s'", dbesc($key), dbesc($secret), dbesc($name), dbesc($redirect), dbesc($icon), local_user(), dbesc($key));
            } else {
                $r = q("INSERT INTO clients\n\t\t\t\t\t\t\t(client_id, pw, name, redirect_uri, icon, uid)\n\t\t\t\t\t\tVALUES ('%s','%s','%s','%s','%s',%d)", dbesc($key), dbesc($secret), dbesc($name), dbesc($redirect), dbesc($icon), local_user());
            }
        }
        goaway($a->get_baseurl() . "/settings/oauth/");
        return;
    }
    if ($a->argc > 1 && $a->argv[1] == 'addon') {
        call_hooks('plugin_settings_post', $_POST);
        return;
    }
    if ($a->argc > 1 && $a->argv[1] == 'connectors') {
        if (x($_POST['imap-submit'])) {
            $mail_server = x($_POST, 'mail_server') ? $_POST['mail_server'] : '';
            $mail_port = x($_POST, 'mail_port') ? $_POST['mail_port'] : '';
            $mail_ssl = x($_POST, 'mail_ssl') ? strtolower(trim($_POST['mail_ssl'])) : '';
            $mail_user = x($_POST, 'mail_user') ? $_POST['mail_user'] : '';
            $mail_pass = x($_POST, 'mail_pass') ? trim($_POST['mail_pass']) : '';
            $mail_replyto = x($_POST, 'mail_replyto') ? $_POST['mail_replyto'] : '';
            $mail_pubmail = x($_POST, 'mail_pubmail') ? $_POST['mail_pubmail'] : '';
            $mail_disabled = function_exists('imap_open') && !get_config('system', 'imap_disabled') ? 0 : 1;
            if (get_config('system', 'dfrn_only')) {
                $mail_disabled = 1;
            }
            if (!$mail_disabled) {
                $failed = false;
                $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval(local_user()));
                if (!count($r)) {
                    q("INSERT INTO `mailacct` (`uid`) VALUES (%d)", intval(local_user()));
                }
                if (strlen($mail_pass)) {
                    $pass = '';
                    openssl_public_encrypt($mail_pass, $pass, $a->user['pubkey']);
                    q("UPDATE `mailacct` SET `pass` = '%s' WHERE `uid` = %d LIMIT 1", dbesc(bin2hex($pass)), intval(local_user()));
                }
                $r = q("UPDATE `mailacct` SET `server` = '%s', `port` = %d, `ssltype` = '%s', `user` = '%s',\n\t\t\t\t\t`mailbox` = 'INBOX', `reply_to` = '%s', `pubmail` = %d WHERE `uid` = %d LIMIT 1", dbesc($mail_server), intval($mail_port), dbesc($mail_ssl), dbesc($mail_user), dbesc($mail_replyto), intval($mail_pubmail), intval(local_user()));
                $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", intval(local_user()));
                if (count($r)) {
                    $eacct = $r[0];
                    require_once 'include/email.php';
                    $mb = construct_mailbox_name($eacct);
                    if (strlen($eacct['server'])) {
                        $dcrpass = '';
                        openssl_private_decrypt(hex2bin($eacct['pass']), $dcrpass, $a->user['prvkey']);
                        $mbox = email_connect($mb, $mail_user, $dcrpass);
                        unset($dcrpass);
                        if (!$mbox) {
                            $failed = true;
                            notice(t('Failed to connect with email account using the settings provided.') . EOL);
                        }
                    }
                }
                if (!$failed) {
                    info(t('Email settings updated.') . EOL);
                }
            }
        }
        call_hooks('connector_settings_post', $_POST);
        return;
    }
    call_hooks('settings_post', $_POST);
    if (x($_POST, 'npassword') || x($_POST, 'confirm')) {
        $newpass = $_POST['npassword'];
        $confirm = $_POST['confirm'];
        $err = false;
        if ($newpass != $confirm) {
            notice(t('Passwords do not match. Password unchanged.') . EOL);
            $err = true;
        }
        if (!x($newpass) || !x($confirm)) {
            notice(t('Empty passwords are not allowed. Password unchanged.') . EOL);
            $err = true;
        }
        if (!$err) {
            $password = hash('whirlpool', $newpass);
            $r = q("UPDATE `user` SET `password` = '%s' WHERE `uid` = %d LIMIT 1", dbesc($password), intval(local_user()));
            if ($r) {
                info(t('Password changed.') . EOL);
            } else {
                notice(t('Password update failed. Please try again.') . EOL);
            }
        }
    }
    $theme = x($_POST, 'theme') ? notags(trim($_POST['theme'])) : '';
    $username = x($_POST, 'username') ? notags(trim($_POST['username'])) : '';
    $email = x($_POST, 'email') ? notags(trim($_POST['email'])) : '';
    $timezone = x($_POST, 'timezone') ? notags(trim($_POST['timezone'])) : '';
    $defloc = x($_POST, 'defloc') ? notags(trim($_POST['defloc'])) : '';
    $openid = x($_POST, 'openid_url') ? notags(trim($_POST['openid_url'])) : '';
    $maxreq = x($_POST, 'maxreq') ? intval($_POST['maxreq']) : 0;
    $expire = x($_POST, 'expire') ? intval($_POST['expire']) : 0;
    $expire_items = x($_POST, 'expire_items') ? intval($_POST['expire_items']) : 0;
    $expire_notes = x($_POST, 'expire_notes') ? intval($_POST['expire_notes']) : 0;
    $expire_starred = x($_POST, 'expire_starred') ? intval($_POST['expire_starred']) : 0;
    $expire_photos = x($_POST, 'expire_photos') ? intval($_POST['expire_photos']) : 0;
    $allow_location = x($_POST, 'allow_location') && intval($_POST['allow_location']) == 1 ? 1 : 0;
    $publish = x($_POST, 'profile_in_directory') && intval($_POST['profile_in_directory']) == 1 ? 1 : 0;
    $net_publish = x($_POST, 'profile_in_netdirectory') && intval($_POST['profile_in_netdirectory']) == 1 ? 1 : 0;
    $old_visibility = x($_POST, 'visibility') && intval($_POST['visibility']) == 1 ? 1 : 0;
    $page_flags = x($_POST, 'page-flags') && intval($_POST['page-flags']) ? intval($_POST['page-flags']) : 0;
    $blockwall = x($_POST, 'blockwall') && intval($_POST['blockwall']) == 1 ? 0 : 1;
    // this setting is inverted!
    $blocktags = x($_POST, 'blocktags') && intval($_POST['blocktags']) == 1 ? 0 : 1;
    // this setting is inverted!
    $suggestme = x($_POST, 'suggestme') ? intval($_POST['suggestme']) : 0;
    $hide_friends = $_POST['hide-friends'] == 1 ? 1 : 0;
    $hidewall = $_POST['hidewall'] == 1 ? 1 : 0;
    $notify = 0;
    if (x($_POST, 'notify1')) {
        $notify += intval($_POST['notify1']);
    }
    if (x($_POST, 'notify2')) {
        $notify += intval($_POST['notify2']);
    }
    if (x($_POST, 'notify3')) {
        $notify += intval($_POST['notify3']);
    }
    if (x($_POST, 'notify4')) {
        $notify += intval($_POST['notify4']);
    }
    if (x($_POST, 'notify5')) {
        $notify += intval($_POST['notify5']);
    }
    $email_changed = false;
    $err = '';
    $name_change = false;
    if ($username != $a->user['username']) {
        $name_change = true;
        if (strlen($username) > 40) {
            $err .= t(' Please use a shorter name.');
        }
        if (strlen($username) < 3) {
            $err .= t(' Name too short.');
        }
    }
    if ($email != $a->user['email']) {
        $email_changed = true;
        if (!valid_email($email)) {
            $err .= t(' Not valid email.');
        }
        if (x($a->config, 'admin_email') && strcasecmp($email, $a->config['admin_email']) == 0) {
            $err .= t(' Cannot change to that email.');
            $email = $a->user['email'];
        }
    }
    if (strlen($err)) {
        notice($err . EOL);
        return;
    }
    if ($timezone != $a->user['timezone']) {
        if (strlen($timezone)) {
            date_default_timezone_set($timezone);
        }
    }
    $str_group_allow = perms2str($_POST['group_allow']);
    $str_contact_allow = perms2str($_POST['contact_allow']);
    $str_group_deny = perms2str($_POST['group_deny']);
    $str_contact_deny = perms2str($_POST['contact_deny']);
    $openidserver = $a->user['openidserver'];
    // If openid has changed or if there's an openid but no openidserver, try and discover it.
    if ($openid != $a->user['openid'] || strlen($openid) && !strlen($openidserver)) {
        $tmp_str = $openid;
        if (strlen($tmp_str) && validate_url($tmp_str)) {
            logger('updating openidserver');
            require_once 'library/openid.php';
            $open_id_obj = new LightOpenID();
            $open_id_obj->identity = $openid;
            $openidserver = $open_id_obj->discover($open_id_obj->identity);
        } else {
            $openidserver = '';
        }
    }
    set_pconfig(local_user(), 'expire', 'items', $expire_items);
    set_pconfig(local_user(), 'expire', 'notes', $expire_notes);
    set_pconfig(local_user(), 'expire', 'starred', $expire_starred);
    set_pconfig(local_user(), 'expire', 'photos', $expire_photos);
    set_pconfig(local_user(), 'system', 'suggestme', $suggestme);
    $r = q("UPDATE `user` SET `username` = '%s', `email` = '%s', `openid` = '%s', `timezone` = '%s',  `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `notify-flags` = %d, `page-flags` = %d, `default-location` = '%s', `allow_location` = %d, `theme` = '%s', `maxreq` = %d, `expire` = %d, `openidserver` = '%s', `blockwall` = %d, `hidewall` = %d, `blocktags` = %d  WHERE `uid` = %d LIMIT 1", dbesc($username), dbesc($email), dbesc($openid), dbesc($timezone), dbesc($str_contact_allow), dbesc($str_group_allow), dbesc($str_contact_deny), dbesc($str_group_deny), intval($notify), intval($page_flags), dbesc($defloc), intval($allow_location), dbesc($theme), intval($maxreq), intval($expire), dbesc($openidserver), intval($blockwall), intval($hidewall), intval($blocktags), intval(local_user()));
    if ($r) {
        info(t('Settings updated.') . EOL);
    }
    $r = q("UPDATE `profile` \n\t\tSET `publish` = %d, \n\t\t`net-publish` = %d,\n\t\t`hide-friends` = %d\n\t\tWHERE `is-default` = 1 AND `uid` = %d LIMIT 1", intval($publish), intval($net_publish), intval($hide_friends), intval(local_user()));
    if ($name_change) {
        q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `self` = 1 LIMIT 1", dbesc($username), dbesc(datetime_convert()), intval(local_user()));
    }
    if ($old_visibility != $net_publish) {
        // Update global directory in background
        $url = $_SESSION['my_url'];
        if ($url && strlen(get_config('system', 'directory_submit_url'))) {
            proc_run('php', "include/directory.php", "{$url}");
        }
    }
    require_once 'include/profile_update.php';
    profile_change();
    $_SESSION['theme'] = $theme;
    if ($email_changed && $a->config['register_policy'] == REGISTER_VERIFY) {
        // FIXME - set to un-verified, blocked and redirect to logout
    }
    goaway($a->get_baseurl() . '/settings');
    return;
    // NOTREACHED
}