PageRenderTime 69ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full 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)

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