This is script.php which I run which directs the user to callback.php
<?php
session_start();
require_once 'OAuth.php';
require_once 'OAuthCurl.php';
$callback_url = "http://something/bio/callback.html";
$consumer_key = "<code>";
$consumer_secret = "<code>";
$oauth_request_token = "http://api.twitter.com/oauth/request_token";
$oauth_authorize = "http://api.twitter.com/oauth/authorize";
$oauth_access_token = "http://api.twitter.com/oauth/access_token";
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer($consumer_key, $consumer_secret, $callback_url);
$req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "GET", $oauth_request_token);
$req_req->sign_request($sig_method, $test_consumer, NULL);
$oc = new OAuthCurl();
$reqData = $oc->fetchData($req_req->to_url());
parse_str($reqData['content'], $reqOAuthData);
$req_token = new OAuthConsumer($reqOAuthData['oauth_token'], $reqOAuthData['oauth_token_secret'], 1);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "GET", $oauth_authorize);
$acc_req->sign_request($sig_method, $test_consumer, $req_token);
$_SESSION['oauth_token'] = $reqOAuthData['oauth_token'];
$_SESSION['oauth_token_secret'] = $reqOAuthData['oauth_token_secret'];
Header("Location: $acc_req");
?>
This is the callback.php
I'm trying to set a cookie on callback.php but the cookie is not getting set.
I can't seem to understand why?
<?php
session_start();
$_SESSION['oauth_token'];
$_SESSION['oauth_token_secret'];
require_once 'OAuth.php';
require_once 'OAuthCurl.php';
require_once __DIR__ . '/TwitterOAuth/TwitterOAuth.php';
require_once __DIR__ . '/TwitterOAuth/Exception/TwitterException.php';
use TwitterOAuth\TwitterOAuth;
date_default_timezone_set('Asia/Calcutta');
$callback_url = "http://something/bio/callback.php";
$consumer_key = "<code>";
$consumer_secret = "<code>";
$oauth_request_token = "http://api.twitter.com/oauth/request_token";
$oauth_authorize = "http://api.twitter.com/oauth/authorize";
$oauth_access_token = "http://api.twitter.com/oauth/access_token";
//$authenticate_token = "https://api.twitter.com/1.1/account/verify_credentials.json";
//echo($authenticate_token);
//exit();
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer($consumer_key, $consumer_secret, $callback_url);
$params = array();
$acc_token = new OAuthConsumer($_SESSION['oauth_token'],$_SESSION['oauth_token_secret'], 1);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $acc_token, "GET", $oauth_access_token);
$acc_req->sign_request($sig_method, $test_consumer, $acc_token);
$oc = new OAuthCurl();
$reqData = $oc->fetchData("{$acc_req}&oauth_verifier=".$_GET['oauth_verifier']."");
parse_str($reqData['content'], $accOAuthData);
//$username = $accOAuthData[screen_name];
$_SESSION['username'] = $accOAuthData['screen_name'];
$_SESSION['final_oauth_token'] = $accOAuthData['oauth_token'];
$_SESSION['final_oauth_token_secret'] = $accOAuthData['oauth_token_secret'];
$final_oauth_token = $_SESSION['final_oauth_token'];
$final_oauth_token_secret = $_SESSION['final_oauth_token_secret'];
$username = $_SESSION['username'];
/**
* Array with the OAuth tokens provided by Twitter when you create application
*
* output_format - Optional - Values: text|json|array|object - Default: object
*/
$config = array(
'consumer_key' => '<code>',
'consumer_secret' => '<code>',
'oauth_token' => $final_oauth_token,
'oauth_token_secret' => $final_oauth_token_secret,
'output_format' => 'object'
);
/**
* Instantiate TwitterOAuth class with set tokens
*/
$tw = new TwitterOAuth($config);
$params = array(
'screen_name' => $username,
'count' => 5,
'exclude_replies' => true
);
/**
* Send a GET call with set parameters
*/
$response = $tw->get('users/show', $params);
$id =($response-> id);
$description=($response-> description);
$screen_name = ($response-> screen_name);
setcookie("test1", $screen_name, time()+3600*30);
/*Connection String*/
$hostname = 'something';
$database = 'twitter';
$username = '';
$password = '';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn)
{
die("Unable to Connect localhost!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$query = mysql_query("SELECT id FROM twitter_tbl WHERE id = '". $id ."'");
if (mysql_num_rows($query) > 0)
{
}
else
{
$sql='INSERT INTO twitter_tbl(description,screen_name,id,final_oauth_token,final_oauth_token_secret,timestamp) VALUES("'.$description.'","'.$screen_name.'","'.$id.'","'.$final_oauth_token.'","'.$final_oauth_token_secret.'",'.strval(time()).')';
if(!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
$bio_archives1 = 'INSERT INTO bio_archives(bio,screen_name,id,timestamp) VALUES("'.$description.'","'.$screen_name.'","'.$id.'",'.strval(time()).')';
if(!mysql_query($bio_archives1,$conn))
{
die('Error: ' . mysql_error());
}
}
if( strlen($description) < 80)
{
$newtext="is now ".'"'.$description.'"'." 'http://www.biostories.net/user.php?screen_name=".$screen_name."'";
$b = explode( "#tweeted", $newtext );
$txt = trim( $b[0] );
$url = trim( $b[1] );
$txt = substr( $txt, 0, 139 - strlen( $url ) );
$output = $txt . " " . $url;
}
else
{
$description1 = substr($description, 0, 50);
$newtext="is now ".'"'.$description1.'...."'." 'http://www.biostories.net/user.php?screen_name=".$screen_name."'";
$b = explode( "#tweeted", $newtext );
$txt = trim( $b[0] );
$url = trim( $b[1] );
$txt = substr( $txt, 0, 139 - strlen( $url ) );
$output = $txt . " " . $url;
}
$tw = new TwitterOAuth($config);
try{
$tw->post('statuses/update',array('status' =>$output));
}
catch(Exception $e) {
($e->getMessage());
}
$result = mysql_query('SELECT * FROM twitter_tbl WHERE id = "'.$id.'"');
while($row = mysql_fetch_array($result))
{
$desc = $row['description'];
}
if($desc === $description)
{
}
else
{
$query_update = mysql_query("SELECT id FROM twitter_up_tbl WHERE id = '". $id ."'");
if (mysql_num_rows($query_update) > 0)
{
$query1 ="Update twitter_up_tbl SET description='".$description."' WHERE id=".$id."";
$sql1 = mysql_query($query1);
}
else
{
$update_sql = 'INSERT INTO twitter_up_tbl(description,screen_name,id,final_oauth_token,final_oauth_token_secret,lastupdate) VALUES("'.$description.'","'.$screen_name.'","'.$id.'","'.$final_oauth_token.'","'.$final_oauth_token_secret.'",'.strval(time()).')';
if(!mysql_query($update_sql,$conn))
{
die('Error: ' . mysql_error());
}
}
$query ="Update twitter_tbl SET description='".$description."' WHERE id=".$id."";
$sql = mysql_query($query);
$bio_archives = 'INSERT INTO bio_archives(bio,screen_name,id,timestamp) VALUES("'.$description.'","'.$screen_name.'","'.$id.'",'.strval(time()).')';
if(!mysql_query($bio_archives,$conn))
{
die('Error: ' . mysql_error());
}
}
?>
Related
I have written a web service for order creation as below
<?php
#ini_set('display_errors', 'on');
define('_PS_DEBUG_SQL_', true);
require_once('db.php');
require_once('PSWebServiceLibrary.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$customerId = $_POST['customerid'];
$address = $_POST['address'];
$phoneno = $_POST['phoneno'];
$city = $_POST['city'];
$postcode = $_POST['postcode'];
$totalprice = $_POST['totalprice'];
$orders = $_POST['orders'];
$firstname = $_POST['firstname'] ;
$lastname = $_POST['lastname'] ;
$paymethod = "cod"; // cod or payu// cod or payu
$curdate=date('Y-m-d H:i:s');
if($paymethod == "payu") {
$orderModule = "citruspayu" ;
$orderPayment = "PayUmoney " ;
} else if($paymethod =="cod") {
$orderModule = "ps_cashondelivery" ;
$orderPayment = "Cash on delivery (cod)" ;
}
$curdate=date('Y-m-d H:i:s');
$orders = str_replace("\\", "",$orders);
$orders = json_decode($orders, true) ;
$ocnt=sizeof($orders);
//print_r($ocnt);
// need to check with product id and qunatity - ps_stock_available
// for ($i = 0 ; $i < $ocnt ; $i++) {
// $proid= $orders[$i]['product_id'];
// $quan=$orders[$i]['total_qty'];
// }
$result = array() ;
// print_r($result);
try
{
$sql=mysqli_query($con,"select * from `ps_customer` WHERE id_customer='".$customerId."'");
$cnt=mysqli_affected_rows($con);
if($cnt!=0) { //to place order
$row=mysqli_fetch_assoc($sql);
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/addresses?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis'));
$resources = $xml->children()->children();
$resources->id_country = 110; //India
$resources->id_state = 348; //Tamil Nadu
$resources->id_customer = $customerId;
$resources->alias = "My address";
$resources->lastname = $lastname ; //$row['lastname'];// last name is required
$resources->firstname = $firstname;
$resources->address1 = $address;
$resources->postcode = $postcode;
$resources->city = $city;
$resources->phone_mobile = $phoneno;
$resources->active = 1;
$resources->date_add = date('Y-m-d H:i:s');
$resources->date_upd = date('Y-m-d H:i:s');
$sql = mysqli_query($con,"select * from ps_address where id_customer=$customerId and firstname='".$firstname."' and lastname='".$lastname."' and address1='".$address."' and city='".$city."' and postcode='".$postcode."' and (phone_mobile= $phoneno or phone=$phoneno)");
//$sqll= "select * from ps_address where id_customer=$customerId and firstname='".$firstname."' and lastname='".$lastname."' and address1='".$address."' and city='".$city."' and postcode='".$postcode."' and (phone_mobile= $phoneno or phone=$phoneno)";
// echo $sqll;
$cnt=mysqli_num_rows($sql);
// echo "addrs count....".($cnt);
if($cnt == 0) {
$opt = array('resource' => 'addresses?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis');
// echo "111";
$opt['postXml'] = $xml->asXML();// echo $opt['postXml'];
// echo "222";
$xml = $webService->add($opt);
// echo "333";
$addressid = $xml->address->id;
// echo "string".$addressid;
}
else {
$address=mysqli_fetch_assoc($sql) ;
$addressid = $address['id_address'] ;
//echo "address id---".$addressid ;
}
//echo "now";
//exit();
if($addressid) { // if addressid exists
// to insert cart details
$cxml = $webService->get(array('url' => PS_SHOP_PATH.'/api/carts?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis'));
$cresources = $cxml->children()->children();
$cresources->id_carrier = 4;
$cresources->id_shop_group = 1;
$cresources->id_shop = 1;
$cresources->delivery_option = 'a:1:{i:'.$addressid.';s:2:"4,";}';
$cresources->id_customer = $customerId;
$cresources->id_lang = 2;
$cresources->id_address_delivery =$addressid;
$cresources->id_address_invoice = $addressid;
$cresources->id_currency = 1;
$cresources->id_guest = 1;
$cresources->date_add = date('Y-m-d H:i:s');
$cresources->date_upd = date('Y-m-d H:i:s');
$opt = array('resource' => 'carts?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis');
$opt['postXml'] = $cxml->asXML();
$cxml = $webService->add($opt);
$cartid = $cxml->cart->id;
echo "cart id===".$cartid ;
if($cxml) {
/*insert cart product*/
$delqur = mysqli_query($con,"DELETE FROM ps_cart_product WHERE id_cart = $cartid;");
for ($i = 0 ; $i < $ocnt ; $i++) {
$proid= $orders[$i]['product_id'];
$quan=$orders[$i]['total_qty'];
$qur = mysqli_query($con,"INSERT INTO ps_cart_product (`id_cart`,`id_product`,`id_address_delivery`,`id_shop`,
`id_product_attribute`,`quantity`,`date_add`) VALUES('$cartid','$proid','$addressid','1','0','$quan','$curdate');");
}
/*insert cart product*/
/*to insert order details*/
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$orderxml = $webService->get(array('url' => PS_SHOP_PATH.'/api/orders?ws_key='.PS_WS_AUTH_KEY.'&schema=synopsis'));
$orderxml->order->id_address_delivery = $addressid;
$orderxml->order->id_address_invoice = $addressid;
$orderxml->order->id_cart = $cartid;
$orderxml->order->id_currency = 1;
$orderxml->order->id_lang = 2;
$orderxml->order->id_customer = $customerId;
$orderxml->order->id_carrier = 4; // Check your id_carrier
$orderxml->order->current_state = 3;
$orderxml->order->module = $orderModule ;
//'citruspayu' ; //'ps_cashondelivery';
$orderxml->order->valid = 0;
$orderxml->order->id_shop_group = 1;
$xml->order->id_shop = 1;
$orderxml->order->payment = $orderPayment ;
//"PayUmoney" ; //'Cash on delivery (COD)';
$orderxml->order->total_discounts = 0;
$orderxml->order->total_discounts_tax_incl =0;
$orderxml->order->total_discounts_tax_excl =0;
$orderxml->order->total_paid = $totalprice;
$orderxml->order->total_paid_tax_incl = $totalprice;
$orderxml->order->total_paid_tax_excl = $totalprice;
$orderxml->order->total_paid_real = $totalprice;
$orderxml->order->total_products = 2 ;
$orderxml->order->total_products_wt = 200 ;
$orderxml->order->total_shipping = 0;
$orderxml->order->total_shipping_tax_incl = 0;
$orderxml->order->total_shipping_tax_excl = 0;
$orderxml->order->conversion_rate = 1;
// $orderxml->order->from_device="app" ;
$orderxml->order->secure_key = md5(uniqid(rand(), true));;
$opt = array('resource' => 'orders?sendemail=1');
$orderxml = $orderxml->asXML();
$opt['postXml'] = $orderxml ; //echo $opt['postXml'];
$orderxml = $webService->add($opt);
$orderid=$orderxml->order->id;
if($orderxml) {
$findSecLastInvoice=mysqli_query($con,"SELECT * FROM `ps_order_invoice` ORDER BY `delivery_number` DESC LIMIT 1");
$icnt=mysqli_affected_rows($con);
if($icnt!=0) {
$inrow=mysqli_fetch_assoc($findSecLastInvoice);
$dnumber =$inrow['delivery_number'] + 1;
} else {
$dnumber =1;
}
$findOrderid=mysqli_query($con,"SELECT * FROM `ps_orders` WHERE id_cart='$cartid'");
$orderrow=mysqli_fetch_assoc($findOrderid);
$update_orderinvoice = mysqli_query($con, "UPDATE ps_order_invoice SET delivery_number='$dnumber',delivery_date='$curdate' WHERE id_order='".$orderrow['id_order']."'") ;
if($update_orderinvoice) {
$update_order = mysqli_query($con, "UPDATE ps_orders SET delivery_number='$dnumber',delivery_date='$curdate' WHERE id_order='".$orderrow['id_order']."'") ;
$update_orderhistory = mysqli_query($con, "UPDATE ps_order_history WHERE id_order='".$orderrow['id_order']."'") ;
$result['status']= "Success";
$result['orderid'] = strval($orderid) ;
}
} else {
$result['status']= "Error";
} //$oxml
} //$cxml
// to insert cart details
} //$address id
}
else { //not exists
$result['status']="Account Not Found";
}
// header('Content-type: application/json');
echo json_encode($result);
mysqli_close($con);
}
catch (PrestaShopWebserviceException $e)
{
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$e->getMessage();
}
}//post
else {
echo "No Post Parameters" ;
}
//}
?>
While running in postman I get a success message. but when I see app log am getting an error as HTTP XML response is not parsable and LibXMLError::__set_state error...somebody pls help. I have also trimmed it but no use.1
I'm using PSWebServiceLibrary.php for Prestashop and in the add function, this is the code which sends the XML request for parsing.
I'm still a beginner programmer , so I hope you give the solution step by step.
I'm trying to make a private server for a flash game and i have a problem that I don't know how can I solve it at all .
I wanna connect the game with the database , and when someone tries to make an account (register) in the game , the account data supposed to be saved in the database ( like: username,password,mask color,birth date,register date,etc...) but it doesn't happen
The file which is responsible about this step is called " register.php" and
I keep getting this error :
Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4
the problem is in this line :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
and this is "register.php" :
<?php
include_once("db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$FROM_EMAIL = $obj->getEmailFrom();
function generateTribeCurrency($ID, $db) {
// $db = new database();
// get init purse amount
$db->setQuery("SELECT init_purse_amount FROM `cc_def_settings`");
$row = $db->loadResult();
$init_purse_amount = $row->init_purse_amount;
// load tribe info
$db->setQuery("SELECT * FROM `cc_tribes`");
$tribeinfo = $db->loadResults();
$newstr = array();
foreach ($tribeinfo as $i) {
if ($ID == $i->ID) array_push($newstr, $init_purse_amount); else array_push($newstr, 0);
}
$newstr = implode(",", $newstr);
return $newstr;
}
$hackchk = false;
foreach($_POST as $POST) {
$POST = mysqli_real_escape_string($POST);
}
function remove_bad_symbols($s) {
return preg_replace(
array(0=>'#/#', 1=>'#\\\#', 2=>'#;#', 3=>'#{#', 4=>'#}#', 5=>'#<#', 6=>'#>#', 7=>'###', 8=>'#\'#', 9=>'# #', 10=>'#"#') // patterns
, '' // replacements
, $s);
}
$username = isset($_POST['username']) ? remove_bad_symbols($_POST['username']) : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$birthdate = isset($_POST['birthdate']) ? $_POST['birthdate'] : "";
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$sex = isset($_POST['sex']) ? $_POST['sex'] : "";
$tribeid = isset($_POST['clan']) ? $_POST['clan'] : "";
$mask = isset($_POST['mask']) ? $_POST['mask'] : "";
$mask_color = isset($_POST['maskcl']) ? $_POST['maskcl'] : "";
$lang_id = isset($_POST['lang_id']) ? $_POST['lang_id'] : 0;
$error = '';
$purse = generateTribeCurrency((int) $tribeid, $db);
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'";
// for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ($username && $email && $sex && $birthdate) {
if ($email_check_ok) {
if ($res->counter == "0") {
// check that there are no registrations from this same IP in the last 2 hours
$db->setQuery("SELECT COUNT(*) as counter FROM `cc_userreginfo` WHERE IP='".$_SERVER['REMOTE_ADDR']."' AND (DATE_SUB(CURDATE(), INTERVAL 2 HOUR)<register_date)");
$regcheck = $db->loadResult();
if (($regcheck != null && (int)($regcheck->counter) == 0) || $hackchk == false) {
// get number of already registered number of registrations with this email address
$query = $db->setQuery("SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'");
$row = $db->loadResult();
$already_registered_num_emails = $row->registered_num_emails;
// get max number of accounts per email from settings table
$query = $db->setQuery("SELECT max_num_account_per_email from `cc_def_settings`");
$row = $db->loadResult();
$max_num_account_per_email = $row->max_num_account_per_email;
if ($already_registered_num_emails < $max_num_account_per_email) {
$uniqid = uniqid();
$newreq = "INSERT INTO `cc_user` (`ID`,`username`, `password`, `email`, `birth_date`, `first_name`, `last_name`, `sex`, `about`, `mask`, `mask_colors`, `clothing`, `tribe_ID` , `money`, `happyness`, `rank_ID`, `status_ID`, `lang_id`, `register_date`, uniqid, permission_id) VALUES ";
$newreq .= "(NULL, '{$username}', '{$password}', '{$email}', '{$birthdate}', '{$firstname}' , '{$lastname}', '{$sex}', '', '{$mask}', '{$mask_color}', '', '{$tribeid}', '{$purse}', 50, 0, 3, '{$lang_id}', NOW(), '{$uniqid}', 4)";
$db->setQuery($newreq);
$res = $db->runQuery();
if ($res) {
// add registration info into the userreginfo table as well.
$iid = $db->mysqlInsertID();
$db->setQuery("INSERT INTO `cc_userreginfo` (`ID`, `user_id`, `register_IP`, `register_date`, `last_update`) VALUES (NULL, ".$iid.",'".$_SERVER['REMOTE_ADDR']."', NOW(), NOW())");
$res2 = $db->runQuery();
$counter = ($regcheck != null) ? $regcheck->counter : 0;
echo 'response=true®='.$counter;
// ----------------------------------
// send confirmation email
// ----------------------------------
$cur_lang = ($lang != "") ? substr($lang, 1)."/" : "";
$msg = $obj->getTranslation(-13, $lang, "email_templates", "id", "content");
$msg = str_replace("%FIRST_NAME%", $firstname, $msg);
$msg = str_replace("%LAST_NAME%", $lastname, $msg);
$msg = str_replace("'", "'", $msg);
$msg = str_replace("%CONFIRM%", 'confirm', $msg);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
$headers .= 'From: '.$FROM_EMAIL."\r\n";
//mail($email, $obj->getTranslation(-13, $lang, "email_templates", "id", "subject"), $msg, $headers);
include "../../admin/php_mailer/class.phpmailer.php";
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $msg;
$body = eregi_replace("[\]",'',$body);
$mail->SetFrom($FROM_EMAIL);
$mail->AddAddress($email);
$mail->Subject = $obj->getTranslation(-13, $lang, "email_templates", "id", "subject");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
die("Mailer Error: " . $mail->ErrorInfo);
} else {
//echo "Message sent!";
}
// ----------------------------------
} else {
echo 'response=false';
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGISTER_LATER'");
$res = $db->loadResult();
echo 'errorhide='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
//if ($one_registration_per_email == true)
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'"; //else $sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_REGISTRATION'";
// get warning message from db
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGFORM_PROBLEM'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
?>
note : "register.php" requires two files so maybe the error is in one of them
settings.php :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "qazqazqaz1";
$db_name = "coco";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
db.php:
<?php
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "qazqazqaz1";
var $_DBname = "cocol";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
?>
I tried to solve it myself but I lost hope , so please tell me the accurate solution in steps .
thanks.
The error is referring to $obj->get. Basically you're executing the get method on a null variable, meaning it doesn't exist. After looking through all the code you have there, you aren't declaring $obj at any point.
I think you might need to check how you're passing in your settings to your Database object. For example:
$db = new database($db_server, ... , ...);
Updated:
You're hardcoding your connection anyway, just don't pass anything to the DB object.
Change this:
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
To this:
$db = new database();
I created a cronjobs on direct admin, and if that running it will check curl =>>> change values in mysql. But it's not working. Please help me ##. Thanks
This is my code:
<?php
class ControllerVemaybayCronJobapp
{
function index(){
$connect = $this->connect();
$query_routes_1 = $connect->query("SELECT * FROM **** where status = '0' GROUP BY routes ");
for ($result = array();
$row = $query_routes_1->fetch_assoc();
$result[array_shift($row)] = $row);
foreach ($result as $i => $aaa){
$routes = $aaa['routes'];
$detail_routes_2 = $connect->query("SELECT * FROM **** where routes = '" . $routes . "' AND status = '0' ");
for ($result2 = array();
$row2 = $detail_routes_2 ->fetch_assoc();
$result2[array_shift($row2)] = $row2);
foreach ($result2 as $t => $value1) {
$ngay = $value1['ngay'];
$thang = $value1['thang'];
$nam = $value1['nam'];
$min = $value1['minPrice'];
$max = $value1['maxPrice'];
$providers = $value1['providers'];
$startdate = $nam.$thang.'01';
$enddate = $nam.$thang.'31';
$bien = $this->getlist_ticketsofdate($routes,$startdate,$enddate);
foreach ($bien as $k => $value) {
$moi2 = array();
$moi = $value['c'];
$moi2 = $value['f'];
if($value['_id']['dim'] == $ngay ){
if($min <= $value['c'] && $value['c'] <= $max && strpos($providers, $value['p']) !== false){
$connect->query("UPDATE **** SET status='1' where customer_id = '" . $value1['customer_id'] . "' ");
break;
}else{
foreach ($moi2 as $key => $value2) {
if($min <= $value2['cp'] && $value2['cp'] <= $max && strpos($providers, $value2['p']) !== false){
$connect->query("UPDATE **** SET status='1' where customer_id = '" . $value1['customer_id'] . "' ") ;
break;
}
}
}
}
}
}
}
}
function connect(){
$servername = "****";
$username = "****";
$password = "****";
$databasename = "****";
$conn = new mysqli($servername, $username, $password,$databasename);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function getlist_ticketsofdate($diadiem,$startDate,$endDate){
$url = '****';
$providers = array();
$providers[0] = '****';
$providers[1] = '****';
$providers[2] = '****';
$routes = array();
$routes[0] = $diadiem;
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Connection:keep-alive';
$param = array(
'startDate' => $startDate,
'endDate' => $endDate,
'minPrice' => '0',
'maxPrice' => '700000',
'providers' => $providers,
'routes' => $routes,
'type' => 'date',
);
$data_string = json_encode($param);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$result_tickets = json_decode($response,true);
return $result_tickets;
}
}
?>
This is my cronjobs
Cron job may not works directly on admin, cause it may required authentications for some process.
Sample php file name mail.php
<?php
// the message
$msg = "First line of text\nSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("someone#example.com","My subject",$msg);
?>
Cron command:
For url
* * * * * wget http://example.com/mail.php &> /dev/null
For Path
* * * * * <BASE DIR>/mail.php
This cron job send mail every minute.
I get an error in my file "checkusername.php".
The error I get is:
( ! ) Fatal error: Call to a member function get() on null in
C:\wamp\www\Cocolani\php\req\checkusername.php on line 4
There is a "checkusername.php" file :
<?php
include_once("../../includes/db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$username = isset($_POST['username']) ? mysqli_real_escape_string($_POST['username']) : "";
$password = isset($_POST['password']) ? mysqli_real_escape_string($_POST['password']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : '';
$birthdate = isset($_POST['birthdate']) ? mysqli_real_escape_string($_POST['birthdate']) : "";
$firstname = isset($_POST['firstname']) ? mysqli_real_escape_string($_POST['firstname']) : "";
$lastname = isset($_POST['lastname']) ? mysqli_real_escape_string($_POST['lastname']) : "";
$sex = isset($_POST['sex']) ? mysqli_real_escape_string($_POST['sex']) : "";
$tribeid = isset($_POST['clan']) ? mysqli_real_escape_string($_POST['clan']) : "";
$mask = isset($_POST['mask']) ? mysqli_real_escape_string($_POST['mask']) : "";
$mask_color = isset($_POST['maskcl']) ? mysqli_real_escape_string($_POST['maskcl']) : "";
$lang_id = isset($_POST['lang_id']) ? addslashes($_POST['lang_id']) : 0;
$error = '';
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$reg_ok = true;
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'"; // for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
if ($email_check_ok == false) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
/*if ($reg_ok && $email != '') {
// get number of already registered number of registrations with this email address
$sql = "SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
$registered_num_emails = $row->registered_num_emails;
$sql = "SELECT max_num_account_per_email from `cc_def_settings`";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
// it's possible to create new registration using this email address
if ($registered_num_emails >= $row->max_num_account_per_email) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}*/
////////
// echo 'error=111';
// $reg_ok = false;
////////
if ($reg_ok) {
// check for swear words
$db->setQuery("SELECT COUNT(*) as counter from `cc_swear_words` where INSTR('".$username."', `name`)");
$res2 = $db->loadResult();
if ((int)($res2->counter) > 0) { // swear word founded!
$sql = "SELECT * FROM `cc_translations` WHERE caption='USERNAME_NOT_PERMITTED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) {
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ((int)($res->counter) > 0) { // swear word founded!
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) echo 'result=true';
?>
The problem on line 4 which is :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
There is a "settings.php" :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "pass1234";
$db_name = "cocolani_battle";
$appsecret = "80f730a73ac60417c36c341bc975f6f1";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
and there is a "db.php" :
<?php
/*
Usage
$db = new database($dbname);
for selects:
$db->setQuery("SELECT * FROM `table`")
$resultArray = $db->loadResults();
$db->setQuery("SELECT * FROM `table` WHERE `primary_id` = '1'");
$resultObject = $db->loadResult();
for inserts:
$db->setQuery("INSERT INTO `table` (`id`, `example`) VALUES ('1', 'abc')");
if (!$db->runQuery()) {
echo $db->getError();
}
*/
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "pass1234";
var $_DBname = "cocolani_battle";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
}
/*if ($_SERVER["SERVER_ADDR"] == '127.0.0.1') {
$url_root = "http://cocolani.localhost";
} else {
$url_root = "http://dev.cocolani.com";
}*/
?>
How can I fix this error?
As I mentioned in my comment, you can either use the variables you defined in your settings.php:
$db = new database($db_name, $db_server, $db_user, $db_password, $db_urlroot); // You didn't define $db_urlroot anywhere, but you can define it
OR hard-code it into your class. You're not using the variables you pass in anyway, so there's no need to ask for them.
public function __construct() {
Ok, so I have downloaded mibew messenger and I want to customize the buttons, so I go into login.php and the actual submit button for the login is type="image" so I changed to to type="submit" and when I submit the form I get a incorrect username/password error, anyway I was very confused so I was looking through loads of the other files to see if I can find anything that's related to the type="image" just in-case there's something that identifies the type="image", well I dunno, I didn't find anything but what I did notice is that when I type in admin into the username and click login the submit button it returns the login error but also in the box where I put admin there is now the value of the type="submit" so in this case it says login because the value is value="login", I'm really confused, I think maybe it is submitting "login" instead of "admin" as the username.
Here is the before and after submit buttons:
NEW
<input type="submit" name="login" value="login" >
ORIGINAL
<input type="image" name="login" src='<?php echo $webimroot.getlocal("image.button.login") ?>' alt='<?php echo getlocal("button.enter") ?>'/>
If i change it back to the original it works fine, but i want to use css not images.
Also, it would be quite hard to make a jsfiddle, otherwise i would have made one.
This is login.php where is posts the data
require_once('../libs/common.php');
require_once('../libs/operator.php');
$errors = array();
$page = array('formisRemember' => true, 'version' => $version);
if (isset($_POST['login']) && isset($_POST['password'])) {
$login = getparam('login');
$password = getparam('password');
$remember = isset($_POST['isRemember']) && $_POST['isRemember'] == "on";
$operator = operator_by_login($login);
if ($operator && isset($operator['vcpassword']) && $operator['vcpassword'] == md5($password)) {
$target = isset($_SESSION['backpath'])
? $_SESSION['backpath']
: "$root/agent/index.php";
login_operator($operator, $remember);
header("Location: $target");
exit;
} else {
$errors[] = getlocal("page_login.error");
$page['formlogin'] = $login;
}
}
$page['localeLinks'] = get_locale_links("$root/agent/login.php");
start_html_output();
require('../display/login.php');
This is the included operator.php in login.php
$can_administrate = 0;
$can_takeover = 1;
$can_viewthreads = 2;
$can_modifyprofile = 3;
$can_count = 4;
$permission_ids = array(
$can_administrate => "admin",
$can_takeover => "takeover",
$can_viewthreads => "viewthreads",
$can_modifyprofile => "modifyprofile"
);
function operator_by_login($login)
{
global $mysqlprefix;
$link = connect();
$operator = select_one_row(
"select * from ${mysqlprefix}chatoperator where vclogin = '" . mysql_real_escape_string($login) . "'", $link);
mysql_close($link);
return $operator;
}
function operator_by_email($mail)
{
global $mysqlprefix;
$link = connect();
$operator = select_one_row(
"select * from ${mysqlprefix}chatoperator where vcemail = '" . mysql_real_escape_string($mail) . "'", $link);
mysql_close($link);
return $operator;
}
function operator_by_id_($id, $link)
{
global $mysqlprefix;
return select_one_row(
"select * from ${mysqlprefix}chatoperator where operatorid = $id", $link);
}
function operator_by_id($id)
{
$link = connect();
$operator = operator_by_id_($id, $link);
mysql_close($link);
return $operator;
}
function operator_get_all()
{
global $mysqlprefix;
$link = connect();
$query = "select operatorid, vclogin, vclocalename, vccommonname, istatus, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator order by vclogin";
$operators = select_multi_assoc($query, $link);
mysql_close($link);
return $operators;
}
function operator_is_online($operator)
{
global $settings;
return $operator['time'] < $settings['online_timeout'];
}
function operator_is_available($operator)
{
global $settings;
return $operator['istatus'] == 0 && $operator['time'] < $settings['online_timeout'] ? "1" : "";
}
function operator_is_away($operator)
{
global $settings;
return $operator['istatus'] != 0 && $operator['time'] < $settings['online_timeout'] ? "1" : "";
}
function update_operator($operatorid, $login, $email, $password, $localename, $commonname)
{
global $mysqlprefix;
$link = connect();
$query = sprintf(
"update ${mysqlprefix}chatoperator set vclogin = '%s',%s vclocalename = '%s', vccommonname = '%s'" .
", vcemail = '%s', vcjabbername= '%s'" .
" where operatorid = %s",
mysql_real_escape_string($login),
($password ? " vcpassword='" . md5($password) . "'," : ""),
mysql_real_escape_string($localename),
mysql_real_escape_string($commonname),
mysql_real_escape_string($email),
'',
$operatorid);
perform_query($query, $link);
mysql_close($link);
}
function update_operator_avatar($operatorid, $avatar)
{
global $mysqlprefix;
$link = connect();
$query = sprintf(
"update ${mysqlprefix}chatoperator set vcavatar = '%s' where operatorid = %s",
mysql_real_escape_string($avatar), $operatorid);
perform_query($query, $link);
mysql_close($link);
}
function create_operator_($login, $email, $password, $localename, $commonname, $avatar, $link)
{
global $mysqlprefix;
$query = sprintf(
"insert into ${mysqlprefix}chatoperator (vclogin,vcpassword,vclocalename,vccommonname,vcavatar,vcemail,vcjabbername) values ('%s','%s','%s','%s','%s','%s','%s')",
mysql_real_escape_string($login),
md5($password),
mysql_real_escape_string($localename),
mysql_real_escape_string($commonname),
mysql_real_escape_string($avatar),
mysql_real_escape_string($email), '');
perform_query($query, $link);
$id = mysql_insert_id($link);
return select_one_row("select * from ${mysqlprefix}chatoperator where operatorid = $id", $link);
}
function create_operator($login, $email, $password, $localename, $commonname, $avatar)
{
$link = connect();
$newop = create_operator_($login, $email, $password, $localename, $commonname, $avatar, $link);
mysql_close($link);
return $newop;
}
function notify_operator_alive($operatorid, $istatus)
{
global $mysqlprefix;
$link = connect();
perform_query("update ${mysqlprefix}chatoperator set istatus = $istatus, dtmlastvisited = CURRENT_TIMESTAMP where operatorid = $operatorid", $link);
mysql_close($link);
}
function has_online_operators($groupid = "")
{
global $settings, $mysqlprefix;
loadsettings();
$link = connect();
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time from ${mysqlprefix}chatoperator";
if ($groupid) {
$query .= ", ${mysqlprefix}chatgroupoperator where groupid = $groupid and ${mysqlprefix}chatoperator.operatorid = ${mysqlprefix}chatgroupoperator.operatorid and istatus = 0";
} else {
$query .= " where istatus = 0";
}
$row = select_one_row($query, $link);
mysql_close($link);
return $row['time'] < $settings['online_timeout'] && $row['total'] > 0;
}
function is_operator_online($operatorid, $link)
{
global $settings, $mysqlprefix;
loadsettings_($link);
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator where operatorid = $operatorid";
$row = select_one_row($query, $link);
return $row['time'] < $settings['online_timeout'] && $row['total'] == 1;
}
function get_operator_name($operator)
{
global $home_locale, $current_locale;
if ($home_locale == $current_locale)
return $operator['vclocalename'];
else
return $operator['vccommonname'];
}
function append_query($link, $pv)
{
$infix = '?';
if (strstr($link, $infix) !== FALSE)
$infix = '&';
return "$link$infix$pv";
}
function check_login($redirect = true)
{
global $root, $mysqlprefix;
if (!isset($_SESSION["${mysqlprefix}operator"])) {
if (isset($_COOKIE['webim_lite'])) {
list($login, $pwd) = preg_split("/,/", $_COOKIE['webim_lite'], 2);
$op = operator_by_login($login);
if ($op && isset($pwd) && isset($op['vcpassword']) && md5($op['vcpassword']) == $pwd) {
$_SESSION["${mysqlprefix}operator"] = $op;
return $op;
}
}
$requested = $_SERVER['PHP_SELF'];
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['QUERY_STRING']) {
$requested .= "?" . $_SERVER['QUERY_STRING'];
}
if ($redirect) {
$_SESSION['backpath'] = $requested;
header("Location: $root/agent/login.php");
exit;
} else {
return null;
}
}
return $_SESSION["${mysqlprefix}operator"];
}
function get_logged_in()
{
global $mysqlprefix;
return isset($_SESSION["${mysqlprefix}operator"]) ? $_SESSION["${mysqlprefix}operator"] : FALSE;
}
function login_operator($operator, $remember)
{
global $root, $mysqlprefix;
$_SESSION["${mysqlprefix}operator"] = $operator;
if ($remember) {
$value = $operator['vclogin'] . "," . md5($operator['vcpassword']);
setcookie('webim_lite', $value, time() + 60 * 60 * 24 * 1000, "$root/");
} else if (isset($_COOKIE['webim_lite'])) {
setcookie('webim_lite', '', time() - 3600, "$root/");
}
}
function logout_operator()
{
global $root, $mysqlprefix;
unset($_SESSION["${mysqlprefix}operator"]);
unset($_SESSION['backpath']);
if (isset($_COOKIE['webim_lite'])) {
setcookie('webim_lite', '', time() - 3600, "$root/");
}
}
function setup_redirect_links($threadid, $token)
{
global $page, $root, $settings, $mysqlprefix;
loadsettings();
$link = connect();
$operatorscount = db_rows_count("${mysqlprefix}chatoperator", array(), "", $link);
$groupscount = 0;
$groups = array();
if ($settings['enablegroups'] == "1") {
foreach (get_groups($link, true) as $group) {
if ($group['inumofagents'] == 0) {
continue;
}
$groups[] = $group;
}
$groupscount = count($groups);
}
prepare_pagination(max($operatorscount, $groupscount), 8);
$p = $page['pagination'];
$limit = $p['limit'];
$operators = select_multi_assoc(db_build_select(
"operatorid, vclogin, vclocalename, vccommonname, istatus, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time",
"${mysqlprefix}chatoperator", array(), "order by vclogin $limit"), $link);
$groups = array_slice($groups, $p['start'], $p['end'] - $p['start']);
mysql_close($link);
$agent_list = "";
$params = array('thread' => $threadid, 'token' => $token);
foreach ($operators as $agent) {
$params['nextAgent'] = $agent['operatorid'];
$status = $agent['time'] < $settings['online_timeout']
? ($agent['istatus'] == 0
? getlocal("char.redirect.operator.online_suff")
: getlocal("char.redirect.operator.away_suff")
)
: "";
$agent_list .= "<li><a href=\"" . add_params($root . "/agent/redirect.php", $params) .
"\" title=\"" . topage(get_operator_name($agent)) . "\">" .
topage(get_operator_name($agent)) .
"</a> $status</li>";
}
$page['redirectToAgent'] = $agent_list;
$group_list = "";
if ($settings['enablegroups'] == "1") {
$params = array('thread' => $threadid, 'token' => $token);
foreach ($groups as $group) {
$params['nextGroup'] = $group['groupid'];
$status = $group['ilastseen'] !== NULL && $group['ilastseen'] < $settings['online_timeout']
? getlocal("char.redirect.operator.online_suff")
: ($group['ilastseenaway'] !== NULL && $group['ilastseenaway'] < $settings['online_timeout']
? getlocal("char.redirect.operator.away_suff")
: "");
$group_list .= "<li><a href=\"" . add_params($root . "/agent/redirect.php", $params) .
"\" title=\"" . topage(get_group_name($group)) . "\">" .
topage(get_group_name($group)) .
"</a> $status</li>";
}
}
$page['redirectToGroup'] = $group_list;
}
$permission_list = array();
function get_permission_list()
{
global $permission_list, $permission_ids;
if (count($permission_list) == 0) {
foreach ($permission_ids as $permid) {
$permission_list[] = array(
'id' => $permid,
'descr' => getlocal("permission.$permid")
);
}
}
return $permission_list;
}
function is_capable($perm, $operator)
{
$permissions = $operator && isset($operator['iperm']) ? $operator['iperm'] : 0;
return $perm >= 0 && $perm < 32 && ($permissions & (1 << $perm)) != 0;
}
function prepare_menu($operator, $hasright = true)
{
global $page, $settings, $can_administrate;
$page['operator'] = topage(get_operator_name($operator));
if ($hasright) {
loadsettings();
$page['showban'] = $settings['enableban'] == "1";
$page['showgroups'] = $settings['enablegroups'] == "1";
$page['showstat'] = $settings['enablestatistics'] == "1";
$page['showadmin'] = is_capable($can_administrate, $operator);
$page['currentopid'] = $operator['operatorid'];
}
}
function get_all_groups($link)
{
global $mysqlprefix;
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, vclocalname, vclocaldescription from ${mysqlprefix}chatgroup order by vclocalname";
return select_multi_assoc($query, $link);
}
function get_groups($link, $checkaway)
{
global $mysqlprefix;
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, vclocalname, vclocaldescription" .
", (SELECT count(*) from ${mysqlprefix}chatgroupoperator where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid) as inumofagents" .
", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatoperator where istatus = 0 and ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid " .
"and ${mysqlprefix}chatgroupoperator.operatorid = ${mysqlprefix}chatoperator.operatorid) as ilastseen" .
($checkaway
? ", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatoperator where istatus <> 0 and ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid " .
"and ${mysqlprefix}chatgroupoperator.operatorid = ${mysqlprefix}chatoperator.operatorid) as ilastseenaway"
: ""
) .
" from ${mysqlprefix}chatgroup order by vclocalname";
return select_multi_assoc($query, $link);
}
function get_operator_groupids($operatorid)
{
global $mysqlprefix;
$link = connect();
$query = "select groupid from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid";
$result = select_multi_assoc($query, $link);
mysql_close($link);
return $result;
}
And it wont let me add any more code if you need common.php let me know
Without seeing your PHP it's hard to tell, but it could be that image submits "login" as POST/GET variable value array(x, y), where the submit type will just a string value. If you are checking the submission based on that value, you will need to make some changes.
EDIT:
Looking at your code, it looks like you might be using 'login' as the username and the submit button. Try changing the submit button name to something else.
<input type="submit" name="loginButton" value="login" />