PageRenderTime 67ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/library.php

https://bitbucket.org/simonfraser/php-library
PHP | 2125 lines | 968 code | 362 blank | 795 comment | 145 complexity | 0e7015d8fc122acb1ac2f651a86f0647 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * PHP Library -- A simplified toolkit for PHP
  4. *
  5. * @ version 1.7 Beta(β)
  6. * @ author Simon Fraser <http://simonf.co.uk>
  7. * @ acknowledgement php.net community, kirby toolkit, David Turner
  8. * @ copyright Copyright (c) 2012 Simon Fraser
  9. * @ license MIT License <http://www.opensource.org/licenses/mit-license.php>
  10. */
  11. conf::set('charset', 'utf-8');
  12. error_reporting(E_ALL);
  13. /* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
  14. /*
  15. * Array
  16. * Set of array methods
  17. */
  18. class ar {
  19. /*
  20. * Gets an element of an array by key
  21. * @param (array) $array - The source
  22. * @param (string|array) $key - Key or Keys to search for
  23. * @return (array)
  24. */
  25. static function get($array, $key) {
  26. $result = array();
  27. if (is_array($key)) {
  28. foreach($key as $k) { $result[$k] = $array[$k]; }
  29. } else {
  30. $result = (isset($array[$key]))? $array[$key] : false;
  31. }
  32. return $result;
  33. }
  34. /*
  35. * Insert a new element into array
  36. * @param (array) $array - The source
  37. * @param (string) $element - The element to be inserted
  38. * @param (int) $position - Optional position of new element, default is end
  39. * @return (array) - The new array
  40. */
  41. static function set($array, $element=null, $position=null) {
  42. if (empty($position)) {
  43. array_push($array, $element);
  44. return $array;
  45. } else {
  46. return array_merge( array_slice($array,0,(int)$position), (array)$element, array_slice($array, (int)$position) );
  47. }
  48. }
  49. /*
  50. * Removes an element from an array
  51. * @param (array) $array - The source
  52. * @param (string) $search - The value or key to look for
  53. * @param (boolean) $key - To search for a key or value, default true
  54. * @return (array)
  55. */
  56. static function delete($array, $search, $key=true) {
  57. if($key) {
  58. unset($array[$search]);
  59. } else {
  60. for ($i=0; $i<sizeof($array) ; $i++) {
  61. $index = array_search($search, $array);
  62. if ($index!==false) {
  63. unset($array[$index]);
  64. }
  65. }
  66. }
  67. return $array;
  68. }
  69. /*
  70. * Print out array on screen
  71. * @param (array) $array - The source
  72. * @echo (string) - Will echo result on screen
  73. */
  74. static function show($array) {
  75. $output = '<pre>';
  76. $output .= htmlspecialchars(@print_r($array, true));
  77. $output .= '</pre>';
  78. echo $output;
  79. }
  80. /*
  81. * Shuffle an array
  82. * @param (array) $array - The source
  83. * @return (array) - Shuffled array
  84. */
  85. static function shuffle($array) {
  86. $keys = array_keys($array);
  87. shuffle($keys);
  88. return array_merge(array_flip($keys), $array);
  89. }
  90. /*
  91. * Flatten an array to string
  92. * @param (array) $array - The source
  93. * @param (string) $pre_separator
  94. */
  95. static function flatten($array,$pre_separator='',$post_separator=',') {
  96. $output = '';
  97. foreach ($array as $a) {
  98. $output .= $pre_separator.$a.$post_separator;
  99. }
  100. return $output;
  101. }
  102. /*
  103. * Search an array
  104. * @param (array) $array - The source
  105. * @param (string) $search - Searching for
  106. * @param (boolean) $key - Return the key space or boolean yes / no
  107. * @return (array|boolean)
  108. */
  109. static function search($array, $search, $key=false) {
  110. $search = preg_grep('/'.preg_quote($search).'/i', $array);
  111. if ($key) return $search;
  112. return (empty($search))? false : true;
  113. }
  114. } /* Array Methods */
  115. /*
  116. * Cookies (Monster)
  117. * Set of methods to help with cookies
  118. */
  119. class cm {
  120. /*
  121. * Set and make Cookies
  122. * @param (string) $key - Cookie key value
  123. * @param (string) $value - Value to store into cookie
  124. * @param (int) $expires - Expiration date from time created (default 24 hours)
  125. * @param (string) $domain - Domain for cookie
  126. * @return (boolean)
  127. */
  128. static function set($key, $value=null, $expires=31536000, $domain='/') {
  129. if(empty($key)) return false;
  130. return setcookie($key, $value, time()+$expires, $domain);
  131. }
  132. /*
  133. * Get value from cookie based off key
  134. * @param (string) $key - Cookie key to target
  135. * @return (boolean)
  136. */
  137. static function get($key) {
  138. return ar::get($_COOKIE, $key);
  139. }
  140. /*
  141. * Remove cookie based off key
  142. * @param (string) $key - Cookie key value
  143. * @param (string) $domain - Domain for cookie
  144. * @return (boolean)
  145. */
  146. static function remove($key, $domain='/') {
  147. $_COOKIE[$key] = false;
  148. return @setcookie($key, false, time()-86400, $domain);
  149. }
  150. }
  151. /*
  152. * Config Values
  153. * Configuration values, removes the need of GLOBALS
  154. */
  155. class conf {
  156. /*
  157. * The static config array
  158. * @var array
  159. */
  160. private static $config = array();
  161. /*
  162. * Set a configuration value
  163. * @param (string) $key - The reference key
  164. * @param (string) $value - The configuration value
  165. */
  166. static function set($key, $value=null) {
  167. self::$config[$key] = $value;
  168. }
  169. /*
  170. * Retrieve a config value
  171. * @param (string) $key - config key to get
  172. * @return (string)
  173. */
  174. static function get($key) {
  175. return ar::get(self::$config,$key);
  176. }
  177. } /* Config Methods */
  178. /*
  179. * Content & Cache methods
  180. * Content zone to store pieces of data
  181. */
  182. class content {
  183. /*
  184. * The static content array
  185. * @var array
  186. */
  187. private static $contents = array();
  188. /*
  189. * Save ntnt value
  190. * @param (string) $key - The reference key
  191. * @param (string) $value - The value
  192. */
  193. static function set($key, $value=null) {
  194. self::$contents[$key] = $value;
  195. }
  196. /*
  197. * Retrieve a content value
  198. * @param (string) $key - config key to get
  199. * @return (string)
  200. */
  201. static function get($key) {
  202. return ar::get(self::$contents,$key);
  203. }
  204. } /* Content & cache methods */
  205. /*
  206. * Date & Time Class
  207. * Methods and formatting
  208. */
  209. class timedate {
  210. /*
  211. * Return date / time formated string
  212. * @param (string) $datetime - Unix timestamp to convert to date/time
  213. * @param (string) $format - format parameter string like http://php.net/function.date.php
  214. * @return (string) - formated datetime string
  215. */
  216. static function format($datetime=null, $format="D jS M Y G:i:s") {
  217. if (empty($datetime)) $datetime = time();
  218. if (!ex::match('~^[1-9][0-9]*$~', $datetime, true)) {
  219. $date = strtotime($datetime);
  220. } else {
  221. $date = $datetime;
  222. }
  223. return date($format, $date);
  224. }
  225. /*
  226. * Check for a valid Datetime string
  227. * @param (string) $datetime - string to check
  228. * @return (boolean) - string valid or not
  229. */
  230. static function valid($string) {
  231. if ($string=="" || $string=="0000-00-00" || $string=="0000-00-00 00:00:00") return false;
  232. return true;
  233. }
  234. } /* Datetime methods */
  235. /*
  236. * Database Controls
  237. * http://www.php.net/manual/en/mysqli.query.php
  238. *
  239. * Uses four configurations to run and should be set
  240. * db.user, db.password, db.name, (db.host) optional
  241. * Ex : conf::set('db.x','value');
  242. */
  243. class db extends mysqli {
  244. /*
  245. * Connection instance
  246. */
  247. private static $instance;
  248. /*
  249. * Connection status check
  250. * @return (object|boolean) - Will return connection object or false
  251. */
  252. public function connection() {
  253. return (is_resource(self::$instance))? self::$instance : false;
  254. }
  255. /*
  256. * Connect function
  257. * @return (object) - Connection object
  258. */
  259. public function connect() {
  260. $connection = self::connection();
  261. $host = (conf::get('db.host')!='')? conf::get('db.host') : 'localhost';
  262. $user = (conf::get('db.user')!='')? conf::get('db.user') : 'root';
  263. $password = (conf::get('db.password')!='')? conf::get('db.password') : '';
  264. $database = (conf::get('db.name')!='')? conf::get('db.name') : '';
  265. @$connection = (!$connection)? new mysqli($host, $user, $password, $database) : $connection;
  266. if(!$connection) self::error('database connection failed');
  267. self::$instance = $connection;
  268. return $connection;
  269. }
  270. /*
  271. * Database Disconnect
  272. */
  273. public function disconnect() {
  274. $instance = self::connect();
  275. if(!$instance) return $instance;
  276. self::$instance->close();
  277. }
  278. /*
  279. * All is lost error function
  280. * @param (string) $msg - Error to show
  281. * @return (die-string)
  282. */
  283. public function error($msg) {
  284. die('Database error '.$msg);
  285. }
  286. /*
  287. * Run a query
  288. * @param (string) $query - Query to be ran
  289. * @param (boolean) $object - To actually return as total object
  290. * @return (array|object) - string on fault or DB Object
  291. */
  292. public function query($query,$object=false) {
  293. $instance = self::connect();
  294. if(!$instance) return $instance;
  295. @$result = $instance->query($query) or self::error($instance->error);
  296. if ($object) return $result;
  297. if ($result->num_rows===0) {
  298. return false;
  299. } else {
  300. while ($row = $result->fetch_object()) {
  301. $return[] = $row;
  302. }
  303. return $return;
  304. }
  305. $result->close();
  306. self::disconnect();
  307. }
  308. /*
  309. * Datebase read method
  310. * @param (string) $table - Query table name
  311. * @param (string) $after - Fields to return results from, default all
  312. * @param (string) $where - Where condition
  313. * @param (string) $order - Order By condition
  314. * @param (string) $limit - Limit condition
  315. * @param (boolean) $echo - Show constructed query as echo debug output
  316. * @return (array-object) Query results
  317. */
  318. public function read($table, $after="*", $where=null, $order=null, $limit=null, $echo=false) {
  319. $ourquery = "SELECT ".$after." FROM ".$table." ".$where." ".$order." ".$limit;
  320. if($echo == true) echo $ourquery;
  321. return self::query($ourquery);
  322. }
  323. /*
  324. * Datebase single row & column read method
  325. * @param (string) $table - Query table name
  326. * @param (string) $after - Field to read
  327. * @param (string) $where - Where condition
  328. * @param (string) $order - Order By condition
  329. * @param (boolean) $echo - Show constructed query as echo debug output
  330. * @return (array-object) Query results
  331. */
  332. public function single($table, $after=null, $where=null, $order=null, $echo=false) {
  333. if (empty($after)) return false;
  334. $ourquery = "SELECT ".$after." FROM ".$table." ".$where." ".$order." LIMIT 1";
  335. if($echo == true) echo $ourquery;
  336. $result = self::query($ourquery,true);
  337. if ($result->num_rows===0) {
  338. return false;
  339. } else {
  340. while ($row = $result->fetch_object()) {
  341. return str::unquote($row->$after);
  342. }
  343. }
  344. $result->close();
  345. self::disconnect();
  346. }
  347. /*
  348. * Inner Join read method
  349. * @param (string) $table_a - Query table name A
  350. * @param (string) $table_b - Query table name B
  351. * @param (string) $on - On join SQL command
  352. * @param (string) $after - Fields to return results from, default all
  353. * @param (string) $where - Where condition
  354. * @param (string) $order - Order By condition
  355. * @param (string) $limit - Limit condition
  356. * @param (boolean) $echo - Show constructed query as echo debug output
  357. * @return (array-object) Query results
  358. *
  359. */
  360. public function join($table_a, $table_b, $on, $after="*", $where=null, $order=null, $limit=null, $echo=false) {
  361. $ourquery = "SELECT ".$after." FROM ".$table_a." INNER JOIN ".$table_b." ON ".$on." ".$where." ".$order." ".$limit;
  362. if($echo == true) echo $ourquery;
  363. return self::query($ourquery);
  364. }
  365. /*
  366. * Insert row into database table
  367. * @param (string) $table - Query table name
  368. * @param (array) $labels - Array of field labels
  369. * @param (multidimension array) $values - Array of row values
  370. * @param (boolean) $echo - Show constructed query as echo debug output
  371. * @return (int) - Returns ID of new (last) row
  372. */
  373. public function insert($table, $labels, $values, $echo=false) {
  374. $ourlabels='';
  375. $ourvalues='';
  376. if (is_array($labels)) {
  377. // foreach ($labels as $label) {
  378. // $ourlabels .= ($label).",";
  379. // }
  380. // $ourlabels = substr($ourlabels,0,-1);
  381. $ourlabels = implode(',', $labels);
  382. }
  383. if (is_array($values)) {
  384. // foreach ($values as $value) {
  385. // $ourvalues .= "'".(str::escape($value))."',";
  386. // }
  387. // $ourvalues = substr($ourvalues,0,-1);
  388. $ourvalues = ar::flatten($values, "'"."',");
  389. }
  390. $ourquery = "INSERT INTO ".$table." (".$ourlabels.") VALUES (".$ourvalues.")";
  391. if($echo == true) echo $ourquery;
  392. self::query($ourquery,true);
  393. return self::$instance->insert_id;
  394. $result->close();
  395. self::disconnect();
  396. }
  397. /*
  398. * Count of rows
  399. * @param (string) $table - Query table name
  400. * @param (string) $after - Fields to return results from, default all
  401. * @param (string) $where - Where condition
  402. * @param (string) $order - Order By condition
  403. * @param (string) $limit - Limit condition
  404. * @param (boolean) $echo - Show constructed query as echo debug output
  405. * @return (int) - Returns integer of rows
  406. */
  407. public function count($table, $after="*", $where=null, $order=null, $limit=null, $echo=false){
  408. $ourquery = "SELECT ".$after." FROM ".$table." ".$where." ".$order." ".$limit;
  409. if($echo == true) echo $ourquery;
  410. self::query($ourquery,true);
  411. return self::$instance->affected_rows;
  412. $result->close();
  413. self::disconnect();
  414. }
  415. /*
  416. * Update query command
  417. * @param (string) $table - Query table name
  418. * @param (string) $set - Edit criteria (e.g) col='1'
  419. * @param (string) $criteria - Where condition
  420. * @param (boolean) $echo - Show constructed query as echo debug output
  421. * @return (int) - Returns number of affected rows
  422. */
  423. public function update($table, $set, $criteria, $echo=false) {
  424. $ourquery = "UPDATE ".$table." SET ".str::escape($set)." ".$criteria;
  425. if($echo == true) echo $ourquery;
  426. self::query($ourquery,true);
  427. return self::$instance->affected_rows;
  428. $result->close();
  429. self::disconnect();
  430. }
  431. /*
  432. * Delete row from table
  433. * @param (string) $table - Query table name
  434. * @param (string) $where - Where condition
  435. * @param (boolean) $echo - Show constructed query as echo debug output
  436. * @return (int) - Returns number of affected rows
  437. */
  438. public function delete($table, $where, $echo=false){
  439. $ourquery = "DELETE FROM ".$table." ".str::escape($where);
  440. if($echo == true) echo $ourquery;
  441. self::query($ourquery,true);
  442. return self::$instance->affected_rows;
  443. $result->close();
  444. self::disconnect();
  445. }
  446. /*
  447. * Return list of fields from database and field information
  448. * @param (string) $table - Query table name
  449. * @return (array) - Object of field information
  450. */
  451. public function fields($table) {
  452. $ourquery = "SELECT * FROM ".$table." LIMIT 1";
  453. $result = self::query($ourquery,true);
  454. return $result->fetch_fields();
  455. self::disconnect();
  456. }
  457. /*
  458. * Return list of saved MySQL Procedures
  459. * @return () - Object of procedure events
  460. */
  461. public function procedure(){
  462. $query = "select db, type, specific_name, param_list, returns from mysql.proc where definer like concat('%', concat((substring_index( (select user()), '@', 1)), '%'))";
  463. return self::query($query);
  464. self::disconnect();
  465. }
  466. } /* Database Methods */
  467. /*
  468. * Directory Methods
  469. * Easy to create/edit/delete directories
  470. */
  471. class dir {
  472. /*
  473. * Crawl and return information about a directory
  474. * @param (string) $dir - Directory to crawl
  475. * @return (array) - Associative array about directory
  476. */
  477. static function crawl($dir) {
  478. if(!is_dir($dir)) return array();
  479. $skip = array('.', '..', '.DS_Store');
  480. $files = array_diff(scandir($dir),$skip);
  481. $modified = str::datetime("d/m/Y-G:i:s", filemtime($dir));
  482. $data = array(
  483. 'name' => basename($dir),
  484. 'modified' => $modified,
  485. 'files' => array(),
  486. 'children' => array()
  487. );
  488. foreach($files as $file) {
  489. if(is_dir($dir.'/'.$file)) {
  490. $data['children'][] = $file;
  491. } else {
  492. $data['files'][] = $file;
  493. }
  494. }
  495. return $data;
  496. }
  497. /*
  498. * Make new directory, will check for existing directory first
  499. * @param (string) $dir - Directory name/location to create
  500. * @return (boolean)
  501. */
  502. static function make($dir) {
  503. if(is_dir($dir)) return true;
  504. if(!@mkdir($dir, 0755)) return false;
  505. @chmod($dir, 0755);
  506. return true;
  507. }
  508. /*
  509. * Move / Rename directory
  510. * @param (string) $old - current directory name
  511. * @param (string) $new - new directory name / location
  512. * @return (boolean)
  513. */
  514. static function move($old, $new) {
  515. if(!is_dir($old)) return false;
  516. return (@rename($old, $new) && is_dir($new)) ? true : false;
  517. }
  518. /*
  519. * Remove a directory or simply empty it
  520. * @param (string) $dir - Directory to destroy
  521. * @param (boolean) $empty - true = empty and leave directory
  522. * @return (boolean)
  523. */
  524. static function remove($dir, $empty=false) {
  525. if(!is_dir($dir)) return false;
  526. $skip = array('.', '..');
  527. $open = @opendir($dir);
  528. if(!$open) return false;
  529. while($file = @readdir($open)) {
  530. if (!in_array($file, $skip)) {
  531. if(is_dir($dir.'/'.$file)) {
  532. self::remove($dir.'/'.$file);
  533. } else {
  534. @unlink($dir.'/'.$file);
  535. }
  536. }
  537. }
  538. @closedir($open);
  539. if(!$empty) {
  540. return @rmdir($dir);
  541. } else {
  542. return true;
  543. }
  544. }
  545. } /* Directory Methods */
  546. /*
  547. * Regular Expression Methods
  548. */
  549. class ex {
  550. /*
  551. * Filter out expression
  552. * @param (mixed) $patern - patern to replace
  553. * @param (mixed) $subject - subject to run filter on
  554. * @param (mixed) $replace - replacement
  555. * @return (array)
  556. */
  557. static function filter($pattern,$subject,$replace) {
  558. return preg_filter($pattern, $replace, $subject);
  559. }
  560. /*
  561. * Match expression
  562. * @param (mixed) $patern - patern to replace
  563. * @param (mixed) $subject - subject to run match on
  564. * @return (array) - array of matches & offset location
  565. */
  566. static function match($pattern,$subject) {
  567. preg_match_all($pattern, $subject, $matches);
  568. return $matches;
  569. }
  570. /*
  571. * Match single (first) expression
  572. * @param (mixed) $patern - patern to replace
  573. * @param (mixed) $subject - subject to run match on
  574. * @return (array) - array of matches & offset location
  575. */
  576. static function matchsingle($pattern,$subject,$bool=false) {
  577. $result = preg_match($pattern, $subject, $matches);
  578. if($bool) return $result;
  579. return $matches;
  580. }
  581. /*
  582. * Replace expression
  583. * @param (mixed) $patern - patern to replace
  584. * @param (mixed) $subject - subject to run replacement on
  585. * @param (mixed) $replace - replacements to run replacements on
  586. * @return (string) - Subject string with replacements made
  587. */
  588. static function replace($pattern,$subject,$replace) {
  589. $match = preg_replace($pattern, $replace, $subject);
  590. return $match;
  591. }
  592. /*
  593. * Split expression
  594. * @param (string) $patern - patern to replace
  595. * @param (string) $subject - subject to run split on
  596. * @return (array) - array of matches & offset location
  597. */
  598. static function split($pattern,$subject) {
  599. $match = preg_split($pattern, $subject);
  600. return $match;
  601. }
  602. } /* Regular Expression */
  603. /*
  604. * File System
  605. * Set of file methods
  606. */
  607. class fs {
  608. /*
  609. * Download Push
  610. * @param (string) $file - File to push download
  611. * @return (file)
  612. * http://php.net/function.readfile.php
  613. */
  614. static function download($file) {
  615. if (!file_exists($file)) return false;
  616. header('Content-Description: File Transfer');
  617. header('Content-Type: application/octet-stream');
  618. header('Content-Disposition: attachment; filename='.self::filename($file));
  619. header('Content-Transfer-Encoding: binary');
  620. header('Expires: 0');
  621. header('Cache-Control: must-revalidate');
  622. header('Pragma: public');
  623. header('Content-Length: '.self::size($file,false));
  624. ob_clean();
  625. flush();
  626. readfile($file);
  627. exit;
  628. }
  629. /*
  630. * Get the file extension
  631. * @param (string) $file - The file
  632. * @return (boolean|string) returns extension, false on failure
  633. */
  634. static function extension($file) {
  635. if (!file_exists($file)) return false;
  636. $ext = pathinfo($file);
  637. return $ext['extension'];
  638. }
  639. /*
  640. * Get the filename
  641. * @param (string) $file - The file
  642. * @return (boolean|string) returns filename, false on failure
  643. */
  644. static function filename($file) {
  645. if (!file_exists($file)) return false;
  646. return basename($file);
  647. }
  648. /*
  649. * Get file info
  650. * @param (string) $file - The file
  651. * @return file information
  652. */
  653. static function info($file) {
  654. if (!file_exists($file)) return false;
  655. return stat($file);
  656. }
  657. /*
  658. * Get filesize
  659. * @param (string) $file - The file
  660. * @param (boolean) $format - To format with size unit
  661. * @return (string)
  662. * http://php.net/function.filesize.php
  663. */
  664. static function size($file,$format=true) {
  665. if (!file_exists($file)) return false;
  666. if (!$format) return filesize($file);
  667. return self::stringsize(filesize($file));
  668. }
  669. /*
  670. * Get filesize
  671. * @param (string) $size - Size string
  672. * @return (string)
  673. * http://php.net/function.filesize.php
  674. */
  675. static function stringsize($size) {
  676. $units = array(' b', ' kb', ' mb', ' gb', ' tb');
  677. for ($i=0; $size>=1024 && $i<4; $i++) $size/=1024;
  678. return round($size, 2).$units[$i];
  679. }
  680. /*
  681. * Replacement for includes
  682. * @param (string) $file - The file to include (require)
  683. */
  684. static function load($file) {
  685. if (file_exists($file)) require($file);
  686. }
  687. /*
  688. * Read file & return contents
  689. * @param (string) $file - File location
  690. * @return (string) - File contents
  691. */
  692. static function read($file) {
  693. if (!file_exists($file)) return false;
  694. $content = @file_get_contents($file);
  695. return $content;
  696. }
  697. /*
  698. * Write to a file, will create if does not exist
  699. * @param (string) $file - The file to write
  700. * @param (string) $content - The file content to write
  701. * @param (string) $append - Wether to append to the end of the file
  702. * @return (boolean)
  703. */
  704. static function write($file,$content,$append=false) {
  705. $mode = ($append)? FILE_APPEND : false;
  706. $write = @file_put_contents($file, $content, $mode);
  707. @chmod($file, 0666);
  708. return $write;
  709. }
  710. /*
  711. * Simply Append data to file
  712. * @param (string) $file - The file to write
  713. * @param (string) $content - The file content to write
  714. * @return (boolean)
  715. */
  716. static function append($file,$content) {
  717. return self::write($file,$content,true);
  718. }
  719. /*
  720. * Move file to new location
  721. * @param (string) $old - Current filename & location
  722. * @param (string) $new - New filename & location
  723. * @return (boolean)
  724. */
  725. static function move($old,$new) {
  726. if(!file_exists($old)) return false;
  727. return (@rename($old,$new) && file_exists($new))? true : false;
  728. }
  729. /*
  730. * Remove File from system
  731. * @param (string) $file - The file
  732. * @return (boolean)
  733. */
  734. static function remove($file) {
  735. if (!file_exists($file)) return false;
  736. return (is_file($file) && file_exists($file))? @unlink($file) : false;
  737. }
  738. } /* File Methods */
  739. /*
  740. * FTP File transfers
  741. */
  742. class ftp {
  743. /*
  744. * Connection instance
  745. */
  746. private static $instance;
  747. /*
  748. * Connection status check
  749. * @return (object|boolean) - Will return connection object or false
  750. */
  751. public function connection() {
  752. return (is_resource(self::$instance))? self::$instance : false;
  753. }
  754. /*
  755. * Connection Method
  756. */
  757. public function connect() {
  758. $host = (conf::get('ftp.host')!='')? conf::get('ftp.host') : 'localhost';
  759. $user = (conf::get('ftp.user')!='')? conf::get('ftp.user') : 'root';
  760. $password = (conf::get('ftp.password')!='')? conf::get('ftp.password') : '';
  761. $connection = ftp_connect($host);
  762. @$login = ftp_login($connection, $user, $password);
  763. if (!$login) return false;
  764. self::$instance = $connection;
  765. return $connection;
  766. }
  767. /*
  768. * Close Method
  769. */
  770. public function close() {
  771. @ftp_close(self::instance());
  772. }
  773. /*
  774. * Download File
  775. * @param (string) $local - Local File to create
  776. * @param (string) $remote - Remote file to target and download
  777. * @return (boolean)
  778. */
  779. public function get($local,$remote) {
  780. $instance = self::connection();
  781. if(!$instance) return $instance;
  782. $u = ftp_get($instance, $local, $remote, FTP_BINARY);
  783. if($u) return true;
  784. if(!$u) return false;
  785. }
  786. /*
  787. * Listing Method
  788. * @param (string) $dir - Directory
  789. * @return (array)
  790. * @return (boolean)
  791. */
  792. public function listing($dir='.') {
  793. $instance = self::connection();
  794. if(!$instance) return $instance;
  795. $ls = ftp_rawlist($instance, $dir);
  796. foreach ($ls as $list) {
  797. $info = preg_split("/[\s]+/", $list, 9);
  798. // $info = ex::split("/[\s]+/", $list);
  799. $point[] = array(
  800. 'name' => $info[8],
  801. 'size' => fs::stringsize($info[4]),
  802. 'directory' => $info[0]{0} == 'd'
  803. );
  804. }
  805. return @$point;
  806. }
  807. /*
  808. * Make Directory
  809. * @param (string) $dir - Directory name to make
  810. * @return (boolean)
  811. */
  812. public function makedir($dir) {
  813. if(empty($dir)) return false;
  814. $instance = self::connection();
  815. if(!$instance) return $instance;
  816. $u = ftp_mkdir($instance, $dir);
  817. if($u) return true;
  818. if(!$u) return false;
  819. }
  820. /*
  821. * Remove Directory
  822. * @param (string) $dir - Directory name to make
  823. * @return (boolean)
  824. */
  825. public function removedir($dir) {
  826. if(empty($dir)) return false;
  827. $instance = self::connection();
  828. if(!$instance) return $instance;
  829. $u = ftp_rmdir($instance, $dir);
  830. if($u) return true;
  831. if(!$u) return false;
  832. }
  833. /*
  834. * Upload file via FTP
  835. * @param (string) $file - File to upload
  836. * @param (string) $remote - File name on remote
  837. * @return (boolean)
  838. */
  839. public function upload($file,$remote) {
  840. $instance = self::connection();
  841. if(!$instance) return $instance;
  842. $u = ftp_put($instance, $remote, $file, FTP_ASCII);
  843. if($u) return true;
  844. if(!$u) return false;
  845. }
  846. /*
  847. * Delete file
  848. * @param (string) $file - File to upload
  849. * @return (boolean)
  850. */
  851. public function delete($file) {
  852. $instance = self::connection();
  853. if(!$instance) return $instance;
  854. $u = ftp_delete($instance, $file);
  855. if($u) return true;
  856. if(!$u) return false;
  857. }
  858. } /* FTP Methods */
  859. /*
  860. * HTML
  861. * Set of HTML creating Methods
  862. */
  863. class html {
  864. /*
  865. * Create a stylesheet link
  866. * @param (string) $file - File location of stylesheet
  867. * @return (string)
  868. */
  869. static function css($file) {
  870. return '<link rel="stylesheet" href="'.$file.'" />';
  871. }
  872. /*
  873. * Creates a encoded email hyperlink
  874. * @param (string) $email - The email address
  875. * @param (string) $text - optional text to use as hyperlink, default use email
  876. * @param (string) $title - optional HTML title tag
  877. * @param (string) $class - optional HTML class
  878. * @return (string) - A formatted mailto hyperlink
  879. */
  880. static function email($email, $text=false, $class=false, $title=false) {
  881. $string = (empty($text))? $email : $text;
  882. $email = str::ascii($email);
  883. $class = (!empty($class))? ' class="'.$class.'" ':'';
  884. $title = (!empty($title))? ' title="'.$title.'" ':' ';
  885. return '<a'.$title.$class.'href="mailto:'.$email.'">'.str::ascii($string).'</a>';
  886. }
  887. /*
  888. * Create a javascript link
  889. * @param (string) $file - File location of script
  890. * @return (string)
  891. */
  892. static function js($file) {
  893. return '<script src="'.$file.'"></script>';
  894. }
  895. /*
  896. * Creates a link
  897. * @param (string) $link - The URL
  898. * @param (string) $text - Text for the link tag, If false the URL will be used
  899. * @param (string) $title - optional HTML title tag
  900. * @param (string) $class - optional HTML class
  901. * @return (string) - A formatted hyperlink
  902. */
  903. static function link($link, $text=false, $class=false, $target=false, $title=false) {
  904. $text = ($text)?$text:$link;
  905. $class = (!empty($class))? ' class="'.$class.'" ':'';
  906. $title = (!empty($title))? ' title="'.$title.'" ':'';
  907. $target = (!empty($target))? ' target="_'.str::lower($target).'" ':'';
  908. return '<a '.$title.''.$class.'href="'.$link.'"'.$target.'>'.str::sanetize($text).'</a>';
  909. }
  910. /*
  911. * Generate a Table
  912. * @param (array) $headings - An array of table headings
  913. * @param (multidimension array) $rows - Multidimension Array of rows
  914. * @param (string) $class - optional class string
  915. * @param (multidimension array) $tfoot - Multidimension Array of rows for tfoot
  916. */
  917. static function table($headings=null, $rows, $class='', $tfoot=null) {
  918. $html = '<table border="0" cellpadding="0" cellspacing="0" class="'.$class.'">'."\n";
  919. //Table Headings
  920. if ($headings!=null) {
  921. $html .= '<thead>'."\n";
  922. $html .= '<tr>'."\n";
  923. //Loop Headings
  924. foreach ($headings as $thead) {
  925. $html .= ' <th>'.$thead.'</th> ';
  926. }
  927. $html .= '</tr>'."\n";
  928. $html .= '</thead>'."\n";
  929. } // !Headings
  930. //Table Foot
  931. if ($tfoot!=null) {
  932. $html .= '<tfoot>'."\n";
  933. if (is_array($tfoot)) {
  934. if (is_array($tfoot[0])){ //Multi array
  935. foreach ($tfoot as $cells) {
  936. $html .= '<tr>';
  937. foreach ($cells as $key => $value) {
  938. $html .= ' <td>'.$value.'</td> ';
  939. }
  940. $html .= '</tr>'."\n";
  941. }
  942. } else { //Single array
  943. $html .= '<tr>';
  944. foreach ($tfoot as $cells) {
  945. $html .= ' <td>'.$cells.'</td> ';
  946. }
  947. $html .= '</tr>'."\n";
  948. }
  949. }//tfoot array
  950. $html .= '</tfoot>'."\n";
  951. } // !Foot
  952. //Table Body
  953. if (is_array($rows)) {
  954. $html .= '<tbody>'."\n";
  955. if (is_array($rows[0])) {
  956. foreach ($rows as $cells) {
  957. $html .= '<tr>';
  958. foreach ($cells as $key => $value) {
  959. $html .= ' <td>'.$value.'</td> ';
  960. }
  961. $html .= '</tr>'."\n";
  962. }
  963. } else {
  964. $html .= '<tr>';
  965. foreach ($rows as $cells) {
  966. $html .= ' <td>'.$cells.'</td> ';
  967. }
  968. $html .= '</tr>'."\n";
  969. }
  970. $html .= '</tbody>'."\n";
  971. }
  972. $html .='</table>';
  973. return $html;
  974. }
  975. } /* HTML Methods */
  976. /*
  977. * JSON
  978. */
  979. class json {
  980. /*
  981. * Encode to json
  982. * @param (mixed) $value - Value to encode to json
  983. * @return (string)
  984. */
  985. static function create($value) {
  986. return json_encode($value);
  987. }
  988. /*
  989. * Decode json object
  990. * @param (string) $js - Our JSON string
  991. * @return (mixed)
  992. */
  993. static function decode($js) {
  994. return json_decode($js);
  995. }
  996. } /* Json Methods */
  997. /*
  998. * Password Helpful Methods
  999. */
  1000. class password {
  1001. /*
  1002. * Spoken Elements Array
  1003. * Our easly remembered words
  1004. */
  1005. private static $memorables = Array('able','about','above','accept','accident','accuse','across','act','activist','actor','add','administration','admit','advise','affect','afraid','after','again','against','age','agency','aggression','ago','agree','agriculture','aid','aim','air','airplane','airport','alive','all','ally','almost','alone','along','already','also','although','always','ambassador','amend','ammunition','among','amount','anarchy','ancient','anger','animal','anniversary','announce','another','answer','any','apologize','appeal','appear','appoint','approve','area','argue','arms','army','around','arrest','arrive','art','artillery','as','ash','ask','assist','astronaut','asylum','atmosphere','atom','attack','attempt','attend','automobile','autumn','awake','award','away',
  1006. 'back','bad','balance','ball','balloon','ballot','ban','bank','bar','base','battle','beach','beat','beauty','because','become','bed','beg','begin','behind','believe','bell','belong','below','best','betray','better','between','big','bill','bird','bite','bitter','black','blame','blanket','bleed','blind','block','blood','blow','blue','boat','body','boil','bomb','bone','book','border','born','borrow','both','bottle','bottom','box','boy','brain','brave','bread','break','breathe','bridge','brief','bright','bring','broadcast','brother','brown','build','bullet','burn','burst','bury','bus','business','busy',
  1007. 'cabinet','call','calm','camera','campaign','can','cancel','cancer','candidate','cannon','capital','capture','car','care','careful','carry','case','cat','catch','cattle','cause','ceasefire','celebrate','cell','center','century','ceremony','chairman','champion','chance','change','charge','chase','cheat','check','cheer','chemicals','chieg','child','choose','church','circle','citizen','city','civil','civilian','clash','clean','clear','climb','clock','close','cloth','clothes','cloud','coal','coalition','coast','coffee','cold','collect','colony','color','comedy','command','comment','committee','common','communicate','company','compete','complete','compromise','computer','concern','condemn','condition','conference','confirm','conflict','congratulate','congress','connect','conservative','consider','contain','continent','continue','control','convention','cook','cool','cooperate','copy','correct','cost','costitution','cotton','count','country','court','cover','cow','coward','crash','create','creature','credit','crew','crime','criminal','crisis','criticize','crops','cross','crowd','cruel','crush','cry','culture','cure','current','custom','cut',
  1008. 'damage','dance','danger','dark','date','daughter','day','deal','debate','decide','declare','deep','defeat','defend','deficit','degree','delay','delegate','demand','demonstrate','denounce','deny','depend','deplore','deploy','describe','desert','design','desire','destroy','details','develop','device','different','difficult','dig','dinner','diplomat','direct','direction','dirty','disappear','disarm','discover','discuss','disease','dismiss','dispute','dissident','distance','distant','dive','divide','doctor','document','dollar','door','down','draft','dream','drink','drive','drown','dry','during','dust','duty',
  1009. 'each','early','earn','earth','earthquake','ease','east','easy','eat','economy','edge','educate','effect','effort','egg','either','elect','electricity','electron','element','embassy','emergency','emotion','employ','empty','end','enemy','energy','enforce','engine','engineer','enjoy','enough','enter','eqipment','equal','escape','especially','establish','even','event','ever','every','evidence','evil','evironment','exact','examine','example','excellent','except','exchange','excite','excuse','execute','exile','exist','expand','expect','expel','experiment','expert','explain','explode','explore','export','express','extend','extra','extreme',
  1010. 'face','fact','factory','fail','fair','fall','family','famous','fanatic','far','farm','fast','fat','fear','feast','federal','feed','feel','female','few','field','fierce','fight','fill','film','final','find','fine','finish','fire','firm','first','fish','fix','flag','flat','flee','float','flood','floor','flow','flower','fluid','fly','fog','follow','food','fool','foot','force','foreign','forget','forgive','form','former','forward','free','freeze','fresh','friend','frighten','front','fruit','fuel','funeral','furious','future',
  1011. 'gain','game','gas','gather','general','gentle','gift','girl','give','glass','goal','gold','good','goods','govern','government','grain','grass','gray','great','green','grind','ground','group','grow','guarantee','guard','guerilla','guide','guilty','gun',
  1012. 'hair','half','halt','hang','happen','happy','harbor','hard','harm','hat','hate','head','headquarters','health','hear','heart','heat','heavy','helicopter','help','hero','hide','high','hijack','hill','history','hit','hold','hole','holiday','holy','home','honest','honor','hope','horrible','horse','hospital','hostage','hostile','hostilities','hot','hotel','hour','house','how','however','huge','human','humor','hunger','hunt','hurry','hurt','husband',
  1013. 'ice','idea','illegal','imagine','immediate','import','important','improve','incident','incite','include','increase','independent','industry','inflation','influence','inform','injure','innocent','insane','insect','inspect','instead','instrument','insult','intelligent','intense','interest','interfere','international','intervene','invade','invent','invest','investigate','invite','involve','iron','island','issue',
  1014. 'jail','jewel','job','join','joint','joke','judge','jump','jungle','jury','just',
  1015. 'keep','kick','kind','kiss','knife','know',
  1016. 'labor','laboratory','lack','lake','land','language','large','last','late','laugh','launch','law','lead','leak','learn','leave','left','legal','lend','less','let','letter','level','lie','life','light','lightning','like','limit','line','link','liquid','list','listen','little','live','load','local','lonely','long','look','lose','loud','love','low','loyal','luck',
  1017. 'machine','mad','mail','main','major','majority','make','male','man','map','march','mark','marker','mass','material','may','mayor','mean','measure','meat','medicine','meet','melt','member','memorial','memory','mercenary','mercy','message','metal','method','microscope','middle','militant','military','milk','mind','mine','mineral','minister','minor','minority','minute','miss','missile','missing','mistake','mix','mob','moderate','modern','money','month','moon','more','morning','most','mother','motion','mountain','mourn','move','much','music','must','mystery',
  1018. 'naked','name','nation','navy','near','necessary','negotiate','neither','nerve','neutral','never','new','news','next','nice','night','noise','nominate','noon','normal','north','note','nothing','nowhere','nuclear','number','nurse',
  1019. 'obey','object','observe','occupy','ocean','offensive','offer','officer','official','often','oil','old','once','only','open','operate','opinion','oppose','opposite','oppress','orbit','orchestra','order','organize','other','overthrow',
  1020. 'pain','paint','palace','pamphlet','pan','paper','parachute','parade','pardon','parent','parliament','part','party','pass','passenger','passport','past','path','pay','peace','people','percent','perfect','perhaps','period','permanent','permit','person','physics','piano','picture','piece','pilot','pipe','pirate','place','planet','plant','play','please','plenty','plot','poem','point','poison','police','policy','politics','pollute','poor','popular','population','port','position','possess','possible','postpone','pour','power','praise','pray','pregnant','prepare','present','president','press','pressure','prevent','price','priest','prison','private','prize','probably','problem','produce','professor','program','progress','project','promise','propaganda','property','propose','protect','protest','proud','prove','provide','public','publication','publish','pull','pump','punish','purchase','pure','purpose',
  1021. 'question','quick','quiet',
  1022. 'rabbi','race','radar','radiation','radio','raid','railroad','rain','raise','rapid','rare','rate','reach','read','ready','real','realistic','reason','reasonable','rebel','receive','recent','recession','recognize','record','red','reduce','reform','refugee','refuse','regret','relations','release','remain','remember','remove','repair','repeat','report','repress','request','rescue','resign','resolution','responsible','rest','restrain','restrict','result','retire','return','revolt','rice','rich','ride','right','riot','rise','river','road','rock','rocket','roll','room','root','rope','rough','round','rub','rubber','ruin','rule','run',
  1023. 'sabotage','sacrifice','safe','sail','salt','same','satellite','satisfy','save','say','school','science','scream','sea','search','season','seat','second','secret','security','see','seek','seem','seize','self','sell','senate','send','sense','sentence','separate','series','serious','sermon','settle','several','severe','shake','shape','share','sharp','shell','shine','ship','shock','shoe','shoot','short','should','shout','show','shrink','shut','sick','side','sign','signal','silence','silver','similar','simple','since','sing','sink','situation','skeleton','skill','skull','sky','slave','sleep','slide','slow','small','smash','smell','smile','smoke','smooth','snow','social','soft','soldier','solid','solve','some','soon','sorry','sort','sound','south','space','speak','special','speed','spend','spill','spilt','spirit','split','sports','spread','spring','spy','stab','stamp','stand','star','start','starve','state','station','statue','stay','steal','steam','steel','step','stick','still','stomach','stone','stop','store','storm','story','stove','straight','strange','street','stretch','strike','strong','struggle','stubborn','study','stupid','submarine','substance','substitute','subversion','succeed','such','sudden','suffer','sugar','summer','sun','supervise','supply','support','suppose','suppress','sure','surplus','surprise','surrender','surround','survive','suspect','suspend','swallow','swear','sweet','swim','sympathy','system',
  1024. 'take','talk','tall','tank','target','task','taste','tax','teach','team','tear','tears','technical','telephone','telescope','television','tell','temperature','temporary','tense','term','terrible','territory','terror','test','textiles','thank','that','theater','thick','thin','thing','think','third','threaten','through','throw','tie','time','tired','tissue','today','together','tomorrow','tonight','tool','top','torture','touch','toward','town','trade','tradition','tragic','train','traitor','transport','trap','travel','treason','treasure','treat','treaty','tree','trial','tribe','trick','trip','troops','trouble','truce','truck','trust','turn',
  1025. 'under','understand','unite','universe','university','unless','until','up','urge','urgent','usual','valley','value','vehicle','version','veto','vicious','victim','victory','village','violate','violence','violin','virus','visit','voice','volcano','vote','voyage',
  1026. 'wages','wait','walk','wall','want','warm','warn','wash','waste','watch','water','wave','way','weak','wealth','weapon','wear','weather','weigh','welcome','well','west','wet','wheat','wheel','white','wide','wife','wild','will','willing','win','wind','window','wire','wise','wish','withdraw','without','woman','wonder','wood','woods','word','work','world','worry','worse','wound','wreck','write','wrong',
  1027. 'year','yellow','yesterday','young',
  1028. 'zealot','zebra');
  1029. /*
  1030. * Simple Encypt Password
  1031. * Will put system salt into effect if set in configuration
  1032. * @param (string) $string - Password / String to simple encode
  1033. * @return (string)
  1034. */
  1035. static function encypt($string) {
  1036. if (conf::get('salt')) $string .= conf::get('salt');
  1037. $string = hash("sha512", $string);
  1038. return $string;
  1039. }
  1040. /*
  1041. * Generate a Memorable Password instead of random letters
  1042. * @param (int) $length - Optional word length
  1043. * @return (string) - Your new memorable password
  1044. */
  1045. static function memorable($length=2) {
  1046. $string = "";
  1047. for ($i=0; $i<$length ; $i++) {
  1048. $string .= ucfirst(self::$memorables[mt_rand(0, sizeof(self::$memorables))]);
  1049. }
  1050. return $string;
  1051. }
  1052. } /* Password Methods */
  1053. /*
  1054. * Requests
  1055. * Set of methods for Requests
  1056. */
  1057. class req {
  1058. /*
  1059. * Determines if page is being loaded using AJAX.
  1060. * @return (boolean) - Either true or False return on weather request is Ajax
  1061. * Contributed by David Turner <http://davidturner.name>
  1062. */
  1063. function ajax(){
  1064. if (!server::get('HTTP_X_REQUESTED_WITH') && @strtolower(server::get('HTTP_X_REQUESTED_WITH') != 'xmlhttprequest')) {
  1065. return false;
  1066. }else{
  1067. return true;
  1068. }
  1069. }
  1070. /*
  1071. * cUrl request a file
  1072. * @param (string) $request - The file you are requesting
  1073. * @param (string|boolean) $file - The local file to save to
  1074. * @param (array) $post - Optional post variables
  1075. * @param (array) $header - Optional Content HTTP Headers
  1076. * @return (file|string) - Returns result, or can save to file
  1077. */
  1078. static function curl($request, $file=false, $post=false, $header=false) {
  1079. if (empty($request)) return false;
  1080. $ch = curl_init();
  1081. curl_setopt($ch, CURLOPT_URL, $request);
  1082. if ($post) {
  1083. curl_setopt($ch,CURLOPT_POST, 1);
  1084. curl_setopt($ch,CURLOPT_POSTFIELDS ,$post);
  1085. }
  1086. if ($header) {
  1087. curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
  1088. }
  1089. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1090. $return = curl_exec($ch);
  1091. curl_close($ch);
  1092. if (empty($return)) return false;
  1093. if (!$file) return $return;
  1094. fs::write($file,$return);
  1095. return true;
  1096. }
  1097. /*
  1098. * File get request
  1099. * @param (string) $request - The file you are requesting
  1100. * @param (string) $file - The local file to save to
  1101. * @param (array) $post - Use POST
  1102. * @param (array) $header - Optional Content HTTP Headers
  1103. * @return (file|string) - Returns result, or can save to file
  1104. */
  1105. static function file($request, $file=null, $post=false, $header=false) {
  1106. if (empty($request)) return false;
  1107. $met = ($post)?'POST':'GET';
  1108. if (empty($header)) $header = array("Content-Type: text/html;","charset=".conf::get('charset'));
  1109. $options = array(
  1110. 'http' => array(
  1111. 'method'=>$met,
  1112. 'header'=>$header
  1113. )
  1114. );
  1115. $con = stream_context_create($options);
  1116. $return = file_get_contents($request, false, $con);
  1117. if (empty($return)) return false;
  1118. if (empty($file)) return $return;
  1119. fs::write($file,$return);
  1120. return true;
  1121. }
  1122. /*
  1123. * Find the refering link
  1124. * @param (string) $default - referred the user to the page
  1125. * @return (string)
  1126. */
  1127. static function referer($default=null) {
  1128. if(empty($default)) $default = '/';
  1129. return server::get('http_referer', $default);
  1130. }
  1131. } /* Request Methods */
  1132. /*
  1133. * Sessions
  1134. * Set of methods to help with sessions
  1135. */
  1136. class sess {
  1137. /*
  1138. * Starts session
  1139. */
  1140. static function start() {
  1141. @session_start();
  1142. }
  1143. /*
  1144. * Ends session
  1145. */
  1146. static function kill() {
  1147. @session_destroy();
  1148. }
  1149. /*
  1150. * Create a new session variable
  1151. * @param (string) $key - Session variable key name
  1152. * @param (string) $value - String to save to new session variable
  1153. */
  1154. static function set($key, $value=false) {
  1155. if(!isset($_SESSION)) self::start();
  1156. $_SESSION[$key] = $value;
  1157. }
  1158. /*
  1159. * Get a session key or the whole array
  1160. * @param (string) $key - The key to return
  1161. * @return (array|string) - Return single variable if key set, or whole session array
  1162. */
  1163. static function get($key=false) {
  1164. if(!isset($_SESSION)) self::start();
  1165. if(empty($key)) return $_SESSION;
  1166. return ar::get($_SESSION, $key);
  1167. }
  1168. /*
  1169. * Deletes a session key
  1170. * @param (string) $key - The key to delete
  1171. * @return (array) - The updated Session array
  1172. */
  1173. static function delete($key) {
  1174. if(!isset($_SESSION)) self::start();
  1175. $_SESSION = ar::delete($_SESSION, $key, true);
  1176. return $_SESSION;
  1177. }
  1178. } /* Session Methods */
  1179. /*
  1180. * Server
  1181. * Easier method to get variables from global server
  1182. */
  1183. class server {
  1184. /*
  1185. * Get a value from the _SERVER array
  1186. * @param (string) $key - The key to look for
  1187. * @return (boolean|string) - return string result, false on key fault
  1188. */
  1189. static function get($key=false) {
  1190. if(empty($key)) return $_SERVER;
  1191. return ar::get($_SERVER, str::upper($key));
  1192. }
  1193. /*
  1194. * View broken down phpinfo
  1195. * @param (string) $what - info constants
  1196. * @return (array)
  1197. * http://php.net/function.phpinfo.php
  1198. */
  1199. static function info($what=INFO_ALL) {
  1200. ob_start();
  1201. phpinfo($what);
  1202. $info = array();
  1203. $lines = explode("\n", strip_tags(ob_get_clean(), "<tr><td><h2>"));
  1204. $cat="General";
  1205. foreach($lines as $line) {
  1206. preg_match("~<h2>(.*)</h2>~", $line, $match)? $cat = $match[1] : null;
  1207. if(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val)) {
  1208. $info[$cat][$val[1]] = $val[2];
  1209. } elseif(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val)) {
  1210. $info[$cat][$val[1]] = array("local" => $val[2], "master" => $val[3]);
  1211. }
  1212. }
  1213. return $info;
  1214. }
  1215. } /* Server Methods */
  1216. /*
  1217. * String
  1218. * Set of string methods
  1219. */
  1220. class str {
  1221. /*
  1222. * Convert word to hexadecimal color
  1223. * @param (string) $string - String to convert
  1224. * @return (string) - Converted Colour value
  1225. * Contributed by David Turner <http://davidturner.name>
  1226. */
  1227. static function hexcolor($string) {
  1228. $hexcolor = md5 ($string);
  1229. $hexcolor = substr($hexcolor, 0, 6);
  1230. return '#' . $hexcolor;
  1231. }
  1232. /*
  1233. * Curly Quotes and other Text Goodness
  1234. * @param (string) $string - Text to process
  1235. * @return (string) - Processed text
  1236. * Contributed by David Turner <http://davidturner.name>
  1237. */
  1238. static function curly($string) {
  1239. if ($string == '') return '';
  1240. $search = array(
  1241. ' \'',
  1242. '\' ',
  1243. ' "',
  1244. '" ',
  1245. ' “\'',
  1246. '\'” ',
  1247. ' ‘"',
  1248. ' "’',
  1249. '>\'',
  1250. '\'<',
  1251. '>"',
  1252. '"<',
  1253. '>“\'',
  1254. '\'”<',
  1255. '>‘"',
  1256. '>"’',
  1257. '…'
  1258. );
  1259. $replace = array(
  1260. ' ‘',
  1261. '’ ',
  1262. ' “',
  1263. '” ',
  1264. ' “‘',
  1265. '’" ',
  1266. ' ‘“',
  1267. ' ”’',
  1268. '>‘',
  1269. '’<',
  1270. '>“',
  1271. '”<',
  1272. '>“‘',
  1273. '’"<',
  1274. '>‘“',
  1275. '>”’',
  1276. '…'
  1277. );
  1278. $searchsingle = array(
  1279. '"',
  1280. "'"
  1281. );
  1282. $replacestart = array(
  1283. '“',
  1284. '‘'
  1285. );
  1286. $replaceend = array(
  1287. '”',
  1288. '’'
  1289. );
  1290. $string = str::replace(str::replace($string, $search, $replace), '\'', '’');
  1291. $string = ex::replace('/<([^<>]+)>/e', $string, '"<" .str::replace($1, "”", \'"\').">"');
  1292. $string = ex::replace('/<([^<>]+)>/e', $string, '"<" .str::replace($1, "’", "\'").">"');
  1293. $first = $string{0};
  1294. $first = str::replace($first, $searchsingle, $replacestart);
  1295. $string = $first . substr($string, 1);
  1296. $invert = strrev( $string );
  1297. $last = $invert{0};
  1298. $last = str::replace($last, $searchsingle, $replaceend);
  1299. $string = strrev(substr($invert, 1)) . $last;
  1300. return $string;
  1301. }
  1302. /*
  1303. * Encode a string to ASCII
  1304. * @param (string) $string - String to encode
  1305. * @return (string) - encoded string
  1306. */
  1307. static function ascii($string) {
  1308. $encoded = '';
  1309. $length = str::length($string);
  1310. for($i=0; $i<$length; $i++) {
  1311. $encoded .= '&#'.ord($string[$i]).';';
  1312. }
  1313. return $encoded;
  1314. }
  1315. /*
  1316. * Adds an apostrophe to a string if applicable - Works on a word basis
  1317. * @param (string) $string - The string
  1318. * @return (string) - String + apostraphe
  1319. */
  1320. static function apostrophe($string) {
  1321. return (substr($string,-1,1)=='s' || substr($string,-1,1)=='z')? $string .= "'" : $string .= "'s";
  1322. }
  1323. /*
  1324. * Base 64 encode a string
  1325. * @param (string) $string - String to encode
  1326. * @return (string)
  1327. */
  1328. static function encode($string) {
  1329. return base64_encode($string);
  1330. }
  1331. /*
  1332. * Base 64 decode a string
  1333. * @param (string) $string - String to decode
  1334. * @return (string)
  1335. */
  1336. sta

Large files files are truncated, but you can click here to view the full file