PageRenderTime 69ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/app/kirby.php

https://github.com/bastianallgeier/zync
PHP | 1962 lines | 1310 code | 482 blank | 170 comment | 238 complexity | 24499ab73f05ef120797ac0430513049 MD5 | raw file
Possible License(s): JSON
  1. <?php
  2. c::set('version', 0.6);
  3. c::set('language', 'en');
  4. c::set('charset', 'utf-8');
  5. c::set('root', dirname(__FILE__));
  6. /*
  7. ############### HELPER ###############
  8. */
  9. function go($url=false, $code=false) {
  10. if(empty($url)) $url = c::get('url', '/');
  11. // send an appropriate header
  12. if($code) {
  13. switch($code) {
  14. case 301:
  15. header('HTTP/1.1 301 Moved Permanently');
  16. break;
  17. case 302:
  18. header('HTTP/1.1 302 Found');
  19. break;
  20. case 303:
  21. header('HTTP/1.1 303 See Other');
  22. break;
  23. }
  24. }
  25. // send to new page
  26. header('Location:' . $url);
  27. exit();
  28. }
  29. function status($response) {
  30. return core::status($response);
  31. }
  32. function msg($response) {
  33. return core::msg($response);
  34. }
  35. function error($response) {
  36. return core::error($response);
  37. }
  38. function load() {
  39. $root = c::get('plugins', c::get('root') . '/plugins');
  40. $files = func_get_args();
  41. foreach((array)$files AS $f) {
  42. include_once($root . '/' . $f . '.php');
  43. }
  44. }
  45. /*
  46. ############### CORE ###############
  47. */
  48. class core {
  49. public static $trace = array();
  50. function status($response) {
  51. return a::get($response, 'status');
  52. }
  53. function msg($response) {
  54. return a::get($response, 'msg');
  55. }
  56. function error($response) {
  57. return (self::status($response) == 'error') ? true : false;
  58. }
  59. function trace($msg=false) {
  60. if(empty($msg)) return self::$trace;
  61. self::$trace[] = $msg;
  62. }
  63. }
  64. /*
  65. ############### ARRAY ###############
  66. */
  67. class a {
  68. function get($array, $key, $default=null) {
  69. return (isset($array[ $key ])) ? $array[ $key ] : $default;
  70. }
  71. function remove($array, $search, $key=true) {
  72. if($key) {
  73. unset($array[$search]);
  74. } else {
  75. $found_all = false;
  76. while(!$found_all) {
  77. $index = array_search($search, $array);
  78. if($index !== false) {
  79. unset($array[$index]);
  80. } else {
  81. $found_all = true;
  82. }
  83. }
  84. }
  85. return $array;
  86. }
  87. function inject($array, $position, $element='placeholder') {
  88. $start = array_slice($array, 0, $position);
  89. $end = array_slice($array, $position);
  90. return array_merge($start, (array)$element, $end);
  91. }
  92. function show($array, $echo=true) {
  93. $output = '<pre>';
  94. $output .= htmlspecialchars(print_r($array, true));
  95. $output .= '</pre>';
  96. if($echo==true) echo $output;
  97. return $output;
  98. }
  99. function json($array) {
  100. return @json_encode( (array)$array );
  101. }
  102. function xml($array, $tag='root', $head=true, $charset='utf-8', $tab=' ', $level=0) {
  103. $result = ($level==0 && $head) ? '<?xml version="1.0" encoding="' . $charset . '"?>' . "\n" : '';
  104. $nlevel = ($level+1);
  105. $result .= str_repeat($tab, $level) . '<' . $tag . '>' . "\n";
  106. foreach($array AS $key => $value) {
  107. $key = str::lower($key);
  108. if(is_array($value)) {
  109. $mtags = false;
  110. foreach($value AS $key2 => $value2) {
  111. if(is_array($value2)) {
  112. $result .= self::xml($value2, $key, $head, $charset, $tab, $nlevel);
  113. } else if(trim($value2) != '') {
  114. $value2 = (htmlspecialchars($value2) != $value2) ? '<![CDATA[' . $value2 . ']]>' : $value2;
  115. $result .= str_repeat($tab, $nlevel) . '<' . $key . '>' . $value2 . '</' . $key . '>' . "\n";
  116. }
  117. $mtags = true;
  118. }
  119. if(!$mtags && count($value) > 0) {
  120. $result .= self::xml($value, $key, $head, $charset, $tab, $nlevel);
  121. }
  122. } else if(trim($value) != '') {
  123. $value = (htmlspecialchars($value) != $value) ? '<![CDATA[' . $value . ']]>' : $value;
  124. $result .= str_repeat($tab, $nlevel) . '<' . $key . '>' . $value . '</' . $key . '>' . "\n";
  125. }
  126. }
  127. return $result . str_repeat($tab, $level) . '</' . $tag . '>' . "\n";
  128. }
  129. function extract($array, $key) {
  130. $output = array();
  131. foreach($array AS $a) if(isset($a[$key])) $output[] = $a[ $key ];
  132. return $output;
  133. }
  134. function shuffle($array) {
  135. $aux = array();
  136. $keys = array_keys($array);
  137. shuffle($keys);
  138. foreach($keys as $key) {
  139. $aux[$key] = $array[$key];
  140. unset($array[$key]);
  141. }
  142. return $aux;
  143. }
  144. function first($array) {
  145. return array_shift($array);
  146. }
  147. function last($array) {
  148. return array_pop($array);
  149. }
  150. function search($array, $search) {
  151. return preg_grep('#' . preg_quote($search) . '#i' , $array);
  152. }
  153. function contains($array, $search) {
  154. $search = self::search($array, $search);
  155. return (empty($search)) ? false : true;
  156. }
  157. function fill($array, $limit, $fill='placeholder') {
  158. if(count($array) < $limit) {
  159. $diff = $limit-count($array);
  160. for($x=0; $x<$diff; $x++) $array[] = $fill;
  161. }
  162. return $array;
  163. }
  164. function missing($array, $required=array()) {
  165. $missing = array();
  166. foreach($required AS $r) {
  167. if(empty($array[$r])) $missing[] = $r;
  168. }
  169. return $missing;
  170. }
  171. // Not working - atleast not in php 5.3
  172. // example: a::sort($array, 'volume DESC, edition ASC');
  173. function sort($array, $params) {
  174. if(!is_array($array) || empty($array)) return $array;
  175. // prepare the sort params
  176. $params = str::split(str::lower($params));
  177. foreach($array AS $key => $row) {
  178. foreach($params AS $num => $param) {
  179. $param = str::split($param,' ');
  180. if(!empty($param[0])) ${$param[0]}[$key] = $row[$param[0]];
  181. }
  182. }
  183. $args = array();
  184. foreach($params AS $num => $param) {
  185. $param = str::split($param,' ');
  186. $args[] = ${$param[0]};
  187. $args[] = ($param[1] == 'asc') ? SORT_ASC : SORT_DESC;
  188. }
  189. $args[] = &$array;
  190. call_user_func_array('array_multisort', $args);
  191. return $array;
  192. }
  193. }
  194. /*
  195. ############### BROWSER ###############
  196. */
  197. class browser {
  198. static public $ua = false;
  199. static public $browser = false;
  200. static public $engine = false;
  201. static public $version = false;
  202. static public $platform = false;
  203. function name($ua=null) {
  204. self::detect($ua);
  205. return self::$browser;
  206. }
  207. function engine($ua=null) {
  208. self::detect($ua);
  209. return self::$engine;
  210. }
  211. function version($ua=null) {
  212. self::detect($ua);
  213. return self::$version;
  214. }
  215. function platform($ua=null) {
  216. self::detect($ua);
  217. return self::$platform;
  218. }
  219. function mobile($ua=null) {
  220. self::detect($ua);
  221. return (self::$platform == 'mobile') ? true : false;
  222. }
  223. function iphone($ua=null) {
  224. self::detect($ua);
  225. return (in_array(self::$platform, array('ipod', 'iphone'))) ? true : false;
  226. }
  227. function ios($ua=null) {
  228. self::detect($ua);
  229. return (in_array(self::$platform, array('ipod', 'iphone', 'ipad'))) ? true : false;
  230. }
  231. function css($ua=null, $array=false) {
  232. self::detect($ua);
  233. $css[] = self::$engine;
  234. $css[] = self::$browser;
  235. if(self::$version) $css[] = self::$browser . str_replace('.', '_', self::$version);
  236. $css[] = self::$platform;
  237. return ($array) ? $css : implode(' ', $css);
  238. }
  239. function detect($ua=null) {
  240. $ua = ($ua) ? str::lower($ua) : str::lower(server::get('http_user_agent'));
  241. // don't do the detection twice
  242. if(self::$ua == $ua) return array(
  243. 'browser' => self::$browser,
  244. 'engine' => self::$engine,
  245. 'version' => self::$version,
  246. 'platform' => self::$platform
  247. );
  248. self::$ua = $ua;
  249. self::$browser = false;
  250. self::$engine = false;
  251. self::$version = false;
  252. self::$platform = false;
  253. // browser
  254. if(!preg_match('/opera|webtv/i', self::$ua) && preg_match('/msie\s(\d)/', self::$ua, $array)) {
  255. self::$version = $array[1];
  256. self::$browser = 'ie';
  257. self::$engine = 'trident';
  258. } else if(strstr(self::$ua, 'firefox/3.6')) {
  259. self::$version = 3.6;
  260. self::$browser = 'fx';
  261. self::$engine = 'gecko';
  262. } else if (strstr(self::$ua, 'firefox/3.5')) {
  263. self::$version = 3.5;
  264. self::$browser = 'fx';
  265. self::$engine = 'gecko';
  266. } else if(preg_match('/firefox\/(\d+)/i', self::$ua, $array)) {
  267. self::$version = $array[1];
  268. self::$browser = 'fx';
  269. self::$engine = 'gecko';
  270. } else if(preg_match('/opera(\s|\/)(\d+)/', self::$ua, $array)) {
  271. self::$engine = 'presto';
  272. self::$browser = 'opera';
  273. self::$version = $array[2];
  274. } else if(strstr(self::$ua, 'konqueror')) {
  275. self::$browser = 'konqueror';
  276. self::$engine = 'webkit';
  277. } else if(strstr(self::$ua, 'iron')) {
  278. self::$browser = 'iron';
  279. self::$engine = 'webkit';
  280. } else if(strstr(self::$ua, 'chrome')) {
  281. self::$browser = 'chrome';
  282. self::$engine = 'webkit';
  283. if(preg_match('/chrome\/(\d+)/i', self::$ua, $array)) { self::$version = $array[1]; }
  284. } else if(strstr(self::$ua, 'applewebkit/')) {
  285. self::$browser = 'safari';
  286. self::$engine = 'webkit';
  287. if(preg_match('/version\/(\d+)/i', self::$ua, $array)) { self::$version = $array[1]; }
  288. } else if(strstr(self::$ua, 'mozilla/')) {
  289. self::$engine = 'gecko';
  290. self::$browser = 'mozilla';
  291. }
  292. // platform
  293. if(strstr(self::$ua, 'j2me')) {
  294. self::$platform = 'mobile';
  295. } else if(strstr(self::$ua, 'iphone')) {
  296. self::$platform = 'iphone';
  297. } else if(strstr(self::$ua, 'ipod')) {
  298. self::$platform = 'ipod';
  299. } else if(strstr(self::$ua, 'ipad')) {
  300. self::$platform = 'ipad';
  301. } else if(strstr(self::$ua, 'mac')) {
  302. self::$platform = 'mac';
  303. } else if(strstr(self::$ua, 'darwin')) {
  304. self::$platform = 'mac';
  305. } else if(strstr(self::$ua, 'webtv')) {
  306. self::$platform = 'webtv';
  307. } else if(strstr(self::$ua, 'win')) {
  308. self::$platform = 'win';
  309. } else if(strstr(self::$ua, 'freebsd')) {
  310. self::$platform = 'freebsd';
  311. } else if(strstr(self::$ua, 'x11') || strstr(self::$ua, 'linux')) {
  312. self::$platform = 'linux';
  313. }
  314. return array(
  315. 'browser' => self::$browser,
  316. 'engine' => self::$engine,
  317. 'version' => self::$version,
  318. 'platform' => self::$platform
  319. );
  320. }
  321. }
  322. /*
  323. ############### CONFIG ###############
  324. */
  325. class c {
  326. private static $config = array();
  327. function get($key=null, $default=null) {
  328. if(empty($key)) return self::$config;
  329. return a::get(self::$config, $key, $default);
  330. }
  331. function set($key, $value=null) {
  332. if(is_array($key)) {
  333. // set all new values
  334. self::$config = array_merge(self::$config, $key);
  335. } else {
  336. self::$config[$key] = $value;
  337. }
  338. }
  339. function load($file) {
  340. if(file_exists($file)) require_once($file);
  341. return c::get();
  342. }
  343. function get_array($key, $default=null) {
  344. $keys = array_keys(self::$config);
  345. $n = array();
  346. foreach($keys AS $k) {
  347. $pos = strpos($key.'.', $k);
  348. if ($pos === 0) {
  349. $n[substr($k,strlen($key.'.'))] = self::$config[$k];
  350. }
  351. }
  352. return ($n) ? $n : $default;
  353. }
  354. function set_array($key, $value=null) {
  355. if (!is_array($value)) {
  356. $m = self::get_sub($key);
  357. foreach($m AS $k => $v) {
  358. self::set($k, $value);
  359. }
  360. } else {
  361. foreach($value AS $k => $v) {
  362. self::set($key.'.'.$k, $v);
  363. }
  364. }
  365. }
  366. }
  367. /*
  368. ############### CONTENT ###############
  369. */
  370. class content {
  371. function start() {
  372. ob_start();
  373. }
  374. function end($return=false) {
  375. if($return) {
  376. $content = ob_get_contents();
  377. ob_end_clean();
  378. return $content;
  379. }
  380. ob_end_flush();
  381. }
  382. function type() {
  383. $args = func_get_args();
  384. // shortcuts for content types
  385. $ctypes = array(
  386. 'html' => 'text/html',
  387. 'css' => 'text/css',
  388. 'js' => 'text/javascript',
  389. 'jpg' => 'image/jpeg',
  390. 'png' => 'image/png',
  391. 'gif' => 'image/gif'
  392. );
  393. $ctype = a::get($args, 0, c::get('content_type', 'text/html'));
  394. $ctype = a::get($ctypes, $ctype, $ctype);
  395. $charset = a::get($args, 1, c::get('charset', 'utf-8'));
  396. header('Content-type: ' . $ctype . '; ' . $charset);
  397. }
  398. }
  399. /*
  400. ############### COOKIE ###############
  401. */
  402. class cookie {
  403. function set($key, $value, $expires=3600, $domain='/') {
  404. if(is_array($value)) $value = a::json($value);
  405. $_COOKIE[$key] = $value;
  406. return @setcookie($key, $value, time()+$expires, $domain);
  407. }
  408. function get($key, $default=null) {
  409. return a::get($_COOKIE, $key, $default);
  410. }
  411. function remove($key, $domain='/') {
  412. $_COOKIE[$key] = false;
  413. return @setcookie($key, false, time()-3600, $domain);
  414. }
  415. }
  416. /*
  417. ############### DATABASE ###############
  418. */
  419. class db {
  420. public static $trace = array();
  421. private static $connection = false;
  422. private static $database = false;
  423. private static $charset = false;
  424. private static $last_query = false;
  425. private static $affected = 0;
  426. function connect() {
  427. $connection = self::connection();
  428. $args = func_get_args();
  429. $host = a::get($args, 0, c::get('db.host', 'localhost'));
  430. $user = a::get($args, 1, c::get('db.user', 'root'));
  431. $password = a::get($args, 2, c::get('db.password'));
  432. $database = a::get($args, 3, c::get('db.name'));
  433. $charset = a::get($args, 4, c::get('db.charset', 'utf8'));
  434. // don't connect again if it's already done
  435. $connection = (!$connection) ? @mysql_connect($host, $user, $password) : $connection;
  436. // react on connection failures
  437. if(!$connection) return self::error(l::get('db.errors.connect', 'Database connection failed'), true);
  438. self::$connection = $connection;
  439. // select the database
  440. $database = self::database($database);
  441. if(core::error($database)) return $database;
  442. // set the right charset
  443. $charset = self::charset($charset);
  444. if(core::error($charset)) return $charset;
  445. return $connection;
  446. }
  447. function connection() {
  448. return (is_resource(self::$connection)) ? self::$connection : false;
  449. }
  450. function disconnect() {
  451. if(!c::get('db.disconnect')) return false;
  452. $connection = self::connection();
  453. if(!$connection) return false;
  454. // kill the connection
  455. $disconnect = @mysql_close($connection);
  456. self::$connection = false;
  457. if(!$disconnect) return self::error(l::get('db.errors.disconnect', 'Disconnecting database failed'));
  458. return true;
  459. }
  460. function database($database) {
  461. if(!$database) return self::error(l::get('db.errors.missing_db_name', 'Please provide a database name'), true);
  462. // check if there is a selected database
  463. if(self::$database == $database) return true;
  464. // select a new database
  465. $select = @mysql_select_db($database, self::connection());
  466. if(!$select) return self::error(l::get('db.errors.missing_db', 'Selecting database failed'), true);
  467. self::$database = $database;
  468. return $database;
  469. }
  470. function charset($charset='utf8') {
  471. // check if there is a assigned charset and compare it
  472. if(self::$charset == $charset) return true;
  473. // set the new charset
  474. $set = @mysql_query('SET NAMES ' . $charset);
  475. if(!$set) return self::error(l::get('db.errors.setting_charset_failed', 'Setting database charset failed'));
  476. // save the new charset to the globals
  477. self::$charset = $charset;
  478. return $charset;
  479. }
  480. function query($sql, $fetch=true) {
  481. $connection = self::connect();
  482. if(core::error($connection)) return $connection;
  483. // save the query
  484. self::$last_query = $sql;
  485. // execute the query
  486. $result = @mysql_query($sql, $connection);
  487. self::$affected = @mysql_affected_rows();
  488. self::$trace[] = $sql;
  489. if(!$result) return self::error(l::get('db.errors.query_failed', 'The database query failed'));
  490. if(!$fetch) return $result;
  491. $array = array();
  492. while($r = self::fetch($result)) array_push($array, $r);
  493. return $array;
  494. }
  495. function execute($sql) {
  496. $connection = self::connect();
  497. if(core::error($connection)) return $connection;
  498. // save the query
  499. self::$last_query = $sql;
  500. // execute the query
  501. $execute = @mysql_query($sql, $connection);
  502. self::$affected = @mysql_affected_rows();
  503. self::$trace[] = $sql;
  504. if(!$execute) return self::error(l::get('db.errors.query_failed', 'The database query failed'));
  505. $last_id = self::last_id();
  506. return ($last_id === false) ? self::$affected : self::last_id();
  507. }
  508. function affected() {
  509. return self::$affected;
  510. }
  511. function last_id() {
  512. $connection = self::connection();
  513. return @mysql_insert_id($connection);
  514. }
  515. function fetch($result, $type=MYSQL_ASSOC) {
  516. if(!$result) return array();
  517. return @mysql_fetch_array($result, $type);
  518. }
  519. function fields($table) {
  520. $connection = self::connect();
  521. if(core::error($connection)) return $connection;
  522. $fields = @mysql_list_fields(self::$database, self::prefix($table), $connection);
  523. if(!$fields) return self::error(l::get('db.errors.listing_fields_failed', 'Listing fields failed'));
  524. $output = array();
  525. $count = @mysql_num_fields($fields);
  526. for($x=0; $x<$count; $x++) {
  527. $output[] = @mysql_field_name($fields, $x);
  528. }
  529. return $output;
  530. }
  531. function insert($table, $input, $ignore=false) {
  532. $ignore = ($ignore) ? ' IGNORE' : '';
  533. return self::execute('INSERT' . ($ignore) . ' INTO ' . self::prefix($table) . ' SET ' . self::values($input));
  534. }
  535. function insert_all($table, $fields, $values) {
  536. $query = 'INSERT INTO ' . self::prefix($table) . ' (' . implode(',', $fields) . ') VALUES ';
  537. $rows = array();
  538. foreach($values AS $v) {
  539. $str = '(\'';
  540. $sep = '';
  541. foreach($v AS $input) {
  542. $str .= $sep . db::escape($input);
  543. $sep = "','";
  544. }
  545. $str .= '\')';
  546. $rows[] = $str;
  547. }
  548. $query .= implode(',', $rows);
  549. return db::execute($query);
  550. }
  551. function replace($table, $input) {
  552. return self::execute('REPLACE INTO ' . self::prefix($table) . ' SET ' . self::values($input));
  553. }
  554. function update($table, $input, $where) {
  555. return self::execute('UPDATE ' . self::prefix($table) . ' SET ' . self::values($input) . ' WHERE ' . self::where($where));
  556. }
  557. function delete($table, $where='') {
  558. $sql = 'DELETE FROM ' . self::prefix($table);
  559. if(!empty($where)) $sql .= ' WHERE ' . self::where($where);
  560. return self::execute($sql);
  561. }
  562. function select($table, $select='*', $where=null, $order=null, $page=null, $limit=null, $fetch=true) {
  563. $sql = 'SELECT ' . $select . ' FROM ' . self::prefix($table);
  564. if(!empty($where)) $sql .= ' WHERE ' . self::where($where);
  565. if(!empty($order)) $sql .= ' ORDER BY ' . $order;
  566. if($page !== null && $limit !== null) $sql .= ' LIMIT ' . $page . ',' . $limit;
  567. return self::query($sql, $fetch);
  568. }
  569. function row($table, $select='*', $where=null, $order=null) {
  570. $result = self::select($table, $select, $where, $order, 0,1, false);
  571. return self::fetch($result);
  572. }
  573. function column($table, $column, $where=null, $order=null, $page=null, $limit=null) {
  574. $result = self::select($table, $column, $where, $order, $page, $limit, false);
  575. $array = array();
  576. while($r = self::fetch($result)) array_push($array, a::get($r, $column));
  577. return $array;
  578. }
  579. function field($table, $field, $where=null, $order=null) {
  580. $result = self::row($table, $field, $where, $order);
  581. return a::get($result, $field);
  582. }
  583. function join($table_1, $table_2, $on, $select, $where=null, $order=null, $page=null, $limit=null, $type="JOIN") {
  584. return self::select(
  585. self::prefix($table_1) . ' ' . $type . ' ' .
  586. self::prefix($table_2) . ' ON ' .
  587. self::where($on),
  588. $select,
  589. self::where($where),
  590. $order,
  591. $page,
  592. $limit
  593. );
  594. }
  595. function left_join($table_1, $table_2, $on, $select, $where=null, $order=null, $page=null, $limit=null) {
  596. return self::join($table_1, $table_2, $on, $select, $where, $order, $page, $limit, 'LEFT JOIN');
  597. }
  598. function count($table, $where='') {
  599. $result = self::row($table, 'count(*)', $where);
  600. return ($result) ? a::get($result, 'count(*)') : 0;
  601. }
  602. function min($table, $column, $where=null) {
  603. $sql = 'SELECT MIN(' . $column . ') AS min FROM ' . self::prefix($table);
  604. if(!empty($where)) $sql .= ' WHERE ' . self::where($where);
  605. $result = self::query($sql, false);
  606. $result = self::fetch($result);
  607. return a::get($result, 'min', 1);
  608. }
  609. function max($table, $column, $where=null) {
  610. $sql = 'SELECT MAX(' . $column . ') AS max FROM ' . self::prefix($table);
  611. if(!empty($where)) $sql .= ' WHERE ' . self::where($where);
  612. $result = self::query($sql, false);
  613. $result = self::fetch($result);
  614. return a::get($result, 'max', 1);
  615. }
  616. function sum($table, $column, $where=null) {
  617. $sql = 'SELECT SUM(' . $column . ') AS sum FROM ' . self::prefix($table);
  618. if(!empty($where)) $sql .= ' WHERE ' . self::where($where);
  619. $result = self::query($sql, false);
  620. $result = self::fetch($result);
  621. return a::get($result, 'sum', 0);
  622. }
  623. function prefix($table) {
  624. $prefix = c::get('db.prefix');
  625. if(!$prefix) return $table;
  626. return (!str::contains($table,$prefix)) ? $prefix . $table : $table;
  627. }
  628. function simple_fields($array) {
  629. if(empty($array)) return false;
  630. $output = array();
  631. foreach($array AS $key => $value) {
  632. $key = substr($key, strpos($key, '_')+1);
  633. $output[$key] = $value;
  634. }
  635. return $output;
  636. }
  637. function values($input) {
  638. if(!is_array($input)) return $input;
  639. $output = array();
  640. foreach($input AS $key => $value) {
  641. if($value === 'NOW()')
  642. $output[] = $key . ' = NOW()';
  643. elseif(is_array($value))
  644. $output[] = $key . ' = \'' . a::json($value) . '\'';
  645. else
  646. $output[] = $key . ' = \'' . self::escape($value) . '\'';
  647. }
  648. return implode(', ', $output);
  649. }
  650. function escape($value) {
  651. $value = str::stripslashes($value);
  652. return mysql_real_escape_string((string)$value, self::connect());
  653. }
  654. function search_clause($search, $fields, $mode='OR') {
  655. if(empty($search)) return false;
  656. $arr = array();
  657. foreach($fields AS $f) array_push($arr, $f . ' LIKE \'%' . $search . '%\'');
  658. return '(' . implode(' ' . trim($mode) . ' ', $arr) . ')';
  659. }
  660. function select_clause($fields) {
  661. return implode(', ', $fields);
  662. }
  663. function in($array) {
  664. return '\'' . implode('\',\'', $array) . '\'';
  665. }
  666. function where($array, $method='AND') {
  667. if(!is_array($array)) return $array;
  668. $output = array();
  669. foreach($array AS $field => $value) {
  670. $output[] = $field . ' = \'' . self::escape($value) . '\'';
  671. $separator = ' ' . $method . ' ';
  672. }
  673. return implode(' ' . $method . ' ', $output);
  674. }
  675. function error($msg=null, $exit=false) {
  676. $connection = self::connection();
  677. $error = (mysql_error()) ? @mysql_error($connection) : false;
  678. $number = (mysql_errno()) ? @mysql_errno($connection) : 0;
  679. if(c::get('db.debugging')) {
  680. if($error) $msg .= ' -> ' . $error . ' (' . $number . ')';
  681. if(self::$last_query) $msg .= ' Query: ' . self::$last_query;
  682. } else $msg .= ' - ' . l::get('db.errors.msg', 'This will be fixed soon!');
  683. if($exit || c::get('db.debugging')) die($msg);
  684. return array(
  685. 'status' => 'error',
  686. 'msg' => $msg
  687. );
  688. }
  689. }
  690. /*
  691. ############### DIR ###############
  692. */
  693. class dir {
  694. function make($dir) {
  695. if(is_dir($dir)) return true;
  696. if(!@mkdir($dir, 0777)) return false;
  697. @chmod($dir, 0777);
  698. return true;
  699. }
  700. function read($dir) {
  701. if(!is_dir($dir)) return false;
  702. $handle = @opendir($dir);
  703. $files = array();
  704. $skip = array('.', '..', '.DS_Store');
  705. if(!$handle) return false;
  706. while(false !== ($file = @readdir($handle))) {
  707. if(!in_array($file, $skip)) $files[] = $file;
  708. }
  709. @closedir($handle);
  710. asort($files);
  711. return($files);
  712. }
  713. function move($old, $new) {
  714. if(!is_dir($old)) return false;
  715. return (@rename($old, $new) && is_dir($new)) ? true : false;
  716. }
  717. function remove($dir, $keep=false) {
  718. if(!is_dir($dir)) return false;
  719. $handle = @opendir($dir);
  720. $skip = array('.', '..');
  721. if(!$handle) return false;
  722. while($item = @readdir($handle)) {
  723. if(is_dir($dir . '/' . $item) && !in_array($item, $skip)) {
  724. self::remove($dir . '/' . $item);
  725. } else if(!in_array($item, $skip)) {
  726. @unlink($dir . '/' . $item);
  727. }
  728. }
  729. @closedir($handle);
  730. if(!$keep) return @rmdir($dir);
  731. return true;
  732. }
  733. function clean($dir) {
  734. return self::remove($dir, true);
  735. }
  736. function size($path, $recusive=true, $nice=false) {
  737. if(!file_exists($path)) return false;
  738. if(is_file($path)) return self::size($path, $nice);
  739. $size = 0;
  740. foreach(glob($path."/*") AS $file) {
  741. if($file != "." && $file != "..") {
  742. if($recusive) {
  743. $size += self::folder_size($file, true);
  744. } else {
  745. $size += self::size($path);
  746. }
  747. }
  748. }
  749. return ($nice) ? self::nice_size($size) : $size;
  750. }
  751. function modified($dir, $modified=0) {
  752. $files = self::read($dir);
  753. foreach($files AS $file) {
  754. if(!is_dir($dir . '/' . $file)) continue;
  755. $filectime = filectime($dir . '/' . $file);
  756. $modified = ($filectime > $modified) ? $filectime : $modified;
  757. $modified = self::modified($dir . '/' . $file, $modified);
  758. }
  759. return $modified;
  760. }
  761. }
  762. /*
  763. ############### FILE ###############
  764. */
  765. class f {
  766. function write($file,$content,$append=false){
  767. if(is_array($content)) $content = a::json($content);
  768. $mode = ($append) ? FILE_APPEND : false;
  769. $write = @file_put_contents($file, $content, $mode);
  770. @chmod($file, 0777);
  771. return $write;
  772. }
  773. function append($file,$content){
  774. return self::write($file,$content,true);
  775. }
  776. function read($file, $parse=false) {
  777. $content = @file_get_contents($file);
  778. return ($parse) ? str::parse($content, $parse) : $content;
  779. }
  780. function move($old, $new) {
  781. if(!file_exists($old)) return false;
  782. return (@rename($old, $new) && file_exists($new)) ? true : false;
  783. }
  784. function remove($file) {
  785. return (file_exists($file) && is_file($file) && !empty($file)) ? @unlink($file) : false;
  786. }
  787. function extension($filename) {
  788. $ext = str_replace('.', '', strtolower(strrchr(trim($filename), '.')));
  789. return url::strip_query($ext);
  790. }
  791. function filename($name) {
  792. return basename($name);
  793. }
  794. function name($name, $remove_path = false) {
  795. if($remove_path == true) $name = self::filename($name);
  796. $dot=strrpos($name,'.');
  797. if($dot) $name=substr($name,0,$dot);
  798. return $name;
  799. }
  800. function dirname($file=__FILE__) {
  801. return dirname($file);
  802. }
  803. function size($file, $nice=false) {
  804. @clearstatcache();
  805. $size = @filesize($file);
  806. if(!$size) return false;
  807. return ($nice) ? self::nice_size($size) : $size;
  808. }
  809. function nice_size($size) {
  810. $size = str::sanitize($size, 'int');
  811. if($size < 1) return '0 kb';
  812. $unit=array('b','kb','mb','gb','tb','pb');
  813. return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
  814. }
  815. function convert($name, $type='jpg') {
  816. return self::name($name) . $type;
  817. }
  818. function safe_name($string) {
  819. return str::urlify($string);
  820. }
  821. }
  822. /*
  823. ############### GLOBALS ###############
  824. */
  825. class g {
  826. function get($key=null, $default=null) {
  827. if(empty($key)) return $GLOBALS;
  828. return a::get($GLOBALS, $key, $default);
  829. }
  830. function set($key, $value=null) {
  831. if(is_array($key)) {
  832. // set all new values
  833. $GLOBALS = array_merge($GLOBALS, $key);
  834. } else {
  835. $GLOBALS[$key] = $value;
  836. }
  837. }
  838. }
  839. /*
  840. ############### LANGUAGE ###############
  841. */
  842. class l {
  843. public static $lang = array();
  844. function set($key, $value=null) {
  845. if(is_array($key)) {
  846. self::$lang = array_merge(self::$lang, $key);
  847. } else {
  848. self::$lang[$key] = $value;
  849. }
  850. }
  851. function get($key=null, $default=null) {
  852. if(empty($key)) return self::$lang;
  853. return a::get(self::$lang, $key, $default);
  854. }
  855. function change($language='en') {
  856. s::set('language', l::sanitize($language));
  857. return s::get('language');
  858. }
  859. function current() {
  860. if(s::get('language')) return s::get('language');
  861. $lang = str::split(server::get('http_accept_language'), '-');
  862. $lang = str::trim(a::get($lang, 0));
  863. $lang = l::sanitize($lang);
  864. s::set('language', $lang);
  865. return $lang;
  866. }
  867. function locale($language=false) {
  868. if(!$language) $language = l::current();
  869. $default_locales = array(
  870. 'de' => array('de_DE.UTF8','de_DE@euro','de_DE','de','ge'),
  871. 'fr' => array('fr_FR.UTF8','fr_FR','fr'),
  872. 'es' => array('es_ES.UTF8','es_ES','es'),
  873. 'it' => array('it_IT.UTF8','it_IT','it'),
  874. 'pt' => array('pt_PT.UTF8','pt_PT','pt'),
  875. 'zh' => array('zh_CN.UTF8','zh_CN','zh'),
  876. 'en' => array('en_US.UTF8','en_US','en'),
  877. );
  878. $locales = c::get('locales', array());
  879. $locales = array_merge($default_locales, $locales);
  880. setlocale(LC_ALL, a::get($locales, $language, array('en_US.UTF8','en_US','en')));
  881. return setlocale(LC_ALL, 0);
  882. }
  883. function load($file) {
  884. // replace the language variable
  885. $file = str_replace('{language}', l::current(), $file);
  886. // check if it exists
  887. if(file_exists($file)) {
  888. require($file);
  889. return l::get();
  890. }
  891. // try to find the default language file
  892. $file = str_replace('{language}', c::get('language', 'en'), $file);
  893. // check again if it exists
  894. if(file_exists($file)) require($file);
  895. return l::get();
  896. }
  897. function sanitize($language) {
  898. if(!in_array($language, c::get('languages', array('en')) )) $language = c::get('language', 'en');
  899. return $language;
  900. }
  901. }
  902. /*
  903. ############### REQUEST ###############
  904. */
  905. class r {
  906. function set($key, $value=null) {
  907. if(is_array($key)) {
  908. $_REQUEST = array_merge($_REQUEST, $key);
  909. } else {
  910. $_REQUEST[$key] = $value;
  911. }
  912. }
  913. function method() {
  914. return strtoupper(server::get('request_method'));
  915. }
  916. function get($key=false, $default=null) {
  917. $request = (self::method() == 'GET') ? $_REQUEST : array_merge($_REQUEST, self::body());
  918. if(empty($key)) return $request;
  919. $value = a::get($request, $key, $default);
  920. return (!is_array($value)) ? trim(str::stripslashes($value)) : $value;
  921. }
  922. function body() {
  923. @parse_str(@file_get_contents('php://input'), $body);
  924. return (array)$body;
  925. }
  926. function parse() {
  927. $keep = func_get_args();
  928. $result = array();
  929. foreach($keep AS $k) {
  930. $params = explode(':', $k);
  931. $key = a::get($params, 0);
  932. $type = a::get($params, 1, 'str');
  933. $default = a::get($params, 2, '');
  934. $result[$key] = str::sanitize( get($key, $default), $type );
  935. }
  936. return $result;
  937. }
  938. function is_ajax() {
  939. return (strtolower(server::get('http_x_requested_with')) == 'xmlhttprequest') ? true : false;
  940. }
  941. function is_get() {
  942. return (self::method() == 'GET') ? true : false;
  943. }
  944. function is_post() {
  945. return (self::method() == 'POST') ? true : false;
  946. }
  947. function is_delete() {
  948. return (self::method() == 'DELETE') ? true : false;
  949. }
  950. function is_put() {
  951. return (self::method() == 'PUT') ? true : false;
  952. }
  953. function referer($default=null) {
  954. if(empty($default)) $default = '/';
  955. return server::get('http_referer', $default);
  956. }
  957. }
  958. function get($key=false, $default=null) {
  959. return r::get($key, $default);
  960. }
  961. /*
  962. ############### SESSION ###############
  963. */
  964. class s {
  965. function set($key, $value=false) {
  966. if(is_array($key)) {
  967. $_SESSION = array_merge($_SESSION, $key);
  968. } else {
  969. $_SESSION[$key] = $value;
  970. }
  971. }
  972. function get($key=false, $default=null) {
  973. if(empty($key)) return $_SESSION;
  974. return a::get($_SESSION, $key, $default);
  975. }
  976. function remove($key) {
  977. return a::remove(&$_SESSION, $key, true);
  978. }
  979. function start() {
  980. @session_start();
  981. }
  982. function destroy() {
  983. @session_destroy();
  984. }
  985. function expired($time) {
  986. // get the logged in seconds
  987. $elapsed_time = (time() - $time);
  988. // if the session has not expired yet
  989. return ($elapsed_time >= 0 && $elapsed_time <= c::get('session.expires')) ? false : true;
  990. }
  991. }
  992. /*
  993. ############### SERVER ###############
  994. */
  995. class server {
  996. function get($key, $default=null) {
  997. if(empty($key)) return $_SERVER;
  998. return a::get($_SERVER, str::upper($key), $default);
  999. }
  1000. }
  1001. /*
  1002. ############### SIZE ###############
  1003. */
  1004. class size {
  1005. function ratio($width, $height) {
  1006. return ($width / $height);
  1007. }
  1008. function fit($width, $height, $box, $force=false) {
  1009. if($width == 0 || $height == 0) return array('width' => $box, 'height' => $box);
  1010. $ratio = self::ratio($width, $height);
  1011. if($width > $height) {
  1012. if($width > $box || $force == true) $width = $box;
  1013. $height = floor($width / $ratio);
  1014. } elseif($height > $width) {
  1015. if($height > $box || $force == true) $height = $box;
  1016. $width = floor($height * $ratio);
  1017. } elseif($width > $box) {
  1018. $width = $box;
  1019. $height = $box;
  1020. }
  1021. $output = array();
  1022. $output['width'] = $width;
  1023. $output['height'] = $height;
  1024. return $output;
  1025. }
  1026. function fit_width($width, $height, $fit, $force=false) {
  1027. if($width <= $fit && !$force) return array(
  1028. 'width' => $width,
  1029. 'height' => $height
  1030. );
  1031. $ratio = self::ratio($width, $height);
  1032. return array(
  1033. 'width' => $fit,
  1034. 'height' => floor($fit / $ratio)
  1035. );
  1036. }
  1037. function fit_height($width, $height, $fit, $force=false) {
  1038. if($height <= $fit && !$force) return array(
  1039. 'width' => $width,
  1040. 'height' => $height
  1041. );
  1042. $ratio = self::ratio($width, $height);
  1043. return array(
  1044. 'width' => floor($fit * $ratio),
  1045. 'height' => $fit
  1046. );
  1047. }
  1048. }
  1049. /*
  1050. ############### STRING ###############
  1051. */
  1052. class str {
  1053. function html($string, $keep_html=true) {
  1054. if($keep_html) {
  1055. return stripslashes(implode('', preg_replace('/^([^<].+[^>])$/e', "htmlentities('\\1', ENT_COMPAT, 'utf-8')", preg_split('/(<.+?>)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE))));
  1056. } else {
  1057. return htmlentities($string, ENT_COMPAT, 'utf-8');
  1058. }
  1059. }
  1060. function unhtml($string) {
  1061. $string = strip_tags($string);
  1062. return html_entity_decode($string, ENT_COMPAT, 'utf-8');
  1063. }
  1064. function entities() {
  1065. return array(
  1066. '&nbsp;' => '&#160;', '&iexcl;' => '&#161;', '&cent;' => '&#162;', '&pound;' => '&#163;', '&curren;' => '&#164;', '&yen;' => '&#165;', '&brvbar;' => '&#166;', '&sect;' => '&#167;',
  1067. '&uml;' => '&#168;', '&copy;' => '&#169;', '&ordf;' => '&#170;', '&laquo;' => '&#171;', '&not;' => '&#172;', '&shy;' => '&#173;', '&reg;' => '&#174;', '&macr;' => '&#175;',
  1068. '&deg;' => '&#176;', '&plusmn;' => '&#177;', '&sup2;' => '&#178;', '&sup3;' => '&#179;', '&acute;' => '&#180;', '&micro;' => '&#181;', '&para;' => '&#182;', '&middot;' => '&#183;',
  1069. '&cedil;' => '&#184;', '&sup1;' => '&#185;', '&ordm;' => '&#186;', '&raquo;' => '&#187;', '&frac14;' => '&#188;', '&frac12;' => '&#189;', '&frac34;' => '&#190;', '&iquest;' => '&#191;',
  1070. '&Agrave;' => '&#192;', '&Aacute;' => '&#193;', '&Acirc;' => '&#194;', '&Atilde;' => '&#195;', '&Auml;' => '&#196;', '&Aring;' => '&#197;', '&AElig;' => '&#198;', '&Ccedil;' => '&#199;',
  1071. '&Egrave;' => '&#200;', '&Eacute;' => '&#201;', '&Ecirc;' => '&#202;', '&Euml;' => '&#203;', '&Igrave;' => '&#204;', '&Iacute;' => '&#205;', '&Icirc;' => '&#206;', '&Iuml;' => '&#207;',
  1072. '&ETH;' => '&#208;', '&Ntilde;' => '&#209;', '&Ograve;' => '&#210;', '&Oacute;' => '&#211;', '&Ocirc;' => '&#212;', '&Otilde;' => '&#213;', '&Ouml;' => '&#214;', '&times;' => '&#215;',
  1073. '&Oslash;' => '&#216;', '&Ugrave;' => '&#217;', '&Uacute;' => '&#218;', '&Ucirc;' => '&#219;', '&Uuml;' => '&#220;', '&Yacute;' => '&#221;', '&THORN;' => '&#222;', '&szlig;' => '&#223;',
  1074. '&agrave;' => '&#224;', '&aacute;' => '&#225;', '&acirc;' => '&#226;', '&atilde;' => '&#227;', '&auml;' => '&#228;', '&aring;' => '&#229;', '&aelig;' => '&#230;', '&ccedil;' => '&#231;',
  1075. '&egrave;' => '&#232;', '&eacute;' => '&#233;', '&ecirc;' => '&#234;', '&euml;' => '&#235;', '&igrave;' => '&#236;', '&iacute;' => '&#237;', '&icirc;' => '&#238;', '&iuml;' => '&#239;',
  1076. '&eth;' => '&#240;', '&ntilde;' => '&#241;', '&ograve;' => '&#242;', '&oacute;' => '&#243;', '&ocirc;' => '&#244;', '&otilde;' => '&#245;', '&ouml;' => '&#246;', '&divide;' => '&#247;',
  1077. '&oslash;' => '&#248;', '&ugrave;' => '&#249;', '&uacute;' => '&#250;', '&ucirc;' => '&#251;', '&uuml;' => '&#252;', '&yacute;' => '&#253;', '&thorn;' => '&#254;', '&yuml;' => '&#255;',
  1078. '&fnof;' => '&#402;', '&Alpha;' => '&#913;', '&Beta;' => '&#914;', '&Gamma;' => '&#915;', '&Delta;' => '&#916;', '&Epsilon;' => '&#917;', '&Zeta;' => '&#918;', '&Eta;' => '&#919;',
  1079. '&Theta;' => '&#920;', '&Iota;' => '&#921;', '&Kappa;' => '&#922;', '&Lambda;' => '&#923;', '&Mu;' => '&#924;', '&Nu;' => '&#925;', '&Xi;' => '&#926;', '&Omicron;' => '&#927;',
  1080. '&Pi;' => '&#928;', '&Rho;' => '&#929;', '&Sigma;' => '&#931;', '&Tau;' => '&#932;', '&Upsilon;' => '&#933;', '&Phi;' => '&#934;', '&Chi;' => '&#935;', '&Psi;' => '&#936;',
  1081. '&Omega;' => '&#937;', '&alpha;' => '&#945;', '&beta;' => '&#946;', '&gamma;' => '&#947;', '&delta;' => '&#948;', '&epsilon;' => '&#949;', '&zeta;' => '&#950;', '&eta;' => '&#951;',
  1082. '&theta;' => '&#952;', '&iota;' => '&#953;', '&kappa;' => '&#954;', '&lambda;' => '&#955;', '&mu;' => '&#956;', '&nu;' => '&#957;', '&xi;' => '&#958;', '&omicron;' => '&#959;',
  1083. '&pi;' => '&#960;', '&rho;' => '&#961;', '&sigmaf;' => '&#962;', '&sigma;' => '&#963;', '&tau;' => '&#964;', '&upsilon;' => '&#965;', '&phi;' => '&#966;', '&chi;' => '&#967;',
  1084. '&psi;' => '&#968;', '&omega;' => '&#969;', '&thetasym;' => '&#977;', '&upsih;' => '&#978;', '&piv;' => '&#982;', '&bull;' => '&#8226;', '&hellip;' => '&#8230;', '&prime;' => '&#8242;',
  1085. '&Prime;' => '&#8243;', '&oline;' => '&#8254;', '&frasl;' => '&#8260;', '&weierp;' => '&#8472;', '&image;' => '&#8465;', '&real;' => '&#8476;', '&trade;' => '&#8482;', '&alefsym;' => '&#8501;',
  1086. '&larr;' => '&#8592;', '&uarr;' => '&#8593;', '&rarr;' => '&#8594;', '&darr;' => '&#8595;', '&harr;' => '&#8596;', '&crarr;' => '&#8629;', '&lArr;' => '&#8656;', '&uArr;' => '&#8657;',
  1087. '&rArr;' => '&#8658;', '&dArr;' => '&#8659;', '&hArr;' => '&#8660;', '&forall;' => '&#8704;', '&part;' => '&#8706;', '&exist;' => '&#8707;', '&empty;' => '&#8709;', '&nabla;' => '&#8711;',
  1088. '&isin;' => '&#8712;', '&notin;' => '&#8713;', '&ni;' => '&#8715;', '&prod;' => '&#8719;', '&sum;' => '&#8721;', '&minus;' => '&#8722;', '&lowast;' => '&#8727;', '&radic;' => '&#8730;',
  1089. '&prop;' => '&#8733;', '&infin;' => '&#8734;', '&ang;' => '&#8736;', '&and;' => '&#8743;', '&or;' => '&#8744;', '&cap;' => '&#8745;', '&cup;' => '&#8746;', '&int;' => '&#8747;',
  1090. '&there4;' => '&#8756;', '&sim;' => '&#8764;', '&cong;' => '&#8773;', '&asymp;' => '&#8776;', '&ne;' => '&#8800;', '&equiv;' => '&#8801;', '&le;' => '&#8804;', '&ge;' => '&#8805;',
  1091. '&sub;' => '&#8834;', '&sup;' => '&#8835;', '&nsub;' => '&#8836;', '&sube;' => '&#8838;', '&supe;' => '&#8839;', '&oplus;' => '&#8853;', '&otimes;' => '&#8855;', '&perp;' => '&#8869;',
  1092. '&sdot;' => '&#8901;', '&lceil;' => '&#8968;', '&rceil;' => '&#8969;', '&lfloor;' => '&#8970;', '&rfloor;' => '&#8971;', '&lang;' => '&#9001;', '&rang;' => '&#9002;', '&loz;' => '&#9674;',
  1093. '&spades;' => '&#9824;', '&clubs;' => '&#9827;', '&hearts;' => '&#9829;', '&diams;' => '&#9830;', '&quot;' => '&#34;', '&amp;' => '&#38;', '&lt;' => '&#60;', '&gt;' => '&#62;', '&OElig;' => '&#338;',
  1094. '&oelig;' => '&#339;', '&Scaron;' => '&#352;', '&scaron;' => '&#353;', '&Yuml;' => '&#376;', '&circ;' => '&#710;', '&tilde;' => '&#732;', '&ensp;' => '&#8194;', '&emsp;' => '&#8195;',
  1095. '&thinsp;' => '&#8201;', '&zwnj;' => '&#8204;', '&zwj;' => '&#8205;', '&lrm;' => '&#8206;', '&rlm;' => '&#8207;', '&ndash;' => '&#8211;', '&mdash;' => '&#8212;', '&lsquo;' => '&#8216;',
  1096. '&rsquo;' => '&#8217;', '&sbquo;' => '&#8218;', '&ldquo;' => '&#8220;', '&rdquo;' => '&#8221;', '&bdquo;' => '&#8222;', '&dagger;' => '&#8224;', '&Dagger;' => '&#8225;', '&permil;' => '&#8240;',
  1097. '&lsaquo;' => '&#8249;', '&rsaquo;' => '&#8250;', '&euro;' => '&#8364;'
  1098. );
  1099. }
  1100. function xml($text, $html=true) {
  1101. // convert raw text to html safe text
  1102. if($html) $text = self::html($text);
  1103. // convert html entities to xml entities
  1104. return strtr($text, self::entities());
  1105. }
  1106. function unxml($string) {
  1107. // flip the conversion table
  1108. $table = array_flip(self::entities());
  1109. // convert html entities to xml entities
  1110. return strtr($string, $table);
  1111. }
  1112. function parse($string, $mode='json') {
  1113. if(is_array($string)) return $string;
  1114. switch($mode) {
  1115. case 'json':
  1116. $result = (array)@json_decode($string, true);
  1117. break;
  1118. case 'xml':
  1119. $result = x::parse($string);
  1120. break;
  1121. case 'url':
  1122. $result = (array)@parse_url($string);
  1123. break;
  1124. case 'query':
  1125. if(url::has_query($string)) {
  1126. $string = self::split($string, '?');
  1127. $string = a::last($string);
  1128. }
  1129. @parse_str($string, $result);
  1130. break;
  1131. case 'php':
  1132. $result = @unserialize($string);
  1133. break;
  1134. default:
  1135. $result = $string;
  1136. break;
  1137. }
  1138. return $result;
  1139. }
  1140. function encode($string) {
  1141. $encoded = '';
  1142. $length = str::length($string);
  1143. for($i=0; $i<$length; $i++) {
  1144. $encoded .= (rand(1,2)==1) ? '&#' . ord($string[$i]) . ';' : '&#x' . dechex(ord($string[$i])) . ';';
  1145. }
  1146. return $encoded;
  1147. }
  1148. function email($email, $text=false) {
  1149. if(empty($email)) return false;
  1150. $string = (empty($text)) ? $email : $text;
  1151. $email = self::encode($email, 3);
  1152. return '<a title="' . $email . '" class="email" href="mailto:' . $email . '">' . self::encode($string, 3) . '</a>';
  1153. }
  1154. function link($link, $text=false) {
  1155. $text = ($text) ? $text : $link;
  1156. return '<a href="' . $link . '">' . str::html($text) . '</a>';
  1157. }
  1158. function short($string, $chars, $rep='…') {
  1159. if(str::length($string) <= $chars) return $string;
  1160. $string = self::substr($string,0,($chars-str::length($rep)));
  1161. $punctuation = '.!?:;,-';
  1162. $string = (strspn(strrev($string), $punctuation)!=0) ? substr($string, 0, -strspn(strrev($string), $punctuation)) : $string;
  1163. return $string . $rep;
  1164. }
  1165. function shorturl($url, $chars=false, $base=false, $rep='…') {
  1166. return url::short($url, $chars, $base, $rep);
  1167. }
  1168. function cutout($str, $length, $rep='…') {
  1169. $strlength = str::length($str);
  1170. if($length >= $strlength) return $str;
  1171. // calc the how much we have to cut off
  1172. $cut = (($strlength+str::length($rep)) - $length);
  1173. // divide it to cut left and right from the center
  1174. $cutp = round($cut/2);
  1175. // get the center of the string
  1176. $strcenter = round($strlength/2);
  1177. // get the start of the cut
  1178. $strlcenter = ($strcenter-$cutp);
  1179. // get the end of the cut
  1180. $strrcenter = ($strcenter+$cutp);
  1181. // cut and glue
  1182. return str::substr($str, 0, $strlcenter) . $rep . str::substr($str, $strrcenter);
  1183. }
  1184. function apostrophe($name) {
  1185. return (substr($name,-1,1) == 's' || substr($name,-1,1) == 'z') ? $name .= "'" : $name .= "'s";
  1186. }
  1187. function plural($count, $many, $one, $zero = '') {
  1188. if($count == 1) return $one;
  1189. else if($count == 0 && !empty($zero)) return $zero;
  1190. else return $many;
  1191. }
  1192. function substr($str,$start) {
  1193. preg_match_all('/./u', $str, $ar);
  1194. if(func_num_args() >= 3) {
  1195. $end = func_get_arg(2);
  1196. return join('',array_slice($ar[0],$start,$end));
  1197. } else {
  1198. return join('',array_slice($ar[0],$start));
  1199. }
  1200. }
  1201. function lower($str) {
  1202. return mb_strtolower($str, 'UTF-8');
  1203. }
  1204. function upper($str) {
  1205. return mb_strtoupper($str, 'UTF-8');
  1206. }
  1207. function length($str) {
  1208. return mb_strlen($str, 'UTF-8');
  1209. }
  1210. function contains($str, $needle) {
  1211. return strstr($str, $needle);
  1212. }
  1213. function match($string, $preg, $get=false, $placeholder=false) {
  1214. $match = preg_match($preg, $string, $array);
  1215. if(!$match) return false;
  1216. if(!$get) return $array;
  1217. return a::get($array, $get, $placeholder);
  1218. }
  1219. function random($length=false) {
  1220. $length = ($length) ? $length : rand(5,10);
  1221. $chars = range('a','z');
  1222. $num = range(0,9);
  1223. $pool = array_merge($chars, $num);
  1224. $string = '';
  1225. for($x=0; $x<$length; $x++) {
  1226. shuffle($pool);
  1227. $string .= current($pool);
  1228. }
  1229. return $string;
  1230. }
  1231. function urlify($text) {
  1232. $text = trim($text);
  1233. $text = str::lower($text);
  1234. $text = str_replace('ä', 'ae', $text);
  1235. $text = str_replace('ö', 'oe', $text);
  1236. $text = str_replace('ü', 'ue', $text);
  1237. $text = str_replace('ß', 'ss', $text);
  1238. $text = preg_replace("![^a-z0-9]!i","-", $text);
  1239. $text = preg_replace("![-]{2,}!","-", $text);
  1240. $text = preg_replace("!-$!","", $text);
  1241. return $text;
  1242. }
  1243. function split($string, $separator=',', $length=1) {
  1244. if(is_array($string)) return $string;
  1245. $psep = preg_quote($separator);
  1246. $string = preg_replace('!^' . $psep . '!', '', $string);
  1247. $string = preg_replace('!' . $psep . '$!', '', $string);
  1248. $parts = explode($separator, $string);
  1249. $out = array();
  1250. foreach($parts AS $p) {
  1251. $p = self::trim($p);
  1252. if(!empty($p) && str::length($p) >= $length) $out[] = $p;
  1253. }
  1254. return $out;
  1255. }
  1256. function trim($string) {
  1257. $string = preg_replace('/\s\s+/u', ' ', $string);
  1258. return trim($string);
  1259. }
  1260. function sanitize($string, $type='str', $default=null) {
  1261. $string = stripslashes((string)$string);
  1262. $string = urldecode($string);
  1263. $string = str::utf8($string);
  1264. switch($type) {
  1265. case 'int':
  1266. $string = (int)$string;
  1267. break;
  1268. case 'str':
  1269. $string = (string)$string;
  1270. break;
  1271. case 'array':
  1272. $string = (array)$string;
  1273. break;
  1274. case 'nohtml':
  1275. $string = self::unhtml($string);
  1276. break;
  1277. case 'noxml':
  1278. $string = self::unxml($string);
  1279. break;
  1280. case 'enum':
  1281. $string = (in_array($string, array('y', 'n'))) ? $string : $default;
  1282. $string = (in_array($string, array('y', 'n'))) ? $string : 'n';
  1283. break;
  1284. case 'checkbox':
  1285. $string = ($string == 'on') ? 'y' : 'n';
  1286. break;
  1287. case 'url':
  1288. $string = (v::url($string)) ? $string : '';
  1289. break;
  1290. case 'email':
  1291. $string = (v::email($string)) ? $string : '';
  1292. break;
  1293. case 'plain':
  1294. $string = str::unxml($string);
  1295. $string = str::unhtml($string);
  1296. $string = str::trim($string);
  1297. break;
  1298. case 'lower':
  1299. $string = str::lower($string);
  1300. break;
  1301. case 'upper':
  1302. $string = str::upper($string);
  1303. break;
  1304. case 'words':
  1305. $string = str::sanitize($string, 'plain');
  1306. $string = preg_replace('/[^\pL]/u', ' ', $string);
  1307. case 'tags':
  1308. $string = str::sanitize($string, 'plain');
  1309. $string = preg_replace('/[^\pL\pN]/u', ' ', $string);
  1310. $string = str::trim($string);
  1311. case 'nobreaks':
  1312. $string = str_replace('\n','',$string);
  1313. $string = str_replace('\r','',$string);
  1314. $string = str_replace('\t','',$string);
  1315. break;
  1316. case 'url':
  1317. $string = self::urlify($string);
  1318. break;
  1319. case 'filename':
  1320. $string = f::save_name($string);
  1321. break;
  1322. }
  1323. return trim($string);
  1324. }
  1325. function ucwords($str) {
  1326. return mb_convert_case($str, MB_CASE_TITLE, 'UTF-8');
  1327. }
  1328. function ucfirst($str) {
  1329. return str::upper(str::substr($str, 0, 1)) . str::substr($str, 1);
  1330. }
  1331. function utf8($string) {
  1332. $encoding = mb_detect_encoding($string,'UTF-8, ISO-8859-1, GBK');
  1333. return ($encoding != 'UTF-8') ? iconv($encoding,'utf-8',$string) : $string;
  1334. }
  1335. function stripslashes($string) {
  1336. if(is_array($string)) return $string;
  1337. return (get_magic_quotes_gpc()) ? stripslashes(stripslashes($string)) : $string;
  1338. }
  1339. }
  1340. /*
  1341. ############### URL ###############
  1342. */
  1343. class url {
  1344. function current() {
  1345. return 'http://' . server::get('http_host') . server::get('request_uri');
  1346. }
  1347. function short($url, $chars=false, $base=false, $rep='…') {
  1348. $url = str_replace('http://','',$url);
  1349. $url = str_replace('https://','',$url);
  1350. $url = str_replace('ftp://','',$url);
  1351. $url = str_replace('www.','',$url);
  1352. if($base) {
  1353. $a = explode('/', $url);
  1354. $url = a::get($a, 0);
  1355. }
  1356. return ($chars) ? str::short($url, $chars, $rep) : $url;
  1357. }
  1358. function has_query($url) {
  1359. return (str::contains($url, '?')) ? true : false;
  1360. }
  1361. function strip_query($url) {
  1362. return preg_replace('/\?.*$/is', '', $url);
  1363. }
  1364. function strip_hash($url) {
  1365. return preg_replace('/#.*$/is', '', $url);
  1366. }
  1367. function valid($url) {
  1368. return v::url($url);
  1369. }
  1370. }
  1371. /*
  1372. ############### VALID ###############
  1373. */
  1374. class v {
  1375. function string($string, $options) {
  1376. $format = null;
  1377. $min_length = $max_length = 0;
  1378. if(is_array($options)) extract($options);
  1379. if($format && !preg_match('/^[$format]*$/is', $string)) return false;
  1380. if($min_length && str::length($string) < $min_length) return false;
  1381. if($max_length && str::length($string) > $max_length) return false;
  1382. return true;
  1383. }
  1384. function password($password) {
  1385. return self::string($password, array('min_length' => 4));
  1386. }
  1387. function passwords($password1, $password2) {
  1388. if($password1 == $password2
  1389. && self::password($password1)
  1390. && self::password($password2)) {
  1391. return true;
  1392. } else {
  1393. return false;
  1394. }
  1395. }
  1396. function date($date) {
  1397. $time = strtotime($date);
  1398. if(!$time) return false;
  1399. $year = date('Y', $time);
  1400. $month = date('m', $time);
  1401. $day = date('d', $time);
  1402. return (checkdate($month, $day, $year)) ? $time : false;
  1403. }
  1404. function email($email) {
  1405. $regex = '/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
  1406. return (preg_match($regex, $email)) ? true : false;
  1407. }
  1408. function url($url) {
  1409. $regex = '/^(https?|ftp|rmtp|mms|svn):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i';
  1410. return (preg_match($regex, $url)) ? true : false;
  1411. }
  1412. function filename($string) {
  1413. $options = array(
  1414. 'format' => 'a-zA-Z0-9_-',
  1415. 'min_length' => 2,
  1416. );
  1417. return self::string($string, $options);
  1418. }
  1419. }
  1420. /*
  1421. ############### XML ###############
  1422. */
  1423. class x {
  1424. function parse($xml) {
  1425. $xml = preg_replace('/(<\/?)(\w+):([^>]*>)/', '$1$2$3', $xml);
  1426. $xml = @simplexml_load_string($xml, null, LIBXML_NOENT);
  1427. $xml = @json_encode($xml);
  1428. $xml = @json_decode($xml, true);
  1429. return (is_array($xml)) ? $xml : false;
  1430. }
  1431. }
  1432. ?>