File: //opt/proundcontra.mosmuc.de/etc/common.php
<?php
/********************************************************************************
* The contents of this file are subject to the Common Public Attribution License
* Version 1.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.wikiarguments.net/license/. The License is based on the Mozilla
* Public License Version 1.1 but Sections 14 and 15 have been added to cover
* use of software over a computer network and provide for limited attribution
* for the Original Developer. In addition, Exhibit A has been modified to be
* consistent with Exhibit B.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is Wikiarguments. The Original Developer is the Initial
* Developer and is Wikiarguments GbR. All portions of the code written by
* Wikiarguments GbR are Copyright (c) 2012. All Rights Reserved.
* Contributor(s):
* Andreas Wierz (andreas.wierz@gmail.com).
*
* Attribution Information
* Attribution Phrase (not exceeding 10 words): Powered by Wikiarguments
* Attribution URL: http://www.wikiarguments.net
*
* This display should be, at a minimum, the Attribution Phrase displayed in the
* footer of the page and linked to the Attribution URL. The link to the Attribution
* URL must not contain any form of 'nofollow' attribute.
*
* Display of Attribution Information is required in Larger Works which are
* defined in the CPAL as a work which combines Covered Code or portions
* thereof with code not governed by the terms of the CPAL.
*******************************************************************************/
/**
* Generate a random password with letters/numbers but no ambiguous chars
*/
function generatePassword($len = 8, $alphabet = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789")
{
$pass = "";
$alph_len = strlen($alphabet) - 1;
for ($i = 0; $i < $len; $i++)
{
$pos = round(mt_rand(0, $alph_len));
$pass .= substr($alphabet, $pos, 1);
}
return $pass;
}
function salt($len = 16)
{
return generatePassword($len);
}
/**
* a($value) => string-escape for MySQL
* If $value is null, convert to "" to avoid deprecation warnings.
* If $sDB->getLink() is null, just return $value as-is (or ""),
* but note you won't be fully escaped in that scenario.
*/
function a($value)
{
if (is_array($value)) {
// original logic returns NULL if it's an array
return null;
}
global $sDB;
$link = $sDB ? $sDB->getLink() : null;
if (!$link) {
// fallback if no DB connection
// to avoid "passing null to mysqli_real_escape_string"
return $value ?? "";
}
// If $value is NULL, use "" to avoid deprecated warnings
$val = $value ?? "";
return mysqli_real_escape_string($link, $val);
}
/**
* i($value) => integer cast
*/
function i($value)
{
if(!is_array($value))
{
return intval($value);
} else {
return null;
}
}
function send_mail_from($from, $fromName, $to, $subject, $message)
{
$mail = new HTMLMail($to, $to, $fromName, $from);
$mail->buildMessage($subject, $message);
$mail->sendmail();
}
function br2nl($string)
{
return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}
/**
* Timer class for measuring code performance
* Use a modern PHP constructor instead of "public function Timer()".
*/
class Timer
{
public function __construct()
{
$this->m_timer = 0;
$this->m_start = 0;
}
public function start()
{
$this->m_start = microtime(true);
}
public function stop()
{
if ($this->m_start > 0) {
$this->m_timer += (microtime(true) - $this->m_start);
$this->m_start = 0;
}
}
public function getTimeElapsed()
{
return $this->m_timer;
}
public function getTimeElapsedMs()
{
return $this->m_timer * 1000;
}
public function isRunning()
{
return ($this->m_start != 0);
}
private $m_timer;
private $m_start;
}
/*
* valid usernames are alphanumeric and contain no badwords
*/
function isValidUsername($userName)
{
global $sDB;
if($userName == "")
{
return false;
}
mb_internal_encoding("UTF-8");
if(mb_strlen($userName) > USERNAME_MAX_LEN)
{
return false;
}
// check for invalid chars
if(preg_match("/[^\\w-_!§\$%&\\(\\)\\[\\]{}*#\\|öäüÖÄÜáàâéèêíìîóòôúùû]/i", $userName)) {
return false;
}
// check the badwords table
$res = $sDB->exec("SELECT * FROM `badwords` WHERE `category` IN (".BADWORD_CATEGORY_ALL.", ".BADWORD_CATEGORY_USERNAME.");");
while($row = mysqli_fetch_object($res))
{
if(preg_match("/".$row->word."/i", $userName))
{
return false;
}
}
return true;
}
/**
* Return lon/lat/city for a postal code
*/
function getPositionByPostalCode($country_code, $postal_code)
{
global $sDB;
$ret = array("lon" => 0, "lat" => 0, "city" => "");
$escCountry = a($country_code);
$escPostal = a($postal_code);
$qry = "SELECT lat, lon, place_name, admin_name1, admin_name2, admin_name3
FROM `geonames`
WHERE `country_code` = '$escCountry'
AND `postal_code` = '$escPostal'
AND `lat` != 0
AND `lon` != 0
LIMIT 1;";
$res = $sDB->exec($qry);
if(!mysqli_num_rows($res) && ctype_digit($postal_code))
{
// try a range lookup if the postal_code is integral
$qry = "SELECT lat, lon, place_name, admin_name1, admin_name2, admin_name3
FROM `geonames`
WHERE `country_code` = '$escCountry'
AND `postal_code` >= '".i($postal_code)."'
AND `postal_code` <= '".i($postal_code + 1000)."'
AND `lat` != 0
AND `lon` != 0
ORDER BY `postal_code`
LIMIT 1;";
$res = $sDB->exec($qry);
}
if(mysqli_num_rows($res))
{
$row = mysqli_fetch_object($res);
$ret["lon"] = $row->lon;
$ret["lat"] = $row->lat;
$ret["city"] = $row->place_name;
$ret["admin_name1"] = $row->admin_name1;
$ret["admin_name2"] = $row->admin_name2;
$ret["admin_name3"] = $row->admin_name3;
}
return $ret;
}
function validateQuestionType($type, $redirect = true)
{
global $sTemplate;
if(!in_array($type, array(QUESTION_TYPE_LISTED, QUESTION_TYPE_UNLISTED)))
{
if($redirect)
{
$sTemplate->error($sTemplate->getString("ERROR_INVALID_QUESTION_TYPE"));
}
return false;
}
return true;
}
function validateQuestionFlags($flags, $redirect = true)
{
return true; // Not implemented, always returns true
}
function complementFaction($faction)
{
if($faction == FACTION_PRO) {
return FACTION_CON;
} else if($faction == FACTION_CON) {
return FACTION_PRO;
}
return FACTION_NONE;
}
/**
* Return a time-since string (e.g. "2 days ago") using loc strings
*/
function timeSinceString($date)
{
global $sTemplate;
$diff = max(time() - $date, 1);
$years = floor($diff / (60 * 60 * 24 * 30 * 12));
$diff -= $years * (60 * 60 * 24 * 30 * 12);
$month = floor($diff / (60 * 60 * 24 * 30));
$diff -= $month * (60 * 60 * 24 * 30);
$days = floor($diff / (60 * 60 * 24));
$diff -= $days * (60 * 60 * 24);
$hours = floor($diff / (60 * 60));
$diff -= $hours * (60 * 60);
$minutes= floor($diff / 60);
$diff -= $minutes * 60;
$seconds= $diff;
$langVar = false;
$var = false;
if ($years) {
$var = $years;
$langVar = "TIME_SINCE_YEARS";
} else if ($month) {
$var = $month;
$langVar = "TIME_SINCE_MONTHS";
} else if ($days) {
$var = $days;
$langVar = "TIME_SINCE_DAYS";
} else if ($hours) {
$var = $hours;
$langVar = "TIME_SINCE_HOURS";
} else if ($minutes) {
$var = $minutes;
$langVar = "TIME_SINCE_MINUTES";
} else {
$var = $seconds;
$langVar = "TIME_SINCE_SECONDS";
}
return $sTemplate->getStringNumber(
$langVar,
array("[YEARS]", "[MONTHS]", "[DAYS]", "[HOURS]", "[MINUTES]", "[SECONDS]"),
array($years, $month, $days, $hours, $minutes, $seconds),
$var
);
}
/**
* Basic Packet class
*/
class Packet
{
public function __construct($opcode = "SMSG_UNKNOWN_OPCODE", $data = "")
{
$this->opcode = $opcode;
$this->data = $data;
}
public $opcode;
public $data;
}
/**
* The main Request object for GET/POST
*/
class Request
{
public function __construct()
{
// nothing special by default
}
public function getString($key)
{
global $sDB;
// if $this->getPlain($key) is NULL, we pass "" to avoid deprecation
$plain = $this->getPlain($key) ?? "";
return mysqli_real_escape_string($sDB->getLink(), $plain);
}
public function getStringPlain($key)
{
$val = $this->getPlain($key);
return (is_string($val) ? $val : '');
}
public function getObject($key)
{
$val = $this->getPlain($key);
return (is_object($val) ? $val : new stdClass());
}
public function getArray($key)
{
$val = $this->getPlain($key);
return (is_array($val) ? $val : array());
}
public function getInt($key)
{
return i($this->getPlain($key));
}
private function getPlain($key)
{
if (isset($_GET[$key])) {
return $_GET[$key];
}
if (isset($_POST[$key])) {
return $_POST[$key];
}
if (isset($_REQUEST[$key])) {
return $_REQUEST[$key];
}
return null;
}
}
/**
* Extended Request object for AJAX
*/
class AjaxRequest extends Request
{
public function __construct($data)
{
$this->data = $data;
}
public function getString($key)
{
global $sDB;
$plain = $this->getPlain($key) ?? "";
return mysqli_real_escape_string($sDB->getLink(), $plain);
}
// getStringPlain, getObject, getArray, getInt similarly override
// with references to $this->data.
private function getPlain($key)
{
if (is_array($key)) {
// nested access
$c = $this->data;
foreach ($key as $v) {
if (isset($c->$v)) {
$c = $c->$v;
} else {
return null;
}
}
return $c;
} else {
return $this->data->$key ?? null;
}
}
private $data;
}
/**
* Basic packet handler classes
*/
class PacketHandlerStatic
{
public function __construct()
{
}
}
class PacketHandler
{
public function __construct(Request $requestObj, Packet $response)
{
$this->_requestObj = $requestObj;
$this->_response = $response;
}
protected $_requestObj;
protected $_response;
}
/**
* Convert between numeric bases 10 <-> 62
*/
class BaseConvert
{
public function __construct($_number='', $_frBase=10, $_toBase=62)
{
// your original code
$_10to62 = array(
// ...
);
$_62to10 = array(
// ...
);
// Convert to base10
$_in_b10 = 0;
$_pwr_of_frB = 1;
$_chars = str_split($_number);
$_str_len = strlen($_number);
$_pos = 0;
while ($_pos++ < $_str_len) {
$_char = $_chars[$_str_len - $_pos];
$_in_b10 += (((int)$_62to10[$_char]) * $_pwr_of_frB);
$_pwr_of_frB *= $_frBase;
}
// convert to new base
$_dividend = (int)$_in_b10;
$_in_toB = '';
while ($_dividend > 0) {
$_quotient = (int) ($_dividend / $_toBase);
$_remainder = ''.($_dividend % $_toBase);
$_in_toB = $_10to62[$_remainder] . $_in_toB;
$_dividend = $_quotient;
}
if ($_in_toB == '') {
$_in_toB = '0';
}
$this->_in_toB = $_in_toB;
}
public function val()
{
return $this->_in_toB;
}
private $_in_toB;
};
function url_sanitize($url)
{
mb_internal_encoding("UTF-8");
$url = mb_ereg_replace("[^A-Za-z0-9]", "-", mb_strtolower($url));
return $url;
}
?>