How to use class in php - php

I have this php class and I don't know how to use it. I know a little bit php but I don't know how to use/call a class.
<?php
Class Checkserver {
static function getString(&$packet){
$str = "";
$n = strlen($packet);
for($i=0;($packet[$i]!=chr(0)) && ($i < $n);++$i)
$str .= $packet[$i];
$packet = substr($packet, strlen($str));
return trim($str);
}
static function getChar(&$packet){
$char = $packet[0];
$packet = substr($packet, 1);
return $char;
}
function serverInfo($server) {
list($ip,$port) = explode(":", $server);
$fp = #fsockopen('udp://'.$ip, $port);
if($fp) {
stream_set_timeout($fp, 2);
fwrite($fp,"\xFF\xFF\xFF\xFFTSource Engine Query\0\r");
$temp = fread($fp, 4);
$status = socket_get_status($fp);
if($status['unread_bytes']>0) {
$temp = fread($fp, $status['unread_bytes']);
$version = ord(self::getChar($temp));
$array = array();
$array['status'] = "1";
if($version == 109) {
$array['ip'] = self::getString($temp);
$temp = substr($temp, 1);
$array['hostname'] = self::getString($temp);
$temp = substr($temp, 1);
$array['mapname'] = self::getString($temp);
$temp = substr($temp, 1);
self::getString($temp);
$temp = substr($temp, 1);
self::getString($temp);
$temp = substr($temp, 1);
$array['players'] = ord(self::getChar($temp));
$array['maxplayers'] = ord(self::getChar($temp));
} elseif($version == 73) {
self::getChar($temp);
$array['hostname'] = self::getString($temp);
$temp = substr($temp, 1);
$array['mapname'] = self::getString($temp);
$temp = substr($temp, 1);
self::getString($temp);
$temp = substr($temp, 1);
self::getString($temp);
$temp = substr($temp, 3);
$array['players'] = ord(self::getChar($temp));
$array['maxplayers'] = ord(self::getChar($temp));
}
} else {
$array['hostname'] = 'Server offline';
$array['mapname'] = '-';
$array['players'] = '0';
$array['maxplayers'] = '0';
$array['status'] = '0';
}
}
return $array;
}
}
?>
I have tried to query a server by writing this in the same file where the class is:
<?php
$newServer = serverInfo();
$date = $newServer->serverInfo("127.0.0.1:27015");
?>
But I can't get it to work. How can I query a server with udp, with this class and print the output ?

serverInfo belongs to the class, so you need to create a new instance of the class before you can use it.
$newServer = new Checkserver();
$date = $newServer->serverInfo("127.0.0.1:27015");

Related

PHP Script stopping without any error

For some reason i do not know why my script is stopping. It runs for about 20mins and then it stops without retrieving all the records. Im sure something is causing it to stop, but i don't know what. if it were out of memory then i suppose that error message would be thrown, but its not. This project is due next week. We are running this script by a cron job. Please help!
<?php
set_time_limit(0);
ini_set('max_execution_time', 0);
ini_set('memory_limit','4G');
$Num = $_GET['Num'];
$Token = $_GET['Token'];
if(strlen($Num) > 0){
$j = $Num;
$j = 1;
}
else{
$j = 0;
}
$e = 0;
$k = 0;
$g = 1;
$x=0;
$json = '';
$EmailIDs = array();
$leads = new bList();
$leads->listId = 2867;
$AllLeads = array();
$AllLeads = $leads->fields;
if(strlen($Token) > 0){
$NextPage = $Token;
$leads->nextPageToken = $NextPage;
}
RUN();
function RUN(){
global $leads;
global $k;
global $json;
global $Next;
if($k == 0){
AreUnsubscribed($leads->getData());
$k = 1;
$Next = $json[nextPageToken];
$NextPage = $Next;
}
else{
AreUnsubscribed($leads->getData());
$Next = $json[nextPageToken];
if($Next != null){
$NextPage = $Next;
unset($Next);
}
else{
$msg = 'Status = no NextPage' ;
$msg = wordwrap($msg,70);
mail("email#domain.com",'Status = no NextPage - Done',$msg);
}
}
unset($leads,$json,$Next);
}
class bList {
private $host = "Some URL";//CHANGE ME
private $clientId = "###############";//CHANGE ME
private $clientSecret = "###############";//CHANGE ME
public $listId;//id of list to retrieve leads from
public $fields = array("Time","SignUp","createdDate", etc....)
public $batchSize; //max 300 default 300
public $NextPage;
public $nextPageToken; //token returned from previous call for paging
public function getData(){
$url = $this->host . "/rest/v1/list/" . $this->listId . "/leads.json?access_token=" . $this->getToken();
if (isset($this->fields)){
$url = $url . "&fields=" . $this::csvString($this->fields);
}
if (isset($this->batchSize)){
$url = $url . "&batchSize=" . $this->batchSize;
}
if (isset($this->nextPageToken)){
$url = $url . "&nextPageToken=" . $this->nextPageToken;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = curl_exec($ch);
return $response;
}
private function getToken(){
$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = json_decode(curl_exec($ch));
curl_close($ch);
$token = $response->access_token;
return $token;
}
private static function csvString($fields){
$csvString = "";
$rr= implode(",",$fields);
$FF = str_replace(' ', '', $rr);
$csvString = $FF;
$csvString = rtrim($csvString,',');
return $csvString;
}
}
function AreUnsubscribed($G){
global $k;
global $AllLeads;
global $EmailIDs;
global $j;
global $e;
global $json;
global $Next;
$json = json_decode($G, true);
if($j == 0){
$EmailIDs[0] = $AllLeads;
$j=1;
}
if($e == 0){
for($n = 0; $n<=300; $n++){
$SORTING = $json['result'][$n];
if($SORTING == null){
break;
}
else{
array_push($EmailIDs, jj($SORTING));
}
unset($SORTING);
}
$e = 1;
$k =1;
RUN();
}
if($k == 1){
Part2($json);
}
unset($EmailIDs, $json, $AllLeads);
}
function Part2($json){
global $EmailIDs;
global $g;
for($n = 0; $n<=300; $n++, $g++){ // 300 records
$SORTING = $json['result'][$n];
if($SORTING == null){
break;
} else{
$EmailIDs[$g] = array_merge((array)$EmailIDs[$g], jj($SORTING));// position
}
unset($SORTING);
}
GG($EmailIDs);
unset($EmailIDs, $json);
}
function jj($kk){
$NewArray = array();
global $AllLeads;
global $e;
if($e == 0){
for($b = 0; $b<270; $b++){
if($kk[$AllLeads[$b]] == null){
array_push($NewArray, $kk[$AllLeads[$b]]);
}
else{
array_push($NewArray, '"'.$kk[$AllLeads[$b]].'"');
}
}
$kk = null;
} else{
for($b = 270; $b<540; $b++){
if($kk[$AllLeads[$b]] == null){
array_push($NewArray, $kk[$AllLeads[$b]]);
}else{
array_push($NewArray, '"'.$kk[$AllLeads[$b]].'"');
}
}
$kk = null;
}
unset($EmailIDs, $json, $kk);
return $NewArray;
unset($NewArray);
}
function GG($val){
$datetime = date('Y-m-d');
global $EmailIDs;
global $x;
global $e;
global $g;
global $Next;
global $j;
global $json;
$handle = fopen("New" . "-Export-" . $datetime . ".csv", "a");
foreach($val as $value){
fputcsv($handle, (array)$value);
}
fclose($handle);
unset($val);
//echo '<pre>';
//$vars = get_defined_vars();
//foreach($vars as $name=>$var)
//{
// echo '<strong>' . $name . '</strong>: ' . strlen(serialize($var)) . '<br/>';
//}
$EmailIDs = array();
$Next = $json[nextPageToken];
if($Next != null){
print_r('{"Number":"'. $j . '", "Token":"' . $Next .'"}');
unset($EmailIDs, $json);
unset($GLOBALS['leads']);
exit;
}else{
print_r('Finished');
}
}
?>

PHP Link Shortener

Zack here.. I've recently run into a spot of trouble with my URL Shortener.. Can you check the below code for errors? Thanks so much!
<?php
$db = new mysqli("localhost","pretzel_main","00WXE5fMWtaVd6Dd","pretzel");
function code($string_length = 3) {
$permissible_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$char_length = strlen($permissible_characters);
$random = '';
for ($i = 0; $i < $string_length; $i++) {
$random .= $permissible_characters[rand(0, $char_length - 1)];
}
return $random;
}
if (substr($_POST['long'], 0, 7) == http://) {
$url = $_POST['long'];
} elseif (substr($_POST['long'], 0, 8) == https://) {
$url = $_POST['long'];
} else {
$url = "http://".$_POST['long'];
}
$result = $db->prepare("INSERT INTO links VALUES('',?,?)");
$result->bind_param("ss",$url, $title);
$result->execute();
$title = $code();
?>
Good luck, and Thanks in advance!
- Zack
Try this :
<?php
$db = new mysqli("localhost","pretzel_main","00WXE5fMWtaVd6Dd","pretzel");
function code($string_length = 3) {
$permissible_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$char_length = strlen($permissible_characters);
$random = '';
for ($i = 0; $i < $string_length; $i++) {
$random .= $permissible_characters[rand(0, $char_length - 1)];
}
return $random;
}
if (substr($_POST['long'], 0, 7) == "http://") {
$url = $_POST['long'];
} elseif (substr($_POST['long'], 0, 8) == "https://") {
$url = $_POST['long'];
} else {
$url = "http://".$_POST['long'];
}
$result = $db->prepare("INSERT INTO links VALUES('ss','$url','$title')");
$result->execute();
$title = code(); // no need of $ sign here
?>

How to split and count sms messages from file in PHP

I have problem that my sms messages are imported with csv, then it is checked if number is ok and how long sms is. My problem is that if text messages is longer then 160 it still enters 1 in databse. But it should start counting, if it is less or equal than 160, it is 1 messages, if it is more than 160 but less or equal than 320 it is two messages and if it is more then it is 3 messages.
Page code is here:
<?php
$link = #mysql_connect("localhost", "admin", "") or die("Error: Database offline.");
mysql_select_db("database", $link);
mysql_query("SET NAMES 'utf8' ", $link);
function detect_type($smstext) {
$type = 0;
$dec_codes = array();
for ($i = 0; $i < strlen($smstext); $i++) {
$symbol = substr($smstext,$i,1);
if (!in_array(ord($symbol), $dec_codes)) { $type = 1; }
}
return $type;
}
$result_array = array();
$unic_numbers = array();
$fp = file_get_contents($_FILES['filename']['tmp_name']);
$fp = str_replace("\r\n", "\n", $fp);
$fp = str_replace("\r", "\n", $fp);
$fp = str_replace("\t", "", $fp);
$rows = explode("\n", $fp);
$imported_rows = 0;
$duplicate_rows = 0;
$error_rows = 0;
$long_rows = 0;
for ($i = 0; $i < sizeof($rows); $i++) {
$data = explode(";", $rows[$i]);
$data[1] = sms_formatNumbers($data[1]); // formating number
$userid = 78;
if(strlen($data[1]) > 9){
if($unic_numbers[$data[1]] != true ){ // unic number check
$unic_numbers[$data[1]] = true;
$imported_rows++;
$fullSMS = iconv("ISO-8859-1","UTF-8", trim($data[2])." ".trim($data[3])." ".trim($data[4]));
if(strlen($fullSMS) > 164){
$long_rows++;
}
if($_POST['action'] == 'send'){
// SMS TEXT
$smstext = str_replace("õ", "ò", $fullSMS);
$smstext = str_replace("Õ", "ò", $smstext);
$type = detect_type($smstext);
// servicegroup
$char2 = substr($data[1], 0, 2);
$char3 = substr($data[1], 0, 3);
$c1 = mysql_query("SELECT * FROM zone_info WHERE country_code = '".$char2."'", $link);
$c2 = mysql_query("SELECT * FROM zone_info WHERE country_code = '".$char3."'", $link);
if (mysql_num_rows($c1) == 1) {
$r = mysql_fetch_array($c1);
$price = $r['price'];
$z = mysql_query("SELECT * FROM zone WHERE id = ".$r['up']."", $link);
$zone = mysql_fetch_array($z);
$zone_id = $zone['id'];
$servicegroup = $zone['servicegroup'];
} else if (mysql_num_rows($c2) == 1) {
$r = mysql_fetch_array($c2);
$price = $r['price'];
$z = mysql_query("SELECT * FROM zone WHERE id = ".$r['up']."", $link);
$zone = mysql_fetch_array($z);
$zone_id = $zone['id'];
$servicegroup = $zone['servicegroup'];
}
require_once("../scripts/number.class.php");
$receiver = "00".$data[1];
$obj = new NumberClass($receiver);
$operator = $obj -> operator_code;
$country = $obj -> code;
$operator_name = $obj -> operator_name;
if(strlen($operator) > 0) {
$er = mysql_query("SELECT * FROM zone_exception WHERE country = ".$country." AND operator = ".$operator."", $link);
if (mysql_num_rows($er) == 1) {
$erand = mysql_fetch_array($er);
$price = $erand['price'];
$servicegroup = $erand['servicegroup'];
}
} else $operator_name = "-";
if ($operator_name == "-") { $servicegroup = $servicegroup; }
else {
if ($operator_name == " First Operator") $servicegroup = "90";
else if ($operator_name == "Second Operator") $servicegroup = "91";
else if ($operator_name == "Third Operator") $servicegroup = "92";
else $servicegroup = $servicegroup;
}
require_once("../core/init.mini.inc.php");
$servicegroup = UserBasedRerouting($receiver, $userid, $operator_name, $servicegroup);
$client_type ='corporative';
$sender = $data[0];
$zone_id = 11;
$client_sms_id = '0';
$client_want_report = '0';
$client_report_url = '';
$amount = 1;
$dt_delaysend = '1970-01-01 00:00:00';
$SMSsent = 0;
$SMStotal = 1;
$smstext_old = $smstext;
while($SMSsent < $SMStotal){
$sql = mysql_query("insert into sms_queue (user_id,client_type,dt_entered,sender,receiver,operator,smstext,sms_type,zone_id,client_sms_id,client_want_report,client_report_url,sms_price,amount,servicegroup,dt_delaysend) values ('$userid','$client_type','".date('Y-m-d H:i:s')."','$sender','$receiver','$operator_name','$smstext',0,'$zone_id','$client_sms_id','$client_want_report','$client_report_url','$price','$amount','$servicegroup','$dt_delaysend')", $link);
$SMSsent++;
}
}
}else{
$duplicate_rows ++;
}
}else{
$error_rows++;
}
}
$result_array['success'] = true;
$result_array['long_sms'] = $long_rows;
$result_array['send_sms'] = $imported_rows;
$result_array['error_sms'] = $error_rows;
$result_array['duplicate_sms'] = $duplicate_rows;
$result_array['action'] = $_POST['action'];
echo json_encode($result_array);
function sms_formatNumbers($number){
$number = (int)$number;
$start_code = (int)substr($number,0,4);
if($start_code < 3780 or $start_code == 3785 or $start_code > 3789){
return $number;
}else{
return '';
}
}
?>
Can someone help me out with that?
Thank you
Try
if(strlen($fullSMS) > 164){
$long_rows = ceil(strlen($fullSMS)/160);
}
instead of
if(strlen($fullSMS) > 164){
$long_rows++;
}

Splitting and combining files

I have sort of a "beginning" of a solution.
I wrote this function (Sorry about the spacings):
<?php
set_time_limit(0);
// Just to get the remote filesize
function checkFilesize($url, $user = "", $pw = ""){
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
if(!empty($user) && !empty($pw)){
$headers = array('Authorization: Basic ' . base64_encode("$user:$pw"));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$ok = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $head, $matches);
return isset($matches[1]) ? $matches[1] : "unknown";
}
// Split filesize to threads
function fileCutter($filesize,$threads){
$calc = round($filesize / count($threads));
$count = 0;
foreach($threads as $thread){
$rounds[$count] = $calc;
$count++;
}
$count = 0;
foreach($rounds as $round){
$set = $count + 1;
if($count == 0){
$from = 0;
} else {
$from = ($round * $count);
}
$cal = ($round * $set);
$final[$count] = array('from'=>$from,'to'=>$cal);
$count++;
}
// Correct the "Rounded" result
$end = end($final);
$differance = $filesize - $end['to'];
if (strpos($differance,'-') !== false) {} else {$add = '+';}
$end_result = ($end['to'].$add.$differance);
$value=eval("return ($end_result);");
$end_id = end(array_keys($final));
$final[$end_id]['to'] = $value;
// Return the complete array with the corrected result
return $final;
}
$threads = array(
0=>'test',
1=>'test',
2=>'test',
3=>'test',
4=>'test',
5=>'test',
);
$file = 'http://www.example.com/file.zip';
$filesize = checkFilesize($file);
$cuts = fileCutter($filesize,$threads);
print_r($cuts);
?>
(Again, Sorry. :) )
It gives "directions" to split the file in specific bytes.
I've tried to do something like so:
foreach($cuts as $cut){
$start = $cut['from'];
$finish = $cut['to'];
$f = fopen($file, "rb");
fseek($f, $start, SEEK_SET);
while(!(ftell($f) > $finish)){
$data = fgetc($f);
}
fclose($f);
But it's going to a endless loop.
What is the problem? or, is there another solution in PHP to split and combine files?
Instead of reading the file manually and byte-wise you could just use file_get_contents() with the according parameters $offset and $maxlen:
// $incp $ctx $offset $maxlen
$data = file_get_contents($fn, FALSE, NULL, $start, $finish-$start);
That'll do the seeking and cutting for you.

Windows live api get email contact vs email hash

I am trying to get email contact from hotmail with php or javascript.
I have read that windows live api return only hash of the email contact, and it is proved by the code example:
http://isdk.dev.live.com/ISDK.aspx
But some web site like facebook can retrieve the plaintext of email contact from hotmail. How it is possible?
Thanks a lot.
Simply change the scope to:
wl.basic,wl.contacts_emails
You can test this code (dont forget to [SECRET API KEY] with your api key) :
<?php
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
function unfucked_base_convert ($numstring, $frombase, $tobase) {
$chars = "0123456789abcdefghijklmnopqrstuvwxyz";
$tostring = substr($chars, 0, $tobase);
$length = strlen($numstring);
$result = '';
for ($i = 0; $i < $length; $i++) {
$number[$i] = strpos($chars, $numstring{$i});
}
do {
$divide = 0;
$newlen = 0;
for ($i = 0; $i < $length; $i++) {
$divide = $divide * $frombase + $number[$i];
if ($divide >= $tobase) {
$number[$newlen++] = (int)($divide / $tobase);
$divide = $divide % $tobase;
} elseif ($newlen > 0) {
$number[$newlen++] = 0;
}
}
$length = $newlen;
$result = $tostring{$divide} . $result;
}
while ($newlen != 0);
return $result;
}
function hexaTo64SignedDecimal($hexa) {
$bin = unfucked_base_convert($hexa, 16, 2);
if(64 === strlen($bin) and 1 == $bin[0]) {
$inv_bin = strtr($bin, '01', '10');
$i = 63;
while (0 !== $i) {
if(0 == $inv_bin[$i]) {
$inv_bin[$i] = 1;
$i = 0;
}
else {
$inv_bin[$i] = 0;
$i–;
}
}
return '-'.unfucked_base_convert($inv_bin, 2, 10);
}
else {
return unfucked_base_convert($hexa, 16, 10);
}
}
function email2nickname($email) {
$output = str_replace(array('.', '-', '_', ',', ':'), ' ', substr($email, 0, strpos($email, '#')));
$output = str_replace(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), '', $output);
$output = ucwords($output);
return $output;
}
function grabLiveContacts($token) {
if(!empty($token)) {
$HOTMAIL_CLIENT_SECRET='[SECRET API KEY]';
parse_str(urldecode($token), $parsedToken);
$token = base64_decode($parsedToken['delt']);
$cryptkey = substr( hash('sha256', 'ENCRYPTION' . $HOTMAIL_CLIENT_SECRET, true), 0, 16);
parse_str(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $cryptkey, substr($token, 16), MCRYPT_MODE_CBC, substr($token, 0, 16)),$result);
$intlid = hexaTo64SignedDecimal($parsedToken['lid']);
$url = 'https://livecontacts.services.live.com/users/#C#'.$intlid.'/rest/livecontacts';
$headers = array(
'Authorization: DelegatedToken dt="'.$parsedToken['delt'].'"'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
$xml = new SimpleXMLElement($data);
$grab = array();
$grab['user'] = array(
'name'=>trim(strval($xml->Owner->Profiles->Personal->DisplayName)),
'email'=>trim(strval($xml->Owner->WindowsLiveID)), 'token'=>$token
);
$grab['contacts'] = array();
foreach ($xml->Contacts->Contact as $entry) {
$name = trim(strval($entry->Profiles->Personal->DisplayName));
if (isset($entry->Emails->Email->Address)){
$email = trim(strval($entry->Emails->Email->Address));
if(!empty($email)) {
if(empty($name)) {
$name = trim(strval($entry->Profiles->Personal->FirstName));
$name .= ' '.trim(strval($entry->Profiles->Personal->LastName));
$name = trim($name);
}
if(empty($name)) {
$name = trim(strval($entry->Profiles->Personal->NickName));
}
if(empty($name) or isEmail($name)) {
$name = email2nickname($email);
}
$grab['contacts'][] = array('name'=>$name, 'email'=>$email);
}
}
}
return $grab;
}
else return false;
}
if(isset($_POST['ConsentToken'])) {
$grab = grabLiveContacts($_POST['ConsentToken']);
foreach ($grab['contacts'] as $contact){
if (isset($contact['email'])){
echo($contact['email']."</br>");
}
}
}
?>

Categories