PageRenderTime 59ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/admin/_inc/global_function.php

https://github.com/lslucas/105fm
PHP | 2727 lines | 1826 code | 509 blank | 392 comment | 272 complexity | 313e1a6f8d83a1fe27a379717376a97c MD5 | raw file
  1. <?php
  2. function fileUpload($name, array $var, $filename='')
  3. {
  4. global $_FILES;
  5. if (isset($_FILES[$name])) {
  6. include_once "admin/_inc/class.upload.php";
  7. $handle = new Upload($_FILES[$name]);
  8. $filename = empty($filename) ? linkfy($_FILES[$name]['name'].'_'.time()) : $filename;
  9. if ($handle->uploaded) {
  10. $handle->file_new_name_body = $filename;
  11. $handle->Process($var['path']);
  12. if (!$handle->processed) echo 'error : ' . $handle->error;
  13. return $imagem = $handle->file_dst_name;
  14. }
  15. }
  16. }
  17. function nomeCategoria($cat)
  18. {
  19. switch ($cat) {
  20. case 'agenda': return 'Agenda';
  21. break;
  22. case 'noticia': return 'Notícia';
  23. break;
  24. case 'promocao': return 'Promoção';
  25. break;
  26. case 'show': return 'Show';
  27. default: return '[undefined]';
  28. }
  29. }
  30. function nomeCategoriaContato($cat)
  31. {
  32. switch ($cat) {
  33. case 'promocoes': return 'Promoções';
  34. break;
  35. case 'programacao': return 'Programação';
  36. break;
  37. case 'site': return 'Site';
  38. break;
  39. case 'suporte': return 'Suporte';
  40. break;
  41. case 'comercial': return 'Comercial';
  42. break;
  43. case 'arquivo-samba': return 'Arquivo Samba';
  44. break;
  45. case 'balanco-rap': return 'Balanço Rap';
  46. break;
  47. case 'black-105': return 'Black 105';
  48. break;
  49. case 'bom-dia-com-fe': return 'Bom dia com Fé';
  50. break;
  51. case 'charmin-love': return 'Chamin Love';
  52. break;
  53. case 'conexao-105-com-sandra-groth': return 'Conexão 105 com Sandra Groth';
  54. break;
  55. case 'encontro-das-tribos': return 'Encontro das Tribos';
  56. break;
  57. case 'espaco-rap': return 'Espaço Rap';
  58. break;
  59. case 'festa-da-105': return 'Festa da 105';
  60. break;
  61. case 'festa-dj-hum': return 'Festa DJ Hum';
  62. break;
  63. case 'portal-105fm': return 'Portal 105FM';
  64. break;
  65. case 'rap-du-bom': return 'Rap du Bom';
  66. break;
  67. case 'rede-nacional-do-samba': return 'Rede Nacional do Samba';
  68. break;
  69. case 'selecao-ouvinte-com-giuliano-faccio': return 'Seleção do Ouvinte com Giuliano Faccio';
  70. break;
  71. case 'selecao-ouvinte-com-fabiano-olivato': return 'Seleção do Ouvinte com Fabiano Olivato';
  72. break;
  73. case 'selecao-ouvinte-com-mauricio-oliveira': return 'Seleção do Ouvinte com Maurício Oliveira';
  74. break;
  75. case 'selecao-ouvinte-com-sandra-groth': return 'Seleção do Ouvinte com Sandra Groth';
  76. break;
  77. case 'toque-direto': return 'Toque Direto';
  78. break;
  79. case 'ofereca-uma-musica': return '"Ofereça uma música" no Toque Direto - Oferecimento Musical';
  80. break;
  81. case 'aniversario': return '"Coloque a data de seu aniversário" no Toque Direto - Aniversário do Dia';
  82. break;
  83. case 'caracteristicas': return '"Coloque suas características" no Toque Direto - Ponto de Encontro';
  84. break;
  85. case 'recados-imediatos': return 'Recados Imediatos';
  86. break;
  87. case 'festa-conexao': return 'Festa Conexão';
  88. break;
  89. default: return '[undefined]';
  90. }
  91. }
  92. function httpStatusCode($url) {
  93. $handle = curl_init($url);
  94. curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
  95. $response = curl_exec($handle);
  96. $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
  97. curl_close($handle);
  98. return $httpCode;
  99. }
  100. function getNormalizedFILES()
  101. {
  102. $newfiles = array();
  103. foreach($_FILES as $fieldname => $fieldvalue)
  104. foreach($fieldvalue as $paramname => $paramvalue)
  105. foreach((array)$paramvalue as $index => $value)
  106. $newfiles[$fieldname][$index][$paramname] = $value;
  107. return $newfiles;
  108. }
  109. /* format the result */
  110. function format_result($input)
  111. {
  112. return str_replace(array(' ', '(', ')'), array('-', '-', ''), $input);
  113. }
  114. /* helper: does regex */
  115. function get_match($regex,$content)
  116. {
  117. preg_match($regex,$content,$matches);
  118. return (isset($matches[1]) ? $matches[1] : false);
  119. }
  120. function estadoFromUF($uf) {
  121. switch($uf) {
  122. case 'AC': $estado = 'Acre';
  123. break;
  124. case 'AL': $estado = 'Alagoas';
  125. break;
  126. case 'AM': $estado = 'Amazonas';
  127. break;
  128. case 'AP': $estado = 'Amapá';
  129. break;
  130. case 'BA': $estado = 'Bahia';
  131. break;
  132. case 'CE': $estado = 'Ceará';
  133. break;
  134. case 'DF': $estado = 'Distrito Federal';
  135. break;
  136. case 'ES': $estado = 'Espirito Santo';
  137. break;
  138. case 'GO': $estado = 'Goiais';
  139. break;
  140. case 'MA': $estado = 'Maranhão';
  141. break;
  142. case 'MG': $estado = 'Minas Gerais';
  143. break;
  144. case 'MS': $estado = 'Mato Grosso do Sul';
  145. break;
  146. case 'MT': $estado = 'Mato Grosso';
  147. break;
  148. case 'PA': $estado = 'Pará';
  149. break;
  150. case 'PB': $estado = 'Paraíba';
  151. break;
  152. case 'PE': $estado = 'Pernambuco';
  153. break;
  154. case 'PI': $estado = 'Piauí';
  155. break;
  156. case 'PR': $estado = 'Paraná';
  157. break;
  158. case 'RJ': $estado = 'Rio de Janeiro';
  159. break;
  160. case 'RN': $estado = 'Rio Grande do Norte';
  161. break;
  162. case 'RO': $estado = 'Rondônia';
  163. break;
  164. case 'RR': $estado = 'Roraima';
  165. break;
  166. case 'RS': $estado = 'Rio Grande do Sul';
  167. break;
  168. case 'SC': $estado = 'Santa Catarina';
  169. break;
  170. case 'SE': $estado = 'Sergipe';
  171. break;
  172. case 'SP': $estado = 'São Paulo';
  173. break;
  174. case 'TO': $estado = 'Tocantins';
  175. break;
  176. default: $estado = 'Indefinido';
  177. break;
  178. }
  179. return $estado;
  180. }
  181. function cotacao($moeda='USD')
  182. {
  183. $cotacao = google_finance_convert($moeda, 'BRL', 1);
  184. return number_format($cotacao, 4,',','.');
  185. }
  186. function google_finance_convert($from_Currency, $to_Currency, $amount) {
  187. $amount = urlencode($amount);
  188. $from_Currency = urlencode($from_Currency);
  189. $to_Currency = urlencode($to_Currency);
  190. $url = "http://www.google.com/ig/calculator?q=$amount$from_Currency=?$to_Currency";
  191. $ch = curl_init();
  192. $timeout = 0;
  193. curl_setopt ($ch, CURLOPT_URL, $url);
  194. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  195. curl_setopt ($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
  196. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  197. $rawdata = curl_exec($ch);
  198. curl_close($ch);
  199. $data = explode('"', $rawdata);
  200. $data = explode(' ', $data[3]);
  201. $converted = $data[0];
  202. return $converted;
  203. }
  204. function full_url()
  205. {
  206. $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
  207. $sp = strtolower($_SERVER["SERVER_PROTOCOL"]);
  208. $protocol = substr($sp, 0, strpos($sp, "/")) . $s;
  209. $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
  210. return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
  211. }
  212. function bannerLaterial($banners, $i) {
  213. if (isset($banners['Lateral '.$i]) && is_array($banners['Lateral '.$i]) && count($banners['Lateral '.$i])>0) {
  214. $numBanners = (count($banners['Lateral '.$i])-1);
  215. $rand = rand(0, $numBanners);
  216. $banner = $banners['Lateral '.$i][$rand];
  217. plusBannerViews($banner['id']);
  218. if ($banner['type']<>'swf') {
  219. if (!empty($banner['link']))
  220. echo "<a href='{$banner['link']}' title='{$banner['titulo']}' target='_blank'>";
  221. echo "<img src='{$banner['imagem']}' border=0 alt='{$banner['titulo']}'/>";
  222. if (!empty($banner['link']))
  223. echo "</a>";
  224. } else {
  225. $incJS .= "
  226. /*
  227. *Vars Globais
  228. */
  229. var flashvarsGlob = {
  230. 'autostart': 'true'
  231. };
  232. var paramsGlob = {
  233. 'wmode': 'transparent',
  234. 'allowfullscreen': 'false',
  235. 'allowscriptaccess': 'always',
  236. 'bgcolor': '#ffffff'
  237. };
  238. var attributesGlob = {
  239. 'id': 'BannerLateral{$i}',
  240. 'name': 'BannerLateral{$i}'
  241. };
  242. swfobject.embedSWF('{$banner['imagem']}', 'bannerLateral 1', '115', '290', '9', 'false', flashvarsGlob, paramsGlob, attributesGlob);
  243. ";
  244. echo "\n\t\t<div id='bannerLateral {$i}'></div>";
  245. }
  246. }
  247. }
  248. function bannerHome($banners, $i) {
  249. if (isset($banners['Home Final '.$i]) && is_array($banners['Home Final '.$i]) && count($banners['Home Final '.$i])>0) {
  250. $numBanners = (count($banners['Home Final '.$i])-1);
  251. $rand = rand(0, $numBanners);
  252. $banner = $banners['Home Final '.$i][$rand];
  253. plusBannerViews($banner['id']);
  254. if ($banner['type']<>'swf') {
  255. if (!empty($banner['link']))
  256. echo "<a href='{$banner['link']}' title='{$banner['titulo']}' target='_blank'>";
  257. echo "<img src='{$banner['imagem']}' border=0 alt='{$banner['titulo']}'/>";
  258. if (!empty($banner['link']))
  259. echo "</a>";
  260. } else {
  261. $incJS .= "
  262. /*
  263. *Vars Globais
  264. */
  265. var flashvarsGlob = {
  266. 'autostart': 'true'
  267. };
  268. var paramsGlob = {
  269. 'wmode': 'transparent',
  270. 'allowfullscreen': 'false',
  271. 'allowscriptaccess': 'always',
  272. 'bgcolor': '#ffffff'
  273. };
  274. var attributesGlob = {
  275. 'id': 'BannerHomeFinal{$i}',
  276. 'name': 'BannerHomeFinal{$i}'
  277. };
  278. swfobject.embedSWF('{$banner['imagem']}', 'bannerHomeFinal {$i}', '115', '290', '9', 'false', flashvarsGlob, paramsGlob, attributesGlob);
  279. ";
  280. echo "\n\t\t<div id='bannerHomeFinal {$i}'></div>";
  281. }
  282. }
  283. }
  284. /*
  285. *retorna lista da coluna
  286. */
  287. /*
  288. function produtosByUF($order='titulo')
  289. {
  290. global $conn;
  291. $lst = array();
  292. $sql = "SELECT , cat_titulo FROM ".TP."_categoria WHERE cat_status=1 ORDER BY cat_{$order};";
  293. if(!$qry = $conn->prepare($sql))
  294. echo divAlert($conn->error, 'error');
  295. else {
  296. // $qry->bind_param('s', $area);
  297. $qry->execute();
  298. $qry->bind_result($id, $titulo);
  299. while ($qry->fetch()) {
  300. if ($min===true)
  301. $titulo = linkfySmart($titulo);
  302. $lst[$titulo] = $id;
  303. }
  304. $qry->close();
  305. }
  306. return $lst;
  307. }
  308. */
  309. /*
  310. *retorna lista de usuários
  311. */
  312. function getUsuarios($simple=true)
  313. {
  314. global $conn, $hashids;
  315. $whrFiltro = null;
  316. $list = array();
  317. $sql = "SELECT usr_id, usr_nome, usr_nome_fantasia
  318. FROM `".TP."_usuario`
  319. LEFT JOIN `".TP."_usuario_produto`
  320. ON upr_usr_id=usr_id
  321. AND upr_status=1
  322. WHERE usr_status=1
  323. {$whrFiltro}
  324. GROUP BY usr_id
  325. ORDER BY usr_nome_fantasia";
  326. if (!$res = $conn->prepare($sql))
  327. echo __FUNCTION__.$conn->error;
  328. else {
  329. $res->bind_result($id, $nome, $nomeFantasia);
  330. $res->execute();
  331. $i=0;
  332. while ($res->fetch()) {
  333. $empresa = empty($nomeFantasia) ? $nome : $nomeFantasia;
  334. if (!$simple)
  335. $i = linkfySmart($empresa);
  336. $list[$i]['id'] = $hashids->encrypt($id);
  337. $list[$i]['id_numeric'] = $id;
  338. $list[$i]['titulo'] = $empresa;
  339. if ($simple)
  340. $i++;
  341. }
  342. return $list;
  343. $res->close();
  344. }
  345. }
  346. /*
  347. *retorna lista de usuários dos classificados
  348. */
  349. function getUsuariosFromClassificados($simple=true)
  350. {
  351. global $conn, $hashids;
  352. $whrFiltro = null;
  353. $list = array();
  354. $sql = "SELECT usr_id, usr_nome, usr_nome_fantasia
  355. FROM `".TP."_usuario`
  356. INNER JOIN `".TP."_usuario_classificado`
  357. ON ucl_usr_id=usr_id
  358. AND ucl_status=1
  359. WHERE usr_status=1
  360. {$whrFiltro}
  361. GROUP BY usr_id
  362. ORDER BY usr_nome_fantasia";
  363. if (!$res = $conn->prepare($sql))
  364. echo __FUNCTION__.$conn->error;
  365. else {
  366. $res->bind_result($id, $nome, $nomeFantasia);
  367. $res->execute();
  368. $i=0;
  369. while ($res->fetch()) {
  370. $empresa = empty($nomeFantasia) ? $nome : $nomeFantasia;
  371. if (!$simple)
  372. $i = linkfySmart($empresa);
  373. $list[$i]['id'] = $hashids->encrypt($id);
  374. $list[$i]['id_numeric'] = $id;
  375. $list[$i]['titulo'] = $empresa;
  376. if ($simple)
  377. $i++;
  378. }
  379. return $list;
  380. $res->close();
  381. }
  382. }
  383. /*
  384. *retorna coluna do usuario
  385. */
  386. function getUsuarioEmpresaById($id)
  387. {
  388. global $conn, $hashids;
  389. $id = $hashids->decrypt($id);
  390. $id = isset($id[0]) ? $id[0] : null;
  391. if (empty($id))
  392. return 'ID inválido';
  393. $sql = "SELECT usr_nome, usr_nome_fantasia
  394. FROM `".TP."_usuario`
  395. LEFT JOIN `".TP."_usuario_produto`
  396. ON upr_usr_id=usr_id
  397. AND upr_status=1
  398. WHERE usr_status=1
  399. AND usr_id=?
  400. GROUP BY usr_id";
  401. if (!$res = $conn->prepare($sql))
  402. echo __FUNCTION__.$conn->error;
  403. else {
  404. $res->bind_param('i', $id);
  405. $res->bind_result($nome, $nomeFantasia);
  406. $res->execute();
  407. $res->fetch();
  408. $res->close();
  409. return (empty($nomeFantasia) ? $nome : $nomeFantasia);
  410. }
  411. }
  412. /*
  413. *retorna lista da localidades
  414. */
  415. function getLocalizacao()
  416. {
  417. global $conn;
  418. $whrFiltro = null;
  419. $listUf = array();
  420. $sqluf = "SELECT adb_uf, COUNT(upr_id) `num`
  421. FROM `".TP."_usuario_produto`
  422. LEFT JOIN ".TP."_address_book
  423. ON adb_usr_id=upr_usr_id
  424. INNER JOIN ".TP."_produto
  425. ON pro_id=upr_pro_id
  426. WHERE upr_status=1
  427. {$whrFiltro}
  428. GROUP BY adb_uf
  429. ORDER BY upr_timestamp DESC";
  430. if (!$resuf = $conn->prepare($sqluf))
  431. echo __FUNCTION__.$conn->error;
  432. else {
  433. $resuf->bind_result($uf, $num);
  434. $resuf->execute();
  435. $i=0;
  436. while ($resuf->fetch()) {
  437. $ufmin = strtolower($uf);
  438. $estado = estadoFromUF($uf);
  439. $listUf[$i]['id'] = empty($ufmin) ? 'none': $ufmin;
  440. $listUf[$i]['titulo'] = $estado.' ('.$num.')';
  441. $listUf[$i]['num'] = $num;
  442. $i++;
  443. }
  444. return $listUf;
  445. $resuf->close();
  446. }
  447. }
  448. /*
  449. *retorna lista da localidades dos classificados
  450. */
  451. function getLocalizacaoFromClassificados()
  452. {
  453. global $conn;
  454. $whrFiltro = null;
  455. $listUf = array();
  456. $sqluf = "SELECT adb_uf, COUNT(ucl_id) `num`
  457. FROM `".TP."_usuario_classificado`
  458. LEFT JOIN ".TP."_address_book
  459. ON adb_usr_id=ucl_usr_id
  460. WHERE ucl_status=1
  461. {$whrFiltro}
  462. GROUP BY adb_uf
  463. ORDER BY ucl_timestamp DESC";
  464. if (!$resuf = $conn->prepare($sqluf))
  465. echo __FUNCTION__.$conn->error;
  466. else {
  467. $resuf->bind_result($uf, $num);
  468. $resuf->execute();
  469. $i=0;
  470. while ($resuf->fetch()) {
  471. $ufmin = strtolower($uf);
  472. $estado = estadoFromUF($uf);
  473. $listUf[$i]['id'] = empty($ufmin) ? 'none': $ufmin;
  474. $listUf[$i]['titulo'] = $estado.' ('.$num.')';
  475. $listUf[$i]['num'] = $num;
  476. $i++;
  477. }
  478. return $listUf;
  479. $resuf->close();
  480. }
  481. }
  482. /*
  483. *retorna lista da coluna
  484. */
  485. function getCategoriaIdByTitulo($min=false, $order='titulo')
  486. {
  487. global $conn;
  488. /*
  489. *query da disciplina
  490. */
  491. $lst = array();
  492. $sql = "SELECT cat_id, cat_titulo FROM ".TP."_categoria WHERE cat_status=1 /*AND cat_area=?*/ ORDER BY cat_{$order};";
  493. if(!$qry = $conn->prepare($sql))
  494. echo divAlert($conn->error, 'error');
  495. else {
  496. // $qry->bind_param('s', $area);
  497. $qry->execute();
  498. $qry->bind_result($id, $titulo);
  499. while ($qry->fetch()) {
  500. if ($min===true)
  501. $titulo = linkfySmart($titulo);
  502. $lst[$titulo] = $id;
  503. }
  504. $qry->close();
  505. }
  506. return $lst;
  507. }
  508. /*
  509. *retorna lista de produtos
  510. */
  511. function getTodosProdutos($order='titulo ASC', $startwith=null, $simple=true)
  512. {
  513. global $conn;
  514. $order = !empty($order) ? $order : 'titulo ASC';
  515. $whr = null;
  516. $sql = "SELECT
  517. pro_id,
  518. pro_titulo,
  519. pro_tipo,
  520. pro_valor
  521. FROM ".TP."_produto
  522. WHERE pro_status=1
  523. ORDER BY pro_{$order};";
  524. $lst = array();
  525. if(!$qry = $conn->prepare($sql))
  526. echo divAlert($conn->error, 'error');
  527. else {
  528. $qry->execute();
  529. $qry->bind_result($id, $titulo, $tipo, $valor);
  530. if (!empty($startwith))
  531. $lst[0] = array('id'=>0, 'titulo'=>$startwith);
  532. $i=1;
  533. while ($qry->fetch()) {
  534. if (!$simple)
  535. $i = linkfySmart($titulo);
  536. $lst[$i]['id'] = $id;
  537. $lst[$i]['titulo'] = mb_strtoupper($titulo, 'utf8');
  538. $lst[$i]['tipo'] = $tipo;
  539. $lst[$i]['valor'] = 'R$ '.Moeda($valor);
  540. $lst[$i]['valor_decimal'] = $valor;
  541. if ($simple)
  542. $i++;
  543. }
  544. $qry->close();
  545. return $lst;
  546. }
  547. }
  548. /*
  549. *retorna lista de produtos
  550. */
  551. function getProdutosByOptions($option, $startwith=null, $order='titulo', $userProducts=false)
  552. {
  553. global $conn, $hashids;
  554. $whr = null;
  555. if (is_array($option))
  556. foreach ($option as $optkey=>$optval) {
  557. if (!empty($optval))
  558. $whr .= " AND pro_{$optkey}=\"{$optval}\"";
  559. }
  560. if ($userProducts===true)
  561. $sql = "SELECT * FROM (
  562. SELECT
  563. upr_id,
  564. COALESCE(NULLIF(pro_titulo,''), upr_nomeProduto) `produto`,
  565. upr_valor
  566. FROM ".TP."_usuario_produto
  567. INNER JOIN ".TP."_usuario
  568. ON upr_usr_id=usr_id
  569. AND usr_status=1
  570. LEFT JOIN ".TP."_produto
  571. ON pro_id=upr_pro_id
  572. AND pro_status=1
  573. WHERE upr_status=1
  574. {$whr}
  575. ) as `tmp`
  576. GROUP BY `produto`
  577. ORDER BY `produto`;";
  578. else
  579. $sql = "SELECT * FROM (
  580. SELECT
  581. pro_id,
  582. COALESCE(NULLIF(pro_titulo,''), upr_nomeProduto) `produto`,
  583. pro_valor
  584. FROM ".TP."_produto
  585. WHERE pro_status=1
  586. {$whr}
  587. GROUP BY pro_id
  588. ) as `tmp`
  589. ORDER BY `produto`;";
  590. $lst = array();
  591. if(!$qry = $conn->prepare($sql))
  592. echo divAlert($conn->error, 'error');
  593. else {
  594. $qry->execute();
  595. $qry->bind_result($id, $titulo, $valor);
  596. if (!empty($startwith))
  597. $lst[0] = array('id'=>0, 'titulo'=>$startwith);
  598. $i=1;
  599. while ($qry->fetch()) {
  600. // $lst[$i]['id'] = $id;
  601. $lst[$i]['id'] = mb_strtolower(urlencode($titulo), 'utf8');
  602. $lst[$i]['titulo'] = mb_strtoupper($titulo, 'utf8');
  603. $lst[$i]['valor'] = 'R$ '.Moeda($valor);
  604. $lst[$i]['valor_decimal'] = $valor;
  605. $i++;
  606. }
  607. $qry->close();
  608. return $lst;
  609. }
  610. }
  611. /*
  612. *retorna lista de classificados
  613. */
  614. function getClassificadosByOptions($option, $startwith=null, $order='titulo')
  615. {
  616. global $conn, $hashids;
  617. $whr = null;
  618. if (is_array($option))
  619. foreach ($option as $optkey=>$optval) {
  620. if (!empty($optval))
  621. $whr .= " AND ucl_{$optkey}=\"{$optval}\"";
  622. }
  623. $sql = "SELECT * FROM (
  624. SELECT
  625. ucl_id,
  626. ucl_titulo `produto`,
  627. ucl_valor
  628. FROM ".TP."_usuario_classificado
  629. INNER JOIN ".TP."_usuario
  630. ON ucl_usr_id=usr_id
  631. AND usr_status=1
  632. WHERE ucl_status=1
  633. {$whr}
  634. ) as `tmp`
  635. GROUP BY `produto`
  636. ORDER BY `produto`;";
  637. $lst = array();
  638. if(!$qry = $conn->prepare($sql))
  639. echo divAlert($conn->error, 'error');
  640. else {
  641. $qry->execute();
  642. $qry->bind_result($id, $titulo, $valor);
  643. if (!empty($startwith))
  644. $lst[0] = array('id'=>0, 'titulo'=>$startwith);
  645. $i=1;
  646. while ($qry->fetch()) {
  647. // $lst[$i]['id'] = $id;
  648. $lst[$i]['id'] = mb_strtolower(urlencode($titulo), 'utf8');
  649. $lst[$i]['titulo'] = mb_strtoupper($titulo, 'utf8');
  650. $lst[$i]['valor'] = 'R$ '.Moeda($valor);
  651. $lst[$i]['valor_decimal'] = $valor;
  652. $i++;
  653. }
  654. $qry->close();
  655. return $lst;
  656. }
  657. }
  658. /*
  659. *retorna lista da coluna
  660. */
  661. function getCategoriaListArea($area, $rel=null, $startwith=null, $limit=null, $groupby=null, $order='titulo')
  662. {
  663. global $conn;
  664. $_groupby = null;
  665. if (!empty($groupby))
  666. $_groupby = "GROUP BY ".$groupby;
  667. /*
  668. *query da disciplina
  669. */
  670. $areaQry = !empty($area) ? ' AND cat_area=? ' : null;
  671. $relQry = !empty($rel) ? ' AND cat_idrel=? ' : null;
  672. $limitQry = !empty($limit) ? ' LIMIT 0, '.$limit : null;
  673. $sql = "SELECT cat_id, cat_titulo FROM ".TP."_categoria WHERE cat_status=1 {$areaQry} {$relQry} {$_groupby} ORDER BY cat_{$order} {$limitQry};";
  674. $lst = array();
  675. if(!$qry = $conn->prepare($sql))
  676. echo divAlert($conn->error, 'error');
  677. else {
  678. if (empty($relQry) && !empty($area))
  679. $qry->bind_param('s', $area);
  680. elseif (isset($rel) && !empty($area))
  681. $qry->bind_param('si', $area, $rel);
  682. $qry->execute();
  683. $qry->bind_result($id, $titulo);
  684. if (!empty($startwith))
  685. $lst[0] = array('id'=>0, 'titulo'=>$startwith);
  686. $i=1;
  687. while ($qry->fetch()) {
  688. $lst[$i]['id'] = $id;
  689. $lst[$i]['titulo'] = $titulo;
  690. $i++;
  691. }
  692. $qry->close();
  693. return $lst;
  694. }
  695. }
  696. /*
  697. *retorna lista da coluna
  698. */
  699. function convertCatList2Option($var, $selected=null)
  700. {
  701. $opt = null;
  702. foreach ($var as $int=>$val) {
  703. if (isset($val['id']) && isset($val['titulo'])) {
  704. $opt .= "<option value='{$val['id']}'";
  705. if(isset($selected) && $selected==$val['id'])
  706. $opt .= ' selected=selected';
  707. $opt .=">{$val['titulo']}</option>";
  708. }
  709. }
  710. return $opt;
  711. }
  712. function aesEncrypt($val)
  713. {
  714. include_once "vendor/phpAES/AES.class.php";
  715. $z = "abcdefghijuklmno0123456789012345";
  716. $aes = new AES($z);
  717. return base64_encode($aes->encrypt($val));
  718. }
  719. function replaceQueryStringVar($url, $key, $replaceVal) {
  720. if (isset($_GET[$key])) {
  721. $url = str_replace("{$key}={$_GET[$key]}", "{$key}={$replaceVal}", $url);
  722. } else {
  723. if (strpos($url, '?')!==false)
  724. $url .= "&{$key}=".$replaceVal;
  725. else
  726. $url .= "?{$key}=".$replaceVal;
  727. }
  728. return $url;
  729. }
  730. function removeQueryStringVar($url, $key) {
  731. $url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
  732. $url = substr($url, 0, -1);
  733. return $url;
  734. }
  735. /**
  736. * FAZ BUSCA NO ARRAY
  737. */
  738. function searchInArray($array, $key=null, $value=null)
  739. {
  740. $results = array();
  741. if (is_array($array))
  742. {
  743. if (isset($array[$key]) && $array[$key] == $value)
  744. $results[] = $array;
  745. foreach ($array as $subarray)
  746. $results = array_merge($results, searchInArray($subarray, $key, $value));
  747. }
  748. return $results;
  749. }
  750. /**
  751. * Get either a Gravatar URL or complete image tag for a specified email address.
  752. *
  753. * @param string $email The email address
  754. * @param string $s Size in pixels, defaults to 80px [ 1 - 2048 ]
  755. * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
  756. * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
  757. * @param boole $img True to return a complete IMG tag False for just the URL
  758. * @param array $atts Optional, additional key/value attributes to include in the IMG tag
  759. * @return String containing either just a URL or a complete image tag
  760. * @source http://gravatar.com/site/implement/images/php/
  761. */
  762. function get_gravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
  763. $url = 'http://www.gravatar.com/avatar/';
  764. $url .= md5( strtolower( trim( $email ) ) );
  765. $url .= "?s=$s&d=$d&r=$r";
  766. if ( $img ) {
  767. $url = '<img src="' . $url . '"';
  768. foreach ( $atts as $key => $val )
  769. $url .= ' ' . $key . '="' . $val . '"';
  770. $url .= ' />';
  771. }
  772. return $url;
  773. }
  774. /*
  775. * RESGATA NOME DO EVENTO
  776. */
  777. function getEventName($item)
  778. {
  779. global $conn;
  780. $item = apenasNumeros($item);
  781. if (empty($item))
  782. exit(__FUNCTION__.' Informe um id!');
  783. $sql= "SELECT eve_titulo FROM ".TP."_evento WHERE eve_id=?";
  784. if (!$qry=$conn->prepare($sql))
  785. return divAlert($conn->error);
  786. else {
  787. $qry->bind_param('i', $item);
  788. $qry->bind_result($titulo);
  789. $qry->execute();
  790. $qry->fetch();
  791. $qry->close();
  792. return $titulo;
  793. }
  794. }
  795. /**
  796. * VALIDA URL
  797. */
  798. function validaURL($url) {
  799. return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
  800. // return var_dump(filter_var($url, FILTER_VALIDATE_URL));
  801. }
  802. /*
  803. * parse url text to html link
  804. */
  805. /*
  806. function parseUrlText2Link($text, $class)
  807. {
  808. $regex = "\^(https?|ftp|telnet):\/\/((?:[a-z0-9@:.-]|%[0-9A-F]{2}){3,})(?::(\d+))?((?:\/(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})*)*)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:\/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:\/?@]|%[0-9A-F]{2})*))?$/i";
  809. return preg_replace($regex, '<a href="$1" class="'.$class.'" target="_blank">$1</a>', $text);
  810. }
  811. */
  812. /*
  813. *CONVERTE @USER PARA <a href="https://twitter.com/user">user</a>
  814. */
  815. function convertTwitterUserText2Link($text, $hashtags=false, $class=null)
  816. {
  817. if ($hashtags)
  818. $text = convertTwitterHashtag2Link($text, $class);
  819. // $text = parseUrlText2Link($text, $class);
  820. $regex = "/(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)/i";
  821. return preg_replace($regex, '<a href="https://twitter.com/$1" class="'.$class.'" target="_blank">@$1</a>', $text);
  822. }
  823. /*
  824. *CONVERTE #SEARCH PARA <a href="https://twitter.com/search/%23search">search</a>
  825. */
  826. function convertTwitterHashtag2Link($text, $class=null)
  827. {
  828. $regex = "/(?<=^|(?<=[^a-zA-Z0-9-_\.]))#([A-Za-z]+[A-Za-z0-9]+)/i";
  829. return preg_replace($regex, '<a href="https://twitter.com/search/%23$1" class="'.$class.'" target="_blank">#$1</a>', $text);
  830. }
  831. /*
  832. * retorna ultimos tweets
  833. */
  834. function getLastTweets($username, $limit=5) {
  835. $feed = 'http://twitter.com/statuses/user_timeline.rss?screen_name='.$username.'&count='.$limit;
  836. $tweets = file_get_contents($feed);
  837. $feed = new SimpleXMLElement($tweets);
  838. $tweetout = array();
  839. foreach($feed->channel->item as $tweet) {
  840. $tweetout[] = $tweet;
  841. }
  842. $tweetout = json_encode($tweetout);
  843. $tweetout = json_decode($tweetout, true);
  844. return $tweetout;
  845. }
  846. /*
  847. *Retorna xml do video
  848. */
  849. function getYoutubeVideoId($url) {
  850. if (strpos($url, 'http://www.youtube.com/watch?v=') === 0) {
  851. //ini_set("allow_url_fopen", 1); //função habilitada
  852. //ini_set("allow_url_include", 1); //função habilitada
  853. $urlArray = explode("=", $url);
  854. $urlArray = explode("&", $urlArray[1]);
  855. $videoid = trim($urlArray[0]);
  856. //$videourl="http://www.youtube.com/api2_rest?method=youtube.videos.get_video_token&video_id=$videoid";
  857. //$t = trim(strip_tags(@file_get_contents($videourl)));
  858. return $videoid;
  859. } else
  860. exit("Wrong URL / Parameters");
  861. }
  862. /*
  863. *salva codigo na tabela
  864. */
  865. function saveTableCode($var, $item, $salt=null)
  866. {
  867. global $conn;
  868. if (empty($item))
  869. exit(__FUNCTION__.' Informe um id!');
  870. if (!is_array($var))
  871. exit(__FUNCTION__.' Argumento válido!');
  872. /**
  873. *SAVE CODE
  874. */
  875. $sql= "UPDATE ".TP."_${var['path']} SET ${var['pre']}_code=? WHERE ${var['pre']}_id=?";
  876. if (!$qry=$conn->prepare($sql))
  877. return divAlert($conn->error);
  878. else {
  879. $code = newCode($salt);
  880. $qry->bind_param('si', $code, $item);
  881. $qry->execute();
  882. $qry->close();
  883. if (saveCode($code))
  884. return $code;
  885. }
  886. }
  887. /*
  888. *gera codigo unico
  889. */
  890. function saveCode($code)
  891. {
  892. global $conn;
  893. if (empty($code))
  894. exit(__FUNCTION__.' Informe um código!');
  895. $sql = "INSERT INTO `".TP."_generated_codes` (`code`) VALUES (?)";
  896. if (!$res = $conn->prepare($sql))
  897. return $conn->error;
  898. else {
  899. $res->bind_param('s', $code);
  900. $res->execute();
  901. $res->close();
  902. return true;
  903. }
  904. }
  905. /*
  906. *gera codigo unico
  907. */
  908. function newCode($var=null, $maxchar=6)
  909. {
  910. global $conn;
  911. //gera o código e verifica se ele já existe antes de continuar
  912. do {
  913. $_code = generateHash($var);
  914. $_code = justAlphanumeric($_code);
  915. $code = substr($_code, 0, $maxchar);
  916. if (strlen($code)!=$maxchar)
  917. $num=1;
  918. else {
  919. $sql = "SELECT NULL FROM `".TP."_generated_codes` WHERE `code`=\"$code\"";
  920. $res = $conn->query($sql);
  921. $num = $res->num_rows;
  922. }
  923. } while ($num>0);
  924. return $code;
  925. }
  926. /*
  927. *gera um hash unico, unique
  928. */
  929. function generateHash($key, $crypt=false)
  930. {
  931. $salt = pseudoRandomKey(256);
  932. $hash = null;
  933. for ($i=0; $i<100; $i++) {
  934. $hash = hash('sha512', $hash.$salt.$key);
  935. }
  936. //return $hash;
  937. if ($crypt)
  938. return encrypt($hash, $key);
  939. else
  940. return $hash;
  941. }
  942. /*
  943. *RANDOM KEY
  944. */
  945. function pseudoRandomKey($size, $strong=true)
  946. {
  947. if (function_exists('openssl_random_pseudo_bytes')) {
  948. $random = openssl_random_pseudo_bytes($size, $strong);
  949. openssl_random_pseudo_bytes($size, $strong);
  950. }
  951. $sha='';
  952. $rnd='';
  953. for ($i=0;$i<$size;$i++) {
  954. $sha = hash('sha256', $random . mt_rand());
  955. $char= mt_rand(0, 62);
  956. $rnd.= chr(hexdec($sha[$char] . $sha[$char+1]));
  957. }
  958. return $rnd;
  959. }
  960. /*
  961. *apenas letras e numeros
  962. */
  963. function justAlphanumeric($var)
  964. {
  965. return preg_replace('/[^0-9A-Za-z]/', '', $var);
  966. }
  967. /*
  968. *retorna apenas os numeros
  969. */
  970. function justNumbers($var)
  971. {
  972. return preg_replace('/[^0-9]/', '', $var);
  973. }
  974. /*
  975. *retorna valor da coluna
  976. */
  977. function getUrlNoticia($not_id)
  978. {
  979. global $conn;
  980. /*
  981. *query da disciplina
  982. */
  983. $sql = "SELECT not_titulo ".TABLE_PREFIX."_noticia SET auto_views=auto_views+1 WHERE not_id=?";
  984. if(!$qry = $conn->prepare($sql))
  985. return false;
  986. else {
  987. $qry->bind_param('i', $not_id);
  988. $qry->bind_result($titulo);
  989. $qry->execute();
  990. $qry->fetch();
  991. $qry->close();
  992. return ABSPATH."noticias/{$id}/".linkfy($titulo);
  993. }
  994. }
  995. function encrypt($_input, $_key='your salt', $_type='mcrypt')
  996. {
  997. /*
  998. *if exists mcrypt and $_type is mcrypt
  999. */
  1000. if (function_exists('mcrypt') && $_type=='mcrypt') {
  1001. $td = mcrypt_module_open(MCRYPT_TWOFISH256, '', 'ofb', '');
  1002. $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_BLOWFISH);
  1003. mcrypt_generic_init($td, $_key, $iv);
  1004. $encryptedData = mcrypt_generic($td, $_input);
  1005. mcrypt_generic_deinit($td);
  1006. mcrypt_module_close($td);
  1007. //else use md5
  1008. } else {
  1009. if(version_compare(PHP_VERSION, '5.0.0', '>='))
  1010. $bool = true;
  1011. else $bool = false;
  1012. $encryptedKey = md5($_key, $bool) . md5($_input, $bool);
  1013. $encryptedData = md5($encryptedKey, $bool);
  1014. }
  1015. // return generated password
  1016. // enjoy
  1017. return utf8_encode($encryptedData);
  1018. }
  1019. /*
  1020. *retorna valor da coluna
  1021. */
  1022. function plusBannerViews($ban_id)
  1023. {
  1024. global $conn;
  1025. $ip = $_SERVER['REMOTE_ADDR'];
  1026. if (!isset($_SESSION[TP]['banner_views'][$ip][$ban_id]) || $_SESSION[TP]['banner_views'][$ip][$ban_id]!=date('Y-m-d')) {
  1027. $sql = "UPDATE ".TABLE_PREFIX."_banner SET ban_views=ban_views+1 WHERE ban_id=?";
  1028. if(!$qry = $conn->prepare($sql))
  1029. return false;
  1030. else {
  1031. $qry->bind_param('i', $ban_id);
  1032. $qry->execute();
  1033. $qry->close();
  1034. $_SESSION[TP]['banner_views'][$ip][$ban_id] = date('Y-m-d');
  1035. return true;
  1036. }
  1037. }
  1038. }
  1039. /*
  1040. *retorna valor da coluna
  1041. */
  1042. function plusBannerClicks($ban_id)
  1043. {
  1044. global $conn;
  1045. $ip = $_SERVER['REMOTE_ADDR'];
  1046. if (!isset($_SESSION[TP]['banner_clicks'][$ip][$ban_id]) || $_SESSION[TP]['banner_clicks'][$ip][$ban_id]!=date('Y-m-d')) {
  1047. $sql = "UPDATE ".TABLE_PREFIX."_banner SET ban_clicks=ban_clicks+1 WHERE ban_id=?";
  1048. if(!$qry = $conn->prepare($sql))
  1049. return false;
  1050. else {
  1051. $qry->bind_param('i', $ban_id);
  1052. $qry->execute();
  1053. $qry->close();
  1054. $_SESSION[TP]['banner_clicks'][$ip][$ban_id] = date('Y-m-d');
  1055. return true;
  1056. }
  1057. }
  1058. }
  1059. /*
  1060. *retorna valor da coluna
  1061. */
  1062. function getProdutoCol($col, $ref, $rel)
  1063. {
  1064. global $conn;
  1065. /*
  1066. *query da disciplina
  1067. */
  1068. $sql = "SELECT pro_{$col} FROM ".TABLE_PREFIX."_produto WHERE pro_{$ref}=?";
  1069. if(!$qry = $conn->prepare($sql))
  1070. echo divAlert($conn->error, 'error');
  1071. else {
  1072. if (!apenasNumeros($rel))
  1073. $qry->bind_param('s', $rel);
  1074. else
  1075. $qry->bind_param('i', $rel);
  1076. $qry->execute();
  1077. $qry->bind_result($$col);
  1078. $qry->fetch();
  1079. $qry->close();
  1080. return $$col;
  1081. }
  1082. }
  1083. /*
  1084. *retorna valor da coluna
  1085. */
  1086. function getCategoriaCol($col, $ref, $rel)
  1087. {
  1088. global $conn;
  1089. /*
  1090. *query da disciplina
  1091. */
  1092. $sql = "SELECT cat_{$col} FROM ".TABLE_PREFIX."_categoria WHERE cat_{$ref}=?";
  1093. if(!$qry = $conn->prepare($sql))
  1094. echo divAlert($conn->error, 'error');
  1095. else {
  1096. $qry->bind_param('s', $rel);
  1097. $qry->execute();
  1098. $qry->bind_result($$col);
  1099. $qry->fetch();
  1100. $qry->close();
  1101. return $$col;
  1102. }
  1103. }
  1104. /*
  1105. *retorna mes por extenso
  1106. */
  1107. function mesExtenso($mes, $type='min')
  1108. {
  1109. if (!empty($mes)) {
  1110. switch ($mes) {
  1111. case 1:
  1112. case 01:
  1113. $mesMin = 'Jan';
  1114. $mesFull = 'Janeiro';
  1115. break;
  1116. case 2:
  1117. case 02:
  1118. $mesMin = 'Fev';
  1119. $mesFull = 'Fevereiro';
  1120. break;
  1121. case 3:
  1122. case 03:
  1123. $mesMin = 'Mar';
  1124. $mesFull = 'Março';
  1125. break;
  1126. case 4:
  1127. case 04:
  1128. $mesMin = 'Abr';
  1129. $mesFull = 'Abril';
  1130. break;
  1131. case 5:
  1132. case 05:
  1133. $mesMin = 'Mai';
  1134. $mesFull = 'Maio';
  1135. break;
  1136. case 6:
  1137. case 06:
  1138. $mesMin = 'Jun';
  1139. $mesFull = 'Junho';
  1140. break;
  1141. case 7:
  1142. case 07:
  1143. $mesMin = 'Jul';
  1144. $mesFull = 'Julho';
  1145. break;
  1146. case 8:
  1147. case 08:
  1148. $mesMin = 'Ago';
  1149. $mesFull = 'Agosto';
  1150. break;
  1151. case 9:
  1152. case 09:
  1153. $mesMin = 'Set';
  1154. $mesFull = 'Setembro';
  1155. break;
  1156. case 10:
  1157. $mesMin = 'Out';
  1158. $mesFull = 'Outubro';
  1159. break;
  1160. case 11:
  1161. $mesMin = 'Nov';
  1162. $mesFull = 'Novembro';
  1163. break;
  1164. case 12:
  1165. $mesMin = 'Dez';
  1166. $mesFull = 'Dezembro';
  1167. break;
  1168. }
  1169. if ($type=='min')
  1170. return $mesMin;
  1171. else
  1172. return $mesFull;
  1173. }
  1174. }
  1175. /*
  1176. *retorna array com todas as disciplinas
  1177. */
  1178. function getListAgencias($age=false)
  1179. {
  1180. global $conn;
  1181. /*
  1182. *query da disciplina
  1183. */
  1184. $sqla = "SELECT
  1185. adm_id,
  1186. adm_nome,
  1187. adm_status,
  1188. (SELECT age_id FROM ".TP."_agencia WHERE age_adm_id=adm_id) age_id,
  1189. adm_email
  1190. FROM ".TABLE_PREFIX."_administrador
  1191. WHERE adm_tipo='Agência'
  1192. ORDER BY adm_nome";
  1193. $agencia = $agenciaage = array();
  1194. if(!$qrya = $conn->prepare($sqla))
  1195. return false;
  1196. else {
  1197. $qrya->execute();
  1198. $qrya->bind_result($id, $nome, $status, $age_id, $email);
  1199. while ($qrya->fetch()) {
  1200. $agencia[$id] = array('id'=>$id, 'age_id'=>$age_id, 'nome'=>$nome, 'email'=>$email, 'status'=>$status);
  1201. $agenciaage[$age_id] = array('id'=>$id, 'age_id'=>$age_id, 'nome'=>$nome, 'email'=>$email, 'status'=>$status);
  1202. }
  1203. if (!$age)
  1204. return $agencia;
  1205. else
  1206. return $agenciaage;
  1207. $qrya->close();
  1208. }
  1209. }
  1210. /*
  1211. *retorna array com todas as disciplinas
  1212. */
  1213. function getListMarca()
  1214. {
  1215. global $conn;
  1216. /*
  1217. *query da disciplina
  1218. */
  1219. $sqld = "SELECT
  1220. cat_id,
  1221. cat_titulo
  1222. FROM ".TABLE_PREFIX."_categoria
  1223. WHERE cat_status=1 AND cat_area='Marca'
  1224. ORDER BY cat_titulo";
  1225. $disciplina = array();
  1226. if(!$qryd = $conn->prepare($sqld))
  1227. echo divAlert($conn->error, 'error');
  1228. else {
  1229. $qryd->execute();
  1230. $qryd->bind_result($id, $titulo);
  1231. while ($qryd->fetch())
  1232. $disciplina[$id] = $titulo;
  1233. $qryd->close();
  1234. }
  1235. return $disciplina;
  1236. }
  1237. /*
  1238. *retorna array com todas as disciplinas
  1239. */
  1240. function getListModelo()
  1241. {
  1242. global $conn;
  1243. /*
  1244. *query da disciplina
  1245. */
  1246. $sqld = "SELECT
  1247. cat_id,
  1248. cat_titulo
  1249. FROM ".TABLE_PREFIX."_categoria
  1250. WHERE cat_status=1 AND cat_area='Modelo'
  1251. ORDER BY cat_titulo";
  1252. $disciplina = array();
  1253. if(!$qryd = $conn->prepare($sqld))
  1254. echo divAlert($conn->error, 'error');
  1255. else {
  1256. $qryd->execute();
  1257. $qryd->bind_result($id, $titulo);
  1258. while ($qryd->fetch())
  1259. $disciplina[$id] = $titulo;
  1260. $qryd->close();
  1261. }
  1262. return $disciplina;
  1263. }
  1264. /*
  1265. *retorna array com todas as disciplinas
  1266. */
  1267. function getListOpcional()
  1268. {
  1269. global $conn;
  1270. /*
  1271. *query da disciplina
  1272. */
  1273. $sqld = "SELECT
  1274. cat_id,
  1275. cat_titulo
  1276. FROM ".TABLE_PREFIX."_categoria
  1277. WHERE cat_status=1 AND cat_area='Disciplinas'
  1278. ORDER BY cat_titulo";
  1279. $opc = array();
  1280. if(!$qryd = $conn->prepare($sqld))
  1281. echo divAlert($conn->error, 'error');
  1282. else {
  1283. $qryd->execute();
  1284. $qryd->bind_result($id, $titulo);
  1285. while ($qryd->fetch())
  1286. $opc[$id] = $titulo;
  1287. $qryd->close();
  1288. }
  1289. return $opc;
  1290. }
  1291. /*
  1292. *mostra mensagens de erro com css
  1293. */
  1294. function divAlert($msg, $type='error')
  1295. {
  1296. $alert = "<div class='alert alert-{$type}'>";
  1297. $alert.= "<a class='close' data-dismiss='alert'>×</a>";
  1298. $alert.= $msg;
  1299. $alert.= "</div>";
  1300. return $alert;
  1301. }
  1302. //-----------------------------------------------------
  1303. //Funcao: validaCNPJ($cnpj)
  1304. //Sinopse: Verifica se o valor passado é um CNPJ válido
  1305. // Retorno: Booleano
  1306. // Autor: Gabriel Fróes - www.codigofonte.com.br
  1307. //-----------------------------------------------------
  1308. function validaCNPJ($cnpj)
  1309. {
  1310. if (strlen($cnpj) <> 18) return 0;
  1311. $soma1 = ($cnpj[0] * 5) +
  1312. ($cnpj[1] * 4) +
  1313. ($cnpj[3] * 3) +
  1314. ($cnpj[4] * 2) +
  1315. ($cnpj[5] * 9) +
  1316. ($cnpj[7] * 8) +
  1317. ($cnpj[8] * 7) +
  1318. ($cnpj[9] * 6) +
  1319. ($cnpj[11] * 5) +
  1320. ($cnpj[12] * 4) +
  1321. ($cnpj[13] * 3) +
  1322. ($cnpj[14] * 2);
  1323. $resto = $soma1 % 11;
  1324. $digito1 = $resto < 2 ? 0 : 11 - $resto;
  1325. $soma2 = ($cnpj[0] * 6) +
  1326. ($cnpj[1] * 5) +
  1327. ($cnpj[3] * 4) +
  1328. ($cnpj[4] * 3) +
  1329. ($cnpj[5] * 2) +
  1330. ($cnpj[7] * 9) +
  1331. ($cnpj[8] * 8) +
  1332. ($cnpj[9] * 7) +
  1333. ($cnpj[11] * 6) +
  1334. ($cnpj[12] * 5) +
  1335. ($cnpj[13] * 4) +
  1336. ($cnpj[14] * 3) +
  1337. ($cnpj[16] * 2);
  1338. $resto = $soma2 % 11;
  1339. $digito2 = $resto < 2 ? 0 : 11 - $resto;
  1340. return (($cnpj[16] == $digito1) && ($cnpj[17] == $digito2));
  1341. }
  1342. /*
  1343. *valida CPF
  1344. */
  1345. function validaCPF($cpf)
  1346. { // Verifiva se o número digitado contém todos os digitos
  1347. $cpf = str_pad(preg_replace('/[^0-9]/', '', $cpf), 11, '0', STR_PAD_LEFT);
  1348. // Verifica se nenhuma das sequências abaixo foi digitada, caso seja, retorna falso
  1349. if (strlen($cpf) != 11 || $cpf == '00000000000' || $cpf == '11111111111' || $cpf == '22222222222' || $cpf == '33333333333' || $cpf == '44444444444' || $cpf == '55555555555' || $cpf == '66666666666' || $cpf == '77777777777' || $cpf == '88888888888' || $cpf == '99999999999')
  1350. {
  1351. return false;
  1352. }
  1353. else
  1354. { // Calcula os números para verificar se o CPF é verdadeiro
  1355. for ($t = 9; $t < 11; $t++) {
  1356. for ($d = 0, $c = 0; $c < $t; $c++) {
  1357. $d += $cpf{$c} * (($t + 1) - $c);
  1358. }
  1359. $d = ((10 * $d) % 11) % 10;
  1360. if ($cpf{$c} != $d) {
  1361. return false;
  1362. }
  1363. }
  1364. return true;
  1365. }
  1366. }
  1367. /*
  1368. *valida data
  1369. */
  1370. function validaData ($ano, $mes, $dia)
  1371. {
  1372. return checkdate($mes, $dia, $ano);
  1373. }
  1374. /*
  1375. *valida data nascimento
  1376. */
  1377. function validaNascimento($ano, $mes, $dia)
  1378. {
  1379. $dataCheck = $ano.'-'.$mes.'-'.$dia;
  1380. if (checkdate($mes, $dia, $ano) && $dataCheck<=date('Y-m-d'))
  1381. return true;
  1382. else return false;
  1383. }
  1384. /*
  1385. *show javascript modal
  1386. */
  1387. function showModal($args)
  1388. {
  1389. global $res;
  1390. $modalHeader = $closeButton = null;
  1391. if (!is_array($args))
  1392. exit('Parametro inválido');
  1393. if (is_array($args) && count($args)==1 && !isset($args['content']))
  1394. $args['content'] = $args[0];
  1395. if (!isset($args['button']['param']))
  1396. $args['button']['param'] = null;
  1397. if (!isset($args['button']['link']))
  1398. $args['button']['link'] = null;
  1399. if (!isset($args['button']['value']))
  1400. $args['button']['value'] = null;
  1401. if (!isset($args['button']['class']))
  1402. $args['button']['class'] = null;
  1403. $closeButton = 'Fechar';
  1404. //$closeButton = !empty($args['button']['value']) ? 'Cancelar' : 'Fechar';
  1405. if (isset($args['title']))
  1406. $modalHeader = "<div class='modal-header'> <a class='close' data-dismiss='modal'>×</a> <h3>{$args['title']}</h3> </div>";
  1407. else
  1408. $modalHeader = "<div class='modal-header'> <a class='close' data-dismiss='modal'>×</a> </div>";
  1409. $js = null;
  1410. $js .= "\n\t\tvar template = \"<div class='fixedVersion'><div class='modal fade hide' id='msg-modal'>\";
  1411. template += \"{$modalHeader}\";
  1412. template += \"<div class='modal-body'>\";
  1413. template += \"<p>{$args['content']}</p>\";
  1414. template += \"</div>\";
  1415. template += \"<div class='modal-footer'>\";";
  1416. if (!isset($args['button']['close']) || $args['button']['close']==true)
  1417. $js .= "\n\t\ttemplate += \" <a href='javascript:void(0);' class='btn' data-dismiss='modal'>{$closeButton}</a>\";";
  1418. if (!empty($args['button']['value']))
  1419. $js .= "\n\t\ttemplate += \"<a href='{$args['button']['link']}' id='{$args['button']['param']}' class='btn-rm btn {$args['button']['class']} btn-primary'>{$args['button']['value']}</a>\";";
  1420. $js .= "\n\n\t\ttemplate += \"</div></div></div>\";";
  1421. // $js .= "\n\t\tif ($('#html-msg'))";
  1422. // $js .= "\n\t\t\t$('#html-msg').html(template);";
  1423. // $js .= "\n\t\telse";
  1424. $js .= "\n\t\t\t$(template).appendTo('body');";
  1425. $js .= "\n\t\tif ($('#lightbox')) $('#lightbox').hide();";
  1426. $js .= "\n\t\tif ($('.hide')) $('.hide').hide();";
  1427. $js .= "\n\t\t$('.fixedVersion .modal').modal().on('shown', function(){ $('.modal-backdrop').insertAfter($(this)); } );\n\n";
  1428. return $js;
  1429. }
  1430. /*
  1431. *o mesmo que linffy só que converte toda / na string em -
  1432. */
  1433. function linkfySmart($var, $spacer='-') {
  1434. $url = preg_replace('|[/]|', $spacer, $var);
  1435. return linkfy($url);
  1436. }
  1437. /*
  1438. *encurtador de url
  1439. */
  1440. function shortUrl($url, $service='google', $action='short') {
  1441. if($action=='short') {
  1442. if($service=='google') {
  1443. $urlapi = "https://www.googleapis.com/urlshortener/v1/url";
  1444. $postData = array('longUrl'=>$url, 'key'=>'AIzaSyAcJa1PtXCCRXVUEYiv4iu4MnT4vBM2r-o');
  1445. } else {
  1446. $postData = array('login'=>'lslucas', 'longUrl'=>$url, 'apiKey'=>'R_9413f87bc6b34d74c50254d31a8a55c8', 'format'=>'json');
  1447. $querystring = http_build_query($postData);
  1448. $postData = null;
  1449. $urlapi = "http://api.bitly.com/v3/shorten?".$querystring;
  1450. }
  1451. $post = !is_null($postData) ? json_encode($postData) : null;
  1452. $json = curl_post($urlapi, $post, array('Content-Type: application/json'));
  1453. if($service=='google') return $json->id;
  1454. else {
  1455. if($json->status_code!=500) return $json->data->url;
  1456. }
  1457. }
  1458. }
  1459. /*
  1460. *CURL POST
  1461. */
  1462. function curl_post($url, $post, $header) {
  1463. $curlObj = curl_init();
  1464. curl_setopt($curlObj, CURLOPT_URL, $url);
  1465. curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
  1466. // se é um post
  1467. if(!empty($post)) {
  1468. curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
  1469. curl_setopt($curlObj, CURLOPT_HEADER, 0);
  1470. if(is_array($header)) curl_setopt($curlObj, CURLOPT_HTTPHEADER, $header);
  1471. curl_setopt($curlObj, CURLOPT_POST, 1);
  1472. curl_setopt($curlObj, CURLOPT_POSTFIELDS, $post);
  1473. }
  1474. $response = curl_exec($curlObj);
  1475. curl_close($curlObj);
  1476. //change the response json string to object
  1477. $json = json_decode($response);
  1478. return $json;
  1479. }
  1480. /*
  1481. *Converte decimal em moeda
  1482. */
  1483. function Moeda($val) {
  1484. //setlocale(LC_MONETARY, 'pt_BR', 'ptb');
  1485. //return money_format('%4n', $val);
  1486. return number_format($val, 2,',','.');
  1487. }
  1488. /*
  1489. *Converte de Float para moeda
  1490. */
  1491. function Currency2Decimal($number, $reverse=0) {
  1492. if($reverse===1) {
  1493. $number = preg_replace('/[^0-9,]/', '', $number);
  1494. $number = preg_replace('/[, ]/', '.', $number);
  1495. $number = number_format($number, 2, '.', '');
  1496. return $number;
  1497. } else return number_format($number, 2, ',', '.');
  1498. }
  1499. /*
  1500. *substring melhorado
  1501. */
  1502. function super_substr($texto, $limit) {
  1503. $acentosUpper = "ĄĆĘŁŃÓŚŹŻABCDEFGHIJKLMNOPRSTUWYZQXVЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮÂÀÁÄÃÊÈÉËÎÍÌÏÔÕÒÓÖÛÙÚÜÇ";
  1504. $acentosLower = "ąćęłńóśźżabcdefghijklmnoprstuwyzqxvёйцукенгшщзхъфывапролджэячсмитьбюâàáäãêèéëîíìïôõòóöûùúüç";
  1505. if (strlen($texto)>$limit) {
  1506. $texto = strip_tags($texto);
  1507. $_t = substr($texto, 0, $limit);
  1508. $_p = strrpos($_t, ' ');
  1509. $_t = substr($_t, 0, $_p);
  1510. $_final = preg_replace("/[^A-Za-z{$acentosUpper}{$acentosLower}]/", '', substr($_t, -1,1));
  1511. $res = substr($_t, 0, -1).$_final;
  1512. } else
  1513. $res = $texto;
  1514. return $res;
  1515. }
  1516. /*
  1517. *remove acentos
  1518. */
  1519. function file_extension($filename) {
  1520. $vars = explode(".", $filename);
  1521. return end($vars);
  1522. }
  1523. /**
  1524. * Converts all accent characters to ASCII characters.
  1525. *
  1526. * If there are no accent characters, then the string given is just returned.
  1527. *
  1528. * @param string $string Text that might have accent characters
  1529. * @return string Filtered string with replaced "nice" characters.
  1530. */
  1531. function remove_accents($string) {
  1532. if (!preg_match('/[\x80-\xff]/', $string))
  1533. return $string;
  1534. if (seems_utf8($string)) {
  1535. $chars = array(
  1536. // Decompositions for Latin-1 Supplement
  1537. chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
  1538. chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
  1539. chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
  1540. chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
  1541. chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
  1542. chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
  1543. chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
  1544. chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
  1545. chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
  1546. chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
  1547. chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
  1548. chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
  1549. chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
  1550. chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
  1551. chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
  1552. chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
  1553. chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
  1554. chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
  1555. chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
  1556. chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
  1557. chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
  1558. chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
  1559. chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
  1560. chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
  1561. chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
  1562. chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
  1563. chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
  1564. chr(195).chr(191) => 'y',
  1565. // Decompositions for Latin Extended-A
  1566. chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
  1567. chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
  1568. chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
  1569. chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
  1570. chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
  1571. chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
  1572. chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
  1573. chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
  1574. chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
  1575. chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
  1576. chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
  1577. chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
  1578. chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
  1579. chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
  1580. chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
  1581. chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
  1582. chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
  1583. chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
  1584. chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
  1585. chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
  1586. chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
  1587. chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
  1588. chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
  1589. chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
  1590. chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
  1591. chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
  1592. chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
  1593. chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
  1594. chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
  1595. chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
  1596. chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
  1597. chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
  1598. chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
  1599. chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
  1600. chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
  1601. chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
  1602. chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
  1603. chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
  1604. chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
  1605. chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
  1606. chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
  1607. chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
  1608. chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
  1609. chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
  1610. chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
  1611. chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
  1612. chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
  1613. chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
  1614. chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
  1615. chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
  1616. chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
  1617. chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
  1618. chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
  1619. chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
  1620. chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
  1621. chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
  1622. chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
  1623. chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
  1624. chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
  1625. chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
  1626. chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
  1627. chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
  1628. chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
  1629. chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
  1630. // Euro Sign
  1631. chr(226).chr(130).chr(172) => 'E',
  1632. // GBP (Pound) Sign
  1633. chr(194).chr(163) => '');
  1634. $string = strtr($string, $chars);
  1635. } else {
  1636. // Assume ISO-8859-1 if not UTF-8
  1637. $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
  1638. .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
  1639. .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
  1640. .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
  1641. .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
  1642. .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
  1643. .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
  1644. .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
  1645. .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
  1646. .chr(252).chr(253).chr(255);
  1647. $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
  1648. $string = strtr($string, $chars['in'], $chars['out']);
  1649. $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
  1650. $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
  1651. $string = str_replace($double_chars['in'], $double_chars['out'], $string);
  1652. }
  1653. return $string;
  1654. }
  1655. /**
  1656. * Checks to see if a string is utf8 encoded.
  1657. *
  1658. * @author bmorel at ssi dot fr
  1659. *
  1660. * @param string $Str The string to be checked
  1661. * @return bool True if $Str fits a UTF-8 model, false otherwise.
  1662. */
  1663. function seems_utf8($Str) { # by bmorel at ssi dot fr
  1664. $length = strlen($Str);
  1665. for ($i = 0; $i < $length; $i++) {
  1666. if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
  1667. elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n = 1; # 110bbbbb
  1668. elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n = 2; # 1110bbbb
  1669. elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n = 3; # 11110bbb
  1670. elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n = 4; # 111110bb
  1671. elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n = 5; # 1111110b
  1672. else return false; # Does not match any model
  1673. for ($j = 0; $j < $n; $j++) { # n bytes matching 10bbbbbb follow ?
  1674. if ((++$i == $length) || ((ord($Str[$i]) & 0xC0) != 0x80))
  1675. return false;
  1676. }
  1677. }
  1678. return true;
  1679. }
  1680. function utf8_uri_encode($utf8_string, $length = 0) {
  1681. $unicode = '';
  1682. $values = array();
  1683. $num_octets = 1;
  1684. $unicode_length = 0;
  1685. $string_length = strlen($utf8_string);
  1686. for ($i = 0; $i < $string_length; $i++) {
  1687. $value = ord($utf8_string[$i]);
  1688. if ($value < 128) {
  1689. if ($length && ($unicode_length >= $length))
  1690. break;
  1691. $unicode .= chr($value);
  1692. $unicode_length++;
  1693. } else {
  1694. if (count($values) == 0) $num_octets = ($value < 224) ? 2 : 3;
  1695. $values[] = $value;
  1696. if ($length && ($unicode_length + ($num_octets * 3)) > $length)
  1697. break;
  1698. if (count( $values ) == $num_octets) {
  1699. if ($num_octets == 3) {
  1700. $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
  1701. $unicode_length += 9;
  1702. } else {
  1703. $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
  1704. $unicode_length += 6;
  1705. }
  1706. $values = array();
  1707. $num_octets = 1;
  1708. }
  1709. }
  1710. }
  1711. return $unicode;
  1712. }
  1713. /**
  1714. * Sanitizes title, replacing whitespace with dashes.
  1715. *
  1716. * Limits the output to alphanumeric characters, underscore (_) and dash (-).
  1717. * Whitespace becomes a dash.
  1718. *
  1719. * @param string $title The title to be sanitized.
  1720. * @return string The sanitized title.
  1721. */
  1722. function slugify($title) {
  1723. $title = strip_tags($title);
  1724. // Preserve escaped octets.
  1725. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
  1726. // Remove percent signs that are not part of an octet.
  1727. $title = str_replace('%', '', $title);
  1728. // Restore octets.
  1729. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
  1730. $title = remove_accents($title);
  1731. if (seems_utf8($title)) {
  1732. if (function_exists('mb_strtolower')) {
  1733. $title = mb_strtolower($title, 'UTF-8');
  1734. }
  1735. $title = utf8_uri_encode($title, 200);
  1736. }
  1737. $title = strtolower($title);
  1738. $title = preg_replace('/&.+?;/', '', $title); // kill entities
  1739. $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
  1740. $title = preg_replace('/\s+/', '-', $title);
  1741. $title = preg_replace('|-+|', '-', $title);
  1742. $title = trim($title, '-');
  1743. return $title;
  1744. }
  1745. /**
  1746. * Sanitizes title, replacing whitespace with dashes.
  1747. *
  1748. * Limits the output to alphanumeric characters, underscore (_) and dash (-).
  1749. * Whitespace becomes a dash.
  1750. *
  1751. * @param string $title The title to be sanitized.
  1752. * @return string The sanitized title.
  1753. */
  1754. function linkfy($title) {
  1755. $title = strip_tags($title);
  1756. // Preserve escaped octets.
  1757. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
  1758. // Remove percent signs that are not part of an octet.
  1759. $title = str_replace('%', '', $title);
  1760. // Restore octets.
  1761. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
  1762. $title = remove_accents($title);
  1763. if (seems_utf8($title)) {
  1764. $title = utf8_uri_encode($title, 200);
  1765. }
  1766. $title = preg_replace('/&.+?;/', '', $title); // kill entities*/
  1767. $title = preg_replace('/\s+/', '-', $title);
  1768. $title = preg_replace('|-+|', '-', $title);
  1769. $title = trim($title, '-');
  1770. return mb_strtolower($title, 'utf-8');
  1771. }
  1772. /*
  1773. *tiny mce
  1774. */
  1775. function parse_mytag($content) {
  1776. // Find the tags
  1777. preg_match_all('/\<span style="font-weight: bold;"([^>]*)\>(.*?)\<\/span\>/is', $content, $matches);
  1778. // Loop through each tag
  1779. for ($i=0; $i < count($matches['0']); $i++) {
  1780. $tag = $matches['0'][$i];
  1781. $text = $matches['2'][$i];
  1782. $new = '<b>';
  1783. $new .= $text;
  1784. $new .= '</b>';
  1785. // Replace with actual HTML
  1786. $content = str_replace($tag, $new, $content);
  1787. }
  1788. return $content;
  1789. }
  1790. /*
  1791. *valida email
  1792. */
  1793. function validaEmail($email) {
  1794. if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
  1795. list($username , $domain) = explode('@',$email);
  1796. if(!checkdnsrr($domain, 'MX'))
  1797. return false;
  1798. return true;
  1799. } else
  1800. return false;
  1801. }
  1802. /*
  1803. *REMOVE ACENTOS
  1804. */
  1805. /***
  1806. * Função para remover acentos de uma string
  1807. *
  1808. * @autor Thiago Belem <contato@thiagobelem.net>
  1809. */
  1810. function removeAcentos($string, $slug = false) {
  1811. $string = strtolower($string);
  1812. // Código ASCII das vogais
  1813. $ascii['a'] = range(224, 230);
  1814. $ascii['e'] = range(232, 235);
  1815. $ascii['i'] = range(236, 239);
  1816. $ascii['o'] = array_merge(range(242, 246), array(240, 248));
  1817. $ascii['u'] = range(249, 252);
  1818. // Código ASCII dos outros caracteres
  1819. $ascii['b'] = array(223);
  1820. $ascii['c'] = array(231);
  1821. $ascii['d'] = array(208);
  1822. $ascii['n'] = array(241);
  1823. $ascii['y'] = array(253, 255);
  1824. foreach ($ascii as $key=>$item) {
  1825. $acentos = '';
  1826. foreach ($item AS $codigo) $acentos .= chr($codigo);
  1827. $troca[$key] = '/['.$acentos.']/i';
  1828. }
  1829. $string = preg_replace(array_values($troca), array_keys($troca), $string);
  1830. // Slug?
  1831. if ($slug) {
  1832. // Troca tudo que não for letra ou número por um caractere ($slug)
  1833. $string = preg_replace('/[^a-z0-9]/i', $slug, $string);
  1834. // Tira os caracteres ($slug) repetidos
  1835. $string = preg_replace('/' . $slug . '{2,}/i', $slug, $string);
  1836. $string = trim($string, $slug);
  1837. }
  1838. return $string;
  1839. }
  1840. /*
  1841. *CALCULA IDADE
  1842. */
  1843. function diferencaAnos($var,$ref) {
  1844. $var = explode('-',$var);
  1845. $ref = explode('-',$ref);
  1846. list($ano,$mes,$dia)=$var;
  1847. list($ano_atual,$mes_atual,$dia_atual)=$ref;
  1848. if (!checkdate($mes, $dia, $ano) || !checkdate($mes_atual, $dia_atual, $ano_atual)) {
  1849. return '[data inválida]';
  1850. # echo "A data que você informou está errada <b>[ ${var[0]}/${var[1]}/${var[2]} ou ${ref[0]}/${ref[1]}/${ref[2]}]</b>";
  1851. } else {
  1852. $dif = $ano_atual-$ano;
  1853. if ($mes_atual<$mes) {
  1854. $dif=$dif-1;
  1855. } elseif ($mes==$mes_atual && $dia_atual<$dia) {
  1856. $dif=$dif-1;
  1857. }
  1858. return $dif;
  1859. }
  1860. }
  1861. /*
  1862. *REMOVE TUDO QUE NAO É NÚMERO
  1863. */
  1864. function apenasNumeros($var)
  1865. {
  1866. return preg_replace('/[^0-9]/','',$var);
  1867. }
  1868. /*
  1869. *RETORNA TIMESTAMP DA DATA EM INGLES
  1870. */
  1871. function en2timestamp($date,$sep='-') {
  1872. $date = explode($sep,$date);
  1873. $unix = mktime(0,0,0,$date[1],$date[2],$date[0]);
  1874. return $unix;
  1875. }
  1876. function traduzWeek($dayofweek)
  1877. {
  1878. switch($dayofweek) {
  1879. case 1: return 'Segunda';
  1880. break;
  1881. case 2: return 'Terça';
  1882. break;
  1883. case 3: return 'Quarta';
  1884. break;
  1885. case 4: return 'Quinta';
  1886. break;
  1887. case 5: return 'Sexta';
  1888. break;
  1889. case 6: return 'Sábado';
  1890. break;
  1891. case 7: return 'Domingo';
  1892. break;
  1893. }
  1894. }
  1895. /*
  1896. *RETORNA O DIA DA SEMANA
  1897. */
  1898. function date_diasemana($date,$type='') {
  1899. if (!empty($date)) {
  1900. #pega informações da data
  1901. $date = en2timestamp($date);
  1902. $wday = getdate($date);
  1903. $wday = $wday['wday']; #usa apenas o dia da semana em números de 0 a 6
  1904. switch($wday) {
  1905. case 0: $s_min = 'dom'; $s_nor = 'domingo';
  1906. break;
  1907. case 1: $s_min = 'seg'; $s_nor = 'segunda';
  1908. break;
  1909. case 2: $s_min = 'ter'; $s_nor = 'terça';
  1910. break;
  1911. case 3: $s_min = 'qua'; $s_nor = 'quarta';
  1912. break;
  1913. case 4: $s_min = 'qui'; $s_nor = 'quinta';
  1914. break;
  1915. case 5: $s_min = 'sex'; $s_nor = 'sexta';
  1916. break;
  1917. case 6: $s_min = 'sab'; $s_nor = 'sábado';
  1918. break;
  1919. }
  1920. $return = empty($type)?$s_nor:$s_min;
  1921. return $return;
  1922. }
  1923. }
  1924. /*
  1925. *converte newline para br
  1926. */
  1927. function newline2br($txt){
  1928. $texto0= ereg_replace("(\r)",'<br/>',$txt);
  1929. $texto = ereg_replace("(\n)",'',$texto0);
  1930. $txt = ereg_replace("/(<br\s*\/?>\s*)+/",'<br/>',$texto);
  1931. return $txt;
  1932. }
  1933. /*
  1934. *CASO O TEXTO SEJA DE BBCODE ELE CONVERTE
  1935. */
  1936. function txt_bbcode($var) {
  1937. $txt = utf8_encode(html_entity_decode($var));
  1938. return $txt;
  1939. }
  1940. function parseBBcode ($var) {
  1941. return html_entity_decode($var);
  1942. }
  1943. /*
  1944. *converte br to nl
  1945. */
  1946. function br2nl( $input ) {
  1947. return preg_replace('/<br(\s+)?\/?>/i', "\n", $input);
  1948. }
  1949. # GERA PASSWORD
  1950. ###############
  1951. function gera_senha($numL) {
  1952. $chars = "?abcdefghijkmnopqrstuvwxyz023456789#";
  1953. srand((double)microtime()*1000000);
  1954. $i = 0;
  1955. $pass = '' ;
  1956. while ($i <= $numL) {
  1957. $num = rand() % 36;
  1958. $tmp = substr($chars, $num, 1);
  1959. $pass = $pass . $tmp;
  1960. $i++;
  1961. }
  1962. return $pass;
  1963. }
  1964. # //GERA PASSWORD
  1965. ###
  1966. # CONVERTE A DATA DO PORTUGUES PARA INGLES
  1967. ##########################################
  1968. function datept2en($sep,$data,$nsep='-') {
  1969. if (!empty($data)) {
  1970. $date = explode($sep,$data);
  1971. $hora = null;
  1972. if (strpos($data, ' ')!==false) {
  1973. $time = explode(' ', $date[2]);
  1974. $date[2] = substr($date[2], 0, 2);
  1975. $hora = ' '.$time[1];
  1976. }
  1977. $date = $date[2].$nsep.$date[1].$nsep.$date[0].$hora;
  1978. // var_dump($date);
  1979. // exit;
  1980. return $date;
  1981. }
  1982. }
  1983. # CONVERTE A DATA DO INGLES PARA PORTUGUES
  1984. ##########################################
  1985. function unixtimestamp($date, $rule='dd/mm/YYYY') {
  1986. $_date = null;
  1987. $_date = preg_split('/[\/\-]/', $date);
  1988. if ($rule=='dd/mm/YYYY' || $rule=='dd/mm/yy')
  1989. $_date = $_date[2].'-'.$_date[1].'-'.$_date[0];
  1990. if ($rule=='mm/dd/YYYY' || $rule=='mm/dd/yy')
  1991. $_date = $_date[2].'-'.$_date[0].'-'.$_date[1];
  1992. if ($rule=='YYYY/mm/dd' || $rule=='yy/mm/dd')
  1993. $_date = $date;
  1994. $unix = strtotime($_date);
  1995. return $unix;
  1996. }
  1997. # CONVERTE A DATA DO INGLES PARA PORTUGUES
  1998. ##########################################
  1999. function dateen2pt($sep,$date,$nsep='-') {
  2000. if (!empty($date)) {
  2001. $date = explode($sep,$date);
  2002. return $date[2].$nsep.$date[1].$nsep.$date[0];
  2003. }
  2004. }
  2005. #// CONVERTE A DATA DO PORTUGUES PARA INGLES
  2006. ###
  2007. ## debug do session
  2008. function debug($var) {
  2009. echo '<pre>'. print_r($var, 1) .'</pre>';
  2010. }
  2011. /*
  2012. *user agent
  2013. */
  2014. function getUserAgentName($agent)
  2015. {
  2016. $browserArray = array(
  2017. 'Windows Mobile' => 'IEMobile',
  2018. 'Android Mobile' => 'Android',
  2019. 'iPhone Mobile' => 'iPhone',
  2020. 'Firefox' => 'Firefox',
  2021. 'Google Chrome' => 'Chrome',
  2022. 'Internet Explorer' => 'MSIE',
  2023. 'Opera' => 'Opera',
  2024. 'Safari' => 'Safari'
  2025. );
  2026. foreach ($browserArray as $k => $v) {
  2027. if (preg_match("/$v/", $agent))
  2028. break;
  2029. else
  2030. $k = "Browser Unknown";
  2031. }
  2032. $browser = $k;
  2033. $osArray = array(
  2034. 'Windows 98' => '(Win98)|(Windows 98)',
  2035. 'Windows 2000' => '(Windows 2000)|(Windows NT 5.0)',
  2036. 'Windows ME' => 'Windows ME',
  2037. 'Windows XP' => '(Windows XP)|(Windows NT 5.1)',
  2038. 'Windows Vista' => 'Windows NT 6.0',
  2039. 'Windows 7' => '(Windows NT 6.1)|(Windows NT 7.0)',
  2040. 'Windows NT 4.0' => '(WinNT)|(Windows NT 4.0)|(WinNT4.0)|(Windows NT)',
  2041. 'Linux' => '(X11)|(Linux)',
  2042. 'Mac OS' => '(Mac_PowerPC)|(Macintosh)|(Mac OS)'
  2043. );
  2044. foreach ($osArray as $k => $v) {
  2045. if (preg_match("/$v/", $agent))
  2046. break;
  2047. else
  2048. $k = "Unknown OS";
  2049. }
  2050. $os = $k;
  2051. return $browser.' - '.$os;
  2052. }
  2053. function logextended($acao, $modulo, $params) {
  2054. global $conn;
  2055. if (!is_array($params))
  2056. exit('Parâmetro inválido!');
  2057. if (empty($acao) || empty($params['log_id']))
  2058. exit('Dados inválidos');
  2059. $sql_loge = "INSERT INTO ".TABLE_PREFIX."_log_extended
  2060. (
  2061. lex_log_id,
  2062. lex_acao,
  2063. lex_modulo,
  2064. lex_antes,
  2065. lex_depois
  2066. ) VALUES (?, ?, ?, ?, ?)
  2067. ";
  2068. if(!$qr_loge = $conn->prepare($sql_loge))
  2069. echo $conn->error();
  2070. else {
  2071. $qr_loge->bind_param('issss', $params['log_id'], $acao, $modulo, $params['antes'], $params['depois']);
  2072. $qr_loge->execute();
  2073. $qr_loge->close();
  2074. }
  2075. }
  2076. ## LOG
  2077. #COMPUTA TUDO NA TABELA DE LOG
  2078. ###############################
  2079. function logquery() {
  2080. global $conn, $log_id;
  2081. if (!isset($_SESSION['user'])) {
  2082. $userdata = array(
  2083. 'id' => '',
  2084. 'nome' => '',
  2085. 'email' => '',
  2086. 'senha' => '',
  2087. 'ip' => $_SERVER['REMOTE_ADDR'],
  2088. 'host' => gethostbyaddr($_SERVER['REMOTE_ADDR']),
  2089. 'useragent' => $_SERVER['HTTP_USER_AGENT']
  2090. );
  2091. foreach($userdata as $k=>$v) {
  2092. $log[$k]=$v;
  2093. }
  2094. } else {
  2095. foreach($_SESSION['user'] as $k=>$v) {
  2096. $log[$k]=$v;
  2097. }
  2098. }
  2099. #computa variaveis para o log
  2100. $server = array(
  2101. 'php_self' => $_SERVER['PHP_SELF'],
  2102. 'query_string' => $_SERVER['QUERY_STRING'],
  2103. 'request_uri' => $_SERVER['REQUEST_URI'],
  2104. 'request_time' => $_SERVER['REQUEST_TIME'],
  2105. 'http_referer' => isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:''
  2106. );
  2107. foreach($server as $k=>$v) {
  2108. $slog[$k]=$v;
  2109. }
  2110. $sql_log = "INSERT INTO ".TABLE_PREFIX."_log
  2111. (
  2112. log_adm_id,
  2113. log_nome,
  2114. log_email,
  2115. log_senha,
  2116. log_php_self,
  2117. log_query_string,
  2118. log_request_uri,
  2119. log_request_time,
  2120. log_http_referer,
  2121. log_ip,
  2122. log_host,
  2123. log_useragent
  2124. ) VALUES (
  2125. ?,?,?,?,?,?,?,?,?,?,?,?
  2126. )
  2127. ";
  2128. if(($qr_log = $conn->prepare($sql_log))==false) {
  2129. echo $conn->error();
  2130. $qr_log->close();
  2131. }
  2132. else {
  2133. $qr_log->bind_param('isssssssssss', $log['id'], $log['nome'], $log['email'], $log['senha'], $slog['php_self'], $slog['query_string'], $slog['request_uri'], $slog['request_time'], $slog['http_referer'], $log['ip'], $log['host'],$log['useragent']);
  2134. $qr_log->execute();
  2135. return $log_id = $conn->insert_id;
  2136. $qr_log->close();
  2137. }
  2138. }
  2139. ## //LOG
  2140. #####
  2141. ## Retorna lista de campos e valores
  2142. ###############################
  2143. function getFieldAndValues($params) {
  2144. global $conn;
  2145. if (!is_array($params))
  2146. exit('Parâmetro inválido!');
  2147. $id = $params['id'];
  2148. $mod = $params['modulo'];
  2149. $pre = $params['pre'];
  2150. $ref = isset($params['ref']) ? $params['ref'] : 'id';
  2151. if (empty($id) || empty($mod) || empty($pre))
  2152. exit('Dados inválidos');
  2153. /*
  2154. *pega lista de colunas
  2155. */
  2156. $sql= "SELECT * FROM ".TABLE_PREFIX."_{$mod} WHERE {$pre}_{$ref}=\"{$id}\"";
  2157. $fields = array();
  2158. if(!$qry = $conn->query($sql))
  2159. echo $conn->error();
  2160. else {
  2161. while($fld = $qry->fetch_field())
  2162. array_push($fields, str_replace($pre.'_', null, $fld->name));
  2163. $qry->close();
  2164. }
  2165. /*
  2166. *pega valores dessas colunas
  2167. */
  2168. $sqlv= "SELECT * FROM ".TABLE_PREFIX."_{$mod} WHERE {$pre}_{$ref}=\"{$id}\"";
  2169. if(!$qryv = $conn->query($sqlv))
  2170. echo $conn->error();
  2171. else {
  2172. $valores = $qryv->fetch_array(MYSQLI_ASSOC);
  2173. $qryv->close();
  2174. }
  2175. $res = null;
  2176. foreach ($fields as $i=>$col)
  2177. $res .= "{$col} = ".$valores[$pre.'_'.$col].";\n";
  2178. return $res."\n";
  2179. }
  2180. ## DEBUG
  2181. # grava todo tipo de erro numa tabela e pode enviar para o administrador
  2182. ########
  2183. function debuglog($numero,$texto,$errfile, $errline){
  2184. global $conn;
  2185. if(DEBUG==1) {
  2186. ## VARIAVEIS DE CONFIG
  2187. if (!isset($_SESSION['user'])) {
  2188. $userdata = array(
  2189. 'id' => '',
  2190. 'nome' => '',
  2191. 'ip' => $_SERVER['REMOTE_ADDR'],
  2192. 'useragent' => $_SERVER['HTTP_USER_AGENT']
  2193. );
  2194. foreach($userdata as $k=>$v) {
  2195. $log[$k]=$v;
  2196. }
  2197. } else {
  2198. foreach($_SESSION['user'] as $k=>$v) {
  2199. $log[$k]=$v;
  2200. }
  2201. }
  2202. # se DEBUG_LOG nao for vazio vai gravar no arquivo de log
  2203. if (DEBUG_LOG<>'') {
  2204. $ddf = fopen(DEBUG_LOG,'a');
  2205. fwrite($ddf,"".date("r").": [$numero] $texto $errfile $errline \r\n [$log[id]]$log[nome] - $log[ip], $log[useragent] \r\n\r\n");
  2206. fclose($ddf);
  2207. }
  2208. }
  2209. }
  2210. if (DEBUG==1)
  2211. set_error_handler('debuglog');
  2212. ## //DEBUG
  2213. #####