PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/blog/wp-content/plugins/cbpress/lib/class.fn.php

https://github.com/BranchesWebDesign/development
PHP | 2281 lines | 1694 code | 424 blank | 163 comment | 221 complexity | 2aeb40029449f862a032e198ec87290f MD5 | raw file
Possible License(s): LGPL-2.1, MIT, Apache-2.0, GPL-2.0, GPL-3.0

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

  1. <?php
  2. /* global helper functions */
  3. define ('cbpPUT','put');
  4. define ('cbpGET','get');
  5. define ('cbpPOST','post');
  6. define ('cbpDELETE','delete');
  7. class cbpressfn {
  8. function whitespaceToLinebreak($input) {
  9. $output = str_replace(' ', "\n", $input);
  10. return $output;
  11. }
  12. function dirify_plus_for_php($s,$t) {
  13. $a = substr($t, 0, 1);
  14. $b = substr($t, 1, 1);
  15. $c = substr($t, 2, 1);
  16. convert_high_ascii($s);
  17. $s = strip_tags($s); ## remove HTML tags.
  18. $s = preg_replace('!&[^;\s]+;!', '', $s); ## remove HTML entities.
  19. $s = preg_replace('![^\w\s\\\/]!', '', $s); ## remove non-word/space chars.
  20. $s = str_replace(' ', ' ', $s); ## remove 2 spaces in a row
  21. if ($b == "l")
  22. {
  23. $s = strtolower($s); ## lower-case.
  24. }
  25. elseif ($b == "i") {
  26. $s = strtolower($s); ## lower-case.
  27. $s = ucwords($s); ## captialize words
  28. }
  29. elseif ($b == "c")
  30. {
  31. $s = ucwords($s); ## captialize words
  32. }
  33. if ($a == "p")
  34. {
  35. $s = preg_replace('![^\w\s]!', '', $s); ## remove non-word/space chars.
  36. }
  37. elseif ($a == "s")
  38. {
  39. $s = preg_replace('![^\w\s\/]!', '', $s); ## remove non-word/space'/' chars.
  40. }
  41. elseif ($a == "b")
  42. {
  43. $s = preg_replace('![^\w\s\\\]!', '', $s); ## remove non-word/space'\' chars.
  44. }
  45. elseif ($a == "c")
  46. {
  47. $s = preg_replace('![^\w\s\\\]!', '', $s); ## remove non-word/space'\' chars.
  48. $s = str_replace('\\','/',$s); ## reverse backslashes
  49. }
  50. elseif ($a == "r")
  51. {
  52. $s = preg_replace('![^\w\s\/]!', '', $s); ## remove non-word/space'/' chars.
  53. $s = str_replace('/','\\',$s); ## reverse slashes
  54. }
  55. if (($c == "u") || (!$c))
  56. {
  57. $s = str_replace(' ','_',$s); ## change space chars to underscores.
  58. }
  59. elseif ($c == "n")
  60. {
  61. $s = str_replace(' ','',$s); ## delete space
  62. }
  63. elseif ($c == "d")
  64. {
  65. $s = str_replace(' ','-',$s); ## change space chars to dashes.
  66. }
  67. return($s);
  68. }
  69. // bullet proof slug creator I think
  70. function CleanForUrl($string, $maxLength = null) {
  71. $string = str_replace(array(" ", '"',"'", '&quot;','&#039;','&amp;'), array("_", "", "", "",'',''), $string);
  72. $string = strtolower(trim(preg_replace(array('~[^0-9a-z]~i', '~-+~'), '-', $string), '-')); // _Slugify
  73. $string = strtolower(preg_replace(array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'), trim($string)));
  74. if ($maxLength) $string = substr($string, 0, $maxLength);
  75. return $string;
  76. }
  77. static function select( $items, $default = '' ) {
  78. if ( count( $items ) > 0 ) {
  79. foreach ( $items AS $key => $value ) {
  80. if ( is_array( $value ) ) {
  81. echo '<optgroup label="'.esc_attr( $key ).'">';
  82. foreach ( $value AS $sub => $subvalue ) {
  83. echo '<option value="'.esc_attr( $sub ).'"'.( $sub == $default ? ' selected="selected"' : '' ).'>'.esc_html( $subvalue ).'</option>';
  84. }
  85. echo '</optgroup>';
  86. }
  87. else
  88. echo '<option value="'.esc_attr( $key ).'"'.( $key == $default ? ' selected="selected"' : '' ).'>'.esc_html( $value ).'</option>';
  89. }
  90. }
  91. }
  92. /**
  93. * Extract wordpress searchwords from $_GET global
  94. *
  95. * @return string searchwords
  96. */
  97. function extractBlogSearchwords(){
  98. if (is_search() && !is_paged() && !is_admin() ) {
  99. $query = urldecode(stripslashes($_GET['s']));
  100. $query=preg_replace('=[\"\'\\n\\r]+=','',$query);
  101. // array of searchwords - from wp-query.php
  102. preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $query, $matches);
  103. $searchwords=$matches[0];
  104. // lowercase all words
  105. $searchwords = array_map('strtolower', $searchwords);
  106. // return the resulting string
  107. return(implode(' ',$searchwords));
  108. }else{
  109. return FALSE;
  110. }
  111. }
  112. function extractSearchwords(){
  113. // returns keywords from common query string variable names
  114. // from both local and referer
  115. $ret = array();
  116. $search_args = array();
  117. $watch = explode(',','wp_s,s,query,q,search,words,p,qs,k,kw,kewords,cat,category,term,terms,text');
  118. if(isset($_SERVER['HTTP_REFERER'])){
  119. $ref = $_SERVER['HTTP_REFERER'];
  120. $search_args = '';
  121. $parts = explode('?', $ref);
  122. if(count($parts) > 1) $search_args = $parts[1];
  123. parse_str($search_args, $search_args);
  124. }
  125. // $search_args['wp_s'] = get_search_query();
  126. $search_args['wp_s'] = self::extractBlogSearchwords();
  127. foreach($watch as $c){
  128. if(isset($search_args[$c])){
  129. $query_parts = urldecode($search_args[$c]);
  130. $query_parts = stripslashes($query_parts);
  131. // replace whitespaces
  132. $query_parts = preg_replace(array('=\'=','=\"='),'',$query_parts);
  133. // array of single searchwords -> split by possible sub delimiter
  134. $searchwords = preg_split('=[\+\s\.,]+=', $query_parts);
  135. // lowercase all words
  136. $searchwords = array_map('strtolower', $searchwords);
  137. $searchwords = array_map('trim', $searchwords);
  138. $searchwords = implode(' ',$searchwords);
  139. if($searchwords != ''){
  140. $ret[] = $searchwords;
  141. }
  142. unset($query_parts,$searchwords);
  143. }
  144. }
  145. $ret = implode(' ',$ret);
  146. $ret = explode(' ',$ret);
  147. $out = array();
  148. foreach($ret as $str){
  149. if(strlen($str) > 2 && ! preg_match('/[^a-zA-Z0-9_ -]/', $str) > 0 ) {
  150. if(! is_numeric($str) || is_string($str)) $out[] = $str;
  151. }
  152. }
  153. $ret = $out;
  154. $ret = implode(',',$ret);
  155. $ret = stripslashes($ret);
  156. $ret = explode(',',$ret);
  157. $ret = array_map('trim', $ret);
  158. $ret = array_unique($ret);
  159. $ret = implode(',',$ret);
  160. // abort($ret);
  161. // $ret = self::remove_words($ret);
  162. // $wordlist = preg_split('%\s*\W+\s*%', strtolower($ret));
  163. // dump($wordlist);
  164. unset($out,$watch,$search_args);
  165. return $ret;
  166. }
  167. function calc_array_average($arr) {
  168. return array_sum($arr)/count($arr);
  169. }
  170. function explodeTree($array, $delimiter = '_', $baseval = false)
  171. {
  172. if(!is_array($array)) return false;
  173. $splitRE = '/' . preg_quote($delimiter, '/') . '/';
  174. $returnArr = array();
  175. foreach ($array as $key => $val) {
  176. // Get parent parts and the current leaf
  177. $parts = preg_split($splitRE, $key, -1, PREG_SPLIT_NO_EMPTY);
  178. $leafPart = array_pop($parts);
  179. // Build parent structure
  180. // Might be slow for really deep and large structures
  181. $parentArr = &$returnArr;
  182. foreach ($parts as $part) {
  183. if (!isset($parentArr[$part])) {
  184. $parentArr[$part] = array();
  185. } elseif (!is_array($parentArr[$part])) {
  186. if ($baseval) {
  187. $parentArr[$part] = array('__base_val' => $parentArr[$part]);
  188. } else {
  189. $parentArr[$part] = array();
  190. }
  191. }
  192. $parentArr = &$parentArr[$part];
  193. }
  194. // Add the final part to the structure
  195. if (empty($parentArr[$leafPart])) {
  196. $parentArr[$leafPart] = $val;
  197. } elseif ($baseval && is_array($parentArr[$leafPart])) {
  198. $parentArr[$leafPart]['__base_val'] = $val;
  199. }
  200. }
  201. return $returnArr;
  202. }
  203. function get_table_data($params) {
  204. global $wpdb;
  205. $params = is_array($params) ? $params : array();
  206. $defaults = array(
  207. 'table' => 'types',
  208. 'columns' => '*',
  209. 'orderby' => 'id ASC',
  210. 'where' => 1,
  211. 'array_key' => 'id'
  212. );
  213. $params = (object) array_merge($defaults, $params);
  214. $query = "SELECT $params->columns FROM $params->table WHERE $params->where ORDER BY $params->orderby";
  215. $result = $wpdb->get_results($query,ARRAY_A);
  216. $num = $wpdb->num_rows;
  217. $data = false;
  218. if (0 < $num) {
  219. for($i = 0; $i < count($result); $i++ ) {
  220. $data[$result[$i][$params->array_key]] = $result[$i];
  221. }
  222. }
  223. return $data;
  224. }
  225. function return_bytes($val) {
  226. $val = trim($val);
  227. $last = strtolower($val[strlen($val)-1]);
  228. switch($last) {
  229. case 'g':
  230. $val *= 1024;
  231. case 'm':
  232. $val *= 1024;
  233. case 'k':
  234. $val *= 1024;
  235. }
  236. return $val;
  237. }
  238. function return_bytes_nice($bytes) {
  239. $units = array('B', 'K', 'M', 'G');
  240. $bytes = max($bytes, 0);
  241. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  242. $pow = min($pow, count($units) - 1);
  243. $bytes /= pow(1024, $pow);
  244. return round($bytes, 0) . $units[$pow];
  245. }
  246. function get_input_element($args) {
  247. global $cbpress;
  248. $defaults = array(
  249. 'name' => 'name',
  250. 'type' => 'text',
  251. 'extra' => false,
  252. 'inputid' => true,
  253. 'value' => null,
  254. 'br' => 1,
  255. 'size'=>''
  256. );
  257. // cbpressfn::get_input_element('text','import_autosync')
  258. // $r = wp_parse_args( $args, $defaults );
  259. // extract($r, EXTR_SKIP);
  260. extract(wp_parse_args( $args, $defaults ), EXTR_SKIP);
  261. if ($inputid === true) $inputid = $name;
  262. // if (isset($id])){ $inputid = $name; }
  263. if (strlen($inputid)){
  264. // $inputid = " id='".self::cb_esc_attr($inputid)."'";
  265. $inputid = " id='".$inputid."'";
  266. }
  267. if ($size > 0){
  268. $size = " size='".$size."'";
  269. } else{
  270. $size = '';
  271. }
  272. $html = '';
  273. //Get HTML element
  274. switch ($type) {
  275. case 'pagelist':
  276. $pageargs = array(
  277. 'name' => $name,
  278. 'child_of' => 0,
  279. 'echo'=> 0,
  280. 'depth'=> 0,
  281. 'selected' => $value,
  282. 'sort_order' => 'ASC',
  283. 'sort_column' => 'post_title',
  284. 'hierarchical' => 1,
  285. 'exclude' => '',
  286. 'include' => '',
  287. 'meta_key' => '',
  288. 'meta_value' => '',
  289. 'authors' => '',
  290. 'exclude_tree' => ''
  291. );
  292. $html .= wp_dropdown_pages($pageargs);
  293. if (is_string($extra)) {
  294. $html = "<label>$html&nbsp;$extra</label>";
  295. }
  296. break;
  297. case 'text':
  298. case 'textbox':
  299. $value = self::cb_esc_editable_html($value);
  300. $html .= "<input name='$name'$inputid"."$size value='$value' type='text' class='textbox ' />";
  301. if (is_string($extra)) {
  302. $extra = self::cb_esc_html($extra);
  303. $html = "<label>$html&nbsp;$extra</label>";
  304. }
  305. break;
  306. case 'textbox_hop':
  307. $value = self::cb_esc_editable_html($value);
  308. $html .= "<input name='$name'$inputid value='$value' type='text' title='Enter ClickBank Product Vendor ID' class='textbox_hop regular-text' />";
  309. break;
  310. case 'textarea':
  311. // $value = esc_textarea( $value );
  312. $value = self::cb_esc_editable_html($value);
  313. $html .= "<textarea name='$name'$inputid type='text' rows='3' cols='50' class='textarea regular-text'>$value</textarea>";
  314. break;
  315. case 'checkbox':
  316. $checked = $value ? " checked='checked'" : '';
  317. $html .= "<input type='hidden' name='{$name}' value='0'>";
  318. $html .= "<input name='$name'$inputid value='1' type='checkbox' class='checkbox'$checked />";
  319. if (is_string($extra)) {
  320. if (strlen($extra) > 0) {
  321. $extra = self::cb_esc_html($extra);
  322. $html = "<label>$html&nbsp;$extra</label>";
  323. }
  324. }
  325. break;
  326. case 'dropdown':
  327. $html = "<select name='$name'$inputid onchange='javascript:cbe_toggle_select_children(this)' class='dropdown'>";
  328. if (is_array($extra)) $html .= self::option_tags($extra, $value); else $html .= $extra;
  329. $html .= "</select>";
  330. break;
  331. case 'hidden_hop':
  332. $html .= "*automatic hoplink*<input name='$name'$inputid value='$value' type='hidden' />";
  333. break;
  334. case 'hidden':
  335. $html .= "<input name='$name'$inputid value='$value' type='hidden' />";
  336. break;
  337. }
  338. if($br > 0) $html = $html . str_repeat('<br>',$br);
  339. return $html;
  340. }
  341. function option_tags($options, $current = true) {
  342. $html = '';
  343. foreach ($options as $value => $label) {
  344. if (is_array($label)) {
  345. $html .= "<optgroup label='$value'>\n".self::option_tags($label, $current)."</optgroup>\n";
  346. } else {
  347. //if (is_numeric($value)) $value = '';
  348. $html .= "\t<option value='$value'";
  349. if ($value == $current) $html .= " selected='selected'";
  350. $html .= ">$label</option>\n";
  351. }
  352. }
  353. return $html;
  354. }
  355. function cb_esc_attr($str) {
  356. $str = str_replace(array("\t", "\r\n", "\n"), ' ', $str);
  357. return esc_attr($str);
  358. }
  359. function cb_esc_html($str) {
  360. return esc_html($str);
  361. }
  362. function cb_esc_editable_html($str) {
  363. return _wp_specialchars($str, ENT_QUOTES, false, true);
  364. }
  365. /**
  366. * Create a form table from an array of rows
  367. */
  368. function form_table($rows,$alternate=1) {
  369. $content = '<table class="form-table">';
  370. $i = 1;
  371. foreach ($rows as $row) {
  372. $class = '';
  373. if($alternate == 1){
  374. if ($i > 1) $class .= 'cbp_row';
  375. if ($i % 2 == 0) $class .= ' even';
  376. }
  377. if($row['id'] == 'heading'){
  378. $content .= '<tr class="cbp_heading"><th colspan="2"><div class="cbp_heading">'.$row['label'].'</div></th></tr>';
  379. }else{
  380. // $class .= '';
  381. $content .= '<tr class="'.$row['id'].'_row '.$class.'"><th valign="top" scrope="row">';
  382. if (isset($row['id']) && $row['id'] != ''){
  383. $content .= '<label for="'.$row['id'].'">'.$row['label'].':</label>';
  384. }else{
  385. $content .= $row['label'];
  386. }
  387. $content .= '</th><td valign="top">';
  388. $content .= $row['content'];
  389. if ( isset($row['desc']) && !empty($row['desc']) ) {
  390. $content .= '<div class="cbp_help_content"><div class="cbp_desc">'.$row['desc'].'</div></div>';
  391. }
  392. $content .= '</td></tr>';
  393. /*
  394. if ( isset($row['desc']) && !empty($row['desc']) ) {
  395. $content .= '<tr class="'.$row['id'].'_row '.$class.'"><td colspan="2" class="yst_desc"><small>'.$row['desc'].'</small></td></tr>';
  396. }
  397. */
  398. }
  399. $i++;
  400. }
  401. $content .= '</table>';
  402. return $content;
  403. }
  404. // wpcb_get_uri
  405. function local_uri($path_to_file_from_root) {
  406. return plugins_url($path_to_file_from_root, __FILE__);
  407. }
  408. // cbCommunication
  409. static function createUrlAndQuery($url,$array){
  410. }
  411. static function cleanUrl($dirty_url){
  412. list($clean_url)= explode('?',htmlspecialchars(strip_tags($dirty_url),ENT_NOQUOTES));
  413. return $clean_url;
  414. }
  415. static function getMethod(){
  416. $tempMethod=$_SERVER['REQUEST_METHOD'];
  417. if(strcasecmp($tempMethod,cbpPUT)==0)
  418. return cbpPUT;
  419. else if(strcasecmp($tempMethod,cbpPOST)==0){
  420. if(isset($_POST['_method'])){
  421. if(strcasecmp($_POST['_method'],cbpPUT)==0)
  422. return cbpPUT;
  423. if(strcasecmp($_POST['_method'],cbpDELETE)==0)
  424. return cbpDELETE;
  425. }
  426. return cbpPOST;
  427. }else if(strcasecmp($tempMethod,cbpGET)==0)
  428. return cbpGET;
  429. else if(strcasecmp($tempMethod,cbpDELETE)==0)
  430. return cbpDELETE;
  431. }
  432. static function getQueryString(){
  433. if(defined('TESTING')){
  434. global $testquery;
  435. return $testquery;
  436. }else{
  437. global $wp_query;
  438. if(isset($wp_query) && !empty($wp_query->query_vars))
  439. return $wp_query->query_vars;
  440. else
  441. return $_GET;
  442. }
  443. }
  444. static function getFormValues($keys=false){
  445. if($keys){
  446. $values = array();
  447. $values=array_intersect_key($_POST,$keys);
  448. return $values;
  449. }
  450. return $_POST;
  451. }
  452. static function getUpload($keys){
  453. $files=array_intersect_key($_FILES,$keys);
  454. return $files;
  455. }
  456. static function getReferer(){
  457. if(function_exists('wp_get_referer'))
  458. return wp_get_referer();
  459. else
  460. return $_SERVER['HTTP_REFERER'];
  461. }
  462. static function redirectTo($url,$data=false){
  463. $data=ltrim($data,"&");
  464. if(is_array($data))
  465. $data=http_build_query($data);
  466. if(strpos($url,'?')===false)
  467. $redirect=$url."?".$data;
  468. else
  469. $redirect = $url."&".$data;
  470. if(function_exists('wp_redirect'))
  471. wp_redirect($redirect);
  472. else{
  473. header( 'Location: '.$redirect );
  474. exit;
  475. }
  476. }
  477. static function useRedirect(){
  478. return self::array_key_exists_v('_redirect',$_POST);
  479. }
  480. function array_key_exists_v($needle,$haystack){
  481. foreach($haystack as $key => $value){
  482. if($needle==$key) return $value;
  483. }
  484. return false;
  485. }
  486. function array_search_key($search,$haystack){
  487. $array= array();
  488. foreach($haystack as $key => $value){
  489. $sub=stristr($key,$search);
  490. if($sub) $array[$key]=$value;
  491. }
  492. return $array;
  493. }
  494. function escaper($string, $esc_type = 'html', $char_set = 'ISO-8859-1'){
  495. switch ($esc_type) {
  496. case 'html':
  497. return htmlspecialchars($string, ENT_QUOTES, $char_set);
  498. case 'htmlall':
  499. return htmlentities($string, ENT_QUOTES, $char_set);
  500. case 'url':
  501. return rawurlencode($string);
  502. case 'urlpathinfo':
  503. return str_replace('%2F','/',rawurlencode($string));
  504. case 'quotes':
  505. // escape unescaped single quotes
  506. return preg_replace("%(?<!\\\\)'%", "\\'", $string);
  507. case 'hex':
  508. // escape every character into hex
  509. $return = '';
  510. for ($x=0; $x < strlen($string); $x++) {
  511. $return .= '%' . bin2hex($string[$x]);
  512. }
  513. return $return;
  514. case 'hexentity':
  515. $return = '';
  516. for ($x=0; $x < strlen($string); $x++) {
  517. $return .= '&#x' . bin2hex($string[$x]) . ';';
  518. }
  519. return $return;
  520. case 'decentity':
  521. $return = '';
  522. for ($x=0; $x < strlen($string); $x++) {
  523. $return .= '&#' . ord($string[$x]) . ';';
  524. }
  525. return $return;
  526. case 'javascript':
  527. // escape quotes and backslashes, newlines, etc.
  528. return strtr($string, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
  529. case 'mail':
  530. // safe way to display e-mail address on a web page
  531. return str_replace(array('@', '.'),array(' [AT] ', ' [DOT] '), $string);
  532. case 'nonstd':
  533. // escape non-standard chars, such as ms document quotes
  534. $_res = '';
  535. for($_i = 0, $_len = strlen($string); $_i < $_len; $_i++) {
  536. $_ord = ord(substr($string, $_i, 1));
  537. // non-standard char, escape it
  538. if($_ord >= 126){
  539. $_res .= '&#' . $_ord . ';';
  540. }
  541. else {
  542. $_res .= substr($string, $_i, 1);
  543. }
  544. }
  545. return $_res;
  546. default:
  547. return $string;
  548. }
  549. }
  550. public function array_key_intersect(&$a, &$b) {
  551. $array = array();
  552. while (list($key,$value) = each($a)) {
  553. if (isset($b[$key])) $array[$key] = $value;
  554. }
  555. return $array;
  556. }
  557. function array_diff_assoc_recursive($array1, $array2) {
  558. foreach($array1 as $key => $value) {
  559. if(is_array($value))
  560. {
  561. if(!isset($array2[$key]))
  562. {
  563. $difference[$key] = $value;
  564. }
  565. elseif(!is_array($array2[$key]))
  566. {
  567. $difference[$key] = $value;
  568. }
  569. else
  570. {
  571. $new_diff = self::array_diff_assoc_recursive($value, $array2[$key]);
  572. if($new_diff != FALSE)
  573. {
  574. $difference[$key] = $new_diff;
  575. }
  576. }
  577. }
  578. elseif(!isset($array2[$key]) || $array2[$key] != $value)
  579. {
  580. $difference[$key] = $value;
  581. }
  582. }
  583. return !isset($difference) ? 0 : $difference;
  584. }
  585. function create_formfield($name,$type,$value,$valtochk=null)
  586. {
  587. switch ($type) {
  588. case "checkbox":
  589. echo "<input name=\"$name\" type=\"$type\" id=\"$name\" ";self::formfield_selected($value,$valtochk,$type);echo " />\n";
  590. break;
  591. case "text":
  592. echo "<input name=\"$name\" type=\"$type\" id=\"$name\" value=\"$value\" />\n";
  593. break;
  594. case "textarea":
  595. echo "<textarea cols=\"20\" rows=\"5\" name=\"$name\">$val</textarea>";
  596. break;
  597. case "password":
  598. echo "<input name=\"$name\" type=\"$type\" id=\"$name\" />\n";
  599. break;
  600. case "hidden":
  601. echo "<input name=\"$name\" type=\"$type\" value=\"$value\" />\n";
  602. break;
  603. }
  604. }
  605. function formfield_selected($value,$valtochk,$type=null)
  606. {
  607. if($value == $valtochk){ echo "checked"; }
  608. }
  609. static function hexToStr2($hex){
  610. $string = '';
  611. for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
  612. $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
  613. }
  614. return $string;
  615. }
  616. static function strToHex($input){
  617. return(bin2hex($input));
  618. }
  619. static function hexToStr($input) {
  620. return(pack("H*",$input));
  621. }
  622. // indents subcat with x number of characters for path length
  623. function indentCategory($fpath) {
  624. $iteration = count(explode(CBE_CATSEP,$fpath))-1;
  625. return str_repeat("-",$iteration);
  626. }
  627. static function ajax_error($message='') {
  628. $message = str_replace("'","",$message);
  629. $string = "({'success':false, 'error':'myerror'})";
  630. $string = str_replace('myerror',$message,$string);
  631. echo $string;
  632. die;
  633. }
  634. static function create_slug($str) {
  635. $str = preg_replace("/([_ ])/", "-", trim($str));
  636. $str = preg_replace("/([^0-9a-z-.])/", "", strtolower($str));
  637. $str = preg_replace("/(-){2,}/", "-", $str);
  638. return $str;
  639. }
  640. static function createslug($string) {
  641. return sanitize_title(trim(strtolower($string)));
  642. }
  643. static function thispage() {
  644. return self::getparam('page');
  645. }
  646. function is_cb_page() {
  647. $pg = self::thispage();
  648. if(substr($pg,0,8) == 'cbpress-' || $pg == 'cbpress'){
  649. return true;
  650. }
  651. return false;
  652. }
  653. /**
  654. * Merges any number of arrays / parameters recursively,
  655. *
  656. * Replacing entries with string keys with values from latter arrays.
  657. * If the entry or the next value to be assigned is an array, then it
  658. * automagically treats both arguments as an array.
  659. * Numeric entries are appended, not replaced, but only if they are
  660. * unique
  661. *
  662. * @source http://us3.php.net/array_merge_recursive
  663. * @version 1.4
  664. **/
  665. function array_merge_recursive_distinct () {
  666. $arrays = func_get_args();
  667. $base = array_shift($arrays);
  668. if(!is_array($base)) $base = empty($base) ? array() : array($base);
  669. foreach($arrays as $append) {
  670. if(!is_array($append)) $append = array($append);
  671. foreach($append as $key => $value) {
  672. if(!array_key_exists($key, $base) and !is_numeric($key)) {
  673. $base[$key] = $append[$key];
  674. continue;
  675. }
  676. if(is_array($value) or is_array($base[$key])) {
  677. $base[$key] = self::array_merge_recursive_distinct($base[$key], $append[$key]);
  678. } else if(is_numeric($key)) {
  679. if(!in_array($value, $base)) $base[] = $value;
  680. } else {
  681. $base[$key] = $value;
  682. }
  683. }
  684. }
  685. return $base;
  686. }
  687. function days_since($date1, $return_number = false) {
  688. if(empty($date1)) return "";
  689. // In case a passed date cannot be ready by strtotime()
  690. // $date1 = apply_filters('CB_F_days_since', $date1);
  691. $date1 = apply_filters('cbpressfn_days_since', $date1);
  692. $date2 = date("Y-m-d");
  693. $date1 = date("Y-m-d", strtotime($date1));
  694. $future = false;
  695. // determine if future or past
  696. if(strtotime($date2) < strtotime($date1)) $future = true;
  697. $difference = abs(strtotime($date2) - strtotime($date1));
  698. $days = round(((($difference/60)/60)/24), 0);
  699. if($return_number)
  700. return $days;
  701. if($days == 0) { return __('Today', CBPRESS_TRANS); }
  702. elseif($days == 1) { return($future ? " Tomorrow " : " Yesterday "); }
  703. elseif($days > 1 && $days <= 6) { return ($future ? " in $days days " : " $days days ago"); }
  704. elseif($days > 6) { return date(get_option('date_format'), strtotime($date1)); }
  705. }
  706. function nice_time($time, $args = false) {
  707. $defaults = array('format' => 'date_and_time');
  708. extract( wp_parse_args( $args, $defaults ), EXTR_SKIP );
  709. if(!$time) return false;
  710. if($format == 'date') return date(get_option('date_format'), $time);
  711. if($format == 'time') return date(get_option('time_format'), $time);
  712. if($format == 'date_and_time') return date(get_option('date_format'), $time) . " " . date(get_option('time_format'), $time);
  713. return false;
  714. }
  715. static function struct($cols='',$default='') {
  716. $out = new stdClass();
  717. if(strlen($cols)){
  718. $arr = explode(',',$cols);
  719. foreach($arr as $key){ $out->$key = $default; }
  720. }
  721. // abort($cols);
  722. return $out;
  723. }
  724. static function struct222($cols='') {
  725. // $out = new stdClass();
  726. $data = array(); foreach(self::listtoarray($cols) as $c) $data[$c] = '';
  727. return self::a2o($data);
  728. }
  729. function arrayToObject(&$array) {
  730. if(!is_array($array)) {
  731. return $array;
  732. }
  733. $object = new stdClass();
  734. if(is_array($array) && count($array) > 0) {
  735. foreach($array as $name => $value) {
  736. $name = strtolower(trim($name));
  737. if(!empty($name)) {
  738. $object->$name = self::arrayToObject($value);
  739. }
  740. }
  741. return $object;
  742. } else {
  743. return false;
  744. }
  745. }
  746. static function o2a($object) { // object_to_array
  747. if(!is_object( $object ) && !is_array( $object )) return $object;
  748. if(is_object($object) ) $object = get_object_vars( $object );
  749. return array_map(array('cbpressfn' , 'o2a'), $object );
  750. }
  751. static function a2o($array = array()) { // array_to_object
  752. if (!empty($array)) {
  753. $data = false;
  754. foreach ($array as $akey => $aval) {
  755. $data -> {$akey} = $aval;
  756. }
  757. return $data;
  758. }
  759. return false;
  760. }
  761. static function listtoarray($lst,$delim=','){
  762. if(is_array($lst)) return $lst;
  763. return explode($delim,$lst);
  764. }
  765. static function l2a($lst,$delim=','){
  766. if(is_array($lst)) return $lst;
  767. return explode($delim,$lst);
  768. }
  769. public static function getCurrentURL()
  770. {
  771. $isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
  772. $port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
  773. $port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
  774. $url = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
  775. return $url;
  776. }
  777. static function getparam($keyname,$default=null) {
  778. if (isset($_GET[$keyname])){
  779. return $_GET[$keyname];
  780. }else if(isset($_POST[$keyname])){
  781. return $_POST[$keyname];
  782. }
  783. return $default;
  784. }
  785. // like above but with a !not check
  786. function igetparam($keyname,$default=null) {
  787. $v = self::getparam($keyname);
  788. if (!$v) $v = $default;
  789. return $v;
  790. }
  791. function parse_tab($filename){
  792. $mappings = array();
  793. $id = fopen($filename, "r"); //open the file
  794. $data = fgetcsv($id, filesize($filename), "\t");
  795. if(!$mappings){
  796. $mappings = $data;
  797. }
  798. while($data = fgetcsv($id, filesize($filename), "\t")){
  799. if($data[0]){
  800. $out = new stdClass();
  801. foreach($data as $key => $value) {
  802. if($mappings[$key] != ''){
  803. $out->$mappings[$key] = addslashes($value);
  804. }
  805. }
  806. $arr[] = $out;
  807. }
  808. }
  809. fclose($id); //close file
  810. return $arr;
  811. }
  812. static function divtag( $content = '' ,$class= '' ) {
  813. if ( $class != '' ) $class = " class='$class'";
  814. return "<div$class>" . $content . '</div>';
  815. }
  816. static function html_link( $url, $title = '', $css='' ) {
  817. if ( empty( $title ) ) $title = $url;
  818. if ( $css != '' ) $css = " class='$css'";
  819. return sprintf( "<a href='%s'%s>%s</a>", esc_url( $url ), $css, $title );
  820. }
  821. static function cbe_html( $tag, $attributes = array(), $content = '' ) {
  822. if ( is_array( $attributes ) ) {
  823. $closing = $tag;
  824. foreach ( $attributes as $key => $value ) {
  825. $tag .= ' ' . $key . '="' . esc_attr( $value ) . '"';
  826. }
  827. } else {
  828. $content = $attributes;
  829. list( $closing ) = explode(' ', $tag, 2);
  830. }
  831. return "<{$tag}>{$content}</{$closing}>";
  832. }
  833. // used by hopads contextual
  834. // used by hopads contextual
  835. // used by hopads contextual
  836. static function get_stop_words() {
  837. /********** ***********/
  838. // $arr = $str;
  839. // $arr = explode(',',$arr);
  840. // $arr = array_unique($arr);
  841. // $arr = implode(',',$arr);
  842. // $arr = explode(',',$arr);
  843. $more = self::get_include_contents(CBP_FILES_DIR.'stop-words.txt');
  844. $more = explode("\r\n", trim($more));
  845. // $more = implode(',',$more) . ',' . $str;
  846. // $more = explode(',',$more);
  847. // $more = array_unique($more);
  848. // $out = implode("\r\n", $more);
  849. // echo '<pre>'.$out.'</pre>';
  850. // abort($more);
  851. // $arr = array_filter($arr);
  852. return $more;
  853. }
  854. static function remove_words($contents) {
  855. $contents = self::extract_keywords($contents,25);
  856. return $contents;
  857. }
  858. function keywords_to_array($keywords) {
  859. if (!empty($keywords)) {
  860. $keywords = stripslashes($keywords);
  861. $keywords = strip_tags($keywords);
  862. $keywords = str_replace(array("\r", "\n", "\t"), '', $keywords);
  863. $keywords = str_replace(array(", ", " ,"), ',', $keywords);
  864. return explode(',',$keywords);
  865. }
  866. return array();
  867. }
  868. function toAscii($str, $replace = array(), $delimiter = ' '){
  869. if( !empty($replace) ){
  870. $str = str_replace((array)$replace, ' ', $str);
  871. }
  872. $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
  873. $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
  874. $clean = strtolower(trim($clean, '-'));
  875. $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
  876. return $clean;
  877. }
  878. static function extract_keywords($content,$num_to_ret = 25) {
  879. $stopwords = self::get_stop_words();
  880. // abort($content);
  881. // $content = (preg_replace("/[^A-Za-z0-9\s\s+\-]/", "", $content));
  882. // $content = ereg_replace("[^A-Za-z0-9]", "", $content );
  883. // $content = preg_replace("/[^A-Za-z0-9\s\s+]/", "",$content);
  884. $wordlist = preg_split('%\s*\W+\s*%', strtolower($content));
  885. // Build an array of the unique words and number of times they occur.
  886. $a = array_count_values($wordlist);
  887. // Remove the stop words from the list.
  888. foreach ($stopwords as $word) {
  889. unset($a[$word]);
  890. }
  891. arsort($a, SORT_NUMERIC);
  892. $num_words = count($a);
  893. $num_to_ret = $num_words > $num_to_ret ? $num_to_ret : $num_words;
  894. $outwords = array_slice($a, 0, $num_to_ret);
  895. return implode(',', array_keys($outwords));
  896. }
  897. static function clean_string_input($string) {
  898. $interim = strip_tags($string);
  899. if(get_magic_quotes_gpc()) {
  900. $interim=stripslashes($interim);
  901. }
  902. // now check for pure ASCII input
  903. // special characters that might appear here:
  904. // 96: opening single quote (not strictly illegal, but substitute anyway)
  905. // 145: opening single quote
  906. // 146: closing single quote
  907. // 147: opening double quote
  908. // 148: closing double quote
  909. // 133: ellipsis (...)
  910. // 163: pound sign (this is safe, so no substitution required)
  911. // 10 lf , 13 cr
  912. // these can be substituted for safe equivalents
  913. $result = '';
  914. for ($i=0; $i<strlen($interim); $i++) {
  915. $char = $interim{$i};
  916. $a_v = ord($char); // asciivalue
  917. if ($a_v == 96) {
  918. $result .= "\\'";
  919. } else if (($a_v > 31 && $a_v < 127) || ($a_v == 163) || ($a_v == 10) || ($a_v == 13)) {
  920. $result .= $char; // it's already safe ASCII
  921. } else if ($a_v == 145){
  922. $result .= "\\'";
  923. } else if ($a_v == 146){
  924. $result .= "'";
  925. } else if ($a_v == 147){
  926. $result .= '"';
  927. } else if ($a_v == 148){
  928. $result .= '"';
  929. } else if ($a_v == 133){
  930. $result .= '...';
  931. }
  932. }
  933. $result = str_replace("\n"," ",$result);
  934. $result = str_replace("'"," ",$result);
  935. $result = str_replace('"'," ",$result);
  936. $result = str_replace("%"," ",$result);
  937. $result = str_replace("“"," ",$result);
  938. $result = str_replace("”"," ",$result);
  939. $result = str_replace("’"," ",$result);
  940. $result = str_replace("‘"," ",$result);
  941. $result = str_replace("."," ",$result);
  942. $result = str_replace("("," ",$result);
  943. $result = str_replace(")"," ",$result);
  944. $result = str_replace("\\","",$result);
  945. $result = str_replace(",","",$result);
  946. $result = str_replace("!","",$result);
  947. return $result;
  948. }
  949. // END used by hopads contextual
  950. // END used by hopads contextual
  951. // END used by hopads contextual
  952. // returns current module directory url for requesting file FROM FILE
  953. static function plugin_dir_url( $file ) {
  954. // __FILE__
  955. return trailingslashit( plugins_url( '', $file ) );
  956. }
  957. static function quotedValueList($in){
  958. $in = is_array($in) ? implode(',',$in) : $in;
  959. $in = "'" . str_replace(array("'", ","), array("\\'", "','"), $in) . "'";
  960. return $in;
  961. }
  962. static function toValuePair($result,$keycol,$valuecol=''){
  963. $data = array();
  964. foreach ($result as $id => $r) {
  965. $o = (is_object($r)) ? 1 : 0;
  966. $r = (array) $r;
  967. $v = $r[$keycol];
  968. if(isset($r[$valuecol])){
  969. $data[$v] = $r[$valuecol];
  970. }else{
  971. $r = ($o == 1) ? (object) $r : $r;
  972. $data[$v] = $r;
  973. }
  974. unset($o,$id,$v,$r);
  975. }
  976. unset($result);
  977. return $data;
  978. }
  979. static function fetchPairs($result){
  980. // uses ARRAY_N
  981. $data = array();
  982. for($j=0; $j<count($result); $j++) {
  983. $data[$result[$j][0]] = $result[$j][1];
  984. }
  985. return $data;
  986. }
  987. // $c = cbpressfn::generateUniqueCode();
  988. // abort($c);
  989. // $get_vars = cbpressfn::getBuildGetVars('page');
  990. // abort($get_vars);
  991. static function getBuildGetVars($var='') {
  992. $get_vars = '';
  993. foreach ( (array) $_GET as $key => $val ) {
  994. if ( $key == $var ) {
  995. $get_vars = $key.'='.$val.'&';
  996. break;
  997. } else {
  998. $get_vars .= $key.'='.$val.'&';
  999. }
  1000. }
  1001. return $get_vars;
  1002. }
  1003. static function generateUniqueCode() {
  1004. $microtime = microtime();
  1005. $unique_code = substr(md5($microtime),0,8);
  1006. return $unique_code;
  1007. }
  1008. static function isDirectoryWritable($path) {
  1009. # generate random file
  1010. $path = $path . uniqid(mt_rand()) . '.tmp';
  1011. $file = @fopen($path, 'a');
  1012. if ($file === false) {
  1013. return false;
  1014. }
  1015. @fclose($file);
  1016. @unlink($path);
  1017. return true;
  1018. }
  1019. static function getMysqlDate($period) {
  1020. # return a formatted, UTC mysql date (yyyy-mm-dd)
  1021. switch ($period) {
  1022. case 'now':
  1023. # also return the time
  1024. return date('Y-m-d H:i:s');
  1025. break;
  1026. case 'today':
  1027. return date('Y-m-d');
  1028. break;
  1029. case 'month':
  1030. default:
  1031. return date('Y-m-01');
  1032. break;
  1033. }
  1034. }
  1035. static function get_post_id() {
  1036. if (is_admin())
  1037. return intval($_REQUEST['post']);
  1038. elseif (in_the_loop())
  1039. return intval(get_the_ID());
  1040. elseif (is_singular()) {
  1041. global $wp_query;
  1042. return $wp_query->get_queried_object_id();
  1043. }
  1044. return false;
  1045. }
  1046. // Creates a search engine friendly link from a string
  1047. // CBFRONT was getSefLinkFromString
  1048. static function string_to_seflink($string) {
  1049. $string = trim(strtolower($string));
  1050. $string = preg_replace('/^\W+|\W+$/', '', $string);
  1051. $string = preg_replace("@[^A-Za-z0-9\-_]+@i","-", $string);
  1052. $string = preg_replace('{(-)\1+}', '-', $string);
  1053. if (strlen($string) > 255) {
  1054. $string = substr($string, 0, 255);
  1055. }
  1056. return $string;
  1057. }
  1058. static function product_permalink_base(){
  1059. $token = '?cbgo=';
  1060. return CBE_BLOGURL . $token;
  1061. // echo self::get_template_name();
  1062. // abort('');
  1063. $token = cbengine_get_option('storetoken');
  1064. $token1 = $cbeo->storetoken . '/';
  1065. $token = '?cbgo=';
  1066. return CBE_BLOG_URL . $token;
  1067. }
  1068. /**
  1069. * Get the current page template and return its filename if it's a
  1070. * PageSpot template. Otherwise return false.
  1071. *
  1072. * @return false|string
  1073. */
  1074. static function get_template_name($id=null) {
  1075. if (empty($id)) {
  1076. $id = get_the_ID();
  1077. }
  1078. //$template_file = get_page_template();
  1079. $template_file = TEMPLATEPATH.'/'.get_post_meta($id, '_wp_page_template', true);
  1080. //print_r($template_file); exit;
  1081. if (false === strpos(strtolower($template_file), '.php')
  1082. || 0 !== strpos(basename(strtolower($template_file)), 'pagespot')
  1083. || !file_exists($template_file)) {
  1084. return false;
  1085. }
  1086. return $template_file;
  1087. }
  1088. // prepares product for display based on options
  1089. static function get_filter(){
  1090. global $cb_engine;
  1091. return $cb_engine->get_module_settings('filter');
  1092. }
  1093. // used for product desciptions
  1094. static function truncate($string, $limit, $break=".", $pad="...") {
  1095. if(strlen($string) <= $limit) return $string;
  1096. if(false !== ($breakpoint = strpos($string, $break, $limit))) {
  1097. if($breakpoint < strlen($string) - 1) {
  1098. $string = substr($string, 0, $breakpoint) . $pad;
  1099. }
  1100. }
  1101. return $string;
  1102. }
  1103. // remove email @ address
  1104. static function remove_email($text){
  1105. return eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '', $text);
  1106. }
  1107. // Remove Last Period
  1108. static function RemovePeriod($str) {
  1109. $str = trim($str);
  1110. $last = $str[strlen($str)-1];
  1111. if($last == '.'){
  1112. $len = strlen($str);
  1113. $str = substr($str,0,($len-1));
  1114. }
  1115. return $str;
  1116. }
  1117. static function getTime() {
  1118. $a = explode (' ',microtime());
  1119. return(double) $a[0] + $a[1];
  1120. }
  1121. /**
  1122. * Convert a string from one UTF-8 char to one UTF-16 char.
  1123. *
  1124. * Normally should be handled by mb_convert_encoding, but
  1125. * provides a slower PHP-only method for installations
  1126. * that lack the multibye string extension.
  1127. *
  1128. * This method is from the Solar Framework by Paul M. Jones
  1129. *
  1130. * @link http://solarphp.com
  1131. * @param string $utf8 UTF-8 character
  1132. * @return string UTF-16 character
  1133. */
  1134. static function _utf82utf16($utf8) {
  1135. // Check for mb extension otherwise do by hand.
  1136. if( function_exists('mb_convert_encoding') ) {
  1137. return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  1138. }
  1139. switch (strlen($utf8)) {
  1140. case 1:
  1141. // this case should never be reached, because we are in ASCII range
  1142. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1143. return $utf8;
  1144. case 2:
  1145. // return a UTF-16 character from a 2-byte UTF-8 char
  1146. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1147. return chr(0x07 & (ord($utf8{0}) >> 2))
  1148. . chr((0xC0 & (ord($utf8{0}) << 6))
  1149. | (0x3F & ord($utf8{1})));
  1150. case 3:
  1151. // return a UTF-16 character from a 3-byte UTF-8 char
  1152. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1153. return chr((0xF0 & (ord($utf8{0}) << 4))
  1154. | (0x0F & (ord($utf8{1}) >> 2)))
  1155. . chr((0xC0 & (ord($utf8{1}) << 6))
  1156. | (0x7F & ord($utf8{2})));
  1157. }
  1158. // ignoring UTF-32 for now, sorry
  1159. return '';
  1160. }
  1161. static function encodeUnicodeString($value) {
  1162. $strlen_var = strlen($value);
  1163. $ascii = "";
  1164. /**
  1165. * Iterate over every character in the string,
  1166. * escaping with a slash or encoding to UTF-8 where necessary
  1167. */
  1168. for($i = 0; $i < $strlen_var; $i++) {
  1169. $ord_var_c = ord($value[$i]);
  1170. switch (true) {
  1171. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  1172. // characters U-00000000 - U-0000007F (same as ASCII)
  1173. $ascii .= $value[$i];
  1174. break;
  1175. case (($ord_var_c & 0xE0) == 0xC0):
  1176. // characters U-00000080 - U-000007FF, mask 110XXXXX
  1177. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1178. $char = pack('C*', $ord_var_c, ord($value[$i + 1]));
  1179. $i += 1;
  1180. $utf16 = self::_utf82utf16($char);
  1181. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1182. break;
  1183. case (($ord_var_c & 0xF0) == 0xE0):
  1184. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  1185. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1186. $char = pack('C*', $ord_var_c,
  1187. ord($value[$i + 1]),
  1188. ord($value[$i + 2]));
  1189. $i += 2;
  1190. $utf16 = self::_utf82utf16($char);
  1191. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1192. break;
  1193. case (($ord_var_c & 0xF8) == 0xF0):
  1194. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  1195. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1196. $char = pack('C*', $ord_var_c,
  1197. ord($value[$i + 1]),
  1198. ord($value[$i + 2]),
  1199. ord($value[$i + 3]));
  1200. $i += 3;
  1201. $utf16 = self::_utf82utf16($char);
  1202. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1203. break;
  1204. case (($ord_var_c & 0xFC) == 0xF8):
  1205. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  1206. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1207. $char = pack('C*', $ord_var_c,
  1208. ord($value[$i + 1]),
  1209. ord($value[$i + 2]),
  1210. ord($value[$i + 3]),
  1211. ord($value[$i + 4]));
  1212. $i += 4;
  1213. $utf16 = self::_utf82utf16($char);
  1214. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1215. break;
  1216. case (($ord_var_c & 0xFE) == 0xFC):
  1217. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  1218. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1219. $char = pack('C*', $ord_var_c,
  1220. ord($value[$i + 1]),
  1221. ord($value[$i + 2]),
  1222. ord($value[$i + 3]),
  1223. ord($value[$i + 4]),
  1224. ord($value[$i + 5]));
  1225. $i += 5;
  1226. $utf16 = self::_utf82utf16($char);
  1227. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1228. break;
  1229. }
  1230. }
  1231. return $ascii;
  1232. }
  1233. /**
  1234. * Loads a webpage and returns its HTML as a string.
  1235. *
  1236. * @param string $url The URL of the webpage to load.
  1237. * @param string $ua The user agent to use.
  1238. * @return string The HTML of the URL.
  1239. */
  1240. static function load_webpage($url, $ua) {
  1241. // $referer
  1242. $options = array();
  1243. $options['headers'] = array(
  1244. 'User-Agent' => $ua
  1245. );
  1246. $response = wp_remote_request($url, $options);
  1247. if ( is_wp_error( $response ) ) return false;
  1248. if ( 200 != $response['response']['code'] ) return false;
  1249. return trim( $response['body'] );
  1250. }
  1251. // array2table (CAB)
  1252. static function array2table($arr,$cols='',$colModel=''){
  1253. $out = '';
  1254. $count = count($arr);
  1255. $use_headings = false;
  1256. if(is_object($colModel)){
  1257. $use_headings = true;
  1258. // $heads = array_values($colModel);
  1259. // $cols = array_values((array) $colModel);
  1260. $heads = array_values((array) $colModel);
  1261. $cols = array_keys((array) $colModel);
  1262. $colModel = (array) $colModel;
  1263. } else {
  1264. $colModel = array();
  1265. if (!is_array($cols)) if(strlen($cols)) $cols = explode(',',$cols);
  1266. if (!is_array($cols)) $cols = array();
  1267. $heads = $cols;
  1268. }
  1269. // if(count($cols) > count($headers)){ }
  1270. // abort(get_defined_vars());
  1271. if($count > 0){
  1272. reset($arr);
  1273. $num = count(current($arr));
  1274. $out .= "<table class=\"widefat\" align=\"center\" border=\"0\"cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n";
  1275. $out .= "<tr><thead>\n";
  1276. $thead = '';
  1277. foreach(current($arr) as $key => $value){
  1278. $label = $key;
  1279. if(!count($cols)){
  1280. $cell = "<th>".$label."&nbsp;"."</th>\n";
  1281. $thead .= $cell;
  1282. }else if(isset($colModel[$key])){
  1283. $label = $colModel[$key];
  1284. $cell = "<th>".$label."&nbsp;"."</th>\n";
  1285. $thead .= $cell;
  1286. }else if(in_array($key, $cols)){
  1287. $cell = "<th>".$label."&nbsp;"."</th>\n";
  1288. $thead .= $cell;
  1289. }
  1290. }
  1291. $out .= $thead;
  1292. $out .= "</thead></tr>\n";
  1293. $out .= "<tr><tfoot>" . $thead . "</tfoot></tr>\n";
  1294. $out .= "<tbody>";
  1295. while ($curr_row = current($arr)) {
  1296. $out .= "<tr>\n";
  1297. $col = 1;
  1298. foreach($curr_row as $key => $value){
  1299. $cell = "<td>".$value."&nbsp;"."</td>\n";
  1300. if(!count($cols)){
  1301. $out .= $cell;
  1302. }else if(in_array($key, $cols)){
  1303. $out .= $cell;
  1304. }
  1305. }
  1306. $out .= "</tr>\n";
  1307. next($arr);
  1308. }
  1309. $out .= "</tbody>";
  1310. $out .= "</table>\n";
  1311. }
  1312. return trim($out);
  1313. }
  1314. static function array_overlay($a1,$a2){
  1315. foreach($a1 as $k => $v) {
  1316. if(!array_key_exists($k,$a2)) continue;
  1317. if(is_array($v) && is_array($a2[$k])){
  1318. $a1[$k] = self::array_overlay($v,$a2[$k]);
  1319. }else{
  1320. $a1[$k] = $a2[$k];
  1321. }
  1322. }
  1323. return $a1;
  1324. }
  1325. // arrays key prefix scoping (CAB)
  1326. static function array_key_prefix( &$array, $prefix ) {
  1327. $r = array();
  1328. foreach ($array as $key=>$value) { $r[$prefix.$key] = $value; }
  1329. return $r;
  1330. }
  1331. // Force script enqueue
  1332. static function do_scripts( $handles ) {
  1333. global $wp_scripts;
  1334. if ( ! is_a( $wp_scripts, 'WP_Scripts' ) )
  1335. $wp_scripts = new WP_Scripts();
  1336. $wp_scripts->do_items( ( array ) $handles );
  1337. }
  1338. // Force style enqueue
  1339. static function do_styles( $handles ) {
  1340. self::do_scripts( 'jquery' );
  1341. global $wp_styles;
  1342. if ( ! is_a( $wp_styles, 'WP_Styles' ) )
  1343. $wp_styles = new WP_Styles();
  1344. ob_start();
  1345. $wp_styles->do_items( ( array ) $handles );
  1346. $content = str_replace( array( '"', "\n" ), array( "'", '' ), ob_get_clean() );
  1347. echo "<script type='text/javascript'>\n";
  1348. echo "jQuery( document ).ready( function( $ ) {\n";
  1349. echo "$( 'head' ).prepend( \"$content\" );\n";
  1350. echo "} );\n";
  1351. echo "</script>";
  1352. }
  1353. /**************************************
  1354. ************************/
  1355. // Enable delayed activation ( to be used with scb_init() )
  1356. static function add_activation_hook( $plugin, $callback ) {
  1357. add_action( 'cbe_activation_' . plugin_basename( $plugin ), $callback );
  1358. }
  1359. // Have more than one uninstall hooks; also prevents an UPDATE query on each page load
  1360. static function add_uninstall_hook( $plugin, $callback ) {
  1361. register_uninstall_hook( $plugin, '__return_false' ); // dummy
  1362. add_action( 'uninstall_' . plugin_basename( $plugin ), $callback );
  1363. }
  1364. // Apply a function to each element of a ( nested ) array recursively
  1365. static function array_map_recursive( $callbac…

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