Trying to update ps_pagination class - php

I have an older pagination script that has served me well over the years, however its been pretty much abandoned by the developer and I'm unable to wrap my head around upgrading the mysql calls to mysqli due to it being oop, which I'm pretty unfamiliar with. My main issue is I know what I need to change, but I can't figure out the syntax when using $this-. simply changing the call isn't enough and when I add the parameters my editor complains about it.
say when I change
$all_rs = #mysql_query($this->sql );
to
$all_rs = mysqli_query($this->conn, $this->sql );
(which is probably totally wrong syntax for oop) Im told I'm missing the query parameter or that I have undeclared vars. Bear in mind the editor is only seeing the class and not the values of the vars being fed to it, so I'm kind of at a loss about how to code it.
heres the full class
<?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 = 10; //Number of records to display per page
var $total_rows = 0; //Total number of rows returned by the query
var $links_per_page = 5; //Number of links to display per page
var $append = ""; //Paremeters to append to pagination links
var $sql = "";
var $debug = false;
var $conn = false;
var $page = 1;
var $max_pages = 0;
var $offset = 0;
/**
* 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
* #param string $append Parameters to be appended to pagination links
*/
function PS_Pagination($connection, $sql, $rows_per_page = 10, $links_per_page = 5, $append = "") {
$this->conn = $connection;
$this->sql = $sql;
$this->rows_per_page = (int)$rows_per_page;
if (intval($links_per_page ) > 0) {
$this->links_per_page = (int)$links_per_page;
} else {
$this->links_per_page = 5;
}
$this->append = $append;
$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() {
//Check for valid mysql connection
if (! $this->conn || ! is_resource($this->conn )) {
if ($this->debug)
echo "MySQL connection missing<br />";
return false;
}
//Find total number of rows
$all_rs = #mysql_query($this->sql );
if (! $all_rs) {
if ($this->debug)
echo "SQL query failed. Check your query.<br /><br />Error Returned: " . mysql_error();
return false;
}
$this->total_rows = mysql_num_rows($all_rs );
#mysql_close($all_rs );
//Return FALSE if no rows found
if ($this->total_rows == 0) {
if ($this->debug)
echo "Query returned zero rows.";
return FALSE;
}
//Max number of pages
$this->max_pages = ceil($this->total_rows / $this->rows_per_page );
if ($this->links_per_page > $this->max_pages) {
$this->links_per_page = $this->max_pages;
}
//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 /><br />Error Returned: " . mysql_error();
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->total_rows == 0)
return FALSE;
if ($this->page == 1) {
return '"previous-off">' . $tag;
} else {
return '"next">' . $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->total_rows == 0)
return FALSE;
if ($this->page == $this->max_pages) {
return '"previous-off">' . $tag;
} else {
return '"next">' . $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->total_rows == 0)
return FALSE;
if ($this->page < $this->max_pages) {
return '"next">' . $tag . '';
} else {
return '"next-off">' . $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->total_rows == 0)
return FALSE;
if ($this->page > 1) {
return ' "next">' . $tag . '';
} else {
return '"previous-off">' . $tag;
}
}
/**
* Display the page links
*
* #access public
* #return string
*/
function renderNav($prefix = '<span class="page_link">', $suffix = '</span>') {
if ($this->total_rows == 0)
return FALSE;
$batch = ceil($this->page / $this->links_per_page );
$end = $batch * $this->links_per_page;
if ($end == $this->page) {
//$end = $end + $this->links_per_page - 1;
//$end = $end + ceil($this->links_per_page/2);
}
if ($end > $this->max_pages) {
$end = $this->max_pages;
}
$start = $end - $this->links_per_page + 1;
$links = '';
for($i = $start; $i <= $end; $i ++) {
if ($i == $this->page) {
$links .= $prefix . ' class="active">' . "$i" . $suffix;
} else {
$links .= ' ' . $prefix . '>' . $i . '' . $suffix . ' ';
}
}
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;
}
}
?>
any thoughts on how I should be formatting these calls?
Thanks

Here, I fixed a few basic things about the way the class is constructed, mainly respecting currently in use standards and modern oop constructs.
The gist of it however, resides in the statement call:
$all_rs = $this->conn->query($this->sql);
PHP has the __construct() function we should use as a constructor.
Use private, protected and public when defining your members.
Use typehints to designate your parameters (php7 offers a lot of scalar typehints that were missing in php5 (int, string, float for example) but we can typehint any class.
There is no need to manually verify if connection was successfull, or to check for errors. The connection object should be built with the desired error reporting level, the mysqli implementation will throw exceptions as needed afterwards.
Never use the fairly ridiculous # in front of the queries. Suppressing error messages is not a sane way to reason about database access, or programming at all as far as my experience goes, and can only lead to hard debugging.
Using setter injection (for the debug parameter) can also only lead to problems. Having it as a constructor parameter ensures correct behavior for all the pagination object's life cycle.
The bad news
However, this is wide open to sql injection, because I haven't changed the function signatures so this can continue to be used along actual code. Normally, you would prepare, then execute the statements with the values to take advantage of parameterized statements.

Related

No such file or directory in C:\xampp\php\pear\Table.php on line 69 it

whem i changed the server from wampp to xamp i got this error
Warning: require_once(HTML/Table/Storage.php): failed to open stream: No such file or directory in C:\xampp\php\pear\Table.php on line 69
and
Fatal error: require_once(): Failed opening required 'HTML/Table/Storage.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\php\pear\Table.php on line 69
and the Storage.php from pear path
C:\xampp\php\pear\Table
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Storage class for HTML::Table data
*
* This class stores data for tables built with HTML_Table. When having
* more than one instance, it can be used for grouping the table into the
* parts <thead>...</thead>, <tfoot>...</tfoot> and <tbody>...</tbody>.
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2005-2007, Adam Daniel <adaniel1#eesus.jnj.com>,
* Bertrand Mansion <bmansion#mamasam.com>,
* Mark Wiesemann <wiesemann#php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* #category HTML
* #package HTML_Table
* #author Adam Daniel <adaniel1#eesus.jnj.com>
* #author Bertrand Mansion <bmansion#mamasam.com>
* #license http://www.opensource.org/licenses/bsd-license.php New BSD License
* #version CVS: $Id: Storage.php 234674 2007-04-29 16:31:06Z wiesemann $
* #link http://pear.php.net/package/HTML_Table
*/
/**
* Storage class for HTML::Table data
*
* This class stores data for tables built with HTML_Table. When having
* more than one instance, it can be used for grouping the table into the
* parts <thead>...</thead>, <tfoot>...</tfoot> and <tbody>...</tbody>.
*
* #category HTML
* #package HTML_Table
* #author Adam Daniel <adaniel1#eesus.jnj.com>
* #author Bertrand Mansion <bmansion#mamasam.com>
* #author Mark Wiesemann <wiesemann#php.net>
* #copyright 2005-2006 The PHP Group
* #license http://www.opensource.org/licenses/bsd-license.php New BSD License
* #version Release: #package_version#
* #link http://pear.php.net/package/HTML_Table
*/
class HTML_Table_Storage extends HTML_Common {
/**
* Value to insert into empty cells
* #var string
* #access private
*/
var $_autoFill = ' ';
/**
* Automatically adds a new row or column if a given row or column index
* does not exist
* #var bool
* #access private
*/
var $_autoGrow = true;
/**
* Array containing the table structure
* #var array
* #access private
*/
var $_structure = array();
/**
* Number of rows composing in the table
* #var int
* #access private
*/
var $_rows = 0;
/**
* Number of column composing the table
* #var int
* #access private
*/
var $_cols = 0;
/**
* Tracks the level of nested tables
* #var int
* #access private
*/
var $_nestLevel = 0;
/**
* Whether to use <thead>, <tfoot> and <tbody> or not
* #var bool
* #access private
*/
var $_useTGroups = false;
/**
* Class constructor
* #param int $tabOffset
* #param bool $useTGroups Whether to use <thead>, <tfoot> and
* <tbody> or not
* #access public
*/
function HTML_Table_Storage($tabOffset = 0, $useTGroups = false)
{
HTML_Common::HTML_Common(null, (int)$tabOffset);
$this->_useTGroups = (boolean)$useTGroups;
}
/**
* Sets the useTGroups value
* #param boolean $useTGroups
* #access public
*/
function setUseTGroups($useTGroups)
{
$this->_useTGroups = $useTGroups;
}
/**
* Returns the useTGroups value
* #access public
* #return boolean
*/
function getUseTGroups()
{
return $this->_useTGroups;
}
/**
* Sets the autoFill value
* #param mixed $fill
* #access public
*/
function setAutoFill($fill)
{
$this->_autoFill = $fill;
}
/**
* Returns the autoFill value
* #access public
* #return mixed
*/
function getAutoFill()
{
return $this->_autoFill;
}
/**
* Sets the autoGrow value
* #param bool $fill
* #access public
*/
function setAutoGrow($grow)
{
$this->_autoGrow = $grow;
}
/**
* Returns the autoGrow value
* #access public
* #return mixed
*/
function getAutoGrow()
{
return $this->_autoGrow;
}
/**
* Sets the number of rows in the table
* #param int $rows
* #access public
*/
function setRowCount($rows)
{
$this->_rows = $rows;
}
/**
* Sets the number of columns in the table
* #param int $cols
* #access public
*/
function setColCount($cols)
{
$this->_cols = $cols;
}
/**
* Returns the number of rows in the table
* #access public
* #return int
*/
function getRowCount()
{
return $this->_rows;
}
/**
* Gets the number of columns in the table
*
* If a row index is specified, the count will not take
* the spanned cells into account in the return value.
*
* #param int Row index to serve for cols count
* #access public
* #return int
*/
function getColCount($row = null)
{
if (!is_null($row)) {
$count = 0;
foreach ($this->_structure[$row] as $cell) {
if (is_array($cell)) {
$count++;
}
}
return $count;
}
return $this->_cols;
}
/**
* Sets a rows type 'TH' or 'TD'
* #param int $row Row index
* #param string $type 'TH' or 'TD'
* #access public
*/
function setRowType($row, $type)
{
for ($counter = 0; $counter < $this->_cols; $counter++) {
$this->_structure[$row][$counter]['type'] = $type;
}
}
/**
* Sets a columns type 'TH' or 'TD'
* #param int $col Column index
* #param string $type 'TH' or 'TD'
* #access public
*/
function setColType($col, $type)
{
for ($counter = 0; $counter < $this->_rows; $counter++) {
$this->_structure[$counter][$col]['type'] = $type;
}
}
/**
* Sets the cell attributes for an existing cell.
*
* If the given indices do not exist and autoGrow is true then the given
* row and/or col is automatically added. If autoGrow is false then an
* error is returned.
* #param int $row Row index
* #param int $col Column index
* #param mixed $attributes Associative array or string of table
* row attributes
* #access public
* #throws PEAR_Error
*/
function setCellAttributes($row, $col, $attributes)
{
if ( isset($this->_structure[$row][$col])
&& $this->_structure[$row][$col] == '__SPANNED__'
) {
return;
}
$attributes = $this->_parseAttributes($attributes);
$err = $this->_adjustEnds($row, $col, 'setCellAttributes', $attributes);
if (PEAR::isError($err)) {
return $err;
}
$this->_structure[$row][$col]['attr'] = $attributes;
$this->_updateSpanGrid($row, $col);
}
/**
* Updates the cell attributes passed but leaves other existing attributes
* intact
* #param int $row Row index
* #param int $col Column index
* #param mixed $attributes Associative array or string of table row
* attributes
* #access public
*/
function updateCellAttributes($row, $col, $attributes)
{
if ( isset($this->_structure[$row][$col])
&& $this->_structure[$row][$col] == '__SPANNED__'
) {
return;
}
$attributes = $this->_parseAttributes($attributes);
$err = $this->_adjustEnds($row, $col, 'updateCellAttributes', $attributes);
if (PEAR::isError($err)) {
return $err;
}
$this->_updateAttrArray($this->_structure[$row][$col]['attr'], $attributes);
$this->_updateSpanGrid($row, $col);
}
/**
* Returns the attributes for a given cell
* #param int $row Row index
* #param int $col Column index
* #return array
* #access public
*/
function getCellAttributes($row, $col)
{
if ( isset($this->_structure[$row][$col])
&& $this->_structure[$row][$col] != '__SPANNED__'
) {
return $this->_structure[$row][$col]['attr'];
} elseif (!isset($this->_structure[$row][$col])) {
return PEAR::raiseError('Invalid table cell reference[' .
$row . '][' . $col . '] in HTML_Table::getCellAttributes');
}
return;
}
/**
* Sets the cell contents for an existing cell
*
* If the given indices do not exist and autoGrow is true then the given
* row and/or col is automatically added. If autoGrow is false then an
* error is returned.
* #param int $row Row index
* #param int $col Column index
* #param mixed $contents May contain html or any object with a
* toHTML() method; if it is an array (with
* strings and/or objects), $col will be used
* as start offset and the array elements will
* be set to this and the following columns
* in $row
* #param string $type (optional) Cell type either 'TH' or 'TD'
* #access public
* #throws PEAR_Error
*/
function setCellContents($row, $col, $contents, $type = 'TD')
{
if (is_array($contents)) {
foreach ($contents as $singleContent) {
$ret = $this->_setSingleCellContents($row, $col, $singleContent,
$type);
if (PEAR::isError($ret)) {
return $ret;
}
$col++;
}
} else {
$ret = $this->_setSingleCellContents($row, $col, $contents, $type);
if (PEAR::isError($ret)) {
return $ret;
}
}
}
/**
* Sets the cell contents for a single existing cell
*
* If the given indices do not exist and autoGrow is true then the given
* row and/or col is automatically added. If autoGrow is false then an
* error is returned.
* #param int $row Row index
* #param int $col Column index
* #param mixed $contents May contain html or any object with a
* toHTML() method; if it is an array (with
* strings and/or objects), $col will be used
* as start offset and the array elements will
* be set to this and the following columns
* in $row
* #param string $type (optional) Cell type either 'TH' or 'TD'
* #access private
* #throws PEAR_Error
*/
function _setSingleCellContents($row, $col, $contents, $type = 'TD')
{
if ( isset($this->_structure[$row][$col])
&& $this->_structure[$row][$col] == '__SPANNED__'
) {
return;
}
$err = $this->_adjustEnds($row, $col, 'setCellContents');
if (PEAR::isError($err)) {
return $err;
}
$this->_structure[$row][$col]['contents'] = $contents;
$this->_structure[$row][$col]['type'] = $type;
}
/**
* Returns the cell contents for an existing cell
* #param int $row Row index
* #param int $col Column index
* #access public
* #return mixed
*/
function getCellContents($row, $col)
{
if ( isset($this->_structure[$row][$col])
&& $this->_structure[$row][$col] == '__SPANNED__'
) {
return;
}
if (!isset($this->_structure[$row][$col])) {
return PEAR::raiseError('Invalid table cell reference[' .
$row . '][' . $col . '] in HTML_Table::getCellContents');
}
return $this->_structure[$row][$col]['contents'];
}
/**
* Sets the contents of a header cell
* #param int $row
* #param int $col
* #param mixed $contents
* #param mixed $attributes Associative array or string of table row
* attributes
* #access public
*/
function setHeaderContents($row, $col, $contents, $attributes = null)
{
$this->setCellContents($row, $col, $contents, 'TH');
if (!is_null($attributes)) {
$this->updateCellAttributes($row, $col, $attributes);
}
}
/**
* Adds a table row and returns the row identifier
* #param array $contents (optional) Must be a indexed array of valid
* cell contents
* #param mixed $attributes (optional) Associative array or string of
* table row attributes. This can
* also be an array of attributes,
* in which case the attributes
* will be repeated in a loop.
* #param string $type (optional) Cell type either 'th' or 'td'
* #param bool $inTR false if attributes are to be
* applied in TD tags; true if
* attributes are to be applied in
* TR tag
* #return int
* #access public
*/
function addRow($contents = null, $attributes = null, $type = 'td',
$inTR = false)
{
if (isset($contents) && !is_array($contents)) {
return PEAR::raiseError('First parameter to HTML_Table::addRow ' .
'must be an array');
}
if (is_null($contents)) {
$contents = array();
}
$type = strtolower($type);
$row = $this->_rows++;
foreach ($contents as $col => $content) {
if ($type == 'td') {
$this->setCellContents($row, $col, $content);
} elseif ($type == 'th') {
$this->setHeaderContents($row, $col, $content);
}
}
$this->setRowAttributes($row, $attributes, $inTR);
return $row;
}
function setRowAttributes($row, $attributes, $inTR = false)
{
if (!$inTR) {
$multiAttr = $this->_isAttributesArray($attributes);
for ($i = 0; $i < $this->_cols; $i++) {
if ($multiAttr) {
$this->setCellAttributes($row, $i,
$attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]);
} else {
$this->setCellAttributes($row, $i, $attributes);
}
}
} else {
$attributes = $this->_parseAttributes($attributes);
$err = $this->_adjustEnds($row, 0, 'setRowAttributes', $attributes);
if (PEAR::isError($err)) {
return $err;
}
$this->_structure[$row]['attr'] = $attributes;
}
}
function updateRowAttributes($row, $attributes = null, $inTR = false)
{
if (!$inTR) {
$multiAttr = $this->_isAttributesArray($attributes);
for ($i = 0; $i < $this->_cols; $i++) {
if ($multiAttr) {
$this->updateCellAttributes($row, $i,
$attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]);
} else {
$this->updateCellAttributes($row, $i, $attributes);
}
}
} else {
$attributes = $this->_parseAttributes($attributes);
$err = $this->_adjustEnds($row, 0, 'updateRowAttributes', $attributes);
if (PEAR::isError($err)) {
return $err;
}
$this->_updateAttrArray($this->_structure[$row]['attr'], $attributes);
}
}
function getRowAttributes($row)
{
if (isset($this->_structure[$row]['attr'])) {
return $this->_structure[$row]['attr'];
}
return;
}
function altRowAttributes($start, $attributes1, $attributes2, $inTR = false,
$firstAttributes = 1)
{
for ($row = $start; $row < $this->_rows; $row++) {
if (($row + $start + ($firstAttributes - 1)) % 2 == 0) {
$attributes = $attributes1;
} else {
$attributes = $attributes2;
}
$this->updateRowAttributes($row, $attributes, $inTR);
}
}
function addCol($contents = null, $attributes = null, $type = 'td')
{
if (isset($contents) && !is_array($contents)) {
return PEAR::raiseError('First parameter to HTML_Table::addCol ' .
'must be an array');
}
if (is_null($contents)) {
$contents = array();
}
$type = strtolower($type);
$col = $this->_cols++;
foreach ($contents as $row => $content) {
if ($type == 'td') {
$this->setCellContents($row, $col, $content);
} elseif ($type == 'th') {
$this->setHeaderContents($row, $col, $content);
}
}
$this->setColAttributes($col, $attributes);
return $col;
}
function setColAttributes($col, $attributes = null)
{
$multiAttr = $this->_isAttributesArray($attributes);
for ($i = 0; $i < $this->_rows; $i++) {
if ($multiAttr) {
$this->setCellAttributes($i, $col,
$attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]);
} else {
$this->setCellAttributes($i, $col, $attributes);
}
}
}
function updateColAttributes($col, $attributes = null)
{
$multiAttr = $this->_isAttributesArray($attributes);
for ($i = 0; $i < $this->_rows; $i++) {
if ($multiAttr) {
$this->updateCellAttributes($i, $col,
$attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]);
} else {
$this->updateCellAttributes($i, $col, $attributes);
}
}
}
function setAllAttributes($attributes = null)
{
for ($i = 0; $i < $this->_rows; $i++) {
$this->setRowAttributes($i, $attributes);
}
}
function updateAllAttributes($attributes = null)
{
for ($i = 0; $i < $this->_rows; $i++) {
$this->updateRowAttributes($i, $attributes);
}
}
function toHtml($tabs = null, $tab = null)
{
$strHtml = '';
if (is_null($tabs)) {
$tabs = $this->_getTabs();
}
if (is_null($tab)) {
$tab = $this->_getTab();
}
$lnEnd = $this->_getLineEnd();
if ($this->_useTGroups) {
$extraTab = $tab;
} else {
$extraTab = '';
}
if ($this->_cols > 0) {
for ($i = 0 ; $i < $this->_rows ; $i++) {
$attr = '';
if (isset($this->_structure[$i]['attr'])) {
$attr = $this->_getAttrString($this->_structure[$i]['attr']);
}
$strHtml .= $tabs .$tab . $extraTab . '<tr'.$attr.'>' . $lnEnd;
for ($j = 0 ; $j < $this->_cols ; $j++) {
$attr = '';
$contents = '';
$type = 'td';
if (isset($this->_structure[$i][$j]) && $this->_structure[$i][$j] == '__SPANNED__') {
continue;
}
if (isset($this->_structure[$i][$j]['type'])) {
$type = (strtolower($this->_structure[$i][$j]['type']) == 'th' ? 'th' : 'td');
}
if (isset($this->_structure[$i][$j]['attr'])) {
$attr = $this->_structure[$i][$j]['attr'];
}
if (isset($this->_structure[$i][$j]['contents'])) {
$contents = $this->_structure[$i][$j]['contents'];
}
$strHtml .= $tabs . $tab . $tab . $extraTab . "<$type" . $this->_getAttrString($attr) . '>';
if (is_object($contents)) {
// changes indent and line end settings on nested tables
if (is_subclass_of($contents, 'html_common')) {
$contents->setTab($tab . $extraTab);
$contents->setTabOffset($this->_tabOffset + 3);
$contents->_nestLevel = $this->_nestLevel + 1;
$contents->setLineEnd($this->_getLineEnd());
}
if (method_exists($contents, 'toHtml')) {
$contents = $contents->toHtml();
} elseif (method_exists($contents, 'toString')) {
$contents = $contents->toString();
}
}
if (is_array($contents)) {
$contents = implode(', ', $contents);
}
if (isset($this->_autoFill) && $contents === '') {
$contents = $this->_autoFill;
}
$strHtml .= $contents;
$strHtml .= "</$type>" . $lnEnd;
}
$strHtml .= $tabs . $tab . $extraTab . '</tr>' . $lnEnd;
}
}
return $strHtml;
}
function _updateSpanGrid($row, $col)
{
if (isset($this->_structure[$row][$col]['attr']['colspan'])) {
$colspan = $this->_structure[$row][$col]['attr']['colspan'];
}
if (isset($this->_structure[$row][$col]['attr']['rowspan'])) {
$rowspan = $this->_structure[$row][$col]['attr']['rowspan'];
}
if (isset($colspan)) {
for ($j = $col + 1; (($j < $this->_cols) && ($j <= ($col + $colspan - 1))); $j++) {
$this->_structure[$row][$j] = '__SPANNED__';
}
}
if (isset($rowspan)) {
for ($i = $row + 1; (($i < $this->_rows) && ($i <= ($row + $rowspan - 1))); $i++) {
$this->_structure[$i][$col] = '__SPANNED__';
}
}
if (isset($colspan) && isset($rowspan)) {
for ($i = $row + 1; (($i < $this->_rows) && ($i <= ($row + $rowspan - 1))); $i++) {
for ($j = $col + 1; (($j <= $this->_cols) && ($j <= ($col + $colspan - 1))); $j++) {
$this->_structure[$i][$j] = '__SPANNED__';
}
}
}
}
?>

Pagination current link not highlighting

I got a strange problem, my current pagination link is not highlighted the pagination urls I made looks like:
site.com/list/50/?some=value
Everything is working great, but the current pagination link in view is not highlighted. I checked CSS and it's ok, the problem comes from the library I guess.
This is my code. I can't see anything wrong in here:
$pagination['base_url'] = site_url('asd');
if($_SERVER['QUERY_STRING'] !==''){
$pagination['suffix'] = '/?'.$_SERVER['QUERY_STRING'];
}
$pagination['first_url'] = site_url('asd');
$pagination['total_rows'] = $total_rows[0]->total;
$pagination['first_link'] = ' First ';
$pagination['last_link'] = ' Last ';
$pagination['next_link'] = ' Next ';
$pagination['prev_link'] = ' Prev ';
$pagination['num_links'] = 5;
$this->pagination->initialize($pagination);
Any clue appreciated.
i post my library which i edited for markup also:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/**
* Pagination Class
*
* #package CodeIgniter
* #subpackage Libraries
* #category Pagination
* #author ExpressionEngine Dev Team
* #link http://codeigniter.com/user_guide/libraries/pagination.html
*/
class CI_Pagination {
var $base_url = ''; // The page we are linking to
var $prefix = ''; // A custom prefix added to the path.
var $suffix = ''; // A custom suffix added to the path.
var $total_rows = ''; // Total number of items (database results)
var $per_page = 10; // Max number of items you want shown per page
var $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
var $cur_page = 0; // The current page being viewed
var $first_link = '‹ First';
var $next_link = '>';
var $prev_link = '<';
var $last_link = 'Last ›';
var $uri_segment = 3;
var $full_tag_open = '<p class="CI-pagination">';
var $full_tag_close = '</p>';
var $first_tag_open = '<span class="pagination-first">';
var $first_tag_close = ' </span>';
var $last_tag_open = '<span class="pagination-last"> ';
var $last_tag_close = '</span>';
var $first_url = ''; // Alternative URL for the First Page.
var $cur_tag_open = '<span class="pagination-current"> <a href="javascript:void(0)" class="btn btn-small">';
var $cur_tag_close = '</a></span>';
var $next_tag_open = '<span class="pagination-next"> ';
var $next_tag_close = ' </span>';
var $prev_tag_open = '<span class="pagination-prev"> ';
var $prev_tag_close = '</span>';
var $num_tag_open = '<span class="pagination-num"> ';
var $num_tag_close = '</span>';
var $page_query_string = FALSE;
var $query_string_segment = 'per_page';
var $display_pages = TRUE;
var $anchor_class = 'btn btn-small';
/**
* Constructor
*
* #access public
* #param array initialization parameters
*/
public function __construct($params = array())
{
if (count($params) > 0)
{
$this->initialize($params);
}
if ($this->anchor_class != '')
{
$this->anchor_class = 'class="'.$this->anchor_class.'" ';
}
log_message('debug', "Pagination Class Initialized");
}
// --------------------------------------------------------------------
/**
* Initialize Preferences
*
* #access public
* #param array initialization parameters
* #return void
*/
function initialize($params = array())
{
if (count($params) > 0)
{
foreach ($params as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
}
}
// --------------------------------------------------------------------
/**
* Generate the pagination links
*
* #access public
* #return string
*/
function create_links()
{
// If our item count or per-page total is zero there is no need to continue.
if ($this->total_rows == 0 OR $this->per_page == 0)
{
return '';
}
// Calculate the total number of pages
$num_pages = ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
if ($num_pages == 1)
{
return '';
}
// Determine the current page number.
$CI =& get_instance();
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
if ($CI->input->get($this->query_string_segment) != 0)
{
$this->cur_page = $CI->input->get($this->query_string_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
else
{
if ($CI->uri->segment($this->uri_segment) != 0)
{
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1)
{
show_error('Your number of links must be a positive number.');
}
if ( ! is_numeric($this->cur_page))
{
$this->cur_page = 0;
}
// Is the page number beyond the result range?
// If so we show the last page
if ($this->cur_page > $this->total_rows)
{
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// Is pagination being used over GET or POST? If get, add a per_page query
// string. If post, add a trailing slash to the base URL if needed
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
$this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'=';
}
else
{
$this->base_url = rtrim($this->base_url, '/') .'/';
}
// And here we go...
$output = '';
// Render the "First" link
if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1))
{
$first_url = ($this->first_url == '') ? $this->base_url : $this->first_url;
$output .= $this->first_tag_open.'<a '.$this->anchor_class.'href="'.$first_url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
}
// Render the "previous" link
if ($this->prev_link !== FALSE AND $this->cur_page != 1)
{
$i = $uri_page_number - $this->per_page;
if ($i == 0 && $this->first_url != '')
{
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
else
{
$i = ($i == 0) ? '' : $this->prefix.$i.$this->suffix;
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$i.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
}
// Render the pages
if ($this->display_pages !== FALSE)
{
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++)
{
$i = ($loop * $this->per_page) - $this->per_page;
if ($i >= 0)
{
if ($this->cur_page == $loop)
{
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}
else
{
$n = ($i == 0) ? '' : $i;
if ($n == '' && $this->first_url != '')
{
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$loop.'</a>'.$this->num_tag_close;
}
else
{
$n = ($n == '') ? '' : $this->prefix.$n.$this->suffix;
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$n.'">'.$loop.'</a>'.$this->num_tag_close;
}
}
}
}
}
// Render the "next" link
if ($this->next_link !== FALSE AND $this->cur_page < $num_pages)
{
$output .= $this->next_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.($this->cur_page * $this->per_page).$this->suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages)
{
$i = (($num_pages * $this->per_page) - $this->per_page);
$output .= $this->last_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->last_link.'</a>'.$this->last_tag_close;
}
// Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;
return $output;
}
}
// END Pagination Class
/* End of file Pagination.php */
/* Location: ./system/libraries/Pagination.php */
According to my pagination library, all my pagination links are printed out as class="pagination-num" and the class="pagination-current" is added only to the first pagination link , unbelievable :/
When changing page, the pagination looks always as shown in this image, no changes between a page to another :/
Read this and find the "Customizing the "Current Page" Link" section. Use that to add custom markup then add appropriate CSS.
Edit: the OP found the following solution:
$pagination['uri_segment'] = 2;
Add these line and write css for .current class
$pagination['cur_tag_open'] = '<a href="javascript:void(0)" class="current">';
$pagination['cur_tag_close'] = '</a>';
$pagination['cur_page'] = {put current page no here};
Check your $config['uri_segment']. Otherwise handle from jquery. Do somethings like:-
Suppose your link:-
<div id="my-ci-link"><?php echo $links; ?></div>
write jQuery:-
$('#my-ci-link strong').css('color','green');
<pre>
if ($this->uri->segment(2))
$data['page'] = $this->uri->segment(2);
else
$data['page'] = 0;
$config["cur_page"] = $data['page'];
...
</pre>

Implementation of Rabin-Karp Algorithm with PHP

Hi I am writing a PHP class to implement Rabin-Karp algorithm. I have issue with re-hashing part. This code doesn't include matching part of the characters. I had to stop since it never matching hash codes due to the issue with re-hashing. Someone please help me to figure it out.
<?php
class RabinKarp
{
/**
* #var String
*/
private $pattern ;
private $patternHash ;
private $text ;
private $previousHash ;
/**
* #var Integer
*/
private $radix ;
private $prime ;
private $position ;
/**
* Constructor
*
* #param String $pattern - The pattern
*
*/
public function __construct($pattern)
{
$this->pattern = $pattern;
$this->radix = 256;
$this->prime = 100007;
$this->previousHash = "";
$this->position = 0;
$this->patternHash = $this->generateHash($pattern);
}
private function generateHash($key)
{
$charArray = str_split($key);
$hash = 0;
foreach($charArray as $char)
{
$hash = ($this->radix * $hash + ord($char)) % $this->prime;
}
return $hash;
}
public function search($character)
{
$this->text .= $character;
if(strlen($this->text) < strlen($this->pattern))
{
return false;
}
else
{
$txtHash = 0;
echo $this->previousHash . "<br/>";
if(empty($this->previousHash))
{
$txtHash = $this->generateHash($this->text);
$this->previousHash = $txtHash;
$this->position = 0;
}
else
{
// The issue is here
$charArray = str_split($this->text);
$txtHash = (($txtHash + $this->prime) - $this->radix * strlen($this->pattern) * ord($charArray[$this->position]) % $this->prime) % $this->prime;
$txtHash = ($txtHash * $this->radix + ord($character)) % $this->prime;
$this->previousHash = $txtHash;
}
if($txtHash == $this->patternHash)
{
echo "Hash Match found";
}
}
}
}
$x = new RabinKarp("ABC");
$x->search("Z");
$x->search("A");
$x->search("B");
$x->search("C");
?>
Thank you.
The value contributed to the hash by the character (c for shortness) you're removing is
ord(c) * radix^(length(pattern)-1)
since a character contributes ord(c) when it first enters the matching window, and the hash - therefore also its contribution - is multiplied with radix for each of the length(pattern)-1 characters entering the matching window until c finally leaves it.
But you're subtracting ord(c) * radix * length(pattern)
$charArray = str_split($this->text);
$txtHash = (($txtHash + $this->prime)
- $this->radix * strlen($this->pattern)
* ord($charArray[$this->position]) % $this->prime)
% $this->prime;
$txtHash = ($txtHash * $this->radix + ord($character)) % $this->prime;
Additionally, in the calculation you're using the variable $txtHash, which you've set to 0, that should be $this->previousHash, and you must increment the text position.
In principle,
$charArray = str_split($this->text);
$txtHash = (($this->previousHash + $this->prime)
- pow($this->radix, strlen($this->pattern)-1)
* ord($charArray[$this->position]) % $this->prime)
% $this->prime;
$txtHash = ($txtHash * $this->radix + ord($character)) % $this->prime;
$this->previousHash = $txtHash;
$this->position += 1;
is what you have to do.
But unless the pattern is very short, pow($this->radix,strlen($this->pattern)-1) will overflow, so you have to replace pow($this-radix, strlen($this->pattern)-1) with a modular exponentiation function
function mod_pow($base,$exponent,$modulus)
{
$aux = 1;
while($exponent > 0) {
if ($exponent % 2 == 1) {
$aux = ($aux * $base) % $modulus;
}
$base = ($base * $base) % $modulus;
$exponent = $exponent/2;
}
return $aux;
}
(this can still overflow if $modulus, that is $this->prime here, is too large). The relevant line of code becomes
$txtHash = (($this->previousHash + $this->prime)
- mod_pow($this->radix, strlen($this->pattern)-1, $this->prime)
* ord($charArray[$this->position]) % $this->prime)
% $this->prime;
Then you have a potentially huge inefficiency
$this->text .= $character;
...
$charArray = str_split($this->text);
If the string becomes long, the concatenation and the splitting may take a lot of time (not sure how PHP implements strings and string operations, but they're likely not constant time). You should probably keep only the relevant part of the string, i.e. drop the first character after recalculating the hash.

How to check if a string already exists and if it does add +1 at the end?

Let's say i check if
$strig = "red-hot-chili-peppers-californication";
already exists in my database:
$query = dbquery("SELECT * FROM `videos` WHERE `slug` = '".$strig."';");
$checkvideo = dbrows($query);
if($checkvideo == 1){
// the code to be executed to rename $strig
// to "red-hot-chili-peppers-californication-2"
// it would be great to work even if $string is defined as
// "red-hot-chili-peppers-californication-2" and
// rename $string to "red-hot-chili-peppers-californication-3" and so on...
}
I want to do this to create unique slugs for a more friendly url structure.
Thanks.
I can offer you the source of Codeigniter's increment_string() function:
/**
* CodeIgniter String Helpers
*
* #package CodeIgniter
* #subpackage Helpers
* #category Helpers
* #author ExpressionEngine Dev Team
* #link http://codeigniter.com/user_guide/helpers/string_helper.html
*/
/**
* Add's _1 to a string or increment the ending number to allow _2, _3, etc
*
* #param string $str required
* #param string $separator What should the duplicate number be appended with
* #param string $first Which number should be used for the first dupe increment
* #return string
*/
function increment_string($str, $separator = '_', $first = 1)
{
preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}
Increments a string by appending a number to it or increasing the
number. Useful for creating "copies" or a file or duplicating database
content which has unique titles or slugs.
Usage example:
echo increment_string('file', '_'); // "file_1"
echo increment_string('file', '-', 2); // "file-2"
echo increment_string('file-4'); // "file-5"
$str = "some-string-that-might-end-in-a-number";
$strLen = strlen($str);
//check the last character of the string for number
if(intval($str[$strLen-1])>0)
{
//Now we replace the last number with the number+1
$newNumber = intval($str[$strLen-1]) +1;
$str = substr($str, 0, -1).$newNumber;
}
else
{
//Now we append a number to the end;
$str .= "-1";
}
Of course the limitation of this is that it can only get the last digit.. what if the number was 10?
$str = "some-string-that-might-end-in-a-number";
$strLen = strlen($str);
$numberOfDigits = 0;
for($i=$strLen-1; $i>0; $i--)
{
if(intval($str[$i])==0)
{
$numberOfDigits = $strLen-($i-1);
break;
}
}
//Now lets do the digit modification
$newNumber = 0;
for($i=1; $i<=$numberOfDigits; $i++)
{
$newNumber += intval($str[$strLen-$i])*((10*$i)-10));
}
if($newNumber == 0)
{ $newNumber = 1; }
$newStr = "-{$newNumber}";
//Now lets add the new string to the old one
$str = substr($str, 0, ($numberOfDigits*-1)).$newNumber;

Scrambled PHP code needs some fixing

I was adding a modification for my phpBB3 discussion board and one of the steps was to add a line of code to includes/functions.php
So when I copied that file and opened in wordpad I saw that it looked all scrambled. Here is how it looks partly:
<?php /** * * #package phpBB3 * #version $Id$ * #copyright (c) 2005 phpBB Group * #license http://opensource.org/licenses/gpl-license.php GNU Public License * */ /** * #ignore */ if (!defined('IN_PHPBB')) { exit; } // Common global functions /** * set_var * * Set variable, used by {#link request_var the request_var function} * * #access private */ function set_var(&$result, $var, $type, $multibyte = false) { settype($var, $type); $result = $var; if ($type == 'string') { $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $result), ENT_COMPAT, 'UTF-8')); if (!empty($result)) { // Make sure multibyte characters are wellformed if ($multibyte) { if (!preg_match('/^./u', $result)) { $result = ''; } } else { // no multibyte, allow only ASCII (0-127) $result = preg_replace('/[\x80-\xFF]/', '?', $result); } } $result = (STRIP) ? stripslashes($result) : $result; } } /** * request_var * * Used to get passed variable */ function request_var($var_name, $default, $multibyte = false, $cookie = false) { if (!$cookie && isset($_COOKIE[$var_name])) { if (!isset($_GET[$var_name]) && !isset($_POST[$var_name])) { return (is_array($default)) ? array() : $default; } $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name]; } $super_global = ($cookie) ? '_COOKIE' : '_REQUEST'; if (!isset($GLOBALS[$super_global][$var_name]) || is_array($GLOBALS[$super_global][$var_name]) != is_array($default)) { return (is_array($default)) ? array() : $default; } $var = $GLOBALS[$super_global][$var_name]; if (!is_array($default)) { $type = gettype($default); } else { list($key_type, $type) = each($default); $type = gettype($type); $key_type = gettype($key_type); if ($type == 'array') { reset($default); $default = current($default); list($sub_key_type, $sub_type) = each($default); $sub_type = gettype($sub_type); $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type; $sub_key_type = gettype($sub_key_type); } } if (is_array($var)) { $_var = $var; $var = array(); foreach ($_var as $k => $v) { set_var($k, $k, $key_type); if ($type == 'array' && is_array($v)) { foreach ($v as $_k => $_v) { if (is_array($_v)) { $_v = null; } set_var($_k, $_k, $sub_key_type, $multibyte); set_var($var[$k][$_k], $_v, $sub_type, $multibyte); } } else { if ($type == 'array' || is_array($v)) { $v = null; } set_var($var[$k], $v, $type, $multibyte); } } } else { set_var($var, $var, $type, $multibyte); } return $var; } /** * Set config value. Creates missing config entry. */ function set_config($config_name, $config_value, $is_dynamic = false) { global $db, $cache, $config; $sql = 'UPDATE ' . CONFIG_TABLE . " SET config_value = '" . $db->sql_escape($config_value) . "' WHERE config_name = '" . $db->sql_escape($config_name) . "'"; $db->sql_query($sql); if (!$db->sql_affectedrows() && !isset($config[$config_name])) { $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array( 'config_name' => $config_name, 'config_value' => $config_value, 'is_dynamic' => ($is_dynamic) ? 1 : 0)); $db->sql_query($sql); } $config[$config_name] = $config_value; if (!$is_dynamic) { $cache->destroy('config'); } } /** * Set dynamic config value with arithmetic operation. */ function set_config_count($config_name, $increment, $is_dynamic = false) { global $db, $cache; switch ($db->sql_layer) { case 'firebird': case 'postgres': $sql_update = 'CAST(CAST(config_value as DECIMAL(255, 0)) + ' . (int) $increment . ' as VARCHAR(255))'; break; // MySQL, SQlite, mssql, mssql_odbc, oracle default: $sql_update = 'config_value + ' . (int) $increment; break; } $db->sql_query('UPDATE ' . CONFIG_TABLE . ' SET config_value = ' . $sql_update . " WHERE config_name = '" . $db->sql_escape($config_name) . "'"); if (!$is_dynamic) { $cache->destroy('config'); } } /** * Generates an alphanumeric random string of given length * * #return string */ function gen_rand_string($num_chars = 8) { // [a, z] + [0, 9] = 36 return substr(strtoupper(base_convert(unique_id(), 16, 36)), 0, $num_chars); } /** * Generates a user-friendly alphanumeric random string of given length * We remove 0 and O so users cannot confuse those in passwords etc. * * #return string */ function gen_rand_string_friendly($num_chars = 8) { $rand_str = unique_id(); // Remove Z and Y from the base_convert(), replace 0 with Z and O with Y // [a, z] + [0, 9] - {z, y} = [a, z] + [0, 9] - {0, o} = 34 $rand_str = str_replace(array('0', 'O'), array('Z', 'Y'), strtoupper(base_convert($rand_str, 16, 34))); return substr($rand_str, 0, $num_chars); } /** * Return unique id * #param string $extra additional entropy */ function unique_id($extra = 'c') { static $dss_seeded = false; global $config; $val = $config['rand_seed'] . microtime(); $val = md5($val); $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra); if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10))) { set_config('rand_seed', $config['rand_seed'], true); set_config('rand_seed_last_update', time(), true); $dss_seeded = true; } return substr($val, 4, 16); } /** * Return formatted string for filesizes * * #param int $value filesize in bytes * #param bool $string_only true if language string should be returned * #param array $allowed_units only allow these units (data array indexes) * * #return mixed data array if $string_only is false * #author bantu */ function get_formatted_filesize($value, $string_only = true, $allowed_units = false) { global $user; $available_units = array( 'gb' => array( 'min' => 1073741824, // pow(2, 30) 'index' => 3, 'si_unit' => 'GB', 'iec_unit' => 'GIB', ), 'mb' => array( 'min' => 1048576, // pow(2, 20) 'index' => 2, 'si_unit' => 'MB', 'iec_unit' => 'MIB', ), 'kb' => array( 'min' => 1024, // pow(2, 10) 'index' => 1, 'si_unit' => 'KB', 'iec_unit' => 'KIB', ), 'b' => array( 'min' => 0, 'index' => 0, 'si_unit' => 'BYTES', // Language index 'iec_unit' => 'BYTES', // Language index ), ); foreach ($available_units as $si_identifier => $unit_info) { if (!empty($allowed_units) && $si_identifier != 'b' && !in_array($si_identifier, $allowed_units)) { continue; } if ($value >= $unit_info['min']) { $unit_info['si_identifier'] = $si_identifier; break; } } unset($available_units); for ($i = 0; $i < $unit_info['index']; $i++) { $value /= 1024; } $value = round($value, 2); // Lookup units in language dictionary $unit_info['si_unit'] = (isset($user->lang[$unit_info['si_unit']])) ? $user->lang[$unit_info['si_unit']] : $unit_info['si_unit']; $unit_info['iec_unit'] = (isset($user->lang[$unit_info['iec_unit']])) ? $user->lang[$unit_info['iec_unit']] : $unit_info['iec_unit']; // Default to IEC $unit_info['unit'] = $unit_info['iec_unit']; if (!$string_only) { $unit_info['value'] = $value; return $unit_info; } return $value . ' ' . $unit_info['unit']; } /** * Determine whether we are approaching the maximum execution time. Should be called once * at the beginning of the script in which it's used. * #return bool Either true if the maximum execution time is nearly reached, or false * if some time is still left. */ function still_on_time($extra_time = 15) { static $max_execution_time, $start_time; $time = explode(' ', microtime()); $current_time = $time[0] + $time[1]; if (empty($max_execution_time)) { $max_execution_time = (function_exists('ini_get')) ? (int) #ini_get('max_execution_time') : (int) #get_cfg_var('max_execution_time'); // If zero, then set to something higher to not let the user catch the ten seconds barrier. if ($max_execution_time === 0) { $max_execution_time = 50 + $extra_time; } $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50); // For debugging purposes // $max_execution_time = 10; global $starttime; $start_time = (empty($starttime)) ? $current_time : $starttime; } return (ceil($current_time - $start_time) < $max_execution_time) ? true : false; } /** * * #version Version 0.1 / slightly modified for phpBB 3.0.x (using $H$ as hash type identifier) * * Portable PHP password hashing framework. * * Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in * the public domain. * * There's absolutely no warranty. * * The homepage URL for this framework is: * * http://www.openwall.com/phpass/ * * Please be sure to update the Version line if you edit this file in any way. * It is suggested that you leave the main version number intact, but indicate * your project name (after the slash) and add your own revision information. * * Please do not change the "private" password hashing method implemented in * here, thereby making your hashes incompatible. However, if you must, please * change the hash type identifier (the "$P$") to something different. * * Obviously, since this code is in the public domain, the above are not * requirements (there can be none), but merely suggestions. * * * Hash the password */ function phpbb_hash($password) { $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; $random_state = unique_id(); $random = ''; $count = 6; if (($fh = #fopen('/dev/urandom', 'rb'))) { $random = fread($fh, $count); fclose($fh); } if (strlen($random) < $count) { $random = ''; for ($i = 0; $i < $count; $i += 16) { $random_state = md5(unique_id() . $random_state); $random .= pack('H*', md5($random_state)); } $random = substr($random, 0, $count); } $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64); if (strlen($hash) == 34) { return $hash; } return md5($password); } /** * Check for correct password * * #param string $password The password in plain text * #param string $hash The stored password hash * * #return bool Returns true if the password is correct, false if not. */ function phpbb_check_hash($password, $hash) { $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; if (strlen($hash) == 34) { return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false; } return (md5($password) === $hash) ? true : false; } /** * Generate salt for hash generation */ function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6) { if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) { $iteration_count_log2 = 8; } $output = '$H$'; $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)]; $output .= _hash_encode64($input, 6, $itoa64); return $output; } /** * Encode hash */ function _hash_encode64($input, $count, &$itoa64) { $output = ''; $i = 0; do { $value = ord($input[$i++]); $output .= $itoa64[$value & 0x3f]; if ($i < $count) { $value |= ord($input[$i]) << 8; } $output .= $itoa64[($value >> 6) & 0x3f]; if ($i++ >= $count) { break; } if ($i < $count) { $value |= ord($input[$i]) << 16; } $output .= $itoa64[($value >> 12) & 0x3f]; if ($i++ >= $count) { break; } $output .= $itoa64[($value >> 18) & 0x3f]; } while ($i < $count); return $output; } /** * The crypt function/replacement */ function _hash_crypt_private($password, $setting, &$itoa64) { $output = '*'; // Check for correct hash if (substr($setting, 0, 3) != '$H$') { return $output; } $count_log2 = strpos($itoa64, $setting[3]); if ($count_log2 < 7 || $count_log2 > 30) { return $output; } $count = 1 << $count_log2; $salt = substr($setting, 4, 8); if (strlen($salt) != 8) { return $output; } /** * We're kind of forced to use MD5 here since it's the only * cryptographic primitive available in all versions of PHP * currently in use. To implement our own low-level crypto * in PHP would result in much worse performance and * consequently in lower iteration counts and hashes that are * quicker to crack (by non-PHP code). */ if (PHP_VERSION >= 5) { $hash = md5($salt . $password, true); do { $hash = md5($hash . $password, true); } while (--$count); } else { $hash = pack('H*', md5($salt . $password)); do { $hash = pack('H*', md5($hash . $password)); } while (--$count); } $output = substr($setting, 0, 12); $output .= _hash_encode64($hash, 16, $itoa64); return $output; } /** * Hashes an email address to a big integer * * #param string $email Email address * * #return string Unsigned Big Integer */ function phpbb_email_hash($email) { return sprintf('%u', crc32(strtolower($email))) . strlen($email); } /** * Global function for chmodding directories and files for internal use * * This function determines owner and group whom the file belongs to and user and group of PHP and then set safest possible file permissions. * The function determines owner and group from common.php file and sets the same to the provided file. * The function uses bit fields to build the permissions. * The function sets the appropiate execute bit on directories. * * Supported constants representing bit fields are: * * CHMOD_ALL - all permissions (7) * CHMOD_READ - read permission (4) * CHMOD_WRITE - write permission (2) * CHMOD_EXECUTE - execute permission (1) * * NOTE: The function uses POSIX extension and fileowner()/filegroup() functions. If any of them is disabled, this function tries to build proper permissions, by calling is_readable() and is_writable() functions. * * #param string $filename The file/directory to be chmodded * #param int $perms Permissions to set * * #return bool true on success, otherwise false * #author faw, phpBB Group */ function phpbb_chmod($filename, $perms = CHMOD_READ) { static $_chmod_info; // Return if the file no longer exists. if (!file_exists($filename)) { return false; } // Determine some common vars if (empty($_chmod_info)) { if (!function_exists('fileowner') || !function_exists('filegroup')) { // No need to further determine owner/group - it is unknown $_chmod_info['process'] = false; } else { global $phpbb_root_path, $phpEx; // Determine owner/group of common.php file and the filename we want to change here $common_php_owner = #fileowner($phpbb_root_path . 'common.' . $phpEx); $common_php_group = #filegroup($phpbb_root_path . 'common.' . $phpEx); // And the owner and the groups PHP is running under. $php_uid = (function_exists('posix_getuid')) ? #posix_getuid() : false; $php_gids = (function_exists('posix_getgroups')) ? #posix_getgroups() : false; // If we are unable to get owner/group, then do not try to set them by guessing if (!$php_uid || empty($php_gids) || !$common_php_owner || !$common_php_group) { $_chmod_info['process'] = false; } else { $_chmod_info = array( 'process' => true, 'common_owner' => $common_php_owner, 'common_group' => $common_php_group, 'php_uid' => $php_uid, 'php_gids' => $php_gids, ); } } } if ($_chmod_info['process']) { $file_uid = #fileowner($filename); $file_gid = #filegroup($filename); // Change owner if (#chown($filename, $_chmod_info['common_owner'])) { clearstatcache(); $file_uid = #fileowner($filename); } // Change group if (#chgrp($filename, $_chmod_info['common_group'])) { clearstatcache(); $file_gid = #filegroup($filename); } // If the file_uid/gid now match the one from common.php we can process further, else we are not able to change something if ($file_uid != $_chmod_info['common_owner'] || $file_gid != $_chmod_info['common_group']) { $_chmod_info['process'] = false; } } // Still able to process? if ($_chmod_info['process']) { if ($file_uid == $_chmod_info['php_uid']) { $php = 'owner'; } else if (in_array($file_gid, $_chmod_info['php_gids'])) { $php = 'group'; } else { // Since we are setting the everyone bit anyway, no need to do expensive operations $_chmod_info['process'] = false; } } // We are not able to determine or change something if (!$_chmod_info['process']) { $php = 'other'; } // Owner always has read/write permission $owner = CHMOD_READ | CHMOD_WRITE; if (is_dir($filename)) { $owner |= CHMOD_EXECUTE; // Only add execute bit to the permission if the dir needs to be readable if ($perms & CHMOD_READ) { $perms |= CHMOD_EXECUTE; } } switch ($php) { case 'owner': $result = #chmod($filename, ($owner << 6) + (0 << 3) + (0 << 0)); clearstatcache(); if (is_readable($filename) && phpbb_is_writable($filename)) { break; } case 'group': $result = #chmod($filename, ($owner << 6) + ($perms << 3) + (0 << 0)); clearstatcache(); if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename))) { break; } case 'other': $result = #chmod($filename, ($owner << 6) + ($perms << 3) + ($perms << 0)); clearstatcache(); if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename))) { break; } default: return false; break; } return $result; } /** * Test if a file/directory is writable * * This function calls the native is_writable() when not running under * Windows and it is not disabled. * * #param string $file Path to perform write test on * #return bool True when the path is writable, otherwise false. */ function phpbb_is_writable($file) { if (strtolower(substr(PHP_OS, 0, 3)) === 'win' || !function_exists('is_writable')) { if (file_exists($file)) { // Canonicalise path to absolute path $file = phpbb_realpath($file); if (is_dir($file)) { // Test directory by creating a file inside the directory $result = #tempnam($file, 'i_w'); if (is_string($result) && file_exists($result)) { unlink($result); // Ensure the file is actually in the directory (returned realpathed) return (strpos($result, $file) === 0) ? true : false; } } else { $handle = #fopen($file, 'r+'); if (is_resource($handle)) { fclose($handle); return true; } } } else { // file does not exist test if we can write to the directory $dir = dirname($file); if (file_exists($dir) && is_dir($dir) && phpbb_is_writable($dir)) { return true; } } return false; } else { return is_writable($file); } } // Compatibility functions if (!function_exists('array_combine')) { /** * A wrapper for the PHP5 function array_combine() * #param array $keys contains keys for the resulting array * #param array $values contains values for the resulting array * * #return Returns an array by using the values from the keys array as keys and the * values from the values array as the corresponding values. Returns false if the * number of elements for each array isn't equal or if the arrays are empty. */ function array_combine($keys, $values) { $keys = array_values($keys); $values = array_values($values); $n = sizeof($keys); $m = sizeof($values); if (!$n || !$m || ($n != $m)) { return false; } $combined = array(); for ($i = 0; $i < $n; $i++) { $combined[$keys[$i]] = $values[$i]; } return $combined; } } if (!function_exists('str_split')) { /** * A wrapper for the PHP5 function str_split() * #param array $string contains the string to be converted * #param array $split_length contains the length of each chunk * * #return Converts a string to an array. If the optional split_length parameter is specified, * the returned array will be broken down into
As you can see all the new lines are cut so its just a big mess. I did still add the new code and it messed everything up. What can I do? Is there some type of script or anything that I can run this php file through that will fix lines? Note that I have no experience with PHP so please be detailed in your reply!
Both WordPad and Notepad++ handle UNIX-style newlines fine. I'm guessing that you or someone else previously opened and saved it with another program such as Notepad, which doesn't understand such newlines and probably messed it up. If you haven't modified the file so far, the simplest solution might be to get a fresh copy of this file from the phpBB3 archive.
The file was probably created in *Nix, and uses the Unix newlines. Wordpad likely can't handle those.
Try opening it up with a program that can handle the different types of newline styles, like Notepad++.
http://beta.phpformatter.com/
This will make your code look better.
See the other solutions or try:
<?php
file_put_contents("source-fixed.php",
str_replace("\n", "\r\n", file_get_contents("source.php")));
?>
Adjust the file names accordingly, of course.

Categories