How I can give regex pattern in yii1 when creating any user? - yii

I want to give a pattern for password. The password must be at least 8 characters long and should contain one uppercase letter, one lowercase letter and one number. I am new in yii1. Please help me.

Try this way:
public function rules() {
return array(
array('username, password', 'required'),
array(
'password',
'match', 'pattern' => '/^[\*a-zA-Z0-9]{6,14}$/',
'message' => 'Invalid characters in password.',
),
array('password', 'length', 'min'=>8),
);
}
You can add any type of Pattern in above code.

It seems you can refer some PHP password validation code as follow,
<?php
$pwd = $_POST['pwd'];
if( strlen($pwd) < 8 ) {
$error .= "Password too short!
";
}
if( strlen($pwd) > 20 ) {
$error .= "Password too long!
";
}
if( strlen($pwd) < 8 ) {
$error .= "Password too short!
";
}
if( !preg_match("#[0-9]+#", $pwd) ) {
$error .= "Password must include at least one number!
";
}
if( !preg_match("#[a-z]+#", $pwd) ) {
$error .= "Password must include at least one letter!
";
}
if( !preg_match("#[A-Z]+#", $pwd) ) {
$error .= "Password must include at least one CAPS!
";
}
if( !preg_match("#\W+#", $pwd) ) {
$error .= "Password must include at least one symbol!
";
}
if($error){
echo "Password validation failure(your choise is weak): $error";
} else {
echo "Your password is strong.";
}
For more detail please refer this post

It can be done by Yii custom validation.
Try below this one. i hope the custom validation may useful to your criteria
public function rules()
{
return array(
array('username, password', 'required'),
array('password', 'length', 'min'=>8, 'max'=>16),
// custom validation
array('password', 'checkStrength', 'password'),
);
}
public function checkStrength($attr)
{
$policy1 = preg_match('/[A-Z]/', $this->$attr) ? 1 : 0 ;
$policy2 = preg_match('/[a-z]/', $this->$attr) ? 1 : 0 ;
$policy3 = preg_match('/[0-9]/', $this->$attr) ? 1 : 0 ;
$policy4 = preg_match('/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:\<\>,\.\?]/', $this->$attr) ? 1 : 0 ;
if(!$policy1)
$this->addError('password', $this->getAttributeLabel($attr) . ' must contains atleast one upper case character.');
if(!$policy2)
$this->addError('password', $this->getAttributeLabel($attr) . ' must contains atleast one lower case character.');
if(!$policy3)
$this->addError('password', $this->getAttributeLabel($attr) . ' must contains atleast one number.');
if(!$policy4)
$this->addError('password', $this->getAttributeLabel($attr) . ' must contains atleast one special character (/~`!##$%^&*()_-+={}[]|;:<>,.?)');
}

Related

How can I change the WordPress Custom Post & Categories to New Custom Post & Categories

In my database I have 2 custom post type and their category.
Old Post Type and Category
Post Type = real-estate
Category = re-category
Mew Post Type and Category
Post Type = real_estate
Category = real_estate_category
Now I want to convert all old post type and their categories to new custom post type and their categories.
So, using this code I can get all the old post type and can change the old post type to new post type BUT how can I change the old post type's attached categories to new post type categories?
add_action( 'template_redirect', 'everstrap_do_migration' );
function everstrap_do_migration() {
// Convert their real-estate to real_estate post type
if( $_REQUEST['action'] && $_REQUEST['action'] == 'convert_re_post_type' ) {
global $wpdb;
$old_custom_post_type = 'real-estate';
$ne_custom_post_type = 'real_estate';
// A sql query to return all real-esate post
$results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $old_custom_post_type ), ARRAY_A );
// Return null if we found no results
if ( ! $results )
return;
foreach ( $result as $key => $value) {
// Update query
$update = $wpdb->update(
$wpdb->posts,
array(
'post_type' => $new_custom_post_type,
),
array(
'post_type' => $old_custom_post_type,
),
array(
'%s',
),
array(
'%s'
)
);
if( $update ) {
echo 'Updated post id ' . $value['ID'];
} else {
echo 'can\' update';
}
}
// echo '<pre>';
// print_r( $results );
// echo '</pre>';
}
}
$new = "real_estate_category";
$old = "re-category";
$cat = get_terms( array (
'taxonomy' => $old,
'hide_empty' => false,
));
global $wpdb;
$table = $wpdb->prefix . "term_taxonomy";
foreach ($cat as $c) {
$wpdb->update($table, array("taxonomy" => $new), array("term_id" => $c->term_id), array("%s"));
}

Twitter API - get tweets with id_str

Sorry , I have a problem with this script :
It's for get tweet with specific id ;
$tweetlist = $twitter->get('https://api.twitter.com/1.1/statuses/show.json?id=694658584664236033');
foreach ($tweetlist->statuses as $key => $value) {
$message = utf8_decode($value->text);
echo $message;
}
Warning: Invalid argument supplied for foreach()
Thank you so much for your help
Nicolas
remove ->statuses, like:
$tweetlist = $twitter->get('https://api.twitter.com/1.1/statuses/show.json?id=694658584664236033');
foreach ($tweetlist as $key => $value) {
$message = utf8_decode($value->text);
echo $message;
}

For each $_POST variable a mysql_real_escape_string?

For my school homework I have to create a function that uses trim(), htmlspecialchars() and mysql_real_escape_string() to prevent SQL- and HTML injection.
I've been trying for a while but I can't get it to work. I've tried a foreach loop and an extract function. I must be doing something wrong, or missing something.
So far, I've got this: (just to see if the variables are being processed)
foreach ($_Post as $Key => $Value) {
$$Key = $Value;
echo $$Key."<br>";
}
But it won't return anything.
I can use the trim etc on every variable on its own, but there must be a much easier way.
I've got the $_POST variables 'voorletters', 'tussenvoegsel', 'naam', 'adres', 'huisnummer' (numbers), 'telefoon' (numbers), 'postcode', 'woonplaats', 'geslacht', 'email' and 'wachtwoord' (password).
Please help me :(! I'm a beginner concerning php, so please try to explain thoroughly.
What about this
foreach($_POST as $key => $value) {
echo 'Current value in $_POST["' . $key . '"] is : ' . $value . '<br>';
$_POST[$key] = your_filter($value);
}
where your_filter() is your function calling trim, htmlspecialchars, etc. :
function your_filter($value) {
$newVal = trim($value);
$newVal = htmlspecialchars($newVal);
$newVal = mysql_real_escape_string($newVal);
return $newVal;
}
Pay attention to the variable name too which is $_POST not $_Post.
You don't need to use $$ here, you have the key name in the loop in $key and you can access/replace the value in the array with $_POST[$key]
EDIT : added an echo to print current value
EDIT2 : added an example of your_filter() function
// $_POST = array('voorletters' => '<<', 'tussenvoegsel' => '>>', 'naam' => '<<');
foreach($_POST as &$val) //pass any post value by reference
$val = mysql_real_escape_string(htmlspecialchars(trim($val)));
extract($_POST);
echo $voorletters;
echo $tussenvoegsel;
echo $naam;
foreach ($_POST as $Key => $Value) {
echo yourFunctionName($Value)."<br/>";
}
Try This...
function real_escape_and_trim($value)
{
$value = trim($value);
$value = mysql_real_escape_string($value);
return $value;
}
foreach($_POST as $key => $value)
{
$_POST[$key] = real_escape_and_trim($value);
}
$field_name = $_POST['field_name'];

Yii: searching for a date period

I've a table with 2 mysql DATE field 'validFrom' and 'validTo'.
I need to allow user to search for a period beetween validFrom and validTo (included)
search using
validFrom >= searched validFrom
and
validTo <= searched validTo
What must I change ? the search() ? .
The Gii created code tell me this (i think it's a 'LIKE %string%' search )
$criteria->compare('validFromDate',$this->validFromDate,true);
$criteria->compare('validToDate',$this->validToDate,true);
$criteria->addBetweenCondition('colName', $this->validFrom, $this->validTo);
public function search() {
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->with = array('user');
$criteria->compare('nota_id', $this->nota_id, true);
$criteria->compare('user.nume', $this->filter_nume, true);
$criteria->compare('persoana1', $this->persoana1, true);
$criteria->compare('persoana2', $this->persoana2, true);
$d = $this->getFilterDateRange($this->data_discutie);
if (!empty($d[0]) && !empty($d[1])) {
// between condition
$criteria->addBetweenCondition('data_discutie', $d[0], $d[1]);
} else if (!empty($d[0])) {
$criteria->compare('data_discutie', '>=' . $d[0]);
} else if (!empty($d[1])) {
$criteria->compare('data_discutie', '<=' . $d[1]);
}
$d = null;
//echo $this->urmatoarea_discutie;
$d = $this->getFilterDateRange($this->urmatoarea_discutie);
//print_R($d);
if (!empty($d[0]) && !empty($d[1])) {
// between condition
$criteria->addBetweenCondition('urmatoarea_discutie', $d[0], $d[1]);
} else if (!empty($d[0])) {
$criteria->compare('urmatoarea_discutie', '>=' . $d[0]);
} else if (!empty($d[1])) {
$criteria->compare('urmatoarea_discutie', '<=' . $d[1]);
}
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => '15',
),
'sort' => array(
'defaultOrder' => 'coalesce(nullif(t.urmatoarea_discutie, ""), \'zzzzzz\') ASC, t.data_discutie ASC',
'attributes' => array(
'urmatoarea_discutie',
'data_discutie',
'persoana2',
'persoana1',
'filter_nume' => array(
'asc' => 'user.nume asc',
'desc' => 'user.nume desc'
),
),
),
));
}
protected function getFilterDateRange($key) {
$ret = array(&$from, &$to);
switch ($key) {
case '-1':
// past
$to = strtotime('next hour');
break;
case '1':
// future
$from = strtotime('last hour');
break;
case '-7':
$from = strtotime('-1 week last monday midnight');
$to = strtotime('last sunday midnight');
break;
case '7':
$from = strtotime('last monday');
$to = strtotime('next sunday midnight');
break;
}
return $ret;
}
Depending on what you want to do, the search() in the model is not necessarily be the place you want to be looking. Here is a standard Yii query:
$model = WhateverModel::model()->findAll(array(
"condition" => "'.date('Y-m-d H:i:s' BETWEEN validRrom AND validTo).'",
));
You will have to give a bit more detail if you more detailed help :)

How can I automatically sign in users in a phpBB3 forum based on accounts in a Rails app?

I have a mobile app that uses Rails/MySQL as a backend (just serves JSON, I know we don't need full blown Rails, but this was the simplest solution to get started). My Rails app uses devise for auth. I'd like my users to be able to also access a Phpbb3 forum without having to sign up again. What's the best way to do this? Have the Phpbb3 forum read accounts right from the same MySQL?
Use the email address as a base.
name a file inside includes/ucp called ucp_my_rails_app_connect.php
<?php
/*
* #package My Package
* #author Me
* #license http://opensource.org/licenses/gpl-license.php GNU Public License
* #link my href
* #copyright (c) my copyright
*
* #license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/*
* #ignore
*/
if (!defined('IN_PHPBB'))
{
exit;
}
/*
* ucp_myclass
* my rails app connect
* #package my package
*/
class ucp_my_rails_app_connect
{
var $u_action;
function main($id, $mode)
{
global $config, $db, $user, $auth, $template, $phpbb_root_path, $phpEx;
/** Do some DB code here for rails or wrap it in a private function*/
$server_url = generate_board_url();
$key_len = 54 - strlen($server_url);
$key_len = max(6, $key_len); // we want at least 6
$key_len = ($config['max_pass_chars']) ? min($key_len, $config['max_pass_chars']) : $key_len; // we want at most $config['max_pass_chars']
$user_actkey = substr(gen_rand_string(10), 0, $key_len);
$new_user_password = gen_rand_string(8);
$data = array(
'username' => utf8_normalize_nfc(/** rails DB username*/),
'steam_id' => request_var('steam_id', ''),
'new_password' => $new_user_password,
'password_confirm' => $new_user_password,
'email' => strtolower(/** rails DB email*/),
'email_confirm' => strtolower(/** rails DB email*/)
);
if($my_rails_exec_func == $some_val) /* make some code so not just anyone can submit stuff to this area*/
{
//Check and initialize some variables if needed
$error = validate_data($data, array(
'username' => array(
array('string', false, $config['min_name_chars'], $config['max_name_chars']),
array('username', '')),
'new_password' => array(
array('string', false, $config['min_pass_chars'], $config['max_pass_chars']),
array('password')),
'password_confirm' => array('string', false, $config['min_pass_chars'], $config['max_pass_chars']),
'email' => array(
array('string', false, 6, 60),
array('email')),
'email_confirm' => array('string', false, 6, 60),
'tz' => array('num', false, -14, 14),
'lang' => array('match', false, '#^[a-z_\-]{2,}$#i'),
));
$error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
if (!sizeof($error))
{
// Which group by default?
$group_name = ($coppa) ? 'REGISTERED_COPPA' : 'REGISTERED';
$sql = 'SELECT group_id
FROM ' . GROUPS_TABLE . "
WHERE group_name = '" . $db->sql_escape($group_name) . "'
AND group_type = " . GROUP_SPECIAL;
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$group_id = $row['group_id'];
if (($config['require_activation'] == USER_ACTIVATION_SELF ||
$config['require_activation'] == USER_ACTIVATION_ADMIN) && $config['email_enable'])
{
$user_actkey = gen_rand_string(mt_rand(6, 10));
$user_type = USER_INACTIVE;
$user_inactive_reason = INACTIVE_REGISTER;
$user_inactive_time = time();
}
else
{
$user_type = USER_NORMAL;
$user_actkey = '';
$user_inactive_reason = 0;
$user_inactive_time = 0;
}
$user_row = array(
'username' => $data['username'],
'user_password' => phpbb_hash($data['new_password']),
'user_email' => $data['email'],
'group_id' => (int) $group_id,
'user_timezone' => (float) $data['tz'],
'user_dst' => $is_dst,
'user_lang' => $data['lang'],
'user_type' => $user_type,
'user_actkey' => $user_actkey,
'user_ip' => $user->ip,
'user_regdate' => time(),
'user_inactive_reason' => $user_inactive_reason,
'user_inactive_time' => $user_inactive_time,
);
if ($config['new_member_post_limit'])
{
$user_row['user_new'] = 1;
}
// Register user...
$user_id = user_add($user_row);
// This should not happen, because the required variables are listed above...
if ($user_id === false)
{
trigger_error('NO_USER', E_USER_ERROR);
}
// DB Error
if(!$result)
{
trigger_error('Unable to connect with phpBB database.');
}
// Okay, captcha, your job is done.
if ($config['enable_confirm'] && isset($captcha))
{
$captcha->reset();
}
if ($coppa && $config['email_enable'])
{
$message = $user->lang['ACCOUNT_COPPA'];
$email_template = 'coppa_welcome_inactive_steam';
}
else if ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable'])
{
$message = $user->lang['ACCOUNT_INACTIVE'];
$email_template = 'user_welcome_inactive_steam';
}
else if ($config['require_activation'] == USER_ACTIVATION_ADMIN && $config['email_enable'])
{
$message = $user->lang['ACCOUNT_INACTIVE_ADMIN'];
$email_template = 'admin_welcome_inactive_steam';
}
else
{
$message = $user->lang['ACCOUNT_ADDED'];
$email_template = 'user_welcome_steam';
}
if ($config['email_enable'])
{
include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);
$messenger = new messenger(false);
$messenger->template($email_template, $data['lang']);
$messenger->to($data['email'], $data['username']);
$messenger->headers('X-AntiAbuse: Board servername - ' . $config['server_name']);
$messenger->headers('X-AntiAbuse: User_id - ' . $user->data['user_id']);
$messenger->headers('X-AntiAbuse: Username - ' . $user->data['username']);
$messenger->headers('X-AntiAbuse: User IP - ' . $user->ip);
$messenger->assign_vars(array(
'WELCOME_MSG' => htmlspecialchars_decode(sprintf($user->lang['WELCOME_SUBJECT'], $config['sitename'])),
'USERNAME' => htmlspecialchars_decode($data['username']),
'U_ACTIVATE' => "$server_url/ucp.$phpEx?mode=activate&u=$user_id&k=$user_actkey")
);
if ($coppa)
{
$messenger->assign_vars(array(
'FAX_INFO' => $config['coppa_fax'],
'MAIL_INFO' => $config['coppa_mail'],
'EMAIL_ADDRESS' => $data['email'])
);
}
$messenger->send(NOTIFY_EMAIL);
if ($config['require_activation'] == USER_ACTIVATION_ADMIN)
{
// Grab an array of user_id's with a_user permissions ... these users can activate a user
$admin_ary = $auth->acl_get_list(false, 'a_user', false);
$admin_ary = (!empty($admin_ary[0]['a_user'])) ? $admin_ary[0]['a_user'] : array();
// Also include founders
$where_sql = ' WHERE user_type = ' . USER_FOUNDER;
if (sizeof($admin_ary))
{
$where_sql .= ' OR ' . $db->sql_in_set('user_id', $admin_ary);
}
$sql = 'SELECT user_id, username, user_email, user_lang, user_jabber, user_notify_type
FROM ' . USERS_TABLE . ' ' .
$where_sql;
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
$messenger->template('admin_activate', $row['user_lang']);
$messenger->to($row['user_email'], $row['username']);
$messenger->im($row['user_jabber'], $row['username']);
$messenger->assign_vars(array(
'USERNAME' => htmlspecialchars_decode($data['username']),
'U_USER_DETAILS' => "$server_url/memberlist.$phpEx?mode=viewprofile&u=$user_id",
'U_ACTIVATE' => "$server_url/ucp.$phpEx?mode=activate&u=$user_id&k=$user_actkey")
);
$messenger->send($row['user_notify_type']);
}
$db->sql_freeresult($result);
}
}
$message = $message . '<br /><br />' . sprintf($user->lang['RETURN_INDEX'], '', '');
trigger_error($message);
}
}
}
}
?>
now we add the class to ucp.php
case 'register':
if ($user->data['is_registered'] || isset($_REQUEST['not_agreed']))
{
redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
}
$module->load('ucp', 'register');
$module->display($user->lang['REGISTER']);
break;
case 'my_rails_app_connect':
if ($user->data['is_registered'])
{
redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
}
$module->load('ucp', 'my_rails_app_connect');
$module->display($user->lang['REGISTER']);
break;
Now we add a login for the rails app
create a file called railsapp.php
<?php define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : '../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
// Load include files.
include($phpbb_root_path . 'common.' . $phpEx);
include_once($phpbb_root_path . 'includes/functions_user.' . $phpEx);
// Set up a new user session.
$user->session_begin();
$auth->acl($user->data);
$user->setup('ucp');
$my_rails_user_email = some_code_to_get_user_email_from_rails_database; //maybe use a cookie or make the user allow the phpBB script access to the rails DB or make them login into the rails app
$mysql = 'SELECT user_id
FROM ' . USERS_TABLE
. " WHERE user_email='$my_user_rails_email'";
// Execute the query.
$result = $db->sql_query($sql);
// Retrieve the row data.
$row = $db->sql_fetchrow($result);
// Free up the result handle from the query.
$db->sql_freeresult($result);
// Check to see if we found a user_id with the associated Facebook Id.
if ($row) // User is registered already, let's log him in!
{
// Check for user ban.
if($user->check_ban($row['user_id']))
{
trigger_error($user->lang['BAN_TRIGGERED_BY_USER']);
}
// Log user in.
$result = $user->session_create($row['user_id'], 0, 0, 1);
// Alert user if we failed to log them in.
if(!$result)
{
trigger_error($user->lang['LOGIN_FAILURE']);
}
$redirect = $phpbb_root_path . 'index.' . $phpEx;
$message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
$l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$phpbb_root_path}index.$phpEx" || $redirect === "index.$phpEx") ? $user->lang['RETURN_INDEX'] : $user->lang['RETURN_PAGE']);
// append/replace SID (may change during the session for AOL users)
$redirect = reapply_sid($redirect);
// Special case... the user is effectively banned, but we allow founders to login
if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
{
return;
}
$redirect = meta_refresh(3, $redirect);
trigger_error($message . '<br /><br />' . sprintf($l_redirect, '', ''));
}
?>
In index_body.html in styles/your_template_name/templates/ add
Connect With Rails
If you need help just drop by MY phpBB mod support forums to discuss further