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

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

Related

Prestashop : Can't make my module work : Get order details when order status is changed to “shipped”

I am developing a module, it gets order details when order status is changed to "shipped" by admin, to post them to a third-party application with API.
I am using Prestashop V 1.7.7.0.
The hook i'm using is hookActionOrderStatusPostUpdate
The module is installed successfully in the Backoffice and there's no syntax errors, But it doesn't do anything.
Can't figure out what's wrong in my code.
Need help please. Thanks
<?php
/**
* 2007-2021 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* #author PrestaShop SA <contact#prestashop.com>
* #copyright 2007-2021 PrestaShop SA
* #license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_VERSION_')) {
exit;
}
class Cargo extends Module
{
protected $config_form = false;
public function __construct()
{
$this->name = 'cargo';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'tekwave';
$this->need_instance = 1;
/**
* Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
*/
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('cargo');
$this->description = $this->l('Ce module permet la synchronisation entre Prestashop et Cargo');
$this->confirmUninstall = $this->l('');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
/**
* Don't forget to create update methods if needed:
* http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
*/
public function install()
{
Configuration::updateValue('CARGO_LIVE_MODE', false);
return parent::install() &&
$this->registerHook('header') &&
$this->registerHook('backOfficeHeader') &&
$this->registerHook('actionOrderStatusPostUpdate');
}
public function uninstall()
{
Configuration::deleteByName('CARGO_LIVE_MODE');
return parent::uninstall();
}
/**
* Load the configuration form
*/
public function getContent()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitCargoModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');
return $output.$this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitCargoModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Live mode'),
'name' => 'CARGO_LIVE_MODE',
'is_bool' => true,
'desc' => $this->l('Use this module in live mode'),
'values' => array(
array(
'id' => 'active_on',
'value' => true,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => false,
'label' => $this->l('Disabled')
)
),
),
array(
'col' => 3,
'type' => 'text',
'prefix' => '<i class="icon icon-envelope"></i>',
'desc' => $this->l('Enter a valid email address'),
'name' => 'CARGO_ACCOUNT_EMAIL',
'label' => $this->l('Email'),
),
array(
'type' => 'password',
'name' => 'CARGO_ACCOUNT_PASSWORD',
'label' => $this->l('Password'),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues()
{
return array(
'CARGO_LIVE_MODE' => Configuration::get('CARGO_LIVE_MODE', true),
'CARGO_ACCOUNT_EMAIL' => Configuration::get('CARGO_ACCOUNT_EMAIL', 'contact#prestashop.com'),
'CARGO_ACCOUNT_PASSWORD' => Configuration::get('CARGO_ACCOUNT_PASSWORD', null),
);
}
/**
* Save form data.
*/
protected function postProcess()
{
$form_values = $this->getConfigFormValues();
foreach (array_keys($form_values) as $key) {
Configuration::updateValue($key, Tools::getValue($key));
}
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*/
public function hookBackOfficeHeader()
{
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path.'views/js/back.js');
$this->context->controller->addCSS($this->_path.'views/css/back.css');
}
}
/**
* Add the CSS & JavaScript files you want to be added on the FO.
*/
public function hookHeader()
{
$this->context->controller->addJS($this->_path.'/views/js/front.js');
$this->context->controller->addCSS($this->_path.'/views/css/front.css');
}
This is my code under hookActionOrderStatusPostUpdate function :
public function hookActionOrderStatusPostUpdate($params)
{
if ($params['newOrderStatus']->id == 6) {
$order = new Order((int)$params['id_order']);
$address = new Address((int)$order->id_address_delivery);
$country = new Country((int)($address->id_country));
$state = new State((int)($address->id_state));
$message = new Message((int)($order->id_message));
$Products = $order->getProducts();
$tel_cl = $address->phone;
$nom_prenom_cl = $address->lastname . ' ' . $address->firstname;
$ville_cl = $country->name;
$delegation_cl = $state->name;
$adresse_cl = $address->address1 . ' ' . $address->address2;
$tel_2_cl = $address->phone_mobile;
$libelle = '';
$nb_piece = 0;
foreach ($Products as $product) {
$libelle .= $product['product_name'] . '<br/>';
$nb_piece += $product['product_quantity'];
}
$cod = $order->total_paid;
$remarque = $message->message;
$Url_str = 'http://admin.cargotunisie.com/cargo_api/set_colis_cargo_get.php?id=1&tel_cl='.$tel_cl.'&nom_prenom_cl='.$nom_prenom_cl.'&ville_cl='.$ville_cl.'&delegation_cl='.$delegation_cl.'&adresse_cl='.$adresse_cl.'&tel_2_cl='.$tel_2_cl.'&libelle='.$libelle.'&cod='.$cod.'&nb_piece='.$nb_piece.'&remarque='.$remarque;
$json = Tools::file_get_contents($Url_str);
$result = json_decode($json);
}
}
}
It could be due to several things.
First: make sure the hook is hooked.
Go to Design > Positions > Then add new hook
Choose your module's name and check if you can select the hook actionOrderStatusPostUpdate. If you can, then it means it was unhooked.
This happens more than we would like, and sometimes you can get crazy until you found it
If that doesn't work you can try this (only if is not on a production site). If it is, just wrap it by using an if that checks if it's from your IP.
Add Tools::dieObject($params); at the beginning of the function.
Then change the an order and check the results. You should see a user friendly list of the values stored in $params.
Make it sure the $params['newOrderStatus'] exists and $params['newOrderStatus']->id is an object.
Also, it should be pretty obvious, but make sure the order ID which are you doing the tests is 6.
With that you should be able to have a general clue of what may be happening.

Creating a RSS feed for several selected categories

If I do this http://www.website.com/index.php?page=search&sCategory=123&sFeed=rss
I can create a RSS feed for a particular category. But what if I want to create a RSS feed for several selected categories? is it possible? OSClass version is 3.3.2
I didnt find a short or integrated way to do it, so I coded it.
<?php
define('ABS_PATH', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME']) . '/'));
if(PHP_SAPI==='cli') {
define('CLI', true);
}
require_once ABS_PATH . 'oc-load.php';
$mSearch = Search::newInstance();
$array_categorias = array("16","22","23","24","31","33","43","102","119","121","122","123","124");
$aItems = $mSearch->doCustomSearch($array_categorias);
View::newInstance()->_exportVariableToView('items', $aItems);
// FEED REQUESTED!
header('Content-type: text/xml; charset=utf-8');
$feed = new RSSFeed;
$feed->setTitle(__('Latest listings added') . ' - ' . osc_page_title());
$feed->setLink(osc_base_url());
$feed->setDescription(__('Latest listings added in') . ' ' . osc_page_title());
$contador_items = osc_count_items();
if(osc_count_items()>0) {
while(osc_has_items()) {
if(osc_count_item_resources() > 0){
osc_has_item_resources();
$feed->addItem(array(
'title' => osc_item_title(),
'link' => htmlentities( osc_item_url(), ENT_COMPAT, "UTF-8" ),
'description' => osc_item_description(),
'dt_pub_date' => osc_item_pub_date(),
'image' => array( 'url' => htmlentities(osc_resource_thumbnail_url(), ENT_COMPAT, "UTF-8"),
'title' => osc_item_title(),
'link' => htmlentities( osc_item_url() , ENT_COMPAT, "UTF-8") )
));
} else {
$feed->addItem(array(
'title' => osc_item_title(),
'link' => htmlentities( osc_item_url() , ENT_COMPAT, "UTF-8"),
'description' => osc_item_description(),
'dt_pub_date' => osc_item_pub_date()
));
}
}
}
$feed->dumpXML();
?>
I also had to add a couple of custom methods to the search model
public function _makeSQLCustomCategories($categories)
{
$cadena_select = DB_TABLE_PREFIX."t_item.*, ".DB_TABLE_PREFIX."t_item.s_contact_name as s_user_name,";
$cadena_select = $cadena_select . DB_TABLE_PREFIX. "t_item_description.s_title, ";
$cadena_select = $cadena_select . DB_TABLE_PREFIX. "t_item_description.s_description";
$this->dao->select($cadena_select);
$this->dao->from( DB_TABLE_PREFIX.'t_item' );
$this->dao->from( DB_TABLE_PREFIX. 't_item_description');
$this->dao->where(DB_TABLE_PREFIX. 't_item_description.fk_i_item_id = '. DB_TABLE_PREFIX. 't_item.pk_i_id');
//$this->dao->where(DB_TABLE_PREFIX. 't_item.b_premium = 1');
$this->dao->where(DB_TABLE_PREFIX. 't_item.b_enabled = 1');
$this->dao->where(DB_TABLE_PREFIX. 't_item.b_active = 1');
$this->dao->where(DB_TABLE_PREFIX. 't_item.b_spam = 0');
$where_categorias = "(";
$contador_categorias = 0;
$tamano_categories = sizeof($categories);
foreach ($categories as $categoria)
{
$contador = $contador + 1;
$where_categorias = $where_categorias. DB_TABLE_PREFIX. 't_item.fk_i_category_id = ' . $categoria ;
if ($contador == $tamano_categories)
break;
$where_categorias = $where_categorias . " OR ";
}
$where_categorias = $where_categorias . ")";
$this->dao->where($where_categorias );
$this->dao->groupBy(DB_TABLE_PREFIX.'t_item.pk_i_id');
$this->dao->orderBy(DB_TABLE_PREFIX. 't_item.pk_i_id', 'DESC');
$sql = $this->dao->_getSelect();
// reset dao attributes
$this->dao->_resetSelect();
return $sql;
}
public function doCustomSearch($categories, $extended = true, $count = true)
{
$sql = $this->_makeSQLCustomCategories($categories);
$result = $this->dao->query($sql);
if($count) {
$sql = $this->_makeSQLCustomCategories($categories);
$datatmp = $this->dao->query( $sql );
if( $datatmp == false ) {
$this->total_results = 0;
} else {
$this->total_results = $datatmp->numRows();
}
} else {
$this->total_results = 0;
}
if( $result == false ) {
return array();
}
if($result) {
$items = $result->result();
} else {
$items = array();
}
if($extended) {
return Item::newInstance()->extendData($items);
} else {
return $items;
}
}

send payments to faucetbox

I have try to do my self this code to implement the automatic send bitcoin payments to faucet box but is some errors there I need help with.
and it give me this error
The bitcoinrotator.publiadds.org.pt page is not working bitcoinrotator.publiadds.org.pt can not process this request for time. 500
<?php
//custom parameters
$api_key = "my_api_key";
$userAddy = $_SESSION['user'];
require_once("faucetbox.php");
$currency = "BTC"; # or LTC or any other supported by FaucetBOX
$faucetbox = new FaucetBOX($api_key, $currency);
$users = array(
'user_id' => clean($user_id),
'user_name' => clean($user_name),
'user_email' => clean($user_email),
'user_pass' => clean($user_pass),
'user_points' => clean($user_points),
'user_wallet' => clean($user_wallet)
);
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$selfNav = mysqli_query($conn, "SELECT user_wallet, user_points FROM users WHERE user_id=".$_SESSION['user']);
$rowNav = mysqli_num_rows($selfNav);
$rowAssoc = mysqli_fetch_assoc($selfNav);
$balance = $rowAssoc['user_points'];
$wallet = $rowAssoc['user_wallet'];
//auto cashout if bal over 0.00010000
if($balance > 0.00010000){
$amount = $rowAssoc['user_points'];
$currency = "BTC";
$faucetbox = new Faucetbox($api_key, $currency);
$result = $faucetbox->send($wallet, $amount);
if($result["success"] === true){
$_SESSION['cashout'] = $result["html"];
//reset balance to zero
mysqli_query($conn, "UPDATE `users` SET user_points = 0 WHERE user_id = " . $_SESSION['user')];
header('Location: ../home.php');
?>
well there it is its work but it stay with some bug there but now its work
the error is
Array ( [user_wallet] => 111111111111111111111111111111111111 [user_points] => 0.00000010 ) Error en balance
<?php
session_start();//Session start is ALWAYS the first thing to do.
if(!isset($_SESSION['user']))
{
header("Location: index.php"); //Sending headers its the next thing to do. Always.
}
include_once 'dbconnect.php';
//custom parameters
$api_key = "my_api_key";
$userAddy = $_SESSION['user'];
require_once("faucetbox.php");
$currency = "BTC"; # or LTC or any other supported by FaucetBOX
$faucetbox = new FaucetBOX($api_key, $currency);
//$users = array(
// 'user_id' => clean($user_id),
// 'user_name' => clean($user_name),
// 'user_email' => clean($user_email),
// 'user_pass' => clean($user_pass),
// 'user_points' => clean($user_points),
// 'user_wallet' => clean($user_wallet)
//);
//You are mixing mysql and mysqli, you need to choose one. Since you are on a shared hosting, mysqli is probably
//not installed/available, so we will keep using mysql. mysqli is safer!
$selfNav = mysql_query("SELECT user_wallet, user_points FROM users WHERE user_id=".$_SESSION['user']);
$rowNav = mysql_num_rows($selfNav);
$rowAssoc = mysql_fetch_assoc($selfNav);
print_r($rowAssoc);
$balance = $rowAssoc['user_points'];
$wallet = $rowAssoc['user_wallet'];
//auto cashout if bal over 0.00010000
if($balance > 0.00010000){
$amount = $rowAssoc['user_points'];
$currency = "BTC";
$result = $faucetbox->send($wallet,$amount); //$amount);
if($result["success"] === true){
$_SESSION['cashout'] = $result["html"];
//reset balance to zero
mysql_query("UPDATE `users` SET user_points = 0 WHERE user_id = " . $_SESSION['user']);
echo "result sucess and location go";
//header('Location: ../home.php');
}else{
echo "Error on faucet";
var_dump($result);
//What happens if there is an error?
}
}else{
echo "do not have enough credit to cash out";
//what happens if they dont have enough balance?
}
?>

(Magento 1.7) How to modify the report module?

I followed a tutorial to create report module and the tutorial show me exactly what I wanted. Now, I would like to modify the database into my database. There are two tables that I want to join (member_download and sales_payment). What should I modify from this code to link it into my database?
Here is the code:
<?php
class Wcl_ReportNewOrders_Model_Reportneworders extends Mage_Reports_Model_Mysql4_Product_Ordered_Collection
{
function __construct() {
parent::__construct();
}
protected function _joinFields($from = '', $to = '')
{
$this->addAttributeToSelect('name')
->addAttributeToSelect('increment_id')
->addOrderedQty($from, $to)
->setOrder('sku', self::SORT_ORDER_ASC);
//Mage::log('SQL: '.$this->getSelect()->__toString());
return $this;
}
public function addOrderedQty($from = '', $to = '')
{
$adapter = $this->getConnection();
$compositeTypeIds = Mage::getSingleton('catalog/product_type')->getCompositeTypes();
$orderTableAliasName = $adapter->quoteIdentifier('order');
$addressTableAliasName = 'a';
$downloadTableAliasName = 'download';
$orderJoinCondition = array(
$orderTableAliasName . '.entity_id = order_items.order_id',
$adapter->quoteInto("{$orderTableAliasName}.state = ?", Mage_Sales_Model_Order::STATE_PROCESSING),
);
$addressJoinCondition = array(
$addressTableAliasName . '.entity_id = order.shipping_address_id'
);
$downloadJoinCondition = array(
$downloadTableAliasName . '.order_id = order_items.order_id'
);
$productJoinCondition = array(
//$adapter->quoteInto('(e.type_id NOT IN (?))', $compositeTypeIds),
'e.entity_id = order_items.product_id',
$adapter->quoteInto('e.entity_type_id = ?', $this->getProductEntityTypeId())
);
if ($from != '' && $to != '') {
$fieldName = $orderTableAliasName . '.created_at';
$orderJoinCondition[] = $this->_prepareBetweenSql($fieldName, $from, $to);
}
$this->getSelect()->reset()
->from(
array('order_items' => $this->getTable('sales/order_item')),
array(
'qty_ordered' => 'order_items.qty_ordered',
'order_items_name' => 'order_items.name',
'order_increment_id' => 'order.increment_id',
'sku' => 'order_items.sku',
'type_id' => 'order_items.product_type',
'shipping_address_id' => 'order.shipping_address_id'
))
->joinInner(
array('order' => $this->getTable('sales/order')),
implode(' AND ', $orderJoinCondition),
array())
->joinLeft(
array('a' => $this->getTable('sales/order_address')),
implode(' AND ', $addressJoinCondition),
array(
'shipto_name' => "CONCAT(COALESCE(a.firstname, ''), ' ', COALESCE(a.lastname, ''))"
),
array())
->joinLeft(
array('e' => $this->getProductEntityTableName()),
implode(' AND ', $productJoinCondition),
array(
'created_at' => 'e.created_at',
'updated_at' => 'e.updated_at'
))
->where('parent_item_id IS NULL')
//->group('order_items.product_id')
->having('order_items.qty_ordered > ?', 0);
return $this;
}
public function addItem(Varien_Object $item)
{
$itemId = $this->_getItemId($item);
if (!is_null($itemId)) {
if (isset($this->_items[$itemId])) {
// Unnecessary exception - http://www.magentocommerce.com/boards/viewthread/10634/P0/
//throw new Exception('Item ('.get_class($item).') with the same id "'.$item->getId().'" already exist');
}
$this->_items[$itemId] = $item;
} else {
$this->_items[] = $item;
}
return $this;
}
}
Please tell me how to modify the database. I am new with magento. Thanks!
i checked your link that you provided. open file at below location
Wcl_ReportNewOrders_Block_Adminhtml_ReportNewOrders_Grid
below is the function where you can modify the database
protected function _prepareCollection() {
parent::_prepareCollection();
// Get the data collection from the model
$this->getCollection()->initReport('reportneworders/reportneworders');
return $this;
}
Replace the above code with below code
protected function _prepareCollection() {
parent::_prepareCollection();
$collection = $this->getCollection()->initReport('reportneworders/reportneworders');
/*
perform your desired operation here
// print_r((string)$collection->getSelect();
*/
$this->setCollection($collection);
return $this;
}

Drupal Creating Votes in Voting API Through Code

I have a custom module I'm writing, part of what I want it to do is create a vote associated with a node, I'm trying to figure out how to call the voting API from my module. I loookd in the documentation but it's a little sparse.
Here is an example from a module I wrote a while ago.
while ($data = db_fetch_object($result)) {
$node = node_load($data->nid);
$node_terms = taxonomy_node_get_terms($node);
$vote['value'] = 0;
$vote['value_type'] = 'points';
foreach ($node_terms as $term) {
$vote['value'] = $vote['value'] + $users_tags[$term->name];
}
$vote['content_id'] = $node->nid;
if (isset($vote['content_id'])) {
votingapi_set_votes($vote);
}
}
Just another example of using this:
function _ept_set_vote($nid, $status, $uid = NULL) {
global $user;
$vote = array(
array(
'entity_type' => 'node',
'value' => 1,
'entity_id' => $nid,
'uid' => (!$uid) ? $user->uid : $uid,
'tag' => $status
)
);
votingapi_set_votes($vote, array());
}
I call it like this:
switch($task_status){
case('start'):
_ept_set_vote($nid, "Start");
break;
case('completed'):
_ept_set_vote($nid, "Completed");
break;
}