PageRenderTime 34ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/Chat/src/pfctools.php

https://code.google.com/
PHP | 515 lines | 343 code | 57 blank | 115 comment | 85 complexity | 7c9a3c71984df98d61ea68b323b95011 MD5 | raw file
Possible License(s): Apache-2.0, GPL-2.0
  1. <?php
  2. /**
  3. * phpfreechattools.class.php
  4. *
  5. * Copyright ??? 2006 Stephane Gully <stephane.gully@gmail.com>
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the
  19. * Free Software Foundation, 51 Franklin St, Fifth Floor,
  20. * Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * this file contains a toolbox with misc. usefull functions
  24. *
  25. * @author Stephane Gully <stephane.gully@gmail.com>
  26. */
  27. // To be sure the directory separator is defined
  28. // I don't know if this constant can be undefined or not so maybe this code is not necessary
  29. if (!defined("DIRECTORY_SEPARATOR"))
  30. define("DIRECTORY_SEPARATOR", "/");
  31. /**
  32. * Returns the absolute script filename
  33. * takes care of php cgi configuration which do not support SCRIPT_FILENAME variable.
  34. */
  35. function pfc_GetScriptFilename()
  36. {
  37. $sf = '';
  38. if(function_exists('debug_backtrace'))
  39. {
  40. // browse the backtrace history and take the first unknown filename as the client script
  41. foreach(debug_backtrace() as $db)
  42. {
  43. $f = $db['file'];
  44. if (!preg_match('/phpfreechat.class.php/',$f) &&
  45. !preg_match('/pfcglobalconfig.class.php/',$f) &&
  46. !preg_match('/pfctools.class.php/',$f) &&
  47. !preg_match('/pfcinfo.class.php/',$f)
  48. )
  49. {
  50. $sf = $f;
  51. break;
  52. }
  53. }
  54. }
  55. else if (isset($_SERVER['PATH_TRANSLATED']) &&
  56. file_exists($_SERVER['SCRIPT_FILENAME'])) // check for a cgi configurations
  57. {
  58. $sf = $_SERVER['PATH_TRANSLATED'];
  59. }
  60. else if (isset($_SERVER['SCRIPT_FILENAME'])&&
  61. file_exists($_SERVER['SCRIPT_FILENAME'])) // for non-cgi configurations
  62. {
  63. $sf = $_SERVER['SCRIPT_FILENAME'];
  64. }
  65. else
  66. {
  67. echo "<pre>";
  68. echo "<span style='color:red'>Error: pfc_GetScriptFilename function returns a wrong path. Please contact the pfc team (contact@phpfreechat.net) and copy/paste these data to help debugging:</span>\n";
  69. print_r($_SERVER);
  70. print_r(debug_backtrace());
  71. echo "</pre>";
  72. exit;
  73. }
  74. return $sf;
  75. }
  76. function pfc_RelativePath($p1, $p2)
  77. {
  78. if (is_file($p1)) $p1 = dirname($p1);
  79. if (is_file($p2)) $p2 = dirname($p2);
  80. // using realpath function is necessary to resolve symbolic links
  81. $p1 = realpath(cleanPath($p1));
  82. $p2 = realpath(cleanPath($p2));
  83. $res = "";
  84. // echo $p1."<br>";
  85. // echo $p2."<br>";
  86. while( $p1 != "" &&
  87. $p1 != "/" && // for unix root dir
  88. !preg_match("/^[a-z]\:\\\$/i",$p1) && // for windows rootdir
  89. strpos($p2, $p1) !== 0)
  90. {
  91. $res .= "../";
  92. $p1 = dirname($p1);
  93. }
  94. if (isset($_SERVER["WINDIR"]) || isset($_SERVER["windir"])) {
  95. $p2 = str_replace("\\","/",substr($p2, strlen($p1)+1, strlen($p2)-strlen($p1)));
  96. } else {
  97. if ($p1 === "/" || $p1 === "") {
  98. $p2 = substr($p2, strlen($p1));
  99. } else {
  100. $p2 = substr($p2, strlen($p1)+1);
  101. }
  102. }
  103. $res .= $p2;
  104. // remove the last "/"
  105. if (preg_match("/.*\/$/", $res)) $res = preg_replace("/(.*)\//","$1",$res);
  106. // if rootpath is empty replace it by "." to avoide url starting with "/"
  107. if ($res == "") $res = ".";
  108. // echo $res."<br>";
  109. return $res;
  110. }
  111. function cleanPath($path)
  112. {
  113. $result = array();
  114. $pathA = explode(DIRECTORY_SEPARATOR, $path);
  115. if (!$pathA[0])
  116. $result[] = '';
  117. foreach ($pathA AS $key => $dir) {
  118. if ($dir == '..') {
  119. if (end($result) == '..') {
  120. $result[] = '..';
  121. } elseif (!array_pop($result)) {
  122. $result[] = '..';
  123. }
  124. } elseif ($dir && $dir != '.') {
  125. $result[] = $dir;
  126. }
  127. }
  128. if (!end($pathA))
  129. $result[] = '';
  130. return implode('/', $result);
  131. }
  132. function mkdir_r($path, $modedir = 0755)
  133. {
  134. // This function creates the specified directory using mkdir(). Note
  135. // that the recursive feature on mkdir() is broken with PHP 5.0.4 for
  136. // Windows, so I have to do the recursion myself.
  137. if (!file_exists($path))
  138. {
  139. // The directory doesn't exist. Recurse, passing in the parent
  140. // directory so that it gets created.
  141. mkdir_r(dirname($path), $modedir);
  142. mkdir($path, $modedir);
  143. }
  144. }
  145. function rm_r($dir)
  146. {
  147. if(!$dh = @opendir($dir)) return;
  148. while (($obj = readdir($dh)))
  149. {
  150. if($obj=='.' || $obj=='..') continue;
  151. if (!@unlink($dir.'/'.$obj)) rm_r($dir.'/'.$obj);
  152. }
  153. closedir($dh);
  154. @rmdir($dir);
  155. }
  156. /**
  157. * Copy a file, or recursively copy a folder and its contents
  158. *
  159. * @author Aidan Lister <aidan@php.net>
  160. * @link http://aidanlister.com/repos/v/function.copyr.php
  161. * @param string $source Source path
  162. * @param string $dest Destination path
  163. * @return bool Returns TRUE on success, FALSE on failure
  164. */
  165. function copy_r($source, $dest, $modedir = 0755, $modefile = 0664)
  166. {
  167. // Simple copy for a file
  168. if (is_file($source)) {
  169. $ret = copy($source, $dest);
  170. chmod($dest, $modefile);
  171. return $ret;
  172. }
  173. // Make destination directory
  174. if (!is_dir($dest)) {
  175. mkdir($dest, $modedir);
  176. }
  177. // Take the directories entries
  178. $dir = dir($source);
  179. $entries = array();
  180. while (false !== $entry = $dir->read())
  181. {
  182. $entries[] = $entry;
  183. }
  184. // Loop through the folder
  185. foreach ($entries as $e)
  186. {
  187. // Skip pointers and subversion directories
  188. if ($e == '.' || $e == '..' || $e == '.svn') continue;
  189. // Deep copy directories
  190. if ($dest !== $source . DIRECTORY_SEPARATOR . $e)
  191. copy_r($source . DIRECTORY_SEPARATOR . $e, $dest . DIRECTORY_SEPARATOR . $e, $modedir, $modefile);
  192. }
  193. // Clean up
  194. $dir->close();
  195. return true;
  196. }
  197. /**
  198. * Check the functions really exists on this server
  199. */
  200. function check_functions_exist( $f_list )
  201. {
  202. $errors = array();
  203. foreach( $f_list as $func => $err )
  204. {
  205. if (!function_exists( $func ))
  206. $errors[] = _pfc("%s doesn't exist: %s", $func, $err);
  207. }
  208. return $errors;
  209. }
  210. function test_writable_dir($dir, $name = "")
  211. {
  212. $errors = array();
  213. if ($dir == "")
  214. $errors[] = _pfc("%s directory must be specified", ($name!="" ? $name : $dir));
  215. if (is_file($dir))
  216. $this->errors[] = _pfc("%s must be a directory",$dir);
  217. if (!is_dir($dir))
  218. mkdir_r($dir);
  219. if (!is_dir($dir))
  220. $errors[] = _pfc("%s can't be created",$dir);
  221. if (!is_writeable($dir))
  222. $errors[] = _pfc("%s is not writeable",$dir);
  223. if (!is_readable($dir))
  224. $errors[] = _pfc("%s is not readable",$dir);
  225. return $errors;
  226. }
  227. function install_file($src_file, $dst_file)
  228. {
  229. $errors = array();
  230. $src_dir = dirname($src_file);
  231. $dst_dir = dirname($dst_file);
  232. if (!is_file($src_file))
  233. $errors[] = _pfc("%s is not a file", $src_file);
  234. if (!is_readable($src_file))
  235. $errors[] = _pfc("%s is not readable", $src_file);
  236. if (!is_dir($src_dir))
  237. $errors[] = _pfc("%s is not a directory", $src_dir);
  238. if (!is_dir($dst_dir))
  239. mkdir_r($dst_dir);
  240. copy( $src_file, $dst_file );
  241. return $errors;
  242. }
  243. function install_dir($src_dir, $dst_dir)
  244. {
  245. $errors = array();
  246. if (!is_dir($src_dir))
  247. $errors[] = _pfc("%s is not a directory", $src_dir);
  248. if (!is_readable($src_dir))
  249. $errors[] = _pfc("%s is not readable", $src_dir);
  250. copy_r( $src_dir, $dst_dir );
  251. return $errors;
  252. }
  253. /**
  254. * file_get_contents_flock
  255. * define an alternative file_get_contents when this function doesn't exists on the used php version (<4.3.0)
  256. */
  257. if (!defined('LOCK_SH')) {
  258. define('LOCK_SH', 1);
  259. }
  260. function file_get_contents_flock($filename, $incpath = false, $resource_context = null)
  261. {
  262. if (false === $fh = fopen($filename, 'rb', $incpath)) {
  263. user_error('file_get_contents() failed to open stream: No such file or directory ['.$filename.']',
  264. E_USER_WARNING);
  265. return false;
  266. }
  267. // Attempt to get a shared (read) lock
  268. if (!flock($fh, LOCK_SH)) {
  269. return false;
  270. }
  271. clearstatcache();
  272. if ($fsize = @filesize($filename)) {
  273. $data = fread($fh, $fsize);
  274. } else {
  275. $data = '';
  276. while (!feof($fh)) {
  277. $data .= fread($fh, 8192);
  278. }
  279. }
  280. fclose($fh);
  281. return $data;
  282. }
  283. /**
  284. * file_get_contents
  285. * define an alternative file_get_contents when this function doesn't exists on the used php version (<4.3.0)
  286. */
  287. if (!function_exists('file_get_contents'))
  288. {
  289. function file_get_contents($filename, $incpath = false, $resource_context = null)
  290. {
  291. if (false === $fh = fopen($filename, 'rb', $incpath))
  292. {
  293. trigger_error('file_get_contents() failed to open stream: No such file or directory ['.$filename.']', E_USER_WARNING);
  294. return false;
  295. }
  296. clearstatcache();
  297. if ($fsize = filesize($filename))
  298. {
  299. $data = fread($fh, $fsize);
  300. }
  301. else
  302. {
  303. while (!feof($fh)) {
  304. $data .= fread($fh, 8192);
  305. }
  306. }
  307. fclose($fh);
  308. return $data;
  309. }
  310. }
  311. /**
  312. * Replace file_put_contents()
  313. *
  314. * @category PHP
  315. * @package PHP_Compat
  316. * @link http://php.net/function.file_put_contents
  317. * @author Aidan Lister <aidan@php.net>
  318. * @internal resource_context is not supported
  319. * @since PHP 5
  320. * @require PHP 4.0.0 (user_error)
  321. */
  322. if (!defined('FILE_USE_INCLUDE_PATH')) {
  323. define('FILE_USE_INCLUDE_PATH', 1);
  324. }
  325. if (!defined('LOCK_EX')) {
  326. define('LOCK_EX', 2);
  327. }
  328. if (!defined('FILE_APPEND')) {
  329. define('FILE_APPEND', 8);
  330. }
  331. if (!function_exists('file_put_contents')) {
  332. function file_put_contents($filename, $content, $flags = null, $resource_context = null)
  333. {
  334. // If $content is an array, convert it to a string
  335. if (is_array($content)) {
  336. $content = implode('', $content);
  337. }
  338. // If we don't have a string, throw an error
  339. if (!is_scalar($content)) {
  340. user_error('file_put_contents() The 2nd parameter should be either a string or an array ['.$filename.']',
  341. E_USER_WARNING);
  342. return false;
  343. }
  344. // Get the length of data to write
  345. $length = strlen($content);
  346. // Check what mode we are using
  347. $mode = ($flags & FILE_APPEND) ?
  348. 'a' :
  349. 'wb';
  350. // Check if we're using the include path
  351. $use_inc_path = ($flags & FILE_USE_INCLUDE_PATH) ?
  352. true :
  353. false;
  354. // Open the file for writing
  355. if (($fh = @fopen($filename, $mode, $use_inc_path)) === false) {
  356. user_error('file_put_contents() failed to open stream: Permission denied ['.$filename.']',
  357. E_USER_WARNING);
  358. return false;
  359. }
  360. // Attempt to get an exclusive lock
  361. $use_lock = ($flags & LOCK_EX) ? true : false ;
  362. if ($use_lock === true) {
  363. if (!flock($fh, LOCK_EX)) {
  364. return false;
  365. }
  366. }
  367. // Write to the file
  368. $bytes = 0;
  369. if (($bytes = @fwrite($fh, $content)) === false) {
  370. $errormsg = sprintf('file_put_contents() Failed to write %d bytes to %s ['.$filename.']',
  371. $length,
  372. $filename);
  373. user_error($errormsg, E_USER_WARNING);
  374. return false;
  375. }
  376. // Close the handle
  377. @fclose($fh);
  378. // Check all the data was written
  379. if ($bytes != $length) {
  380. $errormsg = sprintf('file_put_contents() Only %d of %d bytes written, possibly out of free disk space. ['.$filename.']',
  381. $bytes,
  382. $length);
  383. user_error($errormsg, E_USER_WARNING);
  384. return false;
  385. }
  386. // Return length
  387. return $bytes;
  388. }
  389. }
  390. /**
  391. * iconv
  392. * define an alternative iconv when this function doesn't exists on the php modules
  393. */
  394. if (!function_exists('iconv'))
  395. {
  396. if(function_exists('libiconv'))
  397. {
  398. // use libiconv if it exists
  399. function iconv($input_encoding, $output_encoding, $string)
  400. {
  401. return libiconv($input_encoding, $output_encoding, $string);
  402. }
  403. }
  404. else
  405. {
  406. // fallback if nothing has been found
  407. function iconv($input_encoding, $output_encoding, $string)
  408. {
  409. return $string;
  410. }
  411. }
  412. }
  413. /**
  414. * Replace html_entity_decode()
  415. *
  416. * @category PHP
  417. * @package PHP_Compat
  418. * @link http://php.net/function.html_entity_decode
  419. * @author David Irvine <dave@codexweb.co.za>
  420. * @author Aidan Lister <aidan@php.net>
  421. * @version $Revision: 1.8 $
  422. * @since PHP 4.3.0
  423. * @internal Setting the charset will not do anything
  424. * @require PHP 4.0.0 (user_error)
  425. */
  426. if (!defined('ENT_NOQUOTES')) {
  427. define('ENT_NOQUOTES', 0);
  428. }
  429. if (!defined('ENT_COMPAT')) {
  430. define('ENT_COMPAT', 2);
  431. }
  432. if (!defined('ENT_QUOTES')) {
  433. define('ENT_QUOTES', 3);
  434. }
  435. if (!function_exists('html_entity_decode')) {
  436. function html_entity_decode($string, $quote_style = ENT_COMPAT, $charset = null)
  437. {
  438. if (!is_int($quote_style)) {
  439. user_error('html_entity_decode() expects parameter 2 to be long, ' .
  440. gettype($quote_style) . ' given', E_USER_WARNING);
  441. return;
  442. }
  443. $trans_tbl = get_html_translation_table(HTML_ENTITIES);
  444. $trans_tbl = array_flip($trans_tbl);
  445. // Add single quote to translation table;
  446. $trans_tbl['&#039;'] = '\'';
  447. // Not translating double quotes
  448. if ($quote_style & ENT_NOQUOTES) {
  449. // Remove double quote from translation table
  450. unset($trans_tbl['&quot;']);
  451. }
  452. return strtr($string, $trans_tbl);
  453. }
  454. }
  455. ?>