PageRenderTime 33ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/library/Framework/Framework.Functions.php

http://lussumo-vanilla.googlecode.com/
PHP | 1016 lines | 753 code | 97 blank | 166 comment | 272 complexity | ec9d90d3e03b928b62c4a532c7c150cb MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, Apache-2.0
  1. <?php
  2. /**
  3. * Non-application specific helper functions
  4. * Applications utilizing this file: Vanilla; Filebrowser;
  5. *
  6. * Copyright 2003 Mark O'Sullivan
  7. * This file is part of Lussumo's Software Library.
  8. * Lussumo's Software Library 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 2 of the License, or (at your option) any later version.
  9. * Lussumo's Software Library 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.
  10. * You should have received a copy of the GNU General Public License along with Vanilla; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  11. * The latest source code is available at www.vanilla1forums.com
  12. * Contact Mark O'Sullivan at mark [at] lussumo [dot] com
  13. *
  14. * @author Mark O'Sullivan
  15. * @copyright 2003 Mark O'Sullivan
  16. * @license http://www.gnu.org/licenses/gpl-2.0.html GPL 2
  17. * @package Framework
  18. */
  19. function AddConfigurationSetting(&$Context, $SettingName, $SettingValue = '1') {
  20. if (!array_key_exists($SettingName, $Context->Configuration) || $Context->Configuration[$SettingName] != $SettingValue) {
  21. $Context->Configuration[$SettingName] = '';
  22. $SettingsManager = $Context->ObjectFactory->NewContextObject($Context, 'ConfigurationManager');
  23. $SettingsFile = $Context->Configuration['APPLICATION_PATH'].'conf/settings.php';
  24. $SettingsManager->DefineSetting($SettingName, $SettingValue, 1);
  25. $SettingsManager->SaveSettingsToFile($SettingsFile);
  26. }
  27. }
  28. function AddDaysToTimeStamp($TimeStamp, $NumberOfDaysToAdd) {
  29. if ($NumberOfDaysToAdd == 0) {
  30. return $TimeStamp;
  31. } else {
  32. return strtotime('+'.$NumberOfDaysToAdd.' day', $TimeStamp);
  33. }
  34. }
  35. // Append a folder (or file) to an existing path (ensures the / exists)
  36. function AppendFolder($RootPath, $FolderToAppend) {
  37. if (substr($RootPath, strlen($RootPath)-1, strlen($RootPath)) == '/') $RootPath = substr($RootPath, 0, strlen($RootPath) - 1);
  38. if (substr($FolderToAppend,0,1) == '/') $FolderToAppend = substr($FolderToAppend,1,strlen($FolderToAppend));
  39. return $RootPath.'/'.$FolderToAppend;
  40. }
  41. /**
  42. * Appends code to a php file, typically used for configuration.
  43. *
  44. * The php ending tag "?>" should be either on its own line,
  45. * or be ommited all together
  46. *
  47. * @param string $File Path to configuration file.
  48. * @param string $Append Code to append.
  49. * @return boolean
  50. */
  51. function AppendToConfigurationFile($File, $Append) {
  52. $Success = 0;
  53. if (file_exists($File)) {
  54. $Lines = file($File);
  55. for ($i=0, $c=count($Lines); $i < $c; $i++) {
  56. if (substr(trim($Lines[$i]), 0, 2) == '?>') {
  57. array_splice($Lines, $i);
  58. break;
  59. }
  60. }
  61. $Lines[] = rtrim($Append) . "\r\n";
  62. $Handle = @fopen($File, 'wb');
  63. if ($Handle) {
  64. $Success = @fwrite($Handle, implode('', $Lines));
  65. @fclose($Handle);
  66. }
  67. }
  68. return $Success;
  69. }
  70. /**
  71. * Makes sure that a url and some parameters are concatentated properly
  72. * (ie. an ampersand is used instead of a question mark when necessary)
  73. *
  74. * @param string $Url
  75. * @param string $Parameters
  76. * @return string
  77. */
  78. function AppendUrlParameters($Url, $Parameters) {
  79. $ReturnUrl = $Url;
  80. $ReturnUrl .= (strpos($Url, '?') === false) ? '?' : '&';
  81. $ReturnUrl .= $Parameters;
  82. return $ReturnUrl;
  83. }
  84. // Make sure objects can be cloned in PHP 4 and 5.
  85. // Example: $NewObject = clone ($ObjectName);
  86. // Note: Make sure the space appears between "clone" and the
  87. // first parentheses so that the clone statement in 5
  88. // doesn't break.
  89. if (version_compare(phpversion(), '5.0') < 0) {
  90. eval('
  91. function clone($object) {
  92. return $object;
  93. }
  94. ');
  95. }
  96. // Append two paths
  97. function ConcatenatePath($OriginalPath, $PathToConcatenate) {
  98. global $Configuration;
  99. if (strpos($PathToConcatenate, $Configuration['HTTP_METHOD'].'://') !== false) return $PathToConcatenate;
  100. if (substr($OriginalPath, strlen($OriginalPath)-1, strlen($OriginalPath)) != '/') $OriginalPath .= '/';
  101. if (substr($PathToConcatenate,0,1) == '/') $PathToConcatenate = substr($PathToConcatenate,1,strlen($PathToConcatenate));
  102. return $OriginalPath.$PathToConcatenate;
  103. }
  104. // Based on the total number of items and the number of items per page,
  105. // this function will calculate how many pages there are.
  106. // Returns the number of pages available
  107. function CalculateNumberOfPages($ItemCount, $ItemsPerPage) {
  108. $TmpCount = ($ItemCount/$ItemsPerPage);
  109. $RoundedCount = intval($TmpCount);
  110. $PageCount = 0;
  111. if ($TmpCount > 1) {
  112. if ($TmpCount > $RoundedCount) {
  113. $PageCount = $RoundedCount + 1;
  114. } else {
  115. $PageCount = $RoundedCount;
  116. }
  117. } else {
  118. $PageCount = 1;
  119. }
  120. return $PageCount;
  121. }
  122. function CleanupString($InString) {
  123. $Code = explode(',', '&lt;,&gt;,&#039;,&amp;,&quot;,?&#x20AC;,??,?&#x201A;,?&#x192;,?&#x201E;,&Auml;,?&#x2026;,Ä&#x20AC;,Ä&#x201E;,Ä&#x201A;,?&#x2020;,?&#x2021;,Ä&#x2020;,Ä&#x152;,Ä&#x2C6;,Ä&#x160;,Ä&#x17D;,Ä?,??,?&#x2C6;,?&#x2030;,?&#x160;,?&#x2039;,Ä&#x2019;,Ä&#x2DC;,Ä&#x161;,Ä&#x201D;,Ä&#x2013;,Ä&#x153;,Ä&#x17E;,Ä ,Ä?,Ĥ,Ä?,?&#x152;,??,?&#x17D;,??,Ä?,Ĩ,Ä?,Ď,Ä°,Ä?,Ä´,Ä?,??,Ä?,Ě,Ä?,Ä?,?&#x2018;,?&#x192;,?&#x2021;,?&#x2026;,?&#x160;,?&#x2019;,?&#x201C;,?&#x201D;,?&#x2022;,?&#x2013;,&Ouml;,?&#x2DC;,?&#x152;,??,?&#x17D;,?&#x2019;,?&#x201D;,?&#x2DC;,?&#x2013;,?&#x161;,? ,?&#x17E;,?&#x153;,?&#x2DC;,?¤,??,??,?&#x161;,?&#x2122;,?&#x161;,?&#x203A;,?&#x153;,??,&Uuml;,?Ž,?°,??,?¨,??,?´,??,??,?¸,?š,??,??,?&#x17E;,?&#x17E;,? ,??,??,??,?¤,&auml;,??,Ä?,Ä&#x2026;,Ä&#x192;,??,?§,Ä&#x2021;,Ä?,Ä&#x2030;,Ä&#x2039;,Ä?,Ä&#x2018;,?°,?¨,?Š,??,??,Ä&#x201C;,Ä&#x2122;,Ä&#x203A;,Ä&#x2022;,Ä&#x2014;,?&#x2019;,Ä?,Ä&#x;,Ä?,Ä?,Ä?,ħ,??,?­,?Ž,??,Ä?,Ċ,Ä­,Ä?,Ä?,Ä?,Ä?,Ä?,ĸ,?&#x201A;,Ğ,Ä?,Ä?,?&#x20AC;,??,?&#x201E;,?&#x2C6;,?&#x2020;,?&#x2030;,?&#x2039;,??,??,?´,??,??,&ouml;,?¸,??,?&#x2018;,??,?&#x201C;,?&#x2022;,?&#x2122;,?&#x2014;,??,?š,??,??,??,??,&uuml;,??,??,?­,?Š,??,??,??,??,??,?ž,??,??,?ž,?&#x;,??,??,?&#x2018;,?&#x2019;,?&#x201C;,?&#x201D;,?&#x2022;,??,?&#x2013;,?&#x2014;,?&#x2DC;,?&#x2122;,?&#x161;,?&#x203A;,?&#x153;,??,?&#x17E;,?&#x;,? ,??,??,??,?¤,??,??,?§,?¨,?Š,??,??,?­,?Ž,??,?°,??,??,??,?´,??,?&#x2018;,??,??,?¸,?š,??,??,??,??,?ž,??,?&#x20AC;,??,?&#x201A;,?&#x192;,?&#x201E;,?&#x2026;,?&#x2020;,?&#x2021;,?&#x2C6;,?&#x2030;,?&#x160;,?&#x2039;,??,?&#x17D;,??');
  124. $Translation = explode(',', ',,,,,A,A,A,A,Ae,A,A,A,A,A,Ae,C,C,C,C,C,D,D,D,E,E,E,E,E,E,E,E,E,G,G,G,G,H,H,I,I,I,I,I,I,I,I,I,IJ,J,K,K,K,K,K,K,N,N,N,N,N,O,O,O,O,Oe,Oe,O,O,O,O,OE,R,R,R,S,S,S,S,S,T,T,T,T,U,U,U,Ue,U,Ue,U,U,U,U,U,W,Y,Y,Y,Z,Z,Z,T,T,a,a,a,a,ae,ae,a,a,a,a,ae,c,c,c,c,c,d,d,d,e,e,e,e,e,e,e,e,e,f,g,g,g,g,h,h,i,i,i,i,i,i,i,i,i,ij,j,k,k,l,l,l,l,l,n,n,n,n,n,n,o,o,o,o,oe,oe,o,o,o,o,oe,r,r,r,s,u,u,u,ue,u,ue,u,u,u,u,u,w,y,y,y,z,z,z,t,ss,ss,A,B,V,G,D,E,YO,ZH,Z,I,Y,K,L,M,N,O,P,R,S,T,U,F,H,C,CH,SH,SCH,Y,Y,E,YU,YA,a,b,v,g,d,e,yo,zh,z,i,y,k,l,m,n,o,p,r,s,t,u,f,h,c,ch,sh,sch,y,y,e,yu,ya');
  125. $sReturn = $InString;
  126. $sReturn = str_replace($Code, $Translation, $sReturn);
  127. $sReturn = urldecode($sReturn);
  128. $sReturn = preg_replace('/[^A-Za-z0-9 ]/', '', $sReturn);
  129. $sReturn = str_replace(' ', '-', $sReturn);
  130. return strtolower(str_replace('--', '-', $sReturn));
  131. }
  132. function CreateArrayEntry(&$Array, $Key, $Value) {
  133. if (!array_key_exists($Key, $Array)) $Array[$Key] = $Value;
  134. }
  135. // performs the opposite of htmlentities
  136. function DecodeHtmlEntities($String) {
  137. /*
  138. $TranslationTable = get_html_translation_table(HTML_ENTITIES);
  139. print_r($TranslationTable);
  140. $TranslationTable = array_flip($TranslationTable);
  141. return strtr($String, $TranslationTable);
  142. return html_entity_decode(htmlentities($String, ENT_COMPAT, 'UTF-8'));
  143. */
  144. $String= html_entity_decode($String,ENT_QUOTES,'ISO-8859-1'); #NOTE: UTF-8 does not work!
  145. $String= preg_replace('/&#(\d+);/me','chr(\\1)',$String); #decimal notation
  146. $String= preg_replace('/&#x([a-f0-9]+);/mei','chr(0x\\1)',$String); #hex notation
  147. return $String;
  148. }
  149. // Functions
  150. function DefineExtensions(&$Context, $update=false) {
  151. $Extensions = array();
  152. $CurrExtensions = array();
  153. $CurrentExtensions = @file($Context->Configuration["APPLICATION_PATH"].'conf/extensions.php');
  154. if (!$CurrentExtensions) {
  155. $Context->WarningCollector->Add($Context->GetDefinition('ErrReadFileExtensions').$Context->Configuration["APPLICATION_PATH"].'conf/extensions.php');
  156. } else {
  157. foreach ($CurrentExtensions as $ExLine) {
  158. if (substr($ExLine, 0, 7) == 'include') {
  159. $CurrExtensions[] = substr(trim($ExLine), 43, -15);
  160. }
  161. }
  162. }
  163. // Examine Extensions directory
  164. $FolderHandle = @opendir($Context->Configuration["EXTENSIONS_PATH"]);
  165. if (!$FolderHandle) {
  166. $Context->WarningCollector->Add(
  167. str_replace("//1", $Context->Configuration["EXTENSIONS_PATH"], $Context->GetDefinition('ErrOpenDirectoryExtensions')));
  168. return false;
  169. } else {
  170. // Loop through each Extension folder
  171. while (false !== ($Item = readdir($FolderHandle))) {
  172. $Extension = $Context->ObjectFactory->NewObject($Context, 'Extension');
  173. $RecordItem = true;
  174. // Skip directories and hidden files
  175. if (
  176. strlen($Item) < 1
  177. || !is_dir($Context->Configuration["EXTENSIONS_PATH"].$Item)
  178. || !file_exists($Context->Configuration["EXTENSIONS_PATH"].$Item.'/default.php')
  179. ) continue;
  180. // Retrieve Extension properties
  181. $Lines = @file($Context->Configuration["EXTENSIONS_PATH"].$Item.'/default.php');
  182. if (!$Lines) {
  183. $Context->WarningCollector->Add($Context->GetDefinition('ErrReadExtensionDefinition')." {$Item}");
  184. } else {
  185. // We only examine the first 30 lines of the file
  186. $Header = array_slice($Lines, 0, 30);
  187. $Extension->FileName = $Item."/default.php";
  188. foreach ($Header as $CurrentLine) {
  189. @list($key, $val) = @explode(': ', trim($CurrentLine), 2);
  190. switch ($key) {
  191. case 'Extension Name':
  192. $Extension->Name = FormatStringForDisplay($val);
  193. break;
  194. case 'Extension Url':
  195. $Extension->Url = FormatStringForDisplay($val);
  196. break;
  197. case 'Description':
  198. $Extension->Description = FormatStringForDisplay($val);
  199. break;
  200. case 'Version':
  201. $Extension->Version = FormatStringForDisplay($val);
  202. break;
  203. case 'Author':
  204. $Extension->Author = FormatStringForDisplay($val);
  205. break;
  206. case 'Author Url':
  207. $Extension->AuthorUrl = FormatStringForDisplay($val);
  208. break;
  209. default:
  210. // Nothing
  211. }
  212. }
  213. if ($Extension->IsValid()) {
  214. $isOfficial = false;
  215. // Loop through the list of official extensions so we know to exclude them from update checking
  216. $OfficialExtensionsArray = explode (';', $Context->Configuration['OFFICIAL_EXTENSIONS']);
  217. foreach ($OfficialExtensionsArray as $OfficialExtension) {
  218. if ($Extension->Name == $OfficialExtension) {
  219. $isOfficial = true;
  220. }
  221. }
  222. // If the user is on the "Updates & Reminders" page
  223. if ($update == true) {
  224. // If this isn't an official extension, add it to the list of extensions to be checked for updates
  225. if ($isOfficial == false) {
  226. $Extension->Enabled = in_array($Item, $CurrExtensions);
  227. $Extensions[FormatExtensionKey($Extension->Name)] = $Extension;
  228. }
  229. // If the user is on the Extensions page
  230. } else {
  231. $Extension->Enabled = in_array($Item, $CurrExtensions);
  232. $Extensions[FormatExtensionKey($Extension->Name)] = $Extension;
  233. if ($isOfficial == true) {
  234. $Extension->Official = 1;
  235. }
  236. }
  237. }
  238. }
  239. }
  240. uksort($Extensions, "strnatcasecmp");
  241. return $Extensions;
  242. }
  243. }
  244. // This function is compliments of Entriple on the Lussumo Community
  245. function DefineVerificationKey() {
  246. return md5(
  247. sprintf(
  248. '%04x%04x%04x%03x4%04x%04x%04x%04x',
  249. mt_rand(0, 65535),
  250. mt_rand(0, 65535),
  251. mt_rand(0, 4095),
  252. bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
  253. mt_rand(0, 65535),
  254. mt_rand(0, 65535),
  255. mt_rand(0, 65535),
  256. mt_rand(0, 65535)
  257. )
  258. );
  259. }
  260. if (!function_exists('file_get_contents')) {
  261. /**
  262. * file_get_contents function for php 4.1.x and 4.2.x
  263. *
  264. * It is not the equivalent of the built-in php one
  265. * since it will always read the file in binary mode.
  266. *
  267. * @param string $FileName
  268. * @return unknown
  269. */
  270. function file_get_contents($FileName) {
  271. $Fp = fopen($FileName, 'rb');
  272. if ($Fp) {
  273. $Content = '';
  274. while (!feof($Fp)) {
  275. $Content .= fread($Fp, 4096);
  276. }
  277. return $Content;
  278. }
  279. return false;
  280. }
  281. }
  282. // return the opposite of the given boolean value
  283. function FlipBool($Bool) {
  284. $Bool = ForceBool($Bool, 0);
  285. return $Bool?0:1;
  286. }
  287. // Take a value and force it to be an array.
  288. function ForceArray($InValue, $DefaultValue) {
  289. if(is_array($InValue)) {
  290. $aReturn = $InValue;
  291. } else {
  292. // assume it's a string
  293. $sReturn = trim($InValue);
  294. $length = strlen($sReturn);
  295. if (empty($length) && strlen($sReturn) == 0) {
  296. $aReturn = $DefaultValue;
  297. } else {
  298. $aReturn = array($sReturn);
  299. }
  300. }
  301. return $aReturn;
  302. }
  303. // Force a boolean value
  304. // Accept a default value if the input value does not represent a boolean value
  305. function ForceBool($InValue, $DefaultBool) {
  306. // If the invalue doesn't exist (ie an array element that doesn't exist) use the default
  307. if (!$InValue) return $DefaultBool;
  308. $InValue = strtoupper($InValue);
  309. if ($InValue == 1) {
  310. return 1;
  311. } elseif ($InValue === 0) {
  312. return 0;
  313. } elseif ($InValue == 'Y') {
  314. return 1;
  315. } elseif ($InValue == 'N') {
  316. return 0;
  317. } elseif ($InValue == 'TRUE') {
  318. return 1;
  319. } elseif ($InValue == 'FALSE') {
  320. return 0;
  321. } else {
  322. return $DefaultBool;
  323. }
  324. }
  325. // Take a value and force it to be a float (decimal) with a specific number of decimal places.
  326. function ForceFloat($InValue, $DefaultValue, $DecimalPlaces = 2) {
  327. $fReturn = floatval($InValue);
  328. if ($fReturn == 0) $fReturn = $DefaultValue;
  329. $fReturn = number_format($fReturn, $DecimalPlaces);
  330. return $fReturn;
  331. }
  332. // Check both the get and post incoming data for a variable
  333. function ForceIncomingArray($VariableName, $DefaultValue) {
  334. // First check the querystring
  335. $aReturn = ForceSet(@$_GET[$VariableName], $DefaultValue);
  336. $aReturn = ForceArray($aReturn, $DefaultValue);
  337. // If the default value was defined, then check the post variables
  338. if ($aReturn == $DefaultValue) {
  339. $aReturn = ForceSet(@$_POST[$VariableName], $DefaultValue);
  340. $aReturn = ForceArray($aReturn, $DefaultValue);
  341. }
  342. return $aReturn;
  343. }
  344. // Check both the get and post incoming data for a variable
  345. function ForceIncomingBool($VariableName, $DefaultBool) {
  346. // First check the querystring
  347. $bReturn = ForceSet(@$_GET[$VariableName], $DefaultBool);
  348. $bReturn = ForceBool($bReturn, $DefaultBool);
  349. // If the default value was defined, then check the post variables
  350. if ($bReturn == $DefaultBool) {
  351. $bReturn = ForceSet(@$_POST[$VariableName], $DefaultBool);
  352. $bReturn = ForceBool($bReturn, $DefaultBool);
  353. }
  354. return $bReturn;
  355. }
  356. function ForceIncomingCookieString($VariableName, $DefaultValue) {
  357. $sReturn = ForceSet(@$_COOKIE[$VariableName], $DefaultValue);
  358. $sReturn = ForceString($sReturn, $DefaultValue);
  359. return $sReturn;
  360. }
  361. // Check both the get and post incoming data for a variable
  362. // Does not allow integers to be less than 0
  363. function ForceIncomingInt($VariableName, $DefaultValue) {
  364. // First check the querystring
  365. $iReturn = ForceSet(@$_GET[$VariableName], $DefaultValue);
  366. $iReturn = ForceInt($iReturn, $DefaultValue);
  367. // If the default value was defined, then check the form variables
  368. if ($iReturn == $DefaultValue) {
  369. $iReturn = ForceSet(@$_POST[$VariableName], $DefaultValue);
  370. $iReturn = ForceInt($iReturn, $DefaultValue);
  371. }
  372. // If the value found was less than 0, set it to the default value
  373. if($iReturn < 0) $iReturn = $DefaultValue;
  374. return $iReturn;
  375. }
  376. // Check both the get and post incoming data for a variable
  377. function ForceIncomingString($VariableName, $DefaultValue, $Trim=true) {
  378. if (isset($_GET[$VariableName])) {
  379. return Strip_Slashes(ForceString($_GET[$VariableName], $DefaultValue, $Trim));
  380. } elseif (isset($_POST[$VariableName])) {
  381. return Strip_Slashes(ForceString($_POST[$VariableName], $DefaultValue, $Trim));
  382. } else {
  383. return $DefaultValue;
  384. }
  385. }
  386. // Take a value and force it to be an integer.
  387. function ForceInt($InValue, $DefaultValue) {
  388. $iReturn = intval($InValue);
  389. return ($iReturn == 0) ? $DefaultValue : $iReturn;
  390. }
  391. // Takes a variable and checks to see if it's set.
  392. // Returns the value if set, or the default value if not set.
  393. function ForceSet($InValue, $DefaultValue) {
  394. return isset($InValue) ? $InValue : $DefaultValue;
  395. }
  396. // Take a value and force it to be a string.
  397. function ForceString($InValue, $DefaultValue, $Trim=true) {
  398. if (is_string($InValue)) {
  399. $sReturn = $Trim ? trim($InValue) : $InValue;
  400. if (empty($sReturn) && strlen($sReturn) == 0) $sReturn = $DefaultValue;
  401. } else {
  402. $sReturn = $DefaultValue;
  403. }
  404. return $sReturn;
  405. }
  406. /**
  407. * Check if the cookie domain is valid.
  408. * @todo the Pattern is quite loose
  409. * (don't ckeck the doamin names start by a letter or a digit, allow domain)
  410. * @param $CookieDomain string
  411. * @return string
  412. */
  413. function FormatCookieDomain($CookieDomain) {
  414. $Pattern = '/^[\.-_~a-zA-Z0-9]*\.?[-_~a-zA-Z0-9]+\.[-_~a-zA-Z0-9]+$/';
  415. $Match = preg_match($Pattern, $CookieDomain);
  416. if ($Match) {
  417. return $CookieDomain;
  418. } else {
  419. return '';
  420. }
  421. }
  422. function FormatExtensionKey($Key) {
  423. return preg_replace("/[^[:alnum:]]/i", '', unhtmlspecialchars($Key));
  424. }
  425. function FormatFileSize($FileSize) {
  426. if ($FileSize > 1048576) {
  427. return intval((($FileSize / 1048576) * 100) + 0.5) / 100 ."mb";
  428. } elseif ($FileSize > 1024) {
  429. return ceil($FileSize / 1024)."kb";
  430. } else {
  431. return $FileSize."b";
  432. }
  433. }
  434. function FormatHyperlink($InString, $ExternalTarget = '1', $LinkText = '', $CssClass = '') {
  435. $Display = $LinkText;
  436. if (strpos($InString, 'http://') == 0 && strpos($InString, 'http://') !== false) {
  437. if ($LinkText == '') {
  438. $Display = $InString;
  439. if (substr($Display, strlen($Display)-1,1) == '/') $Display = substr($Display, 0, strlen($Display)-1);
  440. $Display = str_replace('http://', '', $Display);
  441. }
  442. } elseif (strpos($InString, 'mailto:') == 0 && strpos($InString, 'mailto:') !== false) {
  443. if ($LinkText == '') {
  444. $Display = str_replace('mailto:', '', $InString);
  445. }
  446. } elseif (strpos($InString, 'ftp://') == 0 && strpos($InString, 'ftp://') !== false) {
  447. if ($LinkText == '') {
  448. $Display = str_replace('ftp://', '', $InString);
  449. }
  450. } elseif (strpos($InString, 'aim:goim?screenname=') == 0 && strpos($InString, 'aim:goim?screenname=') !== false) {
  451. if ($LinkText == '') {
  452. $Display = str_replace('aim:goim?screenname=', '', $InString);
  453. }
  454. } else {
  455. return $LinkText == '' ? $InString : $LinkText;
  456. }
  457. return '<a href="'.$InString.'"'.($CssClass != '' ? ' class="'.$CssClass.'"' : '').'>'.$Display.'</a>';
  458. }
  459. function FormatHtmlStringForNonDisplay($inValue) {
  460. return str_replace("\r\n", '<br />', htmlspecialchars($inValue));
  461. }
  462. function FormatHtmlStringInline($inValue, $StripSlashes = '0', $StripTags = '0') {
  463. // $sReturn = ForceString($inValue, '');
  464. $sReturn = $inValue;
  465. if ($StripTags) $sReturn = strip_tags($sReturn);
  466. if (ForceBool($StripSlashes, 0)) $sReturn = Strip_Slashes($sReturn);
  467. return str_replace("\r\n", ' ', htmlspecialchars($sReturn));
  468. }
  469. function FormatPlural($Number, $Singular, $Plural) {
  470. return ($Number == 1) ? $Singular : $Plural;
  471. }
  472. // Formats a value so it's safe to insert into the database
  473. function FormatStringForDatabaseInput($inValue, $bStripHtml = '0') {
  474. $bStripHtml = ForceBool($bStripHtml, 0);
  475. // $sReturn = stripslashes($inValue);
  476. $sReturn = $inValue;
  477. if ($bStripHtml) $sReturn = trim(strip_tags($sReturn));
  478. // return MAGIC_QUOTES_ON ? $sReturn : addslashes($sReturn);
  479. return addslashes($sReturn);
  480. }
  481. // Takes a user defined string and formats it for page display.
  482. // You can optionally remove html from the string.
  483. function FormatStringForDisplay($inValue, $bStripHtml = true, $AllowEncodedQuotes = true) {
  484. $sReturn = trim($inValue);
  485. if ($bStripHtml) $sReturn = strip_tags($sReturn);
  486. if (!$AllowEncodedQuotes) $sReturn = preg_replace('/("|\')/', '', $sReturn);
  487. global $Configuration;
  488. $sReturn = htmlspecialchars($sReturn, ENT_QUOTES, $Configuration['CHARSET']);
  489. if ($bStripHtml) $sReturn = str_replace("\r\n", "<br />", $sReturn);
  490. return $sReturn;
  491. }
  492. function GetBasicCheckBox($Name, $Value = 1, $Checked, $Attributes = '') {
  493. return '<input type="checkbox" name="'.$Name.'" value="'.$Value.'" '.(($Checked == 1)?' checked="checked"':'').' '.$Attributes.' />';
  494. }
  495. function GetBool($Bool, $True = 'Yes', $False = 'No') {
  496. return ($Bool ? $True : $False);
  497. }
  498. function GetDynamicCheckBox($Name, $Value = 1, $Checked, $OnClick, $Text, $Attributes = '', $CheckBoxID = '') {
  499. if ($CheckBoxID == '') $CheckBoxID = $Name.'ID';
  500. $Attributes .= ' id="'.$CheckBoxID.'"';
  501. if ($OnClick != '') $Attributes .= ' onclick="'.$OnClick.'"';
  502. return '<label for="'.$CheckBoxID.'">'.GetBasicCheckBox($Name, $Value, $Checked, $Attributes).' '.$Text.'</label>';
  503. }
  504. function GetEmail($Email, $LinkText = '') {
  505. if ($Email == '') {
  506. return '&nbsp;';
  507. } else {
  508. $EmailParts = explode('@', $Email);
  509. if (count($EmailParts) == 2) {
  510. $ScriptID = 'WriteEmail_' . rand();
  511. return "<script id=\"".$ScriptID."\" type=\"text/javascript\">\r\nWriteEmail('".$EmailParts[1]."', '".$EmailParts[0]."', '".$LinkText."', '".$ScriptID."');\r\n</script>";
  512. } else {
  513. // Failsafe
  514. return '<a href="mailto:'.$Email.'">'.($LinkText==''?$Email:$LinkText).'</a>';
  515. }
  516. }
  517. }
  518. function GetImage($ImageUrl, $Height = '', $Width = '', $TagIdentifier = '', $EmptyImageReplacement = '&nbsp;') {
  519. $sReturn = '';
  520. if (ReturnNonEmpty($ImageUrl) == '&nbsp;') {
  521. $sReturn = $EmptyImageReplacement;
  522. } else {
  523. $sReturn = '<img src="'.$ImageUrl.'"';
  524. if ($Height != '') $sReturn .= ' height="'.$Height.'"';
  525. if ($Width != '') $sReturn .= ' width="'.$Width.'"';
  526. if ($TagIdentifier != '') $sReturn .= ' id="'.$TagIdentifier.'"';
  527. $sReturn .= ' alt="" />';
  528. }
  529. return $sReturn;
  530. }
  531. function GetRemoteIp($FormatIpForDatabaseInput = '0') {
  532. $FormatIpForDatabaseInput = ForceBool($FormatIpForDatabaseInput, 0);
  533. $sReturn = ForceString(@$_SERVER['REMOTE_ADDR'], '');
  534. if (strlen($sReturn) > 20) $sReturn = substr($sReturn, 0, 19);
  535. if ($FormatIpForDatabaseInput) $sReturn = FormatStringForDatabaseInput($sReturn, 1);
  536. return $sReturn;
  537. }
  538. /**
  539. * Return the request URL
  540. *
  541. * The returned URL is tainted (based on $_SERVER['QUERY_STRING']).
  542. * However, by default ($FormatUrlForDisplay == true), the url is safe for html used.
  543. *
  544. * @param boolean $FormatUrlForDisplay Set to false to return an unformatted (and tainted) URL
  545. * @return string
  546. */
  547. function GetRequestUri($FormatUrlForDisplay='1') {
  548. global $Configuration;
  549. $Host = ForceString($_SERVER['HTTP_HOST'], '');
  550. if ($Host != '') $Host = PrependString($Configuration['HTTP_METHOD'].'://', $Host);
  551. $Path = @$_SERVER['REQUEST_URI'];
  552. // If the path wasn't provided in the REQUEST_URI variable, let's look elsewhere for it
  553. if ($Path == '') $Path = @$_SERVER['HTTP_X_REWRITE_URL']; // Some servers use this instead
  554. // If the path still wasn't found, let's try building it with other variables
  555. if ($Path == '') {
  556. $Path = @$_SERVER['SCRIPT_NAME'];
  557. $Path .= (@$_SERVER['QUERY_STRING'] == '' ? '' : '?' . @$_SERVER['QUERY_STRING']);
  558. }
  559. $FullPath = ConcatenatePath($Host, $Path);
  560. return $FormatUrlForDisplay ? FormatStringForDisplay($FullPath) : $FullPath;
  561. }
  562. function GetTableName($Key, $TableCollection, $Prefix) {
  563. global $DatabasePrefixLessTables;
  564. $DatabasePrefixLessTables = ForceArray($DatabasePrefixLessTables, array('User'));
  565. if (in_array($Key, $DatabasePrefixLessTables)) {
  566. return $TableCollection[$Key];
  567. } else {
  568. return $Prefix.$TableCollection[$Key];
  569. }
  570. }
  571. function GetUrl($Configuration, $PageName, $Divider = '', $Key = '', $Value = '', $PageNumber='', $Querystring='', $Suffix = '') {
  572. if (!empty($Configuration['URL_BUILDING_METHOD']) && $Configuration['URL_BUILDING_METHOD'] == 'mod_rewrite') {
  573. if ($PageName == './') $PageName = 'index.php';
  574. return $Configuration['BASE_URL']
  575. .($PageName == 'index.php' && $Value != '' ? '' : $Configuration['REWRITE_'.$PageName])
  576. .(strlen($Value) != 0 ? $Divider : '')
  577. .(strlen($Value) != 0 ? $Value.'/' : '')
  578. .(($PageNumber != '' && $PageNumber != '0' && $PageNumber != '1') ? $PageNumber.'/' : '')
  579. .($Suffix != '' ? $Suffix : '')
  580. .($Querystring != '' && substr($Querystring, 0, 1) != '#' ? '?' : '')
  581. .($Querystring != '' ? $Querystring : '');
  582. } else {
  583. if ($PageName == './' || $PageName == 'index.php') $PageName = '';
  584. $sReturn = ($Value != '' && $Value != '0' ? $Key.'='.$Value : '');
  585. if ($PageNumber != '') {
  586. if ($sReturn != '') $sReturn .= '&amp;';
  587. $sReturn .= 'page='.$PageNumber;
  588. }
  589. if ($Querystring != '' && substr($Querystring, 0, 1) != '#') {
  590. if ($sReturn != '') $sReturn .= '&amp;';
  591. $sReturn .= $Querystring;
  592. }
  593. if ($sReturn != '') $sReturn = '?'.$sReturn;
  594. if ($Querystring != '' && substr($Querystring, 0, 1) == '#') $sReturn .= $Querystring;
  595. return $Configuration['BASE_URL'].$PageName.$sReturn;
  596. }
  597. }
  598. // Create the html_entity_decode function for users prior to PHP 4.3.0
  599. if (!function_exists('html_entity_decode')) {
  600. function html_entity_decode($String) {
  601. return strtr($String, array_flip(get_html_translation_table(HTML_ENTITIES)));
  602. }
  603. }
  604. // allows inline if statements
  605. function Iif($Condition, $True, $False) {
  606. return $Condition ? $True : $False;
  607. }
  608. function ThemeFile(&$Context, $FileName) {
  609. $ThemeFileArray = file(ThemeFilePath($Context->Configuration, $FileName));
  610. if (is_array($ThemeFileArray)) {
  611. $ThemeFile = implode('', $ThemeFileArray);
  612. return $ThemeFile;
  613. } else {
  614. // Throw a fatal error because the theme file wasn't found
  615. $Context->ErrorManager->AddError($Context, 'Framework.Functions', 'ThemeFile', 'The requested theme file could not be found.', $FileName, 1);
  616. }
  617. }
  618. /**
  619. * Checks for a custom version of a theme file.
  620. *
  621. * Returns the path to the custom file (if it exists) or the default otherwise.
  622. *
  623. * @param array $Configuration Should have the APPLICATION_PATH and THEME_PATH
  624. * entries.
  625. * @param string $FileName
  626. * @param string $DefaultThemeDir Path to the directory containing the default
  627. * theme file. Set to $Configuration["APPLICATION_PATH"]."themes/"
  628. * by default.
  629. * @return string
  630. */
  631. function ThemeFilePath($Configuration, $FileName, $DefaultThemeDir=Null) {
  632. if ($DefaultThemeDir === Null) {
  633. $DefaultThemeDir = $Configuration["APPLICATION_PATH"]."themes/";
  634. }
  635. if (file_exists($Configuration['THEME_PATH'].$FileName)) {
  636. return $Configuration['THEME_PATH'].$FileName;
  637. } else {
  638. return $DefaultThemeDir.$FileName;
  639. }
  640. }
  641. function MysqlDateTime($Timestamp = '') {
  642. if ($Timestamp == '') $Timestamp = mktime();
  643. return date('Y-m-d H:i:s', $Timestamp);
  644. }
  645. function OpenURL($URL, &$Context) {
  646. $ParsedUrl = parse_url($URL);
  647. $Host = ForceString(@$ParsedUrl['host'], '');
  648. $Port = ForceInt(@$ParsedUrl['port'], 0);
  649. if ($Port == 0) $Port = 80;
  650. $Path = (array_key_exists('path', $ParsedUrl)) ? $ParsedUrl['path'] : '';
  651. if (empty($Path)) $Path = '/';
  652. if (array_key_exists('query', $ParsedUrl) && $ParsedUrl['query'] != '') {
  653. // Do some encoding and cleanup on the querystring
  654. $QueryString = urlencode($ParsedUrl['query']);
  655. $QueryString = str_replace(array('%26', '%3D'), array('&', '='), $QueryString);
  656. $Path .= '?' . $QueryString;
  657. }
  658. $UrlContents = false;
  659. if (empty($Host)) {
  660. $Context->WarningCollector->Add(str_replace('\\1', $URL, $Context->GetDefinition('InvalidHostName')));
  661. } else {
  662. $Headers = "GET $Path HTTP/1.0\r\nHost: $Host\r\n\r\n";
  663. // echo("<div>$Headers</div>");
  664. $ErrorNumber = '';
  665. $ErrorMessage = '';
  666. $Handle = @fsockopen($Host, $Port, $ErrorNumber, $ErrorMessage, 30);
  667. if (!$Handle) {
  668. $Context->WarningCollector->Add(str_replace('\\1', $Host, $Context->GetDefinition("ErrorFopen")).($php_errormsg ? str_replace('\\1', $php_errormsg, $Context->GetDefinition('ErrorFromPHP')) : ''));
  669. } else {
  670. fwrite($Handle, $Headers);
  671. $UrlContents = '';
  672. $HeaderFinished = false;
  673. $String = '';
  674. while (!feof($Handle)) {
  675. $String = fgets($Handle, 128);
  676. if ($HeaderFinished) $UrlContents .= $String;
  677. if ($String == "\r\n") $HeaderFinished = true;
  678. }
  679. fclose($Handle);
  680. }
  681. }
  682. return $UrlContents;
  683. }
  684. function PrefixString($string, $prefix, $length) {
  685. if (strlen($string) >= $length) {
  686. return $string;
  687. } else {
  688. return substr(($prefix.$string),strlen($prefix.$string)-$length, $length);
  689. }
  690. }
  691. function PrependString($Prepend, $String) {
  692. if ($String == '') return '';
  693. if (is_array($Prepend)){
  694. foreach ($Prepend as $str) {
  695. $pos = strpos(strtolower($String), strtolower($str));
  696. if ($pos !== false && $pos == 0) {
  697. $Prepend = '';
  698. }
  699. }
  700. // If the string doesn't start with any array elements, prepend the first element
  701. if ($Prepend <> '') $Prepend = $Prepend[0];
  702. } else {
  703. $pos = strpos(strtolower($String), strtolower($Prepend));
  704. if ($pos !== false && $pos == 0) $Prepend = '';
  705. }
  706. return $Prepend.$String;
  707. }
  708. /**
  709. * Redirect to an other page
  710. *
  711. * @todo Should the Location be encoded in function?
  712. * @param string $Location Absolute URL
  713. * @param string $Code Status code
  714. * @param string $Name Name of the page
  715. * @param bool $Die Should the script terminate
  716. * @return void
  717. */
  718. function Redirect($Location, $Code = '302', $Name = '', $Die = 1) {
  719. // Set status
  720. $CodeList = array(
  721. '301' => 'Moved Permanently',
  722. '303' => 'See Other'
  723. );
  724. if ($Code && array_key_exists($Code, $CodeList)) {
  725. Header( 'HTTP/1.1 ' . $Code . ' ' . $CodeList[$Code] );
  726. }
  727. //Strip CRLFs and replace &amp; with & (case insensitive)
  728. $Location = preg_replace(array('/\r\n/', '/&amp;/i'), array('', '&'), $Location);
  729. //$Location have to be well encoded.
  730. header('Location: ' . $Location);
  731. if ($Die) {
  732. @ob_end_clean();
  733. if (isset($_SERVER['REQUEST_METHOD']) &&
  734. $_SERVER['REQUEST_METHOD'] != 'HEAD')
  735. {
  736. if (!$Name) {
  737. $Name = $Location;
  738. }
  739. // display a lick in case the redirect fails
  740. echo '<a href="' . $Location . '">' . FormatStringForDisplay($Name) . '</a>';
  741. }
  742. //global $Context;
  743. //$Context->Unload();
  744. die();
  745. }
  746. }
  747. function RemoveIllegalChars($FileName) {
  748. return preg_replace('![\s<"\']+!s', '', $FileName);
  749. }
  750. function RenderThemeFile($Context, $ThemeFile) {
  751. echo $ThemeFile;
  752. }
  753. function ReplaceThemeFile($Context, $Replacements, $ThemeFile) {
  754. $theme_file = $ThemeFile;
  755. // Perform standard replacements
  756. while (list($key, $replacement) = each($Replacements)) {
  757. $theme_file = str_replace('['.$key.']', $replacement, $theme_file);
  758. }
  759. // Perform dictionary replacements
  760. // Perform configuration replacements
  761. return $theme_file;
  762. }
  763. // If a value is empty, return the non-empty value
  764. function ReturnNonEmpty($InValue, $NonEmptyValue = '&nbsp;') {
  765. return trim($InValue) == '' ? $NonEmptyValue : $InValue;
  766. }
  767. function SaveAsDialogue($FolderPath, $FileName, $DeleteFile = '0') {
  768. $DeleteFile = ForceBool($DeleteFile, 0);
  769. if ($FolderPath != '') {
  770. if (substr($FolderPath,strlen($FolderPath)-1) != '/') $FolderPath = $FolderPath.'/';
  771. }
  772. $FolderPath = $FolderPath.$FileName;
  773. header('Pragma: public');
  774. header('Expires: 0');
  775. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  776. header('Content-Type: application/force-download');
  777. header('Content-Type: application/octet-stream');
  778. header('Content-Type: application/download');
  779. header('Content-Disposition: attachment; filename="'.$FileName.'"');
  780. header('Content-Transfer-Encoding: binary');
  781. readfile($FolderPath);
  782. if ($DeleteFile) unlink($FolderPath);
  783. die();
  784. }
  785. function SerializeArray($InArray) {
  786. $sReturn = '';
  787. if (is_array($InArray)) {
  788. if (count($InArray) > 0) {
  789. $sReturn = serialize($InArray);
  790. $sReturn = addslashes($sReturn);
  791. }
  792. }
  793. return $sReturn;
  794. }
  795. // Cuts a string to the specified length.
  796. // Then moves back to the previous space so words are not sliced half-way through.
  797. function SliceString($InString, $Length) {
  798. $Space = ' ';
  799. $sReturn = '';
  800. if (strlen($InString) > $Length) {
  801. $sReturn = substr(trim($InString), 0, $Length);
  802. $sReturn = substr($sReturn, 0, strlen($sReturn) - strpos(strrev($sReturn), $Space));
  803. $sReturn .= '...';
  804. } else {
  805. $sReturn = $InString;
  806. }
  807. return $sReturn;
  808. }
  809. function Strip_Slashes($InString) {
  810. return MAGIC_QUOTES_ON ? stripslashes($InString) : $InString;
  811. }
  812. function SubtractDaysFromTimeStamp($TimeStamp, $NumberOfDaysToSubtract) {
  813. if ($NumberOfDaysToSubtract == 0) {
  814. return $TimeStamp;
  815. } else {
  816. return strtotime('-'.$NumberOfDaysToSubtract.' day', $TimeStamp);
  817. }
  818. }
  819. function TimeDiff(&$Context, $Time, $TimeToCompare = '') {
  820. if ($TimeToCompare == '') $TimeToCompare = time();
  821. $Difference = $TimeToCompare-$Time;
  822. $Days = floor($Difference/60/60/24);
  823. if ($Days > 7) {
  824. return date($Context->GetDefinition('OldPostDateFormatCode'), $Time);
  825. } elseif ($Days > 1) {
  826. return str_replace('//1', $Days, $Context->GetDefinition('XDaysAgo'));
  827. } elseif ($Days == 1) {
  828. return str_replace('//1', $Days, $Context->GetDefinition('XDayAgo'));
  829. } else {
  830. $Difference -= $Days*60*60*24;
  831. $Hours = floor($Difference/60/60);
  832. if ($Hours > 1) {
  833. return str_replace('//1', $Hours, $Context->GetDefinition('XHoursAgo'));
  834. } elseif ($Hours == 1) {
  835. return str_replace('//1', $Hours, $Context->GetDefinition('XHourAgo'));
  836. } else {
  837. $Difference -= $Hours*60*60;
  838. $Minutes = floor($Difference/60);
  839. if ($Minutes > 1) {
  840. return str_replace('//1', $Minutes, $Context->GetDefinition('XMinutesAgo'));
  841. } elseif ($Minutes == 1) {
  842. return str_replace('//1', $Minutes, $Context->GetDefinition('XMinuteAgo'));
  843. } else {
  844. $Difference -= $Minutes*60;
  845. $Seconds = $Difference;
  846. if ($Seconds == 1) {
  847. return str_replace('//1', $Seconds, $Context->GetDefinition('XSecondAgo'));
  848. } else {
  849. return str_replace('//1', $Seconds, $Context->GetDefinition('XSecondsAgo'));
  850. }
  851. }
  852. }
  853. }
  854. }
  855. function unhtmlspecialchars($String) {
  856. $String = str_replace('&amp;', '&', $String);
  857. $String = str_replace('&#039;', '\'', $String);
  858. $String = str_replace('&quot;', '\"', $String);
  859. $String = str_replace('&lt;', '<', $String);
  860. $String = str_replace('&gt;', '>', $String);
  861. return $String;
  862. }
  863. // Convert a datetime to a timestamp
  864. function UnixTimestamp($DateTime) {
  865. if (preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/', $DateTime, $Matches)) {
  866. $Year = $Matches[1];
  867. $Month = $Matches[2];
  868. $Day = $Matches[3];
  869. $Hour = $Matches[4];
  870. $Minute = $Matches[5];
  871. $Second = $Matches[6];
  872. return mktime($Hour, $Minute, $Second, $Month, $Day, $Year);
  873. } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $DateTime, $Matches)) {
  874. $Year = $Matches[1];
  875. $Month = $Matches[2];
  876. $Day = $Matches[3];
  877. return mktime(0, 0, 0, $Month, $Day, $Year);
  878. }
  879. }
  880. function UnserializeArray($InSerialArray) {
  881. $aReturn = array();
  882. if ($InSerialArray != '' && !is_array($InSerialArray)) {
  883. $aReturn = unserialize($InSerialArray);
  884. if (is_array($aReturn)) {
  885. $Count = count($aReturn);
  886. $i = 0;
  887. for ($i = 0; $i < $Count; $i++) {
  888. $aReturn[$i] = array_map('Strip_Slashes', $aReturn[$i]);
  889. }
  890. }
  891. }
  892. return $aReturn;
  893. }
  894. function UnserializeAssociativeArray($InSerialArray) {
  895. $aReturn = array();
  896. if ($InSerialArray != '' && !is_array($InSerialArray)) {
  897. $aReturn = @unserialize($InSerialArray);
  898. if (!is_array($aReturn)) $aReturn = array();
  899. }
  900. return $aReturn;
  901. }
  902. // Instantiate a simple validator
  903. function Validate($InputName, $IsRequired, $Value, $MaxLength, $ValidationExpression, &$Context) {
  904. $Validator = $Context->ObjectFactory->NewContextObject($Context, 'Validator');
  905. $Validator->InputName = $InputName;
  906. $Validator->isRequired = $IsRequired;
  907. $Validator->Value = $Value;
  908. $Validator->MaxLength = $MaxLength;
  909. if ($ValidationExpression != '') {
  910. $Validator->ValidationExpression = $ValidationExpression;
  911. $Validator->ValidationExpressionErrorMessage = $Context->GetDefinition('ErrImproperFormat').' '.$InputName;
  912. }
  913. return $Validator->Validate();
  914. }
  915. function WriteEmail($Email, $LinkText = '') {
  916. echo(GetEmail($Email, $LinkText));
  917. }
  918. ?>