Bcmath adding decimal places randomly - php

I have a PHP function I got from the web that uses bcmath functions:
function SteamID64to32($steamId64) {
$iServer = "1";
if(bcmod($steamId64, "2") == "0") {
$iServer = "0";
}
$steamId64 = bcsub($steamId64,$iServer);
if(bccomp("76561197960265728",$steamId64) == -1) {
$steamId64 = bcsub($steamId64,"76561197960265728");
}
$steamId64 = bcdiv($steamId64, "2");
return ("STEAM_0:" . $iServer . ":" . $steamId64);
}
For any valid input the function will at random times add ".0000000000" to the output.
Ex:
$input = 76561198014791430;
SteamID64to32($input);
//result for each run
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851.0000000000
This was tested on 2 different nginx servers running php-fpm.
Please help me understand what is wrong here. Thanks

The answer provided by JD doesn't account for all possible STEAM_ ID types, namely, anything that is in the STEAM_0:1 range. This block of code will:
<?php
function Steam64ToSteam32($Steam64ID)
{
$offset = $Steam64ID - 76561197960265728;
$id = ($offset / 2);
if($offset % 2 != 0)
{
$Steam32ID = 'STEAM_0:1:' . bcsub($id, '0.5');
}
else
{
$Steam32ID = "STEAM_0:0:" . $id;
}
return $Steam32ID;
}
echo Steam64ToSteam32(76561197960435530);
echo "<br/>";
echo Steam64ToSteam32(76561197990323733);
echo "<br/>";
echo Steam64ToSteam32(76561198014791430);
?>
This outputs
STEAM_0:0:84901
STEAM_0:1:15029002
STEAM_0:0:27262851
The first one is for a Valve employee and someone who's had a Steam account since 2003 (hence the low ID), the second is a random profile I found on VACBanned which had an ID in the STEAM_0:1 range. The third is the ID you provided in your sample code.

I found this: SteamProfile
/**
* This file is part of SteamProfile.
*
* Written by Nico Bergemann <barracuda415#yahoo.de>
* Copyright 2009 Nico Bergemann
*
* SteamProfile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SteamProfile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SteamProfile. If not, see <http://www.gnu.org/licenses/>.
*/
// thanks to voogru for the id transformation algorithm (http://forums.alliedmods.net/showthread.php?t=60899)
class SteamID {
private $sSteamID = '';
private $sSteamComID = '';
const STEAMID64_BASE = '76561197960265728';
public function __construct($sID) {
// make sure the bcmath extension is loaded
if(!extension_loaded('bcmath')) {
throw new RuntimeException("BCMath extension required");
}
if($this->isValidSteamID($sID)) {
$this->sSteamID = $sID;
$this->sSteamComID = $this->convertToSteamComID($sID);
} elseif($this->isValidComID($sID)) {
$this->sSteamID = $this->convertToSteamID($sID);
$this->sSteamComID = $sID;
} else {
$this->sSteamID = '';
$this->sSteamComID = '';
}
}
public function getSteamID() {
return $this->sSteamID;
}
public function getSteamComID() {
return $this->sSteamComID;
}
public function isValid() {
return $this->sSteamID != '';
}
private function isValidSteamID($sSteamID) {
return preg_match('/^(STEAM_)?[0-5]:[0-9]:\d+$/i', $sSteamID);
}
private function isValidComID($sSteamComID) {
// anything else than a number is invalid
// (is_numeric() doesn't work for 64 bit integers)
if(!preg_match('/^\d+$/i', $sSteamComID)) {
return false;
}
// the community id must be bigger than STEAMID64_BASE
if(bccomp(self::STEAMID64_BASE, $sSteamComID) == 1) {
return false;
}
// TODO: Upper limit?
return true;
}
private function convertToSteamComID($sSteamID) {
$aTMP = explode(':', $sSteamID);
$sServer = $aTMP[1];
$sAuth = $aTMP[2];
if((count($aTMP) == 3) && $sAuth != '0' && is_numeric($sServer) && is_numeric($sAuth)) {
$sComID = bcmul($sAuth, "2"); // multipy Auth-ID with 2
$sComID = bcadd($sComID, $sServer); // add Server-ID
$sComID = bcadd($sComID, self::STEAMID64_BASE); // add this odd long number
// It seems that PHP appends ".0000000000" at the end sometimes.
// I can't find a reason for this, so I'll take the dirty way...
$sComID = str_replace('.0000000000', '', $sComID);
return $sComID;
} else {
throw new RuntimeException("Unable to convert Steam-ID");
}
}
private function convertToSteamID($sSteamComID) {
$sServer = bcmod($sSteamComID, '2') == '0' ? '0' : '1';
$sCommID = bcsub($sSteamComID, $sServer);
$sCommID = bcsub($sCommID, self::STEAMID64_BASE);
$sAuth = bcdiv($sCommID, '2');
return "STEAM_0:$sServer:$sAuth";
}
}

Related

Can't get actual filesize

I'm working on a class whose purpose is to restrict users to making only 10 requests within any 30 second period. It utilizes a file to maintain IP addresses, last request time. and the number of tries they've made. The problem is that, no matter what I try, I can't get the filesize. I've tried using clearstatcache(), and I've tried using a function I found in the comments on the filesize() page of the PHP manual.
Here's the code, in it's current debugging state.
// Makes sure user can only try to generate a coupon x number of times over x amount of seconds
class IpChecker{
const WAIT_TIME = 30; //seconds until user can try again
const MAX_TRIES = 10; // maximum tries
const COUPON_IP = 0;
const COUPON_TIME = 1;
const COUPON_TRIES = 2;
private $ip_data;
private $path;
private $fh;
private $safe;
public function __construct(){
clearstatcache();
$this->path = realpath(dirname(__FILE__))."/ips/.ips";
$this->fh = fopen($this->path,'w+');
$this->filesize = $this->realfilesize($this->fh);
echo "fs: ".$this->filesize; exit;
$this->getIPs();
$this->checkIP();
$this->logRequest();
fclose($this->fh);
$this->safe || die(json_encode("You have exhausted all available tries. Please try again later."));
}
private function logRequest(){
$str = "";
foreach($this->ip_data as $data){
foreach($data as $col){
if(self::WAIT_TIME < (time() - $col[self::COUPON_TIME])) $str .= $col."\t";
}
$str = rtrim($str, '\t');
$str .= "\n";
}
$str = rtrim($str, '\n');
try{
$fw = fwrite($this->fh, $str) || die(json_encode("Unable to check IP"));
}catch(Exception $e){
die(json_encode($e));
}
}
private function checkIP(){
$IP = $_SERVER['REMOTE_ADDR'];
$TIME = time();
$safe = true;
$user_logged = false;
echo "<pre>"; var_dump($this->ip_data); exit;
foreach($this->ip_data as $key=>$data){
echo "<prE>"; var_dump($data); exit;
// if($data[$key][self::COUPON_IP] == $IP){
// $user_logged = true;
// if(
// (($TIME - $data[$key][self::COUPON_TIME]) < self::WAIT_TIME) ||
// (self::MAX_TRIES >= $data[$key][self::COUPON_TRIES])
// ) $safe = false;
// $this->ip_data[$key][self::COUPON_TRIES] = $this->ip_data[$key][self::COUPON_TRIES]+1;
// $this->ip_data[$key][self::COUPON_TIME] = $TIME;
// }
}
if(!$user_logged){
die("user not logged");
$this->ip_data[] = array(
self::COUPON_IP => $IP,
self::COUPON_TIME => $TIME,
self::COUPON_TRIES => 1
);
}
$this->safe = $safe;
}
private function getIPs(){
$IP_DATA = array();
echo file_get_contents($this->path); exit;
// this always returns 0.
$size = filesize($this->path);
echo "filesize: ".$size; exit;
if($size){
$IPs = fread($this->fh,$size);
$IP_ARR = explode("\n",$IPs);
foreach($IP_ARR as $line) $IP_DATA[] = explode("\t",$line);
}
$this->ip_data = $IP_DATA;
}
// Copied from the comments in the PHP Manual for filesize()
public function realfilesize($fp) {
$return = false;
if (is_resource($fp)) {
if (PHP_INT_SIZE < 8) {
// 32bit
if (0 === fseek($fp, 0, SEEK_END)) {
$return = 0.0;
$step = 0x7FFFFFFF;
while ($step > 0) {
if (0 === fseek($fp, - $step, SEEK_CUR)) {
$return += floatval($step);
} else {
$step >>= 1;
}
}
}
} elseif (0 === fseek($fp, 0, SEEK_END)) {
// 64bit
$return = ftell($fp);
}
}
return $return;
}
}
How can I get the real filesize? I'm on PHP 5.2.
I wasn;t able to figure out what was wrong with my code, if anythign, but I worked around it like this:
/**
* Makes sure user can only access a given page
* x number of times over x amount of seconds.
* If multiple instances of this class are used, the $namespace
* properties for each should be unique.
* Default wait time is 90 seconds while default request limit
* is 10 tries.
*
* -+ Usage +-
* Just create the object with any parameters, no need to assign,
* just make sure it's initialized at the top of the page:
* new RequestThrottler;
*
* -+- Parameters -+-
* null RequestThrottler ( [ string $namespace [, int $WaitTime [, int $MaxTries ] ] ] )
*/
class RequestThrottler{
// settings
private static $WAIT_TIME; // seconds until count expires
private static $MAX_TRIES; // maximum tries
// used to keep session variables unique
// in the event that this class is used in multiple places.
private $namespace;
// for debugging
const DBG = false;
// array index constants
const _TIME = 0;
const _TRIES = 1;
// defines whether or not access is permitted
private $safe;
// seconds until reset
private $secs;
/**
* -+- Constructor -+-
* #param String $namespace - A unique prefix for SESSION data
* #param Int $WaitTime - Total seconds before user can try again
* #param Int $MaxTries - Total tries user can make until their request is denied
*/
public function __construct($namespace='Throttler', $WaitTime=90, $MaxTries=10){
// make sure a session is available
if(!headers_sent() && !isset($_SESSION)) session_start();
if(!isset($_SESSION)) die(json_encode("No session available"));
// save settings
$this->namespace = $namespace;
self::$MAX_TRIES = $MaxTries;
self::$WAIT_TIME = $WaitTime;
// do the footwork
$this->checkHistory();
// if set to debug mode, print a short helpful string
if(self::DBG) die(json_encode(
"You are ".($this->safe ? 'SAFE' : 'NOT SAFE')."! "
. "This is try number {$_SESSION[$this->namespace.'_ATTEMPTS'][self::_TRIES]} of ".self::$MAX_TRIES.". "
. $this->secs." seconds since last attempt. "
. (self::$WAIT_TIME - $this->secs)." seconds until reset."
));
// if not safe, kill the script, show a message
$this->safe || die(json_encode("You're going too fast. Please try again in ".(self::$WAIT_TIME - $this->secs)." seconds."));
}
/**
* -+- checkHistory -+-
* Does the footwork to determine whether
* or not to throttle the current user/request.
*/
private function checkHistory(){
$TIME = time();
$safe = true;
// make sure session is iniitialized
if( !isset($_SESSION[$this->namespace.'_ATTEMPTS']) ||
!isset($_SESSION[$this->namespace.'_ATTEMPTS'][self::_TRIES]) ||
!isset($_SESSION[$this->namespace.'_ATTEMPTS'][self::_TIME]) )
$_SESSION[$this->namespace.'_ATTEMPTS'] = array(
self::_TIME =>$TIME,
self::_TRIES => 1
);
else $_SESSION[$this->namespace.'_ATTEMPTS'][self::_TRIES] =
$_SESSION[$this->namespace.'_ATTEMPTS'][self::_TRIES]+1;
// get seconds since last attempt
$secondSinceLastAttempt = $TIME - $_SESSION[$this->namespace.'_ATTEMPTS'][self::_TIME];
// reset the counter if the wait time has expired
if($secondSinceLastAttempt > self::$WAIT_TIME){
$_SESSION[$this->namespace.'_ATTEMPTS'][self::_TIME] = $TIME;
$_SESSION[$this->namespace.'_ATTEMPTS'][self::_TRIES] = 1;
$secondSinceLastAttempt = 0;
}
// finally, determine if we're safe
if($_SESSION[$this->namespace.'_ATTEMPTS'][self::_TRIES] >= self::$MAX_TRIES) $safe=false;
// log this for debugging
$this->secs = $secondSinceLastAttempt;
// save the "safe" flag
$this->safe = $safe;
}
}

Joomla Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM [duplicate]

This question already has answers here:
PHP expects T_PAAMAYIM_NEKUDOTAYIM?
(11 answers)
Closed 9 years ago.
I have building a web site but i have a error code and i couldnt fould a fix it
Error
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /home/eneskura/public_html/administrator/components/com_tz_portfolio/helpers/tz_portfolio.php on line 42
line 42-
$class::addEntry(JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup');
how i can i fix it?
Site: eneskuray.com php 5.2.17 litespeed
full php
<?php
// No direct access
defined('_JEXEC') or die;
class TZ_PortfolioHelper
{
public static $extension = 'com_content';
/**
* Configure the Linkbar.
*
* #param string $vName The name of the active view.
*
* #return void
* #since 1.6
*/
public static function addSubmenu($vName)
{
$class = 'JHtmlSidebar';
if(!COM_TZ_PORTFOLIO_JVERSION_COMPARE){
$class = 'JSubMenuHelper';
}
$class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup');
$class::addEntry(
JText::_('COM_TZ_PORTFOLIO_SUBMENU_FIELDS'),
'index.php?option=com_tz_portfolio&view=fields',
$vName == 'fields'
);
$class::addEntry(
JText::_('COM_TZ_PORTFOLIO_SUBMENU_CATEGORIES'),
'index.php?option=com_tz_portfolio&view=categories',
$vName == 'categories');
$class::addEntry(
JText::_('COM_TZ_PORTFOLIO_SUBMENU_ARTICLES'),
'index.php?option=com_tz_portfolio&view=articles',
$vName == 'articles'
);
$class::addEntry(
JText::_('COM_TZ_PORTFOLIO_SUBMENU_FEATURED_ARTICLES'),
'index.php?option=com_tz_portfolio&view=featured',
$vName == 'featured'
);
$class::addEntry(
JText::_('COM_TZ_PORTFOLIO_SUBMENU_TAGS'),
'index.php?option=com_tz_portfolio&view=tags',
$vName == 'tags');
$class::addEntry(
JText::_('COM_TZ_PORTFOLIO_SUBMENU_USERS'),
'index.php?option=com_tz_portfolio&view=users',
$vName == 'users');
}
/**
* Gets a list of the actions that can be performed.
*
* #param int The category ID.
* #param int The article ID.
*
* #return JObject
* #since 1.6
*/
public static function getActions($categoryId = 0, $articleId = 0)
{
$user = JFactory::getUser();
$result = new JObject;
if (empty($articleId) && empty($categoryId)) {
$assetName = 'com_tz_portfolio';
}
elseif (empty($articleId)) {
$assetName = 'com_tz_portfolio.category.'.(int) $categoryId;
}
else {
$assetName = 'com_tz_portfolio.article.'.(int) $articleId;
}
$actions = array(
'core.admin', 'core.manage', 'core.create', 'core.edit', 'core.edit.own', 'core.edit.state', 'core.delete'
);
foreach ($actions as $action) {
$result->set($action, $user->authorise($action, $assetName));
}
return $result;
}
/**
* Applies the content tag filters to arbitrary text as per settings for current user group
* #param text The string to filter
* #return string The filtered string
*/
public static function filterText($text)
{
// Filter settings
$config = JComponentHelper::getParams('com_config');
$user = JFactory::getUser();
$userGroups = JAccess::getGroupsByUser($user->get('id'));
$filters = $config->get('filters');
$blackListTags = array();
$blackListAttributes = array();
$customListTags = array();
$customListAttributes = array();
$whiteListTags = array();
$whiteListAttributes = array();
$noHtml = false;
$whiteList = false;
$blackList = false;
$customList = false;
$unfiltered = false;
// Cycle through each of the user groups the user is in.
// Remember they are included in the Public group as well.
foreach ($userGroups as $groupId)
{
// May have added a group but not saved the filters.
if (!isset($filters->$groupId)) {
continue;
}
// Each group the user is in could have different filtering properties.
$filterData = $filters->$groupId;
$filterType = strtoupper($filterData->filter_type);
if ($filterType == 'NH') {
// Maximum HTML filtering.
$noHtml = true;
}
elseif ($filterType == 'NONE') {
// No HTML filtering.
$unfiltered = true;
}
else {
// Black, white or custom list.
// Preprocess the tags and attributes.
$tags = explode(',', $filterData->filter_tags);
$attributes = explode(',', $filterData->filter_attributes);
$tempTags = array();
$tempAttributes = array();
foreach ($tags as $tag)
{
$tag = trim($tag);
if ($tag) {
$tempTags[] = $tag;
}
}
foreach ($attributes as $attribute)
{
$attribute = trim($attribute);
if ($attribute) {
$tempAttributes[] = $attribute;
}
}
// Collect the black or white list tags and attributes.
// Each lists is cummulative.
if ($filterType == 'BL') {
$blackList = true;
$blackListTags = array_merge($blackListTags, $tempTags);
$blackListAttributes = array_merge($blackListAttributes, $tempAttributes);
}
elseif ($filterType == 'CBL') {
// Only set to true if Tags or Attributes were added
if ($tempTags || $tempAttributes) {
$customList = true;
$customListTags = array_merge($customListTags, $tempTags);
$customListAttributes = array_merge($customListAttributes, $tempAttributes);
}
}
elseif ($filterType == 'WL') {
$whiteList = true;
$whiteListTags = array_merge($whiteListTags, $tempTags);
$whiteListAttributes = array_merge($whiteListAttributes, $tempAttributes);
}
}
}
// Remove duplicates before processing (because the black list uses both sets of arrays).
$blackListTags = array_unique($blackListTags);
$blackListAttributes = array_unique($blackListAttributes);
$customListTags = array_unique($customListTags);
$customListAttributes = array_unique($customListAttributes);
$whiteListTags = array_unique($whiteListTags);
$whiteListAttributes = array_unique($whiteListAttributes);
// Unfiltered assumes first priority.
if ($unfiltered) {
// Dont apply filtering.
}
else {
// Custom blacklist precedes Default blacklist
if ($customList) {
$filter = JFilterInput::getInstance(array(), array(), 1, 1);
// Override filter's default blacklist tags and attributes
if ($customListTags) {
$filter->tagBlacklist = $customListTags;
}
if ($customListAttributes) {
$filter->attrBlacklist = $customListAttributes;
}
}
// Black lists take third precedence.
elseif ($blackList) {
// Remove the white-listed attributes from the black-list.
$filter = JFilterInput::getInstance(
array_diff($blackListTags, $whiteListTags), // blacklisted tags
array_diff($blackListAttributes, $whiteListAttributes), // blacklisted attributes
1, // blacklist tags
1 // blacklist attributes
);
// Remove white listed tags from filter's default blacklist
if ($whiteListTags) {
$filter->tagBlacklist = array_diff($filter->tagBlacklist, $whiteListTags);
}
// Remove white listed attributes from filter's default blacklist
if ($whiteListAttributes) {
$filter->attrBlacklist = array_diff($filter->attrBlacklist);
}
}
// White lists take fourth precedence.
elseif ($whiteList) {
$filter = JFilterInput::getInstance($whiteListTags, $whiteListAttributes, 0, 0, 0); // turn off xss auto clean
}
// No HTML takes last place.
else {
$filter = JFilterInput::getInstance();
}
$text = $filter->clean($text, 'html');
}
return $text;
}
}
ATTETION : some texts deleted for privacy.
The scope resolution operator (::) can only be used on a class referenced using a variable from PHP 5.3 -- you're using 5.2.
You'd have to do JHtmlSidebar::addEntry or JSubMenuHelper::addEntry; you can't do $class::addEntry.
JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS') is not calling a method. It should be:
JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS')
See JText.
T_PAAMAYIM_NEKUDOTAYIM refers to the two colons in a row like this ::. Looking at your code sample:
$class::addEntry( JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup');
I believe the issue is with JText::(. As per Joomla documentation that should be formatted with an underscore so it is JText::_( so your code would be:
$class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup');
Not 100% clear on Joomla internals, but that underscore (_) is actually a function/method of some sort within the JText class. So when you were calling it as JText::( PHP choked because it had no idea what you were trying to do with JText. By adding that underscore (_), it will now actually call a function within a class & do what it has to do.

Not displaying the error message in tree login page

I have a tree login page as my first page in a survey. The issue is that , if the user does not select any node and clicks on the next button he is redirected to the same page . The problem is that he does not get any error message .
I want the user to get an error message 'Please select a group'
Please look into the below code which does this action
(P.S check the Display() function )
Correct me where I am going wrong
<?php
/**
* File: TreeLoginWidget.php
*
*
* Purpose: display tree page.
*
* Dependents: none
*
* Dependencies: SurveyItem
*
* Classes:
* 1. PinWidget
*
* Interface/public functions:
*
* Notes: ???
*
* Todo: none
*
**/
class DisplayTreeLoginWidget extends DisplayItem
{
function DisplayTreeLoginWidget(& $sourceObj)
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$this->node = 0;
$surveywidget = getDataFromSession("surveywidget");
DisplayItem::DisplayItem();
$_SESSION["profile"]["rootNode"]=0;
if($_GET["nodeId"]) {
setDataToSession("postVar","");
}
$this->sourceObj =& $sourceObj;
}
/**
* Purpose: display pin page label text
*
* Input Params: none
*
* Output Params: none
*
* Return Value: none
*
* Notes:
*/
function display()
{
global $skin_path,$skin,$path;
setDataToSession("skipPage", 0);
setDataToSession('HideSave&Resume',0);
$currentPageNumber = currentPageNumber();
if($currentPageNumber!=1) {
setDataToSession('HideSave&Resume',1);
}
echo "<script type=\"text/javascript\" src=\"".$path."../lib/java/commonFuncs.js\"></script>";
// include the header
include_once ("../lib/include/path.inc.php");
include_once ("../lib/include/jshelper.php");
include_once("display/tree.inc.php");
include_once("display/commonTreeLayout.php");
include_once ("../lib/include/commonTreeCode.php");
setUpTreeAppProperty();
$postVar = getDataFromSession("postVar");
if(is_array($postVar)) {
$_POST = $postVar;
}
if($this->sourceObj->displayType == "expanded") {
$postVar["Expand_All"] = "Expand All";
$this->sourceObj->displayType = "";
}
if($this->sourceObj->levelShowing != "") {
setDataToSession("levelShowing",$this->sourceObj->levelShowing);
}
setUpElist($postVar, $_GET);
$verifiedStartingNode = getTreeStartingNode();
/** $matchedIdArr contains matched nodeIds or empty if no matches found/no search performed */
$matchedIdArr = doSearch($verifiedStartingNode, $postVar);
$eList = getEList();
$Tree = new TreeWithRadioButton($this->sourceObj);
$Tree->reSetupElist();
$startingNode = &$Tree->nodesArr[$verifiedStartingNode];
echo "<div class=\"body2 IE6trans\">";
displaySearchTable();
if(!$postVar["searchSubmit"]) {
$matchedIdArr = array(getDataFromSession("data,node_id"));
}
displayTree('Search Organization Structure', '', '', $startingNode, $eList, $matchedIdArr, $maxDepth, get_path_prefix(),$this->sourceObj->_errorMsg,$this->sourceObj->_prompt);
echo "<script type=\"text/javascript\">";
echo "$(document).ready(function () { $('input[name=\"wildText\"]').keyup(function(event){ if(event.keyCode == 13){ $('input[name=\"searchSubmit\"]').click(); } }); });";
echo "</script>";
echo "</div>";
}
/**
* Purpose: storing error message to _errorMsg
*
* Input Params: none
*
* Output Params: none
*
* Return Value: Boolean - true or false
*
* Notes:
*/
function validate()
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$surveywidget = getDataFromSession('surveywidget');
$this->getPostData();
$this->sourceObj->_errorMsg = "";
$lastVisitedWidgetOid_Tree = getDataFromSession("lastVisitedWidgetOid_Tree");
setDataToSession("lastVisitedWidgetOid" , $lastVisitedWidgetOid_Tree);
setLoginUserLanguage($this->node);
$operations = ((strcmp($this->operation,getText2($surveywidget->saveResumeButtonText)) == 0)||
(strcmp($this->operation,getText2($surveywidget->backButtonText)) == 0)||
(strcmp($this->operation,getText2($surveywidget->nextButtonText)) == 0));
if(($operations) && ($this->node != "")) {
setDataToSession("data,node_id",$this->node);
// used to track the node id assigned to this pin when more than one login is used
setDataToSession("tree_login,node_id",$this->node);
setDataToSession("tree_login_before_saveresume,node_id",$this->node);
//Custom -
$oids = getListOfOidAndNodes(Array($this->node));
$_SESSION["conditionNodeList"] = $oids;
//End Custom
if(!getDataFromSession('multiLoginIndex')) {
$multiLoginIndex = 1;
} else {
$multiLoginIndex = getDataFromSession('multiLoginIndex');
}
$multiLoginIndex++;
setDataToSession("multiLoginIndex",$multiLoginIndex);
$this->sourceObj->_errorMsg = "";
} else if(($operations) && ($this->node == "")){
$this->sourceObj->_errorMsg = "Please select a group";
return false;
} else {
return false;
}
if($this->node == "") {
$this->node = 0;
}
// user click save&resume before visiting login page, we are redirecting to login page, That time user enter invalid node_id we are mainting save&resume flag to 1 for displaying submitbutton(it act like as save&resume)
if(getDataFromSession('save&resumeflag') == 1) {
setDataToSession('save&resumeloginpage',1);
}
return true;
}
/**
* Purpose: get post data
*
* Input Params: none
*
* Output Params: none
*
* Return Value: none
*
* Notes:
*/
function getPostData()
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$postVar["exactText"] = (empty($_REQUEST["exactText"])==1) ?"" :stripslashes($_REQUEST["exactText"]);
$postVar["wildText"] = (empty($_REQUEST["wildText"])==1) ?"" :stripslashes($_REQUEST["wildText"]);
$postVar["searchSubmit"] = (empty($_REQUEST["searchSubmit"])==1) ?"" :$_REQUEST["searchSubmit"];
$postVar["Collapse_All"] = (empty($_REQUEST["Collapse_All"])==1) ?"" :$_REQUEST["Collapse_All"];
$postVar["idText"] = (empty($_REQUEST["idText"])==1) ?"" :$_REQUEST["idText"];
$postVar["node"] = (empty($_REQUEST["node"])==1) ?"" :$_REQUEST["node"];
$this->node = ($_REQUEST["node"] == "") ?"" :$_REQUEST["node"];
$this->operation = (empty($_REQUEST["Operation"])==1) ?"" :$_REQUEST["Operation"];
if($postVar["Collapse_All"]) {
$postVar["wildText"] = "";
}
setDataToSession('postVar',$postVar);
setDataToSession('Operation',$this->operation);
setDataToSession('node',$this->node);
}
}
?>
Your code is long, and I didn't read it.
But the typical way to do this is to pass a url parameter, and if the parameter exists print it out as a message.

PHP pagination - problem displaying correct content on additional pages

I found this awesome code online to help with pagination, and it's working well, the only problem is: each page displays the same 4 rows.
Any ideas will be much appreciated
<?php
//Include the PS_Pagination class
include('includes/ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect("localhost", "root", "root");
mysql_select_db('database',$conn);
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,4,5);
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
$a=0;
while ($a < $num) {
$id=mysql_result($result,$a,"id");
$title=mysql_result($result,$a,"title");
$strategies=mysql_result($result,$a,"strategies");
$client=mysql_result($result,$a,"client");
$copy=mysql_result($result,$a,"copy");
$thumbmedia=mysql_result($result,$a,"thumbmedia");
$niche=mysql_result($result,$a,"niche");
echo '<div class="container"><p class="subheadred">'.$title.'</p></div>';
echo '<div class="containerstudy"><div class="column1"><p class="subheadsmall">Strategies</p><p class="sidebarred">'.$strategies.'</p>';
echo '<p class="subheadsmall">Client</p><p class="sidebargrey">'.$client.'</p></div>';
echo '<div class="column2"><p class="bodygrey">'.substr($copy, 0, 300).'...more</p></div>';
echo '<div class="column3"><img src="images/'.$thumbmedia.'" height="160" /></div></div>';
$a++;
}
}
//Display the navigation
echo $pager->renderNav();
?>
This is the included file:
<?php
/**
* PHPSense Pagination Class
*
* PHP tutorials and scripts
*
* #package PHPSense
* #author Jatinder Singh Thind
* #copyright Copyright (c) 2006, Jatinder Singh Thind
* #link http://www.phpsense.com
*/
// ------------------------------------------------------------------------
class PS_Pagination {
var $php_self;
var $rows_per_page; //Number of records to display per page
var $total_rows; //Total number of rows returned by the query
var $links_per_page; //Number of links to display per page
var $sql;
var $debug = false;
var $conn;
var $page;
var $max_pages;
var $offset;
/**
* Constructor
*
* #param resource $connection Mysql connection link
* #param string $sql SQL query to paginate. Example : SELECT * FROM users
* #param integer $rows_per_page Number of records to display per page. Defaults to 10
* #param integer $links_per_page Number of links to display per page. Defaults to 5
*/
function PS_Pagination($connection, $sql, $rows_per_page = 1, $links_per_page = 5) {
$this->conn = $connection;
$this->sql = $sql;
$this->rows_per_page = $rows_per_page;
$this->links_per_page = $links_per_page;
$this->php_self = htmlspecialchars($_SERVER['PHP_SELF']);
if(isset($_GET['page'])) {
$this->page = intval($_GET['page']);
}
}
/**
* Executes the SQL query and initializes internal variables
*
* #access public
* #return resource
*/
function paginate() {
if(!$this->conn) {
if($this->debug) echo "MySQL connection missing<br />";
return false;
}
$all_rs = #mysql_query($this->sql);
if(!$all_rs) {
if($this->debug) echo "SQL query failed. Check your query.<br />";
return false;
}
$this->total_rows = mysql_num_rows($all_rs);
#mysql_close($all_rs);
$this->max_pages = ceil($this->total_rows/$this->rows_per_page);
//Check the page value just in case someone is trying to input an aribitrary value
if($this->page > $this->max_pages || $this->page <= 0) {
$this->page = 1;
}
//Calculate Offset
$this->offset = $this->rows_per_page * ($this->page-1);
//Fetch the required result set
$rs = #mysql_query($this->sql." LIMIT {$this->offset}, {$this->rows_per_page}");
if(!$rs) {
if($this->debug) echo "Pagination query failed. Check your query.<br />";
return false;
}
return $rs;
}
/**
* Display the link to the first page
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to 'First'
* #return string
*/
function renderFirst($tag='First') {
if($this->page == 1) {
return $tag;
}
else {
return ''.$tag.'';
}
}
/**
* Display the link to the last page
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to 'Last'
* #return string
*/
function renderLast($tag='Last') {
if($this->page == $this->max_pages) {
return $tag;
}
else {
return ''.$tag.'';
}
}
/**
* Display the next link
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to '>>'
* #return string
*/
function renderNext($tag=' >>') {
if($this->page < $this->max_pages) {
return ''.$tag.'';
}
else {
return $tag;
}
}
/**
* Display the previous link
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to '<<'
* #return string
*/
function renderPrev($tag='<<') {
if($this->page > 1) {
return ''.$tag.'';
}
else {
return $tag;
}
}
/**
* Display the page links
*
* #access public
* #return string
*/
function renderNav() {
for($i=1;$i<=$this->max_pages;$i+=$this->links_per_page) {
if($this->page >= $i) {
$start = $i;
}
}
if($this->max_pages > $this->links_per_page) {
$end = $start+$this->links_per_page;
if($end > $this->max_pages) $end = $this->max_pages+1;
}
else {
$end = $this->max_pages;
}
$links = '';
$niche = $_GET['niche'];
for( $i=$start ; $i<$end ; $i++) {
if($i == $this->page) {
$links .= " $i ";
}
else {
$links .= ' '.$i.' ';
}
}
return $links;
}
/**
* Display full pagination navigation
*
* #access public
* #return string
*/
function renderFullNav() {
return $this->renderFirst().' '.$this->renderPrev().' '.$this->renderNav().' '.$this->renderNext().' '.$this->renderLast();
}
/**
* Set debug mode
*
* #access public
* #param bool $debug Set to TRUE to enable debug messages
* #return void
*/
function setDebug($debug) {
$this->debug = $debug;
}
}
?>
Just at first glance i see your query is repeating itself from the beginning every time you run it, so that means every time you run it it searches from the beggining. you need a counter to tell it where to start from on the next page. something like:
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}' limit $startPoint, $offset";
that way the offset is the same as the number of items you want per page and the $startPoint is the point at which the search beggins at the next iteration.
somehting like this would work:
if(!$startPoint){$startPoint = 0;}else{$startPoint = {$_GET['$startPoint'];}
within your code pass the start point back to the query and increasing it by the offset after each iteration.
Please bear in mind i've not taking into consideration stuff like injection, and the fact that the variable $num doesn't seem to come from anywhere in the 1st file. I cant see where you initialized it so as to test $a against it.
After looking at your code more in depth i found a few things that need to be changed to get it work in the least here is the changed code:
<?php
//Include the PS_Pagination class
include('includes/ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect("localhost", "root", "root");
mysql_select_db('database',$conn);
$sql = "SELECT * FROM studies";// WHERE niche = '{$_GET['niche']}'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,4,5);
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
// $a=0;
// while ($a < $num) {
// $id=mysql_result($result,$a,"id");
// $title=mysql_result($result,$a,"title");
// $strategies=mysql_result($result,$a,"strategies");
// $client=mysql_result($result,$a,"client");
// $copy=mysql_result($result,$a,"copy");
// $thumbmedia=mysql_result($result,$a,"thumbmedia");
// $niche=mysql_result($result,$a,"niche");
$id=$row['id'];
$title=$row['title'];
$strategies=$row['strategies'];
$client=$row['client'];
$copy=$row['copy'];
$thumbmedia=$row['thumbmedia'];
$niche=$row['niche'];
echo '<div class="container"><p class="subheadred">'.$title.'</p></div>';
echo '<div class="containerstudy"><div class="column1"><p class="subheadsmall">Strategies</p><p class="sidebarred">'.$strategies.'</p>';
echo '<p class="subheadsmall">Client</p><p class="sidebargrey">'.$client.'</p></div>';
echo '<div class="column2"><p class="bodygrey">'.substr($copy, 0, 300).'...more</p></div>';
echo '<div class="column3"><img src="images/'.$thumbmedia.'" height="160" /></div></div>';
// $a++;
// }
}
//Display the navigation
echo $pager->renderNav();
?>
Notice i have commented out some part that where not necessary
the variable $a was meaningless as it compared to $num which doesn't exist therefore nothing would show. Now these lines:
// $id=mysql_result($result,$a,"id");
// $title=mysql_result($result,$a,"title");
// $strategies=mysql_result($result,$a,"strategies");
// $client=mysql_result($result,$a,"client");
// $copy=mysql_result($result,$a,"copy");
// $thumbmedia=mysql_result($result,$a,"thumbmedia");
// $niche=mysql_result($result,$a,"niche");
where also wrong as you are trying to get the result set from $result. at no place had you put the result set into $result the class you have imported does that and puts the result set into an identifier called $rs.
Since you are using $row = mysql_fetch_assoc($rs) to read through the result set then to get the variables all you need to do is get the column row through an array like this
$id=$row['id'];
and so on. once you do that then the code should work as expected. However this brings us back to this:
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}'";
i had to get the last part out in that this variable is not getting passed back into the query string (seeing you are using get), the other problem is the 1st time you load the page this variable 'niche' doesn't exist so the 1st time you run the code you will get a blank page, unless this script is accessed through a link that passes in this variable. at this point i have left it commented out as am not sure what you were trying to do through niche.
Hope that helps.
Do you have page set in your query string?
I think that if you changed the paginate function, so that it would have one parameter $page and you would set $this->page = $page at the begining of the function, it would work.
You would also have to change the calling of this function in your code to $pager->paginate($_GET['page']).
The pager is also very inefficient, it gets the whole query just to find out, how many rows does the response have. I would use something like:
$all_rs = #mysql_query('SELECT COUNT(*) FROM (' . $this->sql . ')');
if(!$all_rs) {
if($this->debug) echo "SQL query failed. Check your query.<br />";
return false;
}
$this->total_rows = mysql_result($all_rs, 0, 0);
#mysql_close($all_rs);
I'm not sure what this pagination library does with the index of the rows, but you are always setting $a to 0. Perhaps the index is not relative to the page but to the overall recordset being returned?
In other words, what if you set $a to 0 on page 1, 4 on page 2, etc.
You should be able to use $rows_per_page and $page to calculate it. Or perhaps that is the $offset value, so that you set $a to offset and loop it until you hit $rows_per_page additional rows.
Edit clarifying solution:
So what I see you could do is:
$a=0;
while ($a < $pager->rows_per_page) {
$row = $a + $pager->offset;
$id=mysql_result($result,$row,"id");
$title=mysql_result($result,$row,"title");
$strategies=mysql_result($result,$row,"strategies");
$client=mysql_result($result,$row,"client");
$copy=mysql_result($result,$row,"copy");
$thumbmedia=mysql_result($result,$row,"thumbmedia");
$niche=mysql_result($result,$row,"niche");
...
$a++;
}

How could I parse gettext .mo files in PHP4 without relying on setlocale/locales at all?

I made a couple related threads but this is the one direct question that I'm seeking the answer for. My framework will use Zend_Translate if the php version is 5, otherwise I have to mimic the functionality for 4.
It seems that pretty much every implementation of gettext relies on setlocale or locales, I know there's a LOT of inconsistency across systems which is why I don't want to rely upon it.
I've tried a couple times to get the textdomain, bindtextdomain and gettext functions to work but I've always needed to invoke setlocale.
By the way, all the .mo files will be UTF-8.
Here's some reusable code to parse MO files in PHP, based on Zend_Translate_Adapter_Gettext:
<?php
class MoParser {
private $_bigEndian = false;
private $_file = false;
private $_data = array();
private function _readMOData($bytes)
{
if ($this->_bigEndian === false) {
return unpack('V' . $bytes, fread($this->_file, 4 * $bytes));
} else {
return unpack('N' . $bytes, fread($this->_file, 4 * $bytes));
}
}
public function loadTranslationData($filename, $locale)
{
$this->_data = array();
$this->_bigEndian = false;
$this->_file = #fopen($filename, 'rb');
if (!$this->_file) throw new Exception('Error opening translation file \'' . $filename . '\'.');
if (#filesize($filename) < 10) throw new Exception('\'' . $filename . '\' is not a gettext file');
// get Endian
$input = $this->_readMOData(1);
if (strtolower(substr(dechex($input[1]), -8)) == "950412de") {
$this->_bigEndian = false;
} else if (strtolower(substr(dechex($input[1]), -8)) == "de120495") {
$this->_bigEndian = true;
} else {
throw new Exception('\'' . $filename . '\' is not a gettext file');
}
// read revision - not supported for now
$input = $this->_readMOData(1);
// number of bytes
$input = $this->_readMOData(1);
$total = $input[1];
// number of original strings
$input = $this->_readMOData(1);
$OOffset = $input[1];
// number of translation strings
$input = $this->_readMOData(1);
$TOffset = $input[1];
// fill the original table
fseek($this->_file, $OOffset);
$origtemp = $this->_readMOData(2 * $total);
fseek($this->_file, $TOffset);
$transtemp = $this->_readMOData(2 * $total);
for($count = 0; $count < $total; ++$count) {
if ($origtemp[$count * 2 + 1] != 0) {
fseek($this->_file, $origtemp[$count * 2 + 2]);
$original = #fread($this->_file, $origtemp[$count * 2 + 1]);
$original = explode("\0", $original);
} else {
$original[0] = '';
}
if ($transtemp[$count * 2 + 1] != 0) {
fseek($this->_file, $transtemp[$count * 2 + 2]);
$translate = fread($this->_file, $transtemp[$count * 2 + 1]);
$translate = explode("\0", $translate);
if ((count($original) > 1) && (count($translate) > 1)) {
$this->_data[$locale][$original[0]] = $translate;
array_shift($original);
foreach ($original as $orig) {
$this->_data[$locale][$orig] = '';
}
} else {
$this->_data[$locale][$original[0]] = $translate[0];
}
}
}
$this->_data[$locale][''] = trim($this->_data[$locale]['']);
unset($this->_data[$locale]['']);
return $this->_data;
}
}
Ok, I basically ended up writing a mo file parser based on Zend's Gettext Adapter, as far as I know gettext is pretty much reliant upon the locale, so manually parsing the .mo file would save the hassle of running into odd circumstances with locale issues with setlocale. I also plan on parsing the Zend Locale data provided in the form of xml files.

Categories