PageRenderTime 52ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/public_html/source/inc-functions-accion.php

https://github.com/kendel/VirtualPol
PHP | 611 lines | 496 code | 84 blank | 31 comment | 81 complexity | 0c16505b6c23e6eace8d480a5b2151c4 MD5 | raw file
Possible License(s): Apache-2.0
  1. <?php
  2. /* The source code packaged with this file is Free Software, Copyright (C) 2008 by
  3. ** Javier González González <desarrollo AT virtualpol.com> <gonzomail AT gmail.com>
  4. ** It's licensed under the GNU GENERAL PUBLIC LICENSE v3 unless stated otherwise.
  5. ** You can get copies of the licenses here: http://www.gnu.org/licenses/gpl.html
  6. ** The source: http://www.virtualpol.com/codigo - TOS: http://www.virtualpol.com/TOS
  7. ** VirtualPol, The first Democratic Social Network - http://www.virtualpol.com
  8. */
  9. function api_facebook($accion, $item_ID, $sistema=false) {
  10. /* DOCUMENTACION FB
  11. GRAPH API - https://developers.facebook.com/docs/reference/api/message/
  12. OBTENER TOKENS - http://www.damnsemicolon.com/php/auto-post-facebook-with-facebook-sdk
  13. */
  14. require_once('../img/lib/facebook-php/facebook.php');
  15. global $date, $pol;
  16. $facebook = new Facebook(array(
  17. 'appId' => FB_APIKEY,
  18. 'secret' => FB_SECRET,
  19. 'cookie' => true,
  20. ));
  21. $pub = false;
  22. $result = sql("SELECT *,
  23. (SELECT item_ID FROM api WHERE api_ID = api_posts.api_ID AND estado = 'activo' LIMIT 1) AS item_ID,
  24. (SELECT clave FROM api WHERE api_ID = api_posts.api_ID AND estado = 'activo' LIMIT 1) AS clave,
  25. (SELECT acceso_escribir FROM api WHERE api_ID = api_posts.api_ID AND estado = 'activo' LIMIT 1) AS acceso_escribir,
  26. (SELECT pais FROM api WHERE api_ID = api_posts.api_ID AND estado = 'activo' LIMIT 1) AS api_pais,
  27. (SELECT nombre FROM api WHERE api_ID = api_posts.api_ID AND estado = 'activo' LIMIT 1) AS nombre
  28. FROM api_posts WHERE post_ID = '".$item_ID."' LIMIT 1");
  29. while ($r = r($result)) {
  30. $user_ID = ($sistema?$r['publicado_user_ID']:$pol['user_ID']);
  31. if ((isset($r['clave'])) AND ((nucleo_acceso($r['acceso_escribir'])) OR ($sistema))) {
  32. if (($accion == 'publicar') AND ($r['estado'] != 'publicado')) {
  33. if (strtotime($date) >= strtotime($r['time_cron'])) {
  34. $content_array['clave'] = $r['clave'];
  35. $content_array['message'] = trim(strip_tags($r['message']));
  36. if ($r['link'] != '') { $content_array['type'] = 'link'; $content_array['link'] = $r['link']; } // $content_array['name'] = $r['name'];
  37. if ($r['picture'] != '') { $content_array['type'] = 'photo'; $content_array['picture'] = $r['picture']; }
  38. $pub = $facebook->api('/'.$r['item_ID'].'/'.($r['link']==''?'feed':'links'), 'POST', $content_array);
  39. if (!stristr($pub['id'], '_')) { $pub['id'] = $r['item_ID'].'_'.$pub['id']; }
  40. } else {
  41. sql("UPDATE api_posts SET estado = 'cron', time = '".$date."', publicado_user_ID = '".$user_ID."' WHERE post_ID = '".$r['post_ID']."' LIMIT 1");
  42. return true;
  43. }
  44. if ($pub != false) {
  45. sql("UPDATE api_posts SET estado = 'publicado', time = '".$date."', mensaje_ID = '".$pub['id']."', publicado_user_ID = '".$user_ID."' WHERE post_ID = '".$r['post_ID']."' LIMIT 1");
  46. if ($r['api_pais'] == PAIS) {
  47. evento_chat('<b>[API]</b> Publicación de contenido en <a href="/api/'.$r['item_ID'].'">'.$r['nombre'].'</a> <span class="gris">('.$pol['nick'].', <a href="https://www.facebook.com/permalink.php?story_fbid='.explodear('_', $pub['id'], 1).'&id='.$r['item_ID'].'">ver contenido</a>, Facebook)</span>');
  48. }
  49. return true;
  50. } else { return false; }
  51. } elseif ($accion == 'borrar') {
  52. sql("UPDATE api_posts SET estado = 'pendiente', time = '".$date."', borrado_user_ID = '".$user_ID."' WHERE post_ID = '".$r['post_ID']."' LIMIT 1");
  53. $pub = $facebook->api('/'.$r['mensaje_ID'], 'DELETE', array('access_token'=>$r['clave']));
  54. return true;
  55. }
  56. }
  57. }
  58. }
  59. function actualizar($accion, $user_ID=false) {
  60. global $pol, $link;
  61. if ($user_ID == false) { $user_ID = $pol['user_ID']; }
  62. switch ($accion) {
  63. case 'votaciones':
  64. $result = sql("SELECT COUNT(ID) AS num FROM votacion WHERE estado = 'ok' AND pais = '".PAIS."' AND acceso_ver = 'anonimos'");
  65. while($r = r($result)) {
  66. sql("UPDATE config SET valor = '".$r['num']."' WHERE pais = '".PAIS."' AND dato = 'info_consultas' LIMIT 1");
  67. }
  68. break;
  69. case 'examenes':
  70. $data_array = array();
  71. $result = sql("SELECT cargo_ID, (SELECT ID FROM examenes WHERE pais = '".PAIS."' AND cargo_ID = cargos_users.cargo_ID LIMIT 1) AS examen_ID FROM cargos_users WHERE user_ID = '".$user_ID."' AND aprobado = 'ok'");
  72. while($r = r($result)){ $data_array[] = $r['examen_ID']; }
  73. sql("UPDATE users SET examenes = '".implode(' ', $data_array)."' WHERE ID = '".$user_ID."' LIMIT 1");
  74. break;
  75. case 'cargos':
  76. $data_array = array();
  77. $result = sql("SELECT cargo_ID FROM cargos_users WHERE user_ID = '".$user_ID."' AND cargo = 'true'");
  78. while($r = r($result)){ $data_array[] = $r['cargo_ID']; }
  79. sql("UPDATE users SET cargos = '".implode(' ', $data_array)."' WHERE ID = '".$user_ID."' LIMIT 1");
  80. break;
  81. case 'contador_docs':
  82. $result = sql("SELECT COUNT(ID) AS num FROM docs WHERE estado = 'ok' AND pais = '".PAIS."'");
  83. while($r = r($result)) {
  84. sql("UPDATE config SET valor = '".$r['num']."' WHERE pais = '".PAIS."' AND dato = 'info_documentos' LIMIT 1");
  85. }
  86. break;
  87. }
  88. }
  89. function evento_log($accion, $es_sistema=false) {
  90. global $pol, $link, $_REQUEST;
  91. if (!isset($pol['user_ID'])) { $es_sistema = true; }
  92. if (PAIS == 'Ninguno') { $pais = $pol['pais']; } else { $pais = PAIS; }
  93. sql("INSERT INTO log (pais, user_ID, nick, time, accion, accion_a) VALUES ('".$pais."', '".($es_sistema==false?$pol['user_ID']:0)."', '".($es_sistema==false?$pol['nick']:'Sistema')."', '".date('Y-m-d H:i:s')."', '".$accion."', '".(substr($accion, 0, 6)=='Cargo '?'cargo':$_REQUEST['a'])."')");
  94. }
  95. function presentacion($titulo, $html, $url='http://www.virtualpol.com') {
  96. global $link;
  97. echo '
  98. <!doctype html>
  99. <html lang="es">
  100. <head>
  101. <meta charset="utf-8" />
  102. <title>'.ucfirst($titulo).'</title>
  103. <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:regular,semibold,italic,italicsemibold|PT+Sans:400,700,400italic,700italic|PT+Serif:400,700,400italic,700italic" />
  104. <link rel="stylesheet" href="'.IMG.'lib/impress/css/impress-demo.css" />
  105. </head>
  106. <body>
  107. <div id="impress" class="impress-not-supported">
  108. <div class="fallback-message">
  109. <p>Tu navegador <b>no soporta las caracteristicas requeridas</b> de impress.js, por lo tanto esta es una versión simplificada de esta presentación.</p>
  110. <p>Para una mejor experiencia por favor usa la ultima versión del navegador <b>Chrome</b> o <b>Safari</b>. Firefox 10 (proximamente) tambien será soportado.</p>
  111. </div>
  112. '.str_replace('&#x2F;', '/', str_replace('&quot;', '"', str_replace('&gt;', '>', str_replace('&lt;', '<', strip_tags($html))))).'
  113. <div class="hint">
  114. <p>Usa las teclas de <em>espacio</em> o <em>flechas</em> para navegar</p>
  115. </div>
  116. </div>
  117. <div style="position: fixed; bottom: 10px; left: 10px;">
  118. <a href="https://twitter.com/share" class="twitter-share-button" data-text="Presentación '.$url.'/presentacion VirtualPol" data-lang="es" data-size="large" data-related="VirtualPol">Twittear</a>
  119. <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
  120. </div>
  121. <a href="'.$url.'"><img style="position: absolute; top: -3px; left: -3px; border: 0; border-bottom-right-radius:12px; -moz-border-radius-bottomright:12px; -webkit-border-bottom-right-radius:12px; opacity:0.5;filter:alpha(opacity=50)" src="'.IMG.'logo-virtualpol-1.gif" alt="VirtualPol"></a>
  122. <script src="'.IMG.'lib/impress/js/impress.js"></script>
  123. </body>
  124. </html>';
  125. mysql_close($link);
  126. exit;
  127. }
  128. function pad($control, $ID=false, $txt='') {
  129. if ($control != 'print') {
  130. include('../img/lib/etherpad-lite/etherpad-lite-client.php');
  131. $e = new EtherpadLiteClient(CLAVE_API_ETHERPAD, 'http://www.'.DOMAIN.':9001/api');
  132. }
  133. switch ($control) {
  134. case 'print':
  135. global $pol;
  136. return '<iframe src="http://www.virtualpol.com:9001/p/'.$ID.'?userName='.$pol['nick'].'" width="100%" height="500" frameborder="0" style="background:#FFF;margin:0 -20px -9px -20px;"></iframe>';
  137. break;
  138. case 'create': try { $e->createPad($ID, html_entity_decode(strip_tags(str_replace("<br />", "\n", $txt)), null, 'UTF-8')); return true; } catch (Exception $error) { return false; } break;
  139. case 'get': try { return $e->getHTML($ID)->html; } catch (Exception $error) { return false; } break;
  140. case 'delete': try { $e->deletePad($ID); return true; } catch (Exception $error) { return false; } break;
  141. }
  142. }
  143. // ELIMINACION DE TINYMCE EN CURSO
  144. function editor_enriquecido($name, $txt='') {
  145. $GLOBALS['txt_header'] .= '
  146. <script type="text/javascript" src="'.IMG.'tiny_mce/tiny_mce.js"></script>
  147. <script type="text/javascript">
  148. document.domain = "'.DOMAIN.'";
  149. tinyMCE.init({
  150. mode : "textareas",
  151. theme : "advanced",
  152. language : "es",
  153. plugins : "style,table",
  154. elements : "abshosturls",
  155. relative_urls : false,
  156. remove_script_host : false,
  157. theme_advanced_buttons1 : "bold,italic,underline,|,strikethrough,sub,sup,charmap,|,forecolor,fontselect,fontsizeselect,|,link,unlink,image,|,undo,redo,|,cleanup,removeformat,code",
  158. theme_advanced_buttons2 : "justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,blockquote,hr,|,tablecontrols",
  159. theme_advanced_buttons3 : "",
  160. theme_advanced_toolbar_location : "top",
  161. theme_advanced_toolbar_align : "left",
  162. theme_advanced_statusbar_location : "bottom",
  163. theme_advanced_resizing : true,
  164. });
  165. </script>';
  166. return '<textarea name="'.$name.'" style="width:750px;height:350px;">'.$txt.'</textarea>';
  167. }
  168. function evento_chat($msg, $user_ID='0', $chat_ID='', $secret=false, $tipo='e', $pais='', $nick=false) {
  169. global $pol, $link, $vp;
  170. if (!$nick) { $nick = $pol['nick']; }
  171. if (!$pais) { $pais = PAIS; }
  172. $result = sql("SELECT chat_ID FROM chats WHERE pais = '".$pais."' AND user_ID = '0' ORDER BY fecha_creacion ASC LIMIT 1");
  173. while($r = r($result)){ $chat_ID = $r['chat_ID']; }
  174. sql("INSERT INTO chats_msg (chat_ID, nick, msg, cargo, user_ID, tipo) VALUES ('".$chat_ID."', '".($secret==false?$nick:'')."', '".$msg."', '0', '".$user_ID."', '".$tipo."')");
  175. }
  176. function cargo_add($cargo_ID, $user_ID, $evento_chat=true, $sistema=false) {
  177. global $link, $pol, $date;
  178. $result = sql("SELECT nombre, nivel FROM cargos WHERE pais = '".PAIS."' AND cargo_ID = '".$cargo_ID."' LIMIT 1");
  179. while($r = r($result)){
  180. $result2 = sql("SELECT cargo_ID FROM cargos_users WHERE pais = '".PAIS."' AND cargo_ID = '".$cargo_ID."' AND user_ID = '".$user_ID."' LIMIT 1");
  181. while($r2 = r($result2)){ $tiene_examen = true; }
  182. if ($tiene_examen) {
  183. sql("UPDATE cargos_users SET cargo = 'true', aprobado = 'ok' WHERE pais = '".PAIS."' AND cargo_ID = '".$cargo_ID."' AND user_ID = '".$user_ID."' LIMIT 1");
  184. } else {
  185. sql("INSERT INTO cargos_users (cargo_ID, pais, user_ID, time, aprobado, cargo, nota) VALUES ('".$cargo_ID."', '".PAIS."', '".$user_ID."', '".$date."', 'ok', 'true', '0.0')");
  186. }
  187. sql("UPDATE users SET nivel = '".$r['nivel']."', cargo = '".$cargo_ID."' WHERE ID = '".$user_ID."' AND nivel < '".$r['nivel']."' LIMIT 1");
  188. actualizar('cargos', $user_ID);
  189. if ($evento_chat) {
  190. $result2 = sql("SELECT nick FROM users WHERE ID = '".$user_ID."' LIMIT 1");
  191. while($r2 = r($result2)){ $nick_asignado = $r2['nick']; }
  192. evento_chat('<b>[CARGO]</b> El cargo de <img src="'.IMG.'cargos/'.$cargo_ID.'.gif" /> '.$r['nombre'].' ha sido asignado a '.crear_link($nick_asignado).' por '.crear_link(($sistema==true?'VirtualPol':$pol['nick'])));
  193. notificacion($user_ID, 'Te ha sido asignado el cargo '.$r['nombre'], '/cargos');
  194. }
  195. evento_log('Cargo '.$r['nombre'].' asignado a @'.$nick_asignado.' por '.($sistema==true?'VirtualPol':'@'.$pol['nick']));
  196. }
  197. }
  198. function cargo_del($cargo_ID, $user_ID, $evento_chat=true, $sistema=false) {
  199. global $link, $pol;
  200. $result = sql("SELECT nombre, nivel FROM cargos WHERE pais = '".PAIS."' AND cargo_ID = '".$cargo_ID."' LIMIT 1");
  201. while($r = r($result)){
  202. sql("UPDATE cargos_users SET cargo = 'false' WHERE pais = '".PAIS."' AND cargo_ID = '" . $cargo_ID . "' AND user_ID = '".$user_ID."' LIMIT 1");
  203. $result = sql("SELECT cargo_ID,
  204. (SELECT nivel FROM cargos WHERE pais = '".PAIS."' AND cargo_ID = cargos_users.cargo_ID LIMIT 1) AS nivel
  205. FROM cargos_users
  206. WHERE pais = '".PAIS."' AND user_ID = '".$user_ID."' AND cargo = 'true'
  207. ORDER BY nivel DESC
  208. LIMIT 1");
  209. while($r = r($result)){ $user_nivel_max = $r['nivel']; $user_nivel_sql = ", cargo = '" . $r['cargo_ID'] . "'"; }
  210. if (!$user_nivel_max) { $user_nivel_max = 1; $user_nivel_sql = ", cargo = ''"; }
  211. sql("UPDATE users SET nivel = '" . $user_nivel_max . "'" . $user_nivel_sql . " WHERE ID = '".$user_ID."' LIMIT 1");
  212. actualizar('cargos', $user_ID);
  213. $result2 = sql("SELECT nick FROM users WHERE ID = '".$user_ID."' LIMIT 1");
  214. while($r2 = r($result2)){ $nick_asignado = $r2['nick']; }
  215. if ($evento_chat) {
  216. evento_chat('<b>[CARGO] '.crear_link(($sistema==true?'VirtualPol':$pol['nick'])).' quita</b> el cargo <img src="'.IMG.'cargos/'.$cargo_ID.'.gif" />'.$r['nombre'].' a '. crear_link($nick_asignado));
  217. }
  218. evento_log('Cargo '.$r['nombre'].' quitado a @'.$nick_asignado.' por '.($sistema==true?'VirtualPol':'@'.$pol['nick']));
  219. }
  220. }
  221. // NUEVA FUNCION DE CARGOS EN DESARROLLO
  222. function cargo($accion, $cargo_ID, $user_ID, $evento_chat=true, $sistema=false) {
  223. global $link, $pol;
  224. switch ($accion) {
  225. case 'add':
  226. break;
  227. case 'del':
  228. break;
  229. case 'dimitir':
  230. break;
  231. }
  232. // OLD
  233. $result = sql("SELECT nombre, nivel FROM cargos WHERE pais = '".PAIS."' AND cargo_ID = '".$cargo_ID."' LIMIT 1");
  234. while($r = r($result)){
  235. sql("UPDATE cargos_users SET cargo = 'false' WHERE pais = '".PAIS."' AND cargo_ID = '".$cargo_ID."' AND user_ID = '".$user_ID."' LIMIT 1");
  236. $result = sql("SELECT cargo_ID,
  237. (SELECT nivel FROM cargos WHERE pais = '".PAIS."' AND cargo_ID = cargos_users.cargo_ID LIMIT 1) AS nivel
  238. FROM cargos_users
  239. WHERE pais = '".PAIS."' AND user_ID = '".$user_ID."' AND cargo = 'true'
  240. ORDER BY nivel DESC
  241. LIMIT 1");
  242. while($r = r($result)){ $user_nivel_max = $r['nivel']; $user_nivel_sql = ", cargo = '" . $r['cargo_ID'] . "'"; }
  243. if (!$user_nivel_max) { $user_nivel_max = 1; $user_nivel_sql = ", cargo = ''"; }
  244. sql("UPDATE users SET nivel = '" . $user_nivel_max . "'" . $user_nivel_sql . " WHERE ID = '".$user_ID."' LIMIT 1");
  245. actualizar('cargos', $user_ID);
  246. if ($evento_chat) {
  247. $result2 = sql("SELECT nick FROM users WHERE ID = '".$user_ID."' LIMIT 1");
  248. while($r2 = r($result2)){ $nick_asignado = $r2['nick']; }
  249. evento_chat('<b>[CARGO] '.crear_link(($sistema==true?'VirtualPol':$pol['nick'])).' quita</b> el cargo <img src="'.IMG.'cargos/'.$cargo_ID.'.gif" />'.$r['nombre'].' a '. crear_link($nick_asignado));
  250. }
  251. evento_log('Cargo '.$r['nombre'].' quitado a @'.$nick_asignado.' por '.($sistema==true?'VirtualPol':'@'.$pol['nick']));
  252. }
  253. }
  254. function enviar_email($user_ID, $asunto, $mensaje, $email='') {
  255. $cabeceras = "From: VirtualPol <".CONTACTO_EMAIL.">;\nReturn-Path: VirtualPol <".CONTACTO_EMAIL.">;\nX-Sender: VirtualPol <".CONTACTO_EMAIL.">;\n MIME-Version: 1.0;\nContent-type: text/html; charset=UTF-8\n";
  256. if (($user_ID) AND ($email == '')) {
  257. global $link;
  258. $result = sql("SELECT email FROM users WHERE ID = '".$user_ID."' LIMIT 1");
  259. while($r = r($result)){ $email = $r['email']; }
  260. }
  261. mail($email, $asunto, $mensaje, $cabeceras);
  262. }
  263. function pols_transferir($pols, $emisor_ID, $receptor_ID, $concepto, $pais=false) {
  264. global $link, $pol;
  265. if ($pais == false) { $pais = PAIS; }
  266. $return = false;
  267. $pols = strval($pols);
  268. if ((is_numeric($pols)) AND ($pols != 0) AND ($concepto)) {
  269. $concepto = ucfirst(strip_tags($concepto));
  270. //quitar
  271. if ($emisor_ID > 0) {
  272. sql("UPDATE users SET pols = pols - ".$pols." WHERE ID = '".$emisor_ID."' AND pais = '".$pais."' LIMIT 1");
  273. } else {
  274. if (isset($pol['nick'])) { $concepto = '<b>'.$pol['nick'].'&rsaquo;</b> '.$concepto; }
  275. sql("UPDATE cuentas SET pols = pols - ".$pols." WHERE ID = '".substr($emisor_ID, 1)."' AND pais = '".$pais."' LIMIT 1");
  276. }
  277. //ingresar
  278. if ($receptor_ID > 0) {
  279. sql("UPDATE users SET pols = pols + ".$pols." WHERE ID = '".$receptor_ID."' AND pais = '".$pais."' LIMIT 1");
  280. } else {
  281. sql("UPDATE cuentas SET pols = pols + ".$pols." WHERE ".($receptor_ID==-1?"gobierno = 'true'":"ID = '".substr($receptor_ID, 1)."'")." AND pais = '".$pais."' LIMIT 1");
  282. }
  283. sql("INSERT INTO transacciones (pais, pols, emisor_ID, receptor_ID, concepto, time) VALUES ('".$pais."', ".$pols.", '".$emisor_ID."', '".$receptor_ID."', '".$concepto."', '".date('Y-m-d H:i:s')."')");
  284. if ($receptor_ID > 0) { notificacion($receptor_ID, 'Te han transferido '.$pols.' monedas', '/pols'); }
  285. $return = true;
  286. }
  287. return $return;
  288. }
  289. function eliminar_ciudadano($ID) {
  290. global $link, $pol;
  291. $user_ID = false;
  292. $result3 = sql("SELECT IP, pols, nick, ID, ref, estado".(ECONOMIA?",
  293. (SELECT SUM(pols) FROM cuentas WHERE pais = '".PAIS."' AND user_ID = '".$ID."') AS pols_cuentas":"")."
  294. FROM users
  295. WHERE ID = '".$ID."'
  296. LIMIT 1");
  297. while($r3 = r($result3)) {
  298. $user_ID = $r3['ID'];
  299. $estado = $r3['estado'];
  300. $pols = ($r3['pols'] + $r3['pols_cuentas']);
  301. $nick = $r3['nick'];
  302. $ref = $r3['ref'];
  303. $IP = $r3['IP'];
  304. }
  305. if (is_numeric($user_ID)) {
  306. // ELIMINAR CIUDADANO
  307. if (ECONOMIA) { pols_transferir($pols, $user_ID, '-1', '&dagger; Defuncion: <em>'.$nick.'</em>'); }
  308. if ((ECONOMIA) AND ($ref != '0')) {
  309. sql("UPDATE users SET ref_num = ref_num - 1 WHERE ID = '".$ref."' LIMIT 1");
  310. }
  311. sql("DELETE FROM users WHERE ID = '".$user_ID."' LIMIT 1");
  312. sql("DELETE FROM users_con WHERE user_ID = '".$user_ID."'");
  313. sql("DELETE FROM partidos_listas WHERE pais = '".PAIS."' AND user_ID = '".$user_ID."'");
  314. sql("DELETE FROM partidos WHERE pais = '".PAIS."' AND ID_presidente = '".$user_ID."'");
  315. sql("DELETE FROM cargos_users WHERE user_ID = '".$user_ID."'");
  316. sql("DELETE FROM kicks WHERE pais = '".PAIS."' AND user_ID = '".$user_ID."'");
  317. sql("DELETE FROM chats WHERE user_ID = '".$user_ID."'");
  318. sql("DELETE FROM votos WHERE emisor_ID = '".$user_ID."' OR (tipo = 'confianza' AND item_ID = '".$user_ID."')");
  319. sql("DELETE FROM ".SQL."foros_msg WHERE user_ID = '".$user_ID."' AND hilo_ID = '-1'");
  320. sql("DELETE FROM users_con WHERE user_ID = '".$user_ID."'");
  321. sql("DELETE FROM referencias WHERE user_ID = '".$user_ID."'");
  322. sql("DELETE FROM empresas WHERE pais = '".PAIS."' AND user_ID = '".$user_ID."'");
  323. sql("DELETE FROM mapa WHERE pais = '".PAIS."' AND user_ID = '".$user_ID."'");
  324. sql("DELETE FROM cuentas WHERE pais = '".PAIS."' AND user_ID = '".$user_ID."'");
  325. sql("DELETE FROM referencias WHERE IP = '".$IP."' OR user_ID = '".$ref."'");
  326. $img_root = RAIZ.'/img/a/'.$user_ID;
  327. if (file_exists($img_root.'.jpg')) {
  328. @unlink($img_root.'.jpg');
  329. @unlink($img_root.'_40.jpg');
  330. }
  331. // eliminar
  332. /* PENDIENTE DE ARREGLAR. CODIGO CORRECTO, EXCEPTO QUE NO DEBE BORRAR MENSAJES DE EXPULSADOS POR PETICION PROPIA.
  333. if ($estado == 'expulsado') {
  334. sql("DELETE FROM ".SQL."foros_msg WHERE user_ID = '".$user_ID."'");
  335. sql("DELETE FROM ".SQL."foros_hilos WHERE user_ID = '".$user_ID."'");
  336. }
  337. */
  338. }
  339. }
  340. // accion
  341. function gen_title($title) {
  342. $title = strip_tags($title);
  343. return $title;
  344. }
  345. function gen_url($url) {
  346. if (mb_detect_encoding($url) != 'UTF-8') { $url = utf8_decode($url); }
  347. $url = trim($url);
  348. $url = strtr(utf8_decode($url), utf8_decode(' àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'), utf8_decode('-aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY'));
  349. $url = str_replace(array('&quot;', '&#39;'), '', $url);
  350. $url = ereg_replace("[^A-Za-z0-9-]", "", $url);
  351. $url = substr($url, 0, 90);
  352. $url = strip_tags($url);
  353. $url = strtolower($url);
  354. return $url;
  355. }
  356. function gen_text($text, $type='') {
  357. if (mb_detect_encoding($text) != 'UTF-8') { $text = utf8_encode($text); }
  358. $text = preg_replace('#(<[^>]+[\s\r\n\"\'])(on|xmlns)[^>]*>#iU', "$1>", $text); //prevent XSS
  359. if ($type == 'plain') {
  360. // $text = strip_tags($text, '<br>');
  361. $text = strip_tags($text);
  362. } else {
  363. $text = strip_tags($text, "<br>,<img>,<b>,<i>,<s>,<embed>,<object>,<param>,<span>,<font>,<strong>,<p>,<b>,<em>,<ul>,<ol>,<li>,<blockquote>,<a>,<h2>,<h3>,<h4>,<br>,<hr>,<table>,<tr>,<td>,<th>");
  364. }
  365. $text = nl2br($text);
  366. return $text;
  367. }
  368. function imageCompression($imgfile='', $thumbsize=0, $savePath=NULL, $format='jpeg', $o_width=false, $o_height=false) {
  369. list($width,$height) = getimagesize($imgfile);
  370. $newwidth = $thumbsize;
  371. $newheight = $thumbsize;
  372. if ($o_width != false) {
  373. $newwidth = $o_width;
  374. $newheight = $o_height;
  375. }
  376. $thumb = imagecreatetruecolor($newwidth,$newheight);
  377. if ($format == 'gif') {
  378. $source = imagecreatefromgif($imgfile);
  379. } elseif ($format == 'png') {
  380. imagealphablending($thumb, false);
  381. imagesavealpha($thumb, true);
  382. $source = imagecreatefrompng($imgfile);
  383. } else {
  384. $source = imagecreatefromjpeg($imgfile);
  385. }
  386. imagecopyresampled($thumb,$source,0,0,0,0,$newwidth,$newheight,$width,$height);
  387. if ($format == 'png') {
  388. imagepng($thumb,$savePath,85);
  389. } else {
  390. imagejpeg($thumb,$savePath,85);
  391. }
  392. }
  393. function barajar_votos($votacion_ID) { // FUNCION CRITICA. Especialmente comentada.
  394. global $link;
  395. // El objetivo de esta funcion es barajar los votos de forma que quede rota la relación Usuario-Voto.
  396. // Comprueba que la votacion está terminada y los votos no son publicos (para evitar corrupciones)
  397. $result = sql("SELECT privacidad FROM votacion WHERE ID = '".$votacion_ID."' AND estado = 'end' AND privacidad = 'true' LIMIT 1");
  398. while($r = r($result)){ $ok = $r['privacidad']; }
  399. if ($ok != 'true') { return false; }
  400. // Extrae los IDs de votos y los guarda en array.
  401. $votos = array();
  402. $n = 0;
  403. $result = sql("SELECT * FROM votacion_votos WHERE ref_ID = '".$votacion_ID."'");
  404. while($r = r($result)){
  405. $n++;
  406. $votos[$n]['ID'] = $r['ID'];
  407. }
  408. // Extrae los datos a barajar de la tabla de votos, ya ordenados aleatoriamente.
  409. $n = 0;
  410. $result = sql("SELECT * FROM votacion_votos WHERE ref_ID = '".$votacion_ID."' ORDER BY RAND()");
  411. while($r = r($result)){
  412. $n++;
  413. $votos[$n]['voto'] = $r['voto'];
  414. $votos[$n]['validez'] = $r['validez'];
  415. $votos[$n]['autentificado'] = $r['autentificado'];
  416. $votos[$n]['mensaje'] = $r['mensaje'];
  417. $votos[$n]['comprobante'] = $r['comprobante'];
  418. }
  419. // Recorre el array para volver a guardar los mismos datos, pero barajados.
  420. foreach ($votos AS $null => $voto) {
  421. $sql_set = array();
  422. foreach ($voto AS $dato => $valor) {
  423. if ($dato == 'ID') { $voto_ID = $valor; }
  424. else { $sql_set[] = "".$dato." = '".str_replace("'", "", $valor)."'"; }
  425. }
  426. sql("UPDATE votacion_votos SET ".implode(', ', $sql_set)." WHERE ID = '".$voto_ID."' LIMIT 1");
  427. }
  428. // Elimina relación usuario-voto también en los argumentos de votacion
  429. sql("UPDATE votacion_argumentos SET user_ID = 0 WHERE ref_ID = '".$votacion_ID."'");
  430. return true;
  431. }
  432. function distancia($lat1, $lng1, $lat2, $lng2, $dec=0) {
  433. $pi80 = M_PI / 180;
  434. $lat1 *= $pi80;
  435. $lng1 *= $pi80;
  436. $lat2 *= $pi80;
  437. $lng2 *= $pi80;
  438. $r = 6372.797; // mean radius of Earth in km
  439. $dlat = $lat2 - $lat1;
  440. $dlng = $lng2 - $lng1;
  441. $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
  442. $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
  443. $km = $r * $c;
  444. return round($km, $dec);
  445. }
  446. function form_select_cat($tipo='docs', $cat_now='') {
  447. global $pol, $link;
  448. $f .= '<select name="cat">';
  449. $result = sql("
  450. SELECT ID, nombre, nivel
  451. FROM cat
  452. WHERE pais = '".PAIS."' AND tipo = '" . $tipo . "'
  453. ORDER BY orden ASC");
  454. while($row = r($result)){
  455. if ($cat_now == $row['ID']) {
  456. $selected = ' selected="selected"';
  457. } elseif ($pol['nivel'] < $row['nivel']) {
  458. $selected = ' disabled="disabled"';
  459. $row['nombre'] = $row['nombre'] . ' (Nivel: ' . $row['nivel'] . ')';
  460. } else {
  461. $selected = '';
  462. }
  463. $f .= '<option value="' . $row['ID'] . '"' . $selected . '>' . $row['nombre'] . '</option>' . "\n";
  464. }
  465. $f .= '</select>';
  466. return $f;
  467. }
  468. function users_con($user_ID, $extra='', $tipo='session', $rejs=false) {
  469. $IP = direccion_IP('longip');
  470. $host = strtolower(gethostbyaddr(long2ip($IP))); if ($host == '') { $host = long2ip($IP); }
  471. $extra_array = explode('|', $extra); // res1|res2|login_seg|bitdepth|dispositivo
  472. if (!is_numeric(substr($host, -1, 1))) {
  473. $hoste = explode('.', $host);
  474. $ISP = ucfirst($hoste[count($hoste)-(in_array($hoste[count($hoste)-2], array('com', 'net', 'org'))?3:2)]).(!in_array($hoste[count($hoste)-1], array('com', 'net'))?' '.strtoupper($hoste[count($hoste)-1]):'');
  475. if (substr(long2ip($IP), 0, 10) == '80.58.205.') { $ISP = 'CanguroNet (proxy)'; }
  476. elseif ((stristr($host, 'proxy')) OR (stristr($host, 'cache')) OR (stristr($host, 'server'))) { $ISP .= ' (proxy)'; }
  477. elseif ((stristr($host, 'dyn')) OR stristr($host, 'pool')) { $ISP .= ' (dynamic)'; }
  478. elseif ((stristr($host, 'static')) OR (stristr($host, 'client'))) { $ISP .= ' (static)'; }
  479. elseif (stristr($host, 'cable')) { $ISP .= ' (cable)'; }
  480. elseif (stristr($host, 'dsl')) { $ISP .= ' (adsl)'; }
  481. elseif (stristr($host, 'wimax')) { $ISP .= ' (wimax)'; }
  482. if ((stristr($host, 'vpn')) OR (stristr($host, 'vps')) OR (stristr($host, 'www'))) { $ISP = 'Ocultado (VPN)'; }
  483. if ((stristr($host, 'tor')) OR (stristr($host, 'anon')) OR (stristr($host, 'exit')) OR (stristr($host, 'onion'))) { $ISP = 'Ocultado (TOR)'; }
  484. $ISP = "'".$ISP."'";
  485. } else { $ISP = "NULL"; }
  486. $la_IP = explode('.', long2ip($IP));
  487. $result = sql("SELECT IP_pais FROM users_con WHERE IP_rango = '".$la_IP[0].".".$la_IP[1]."' LIMIT 1");
  488. while($r = r($result)){ $el_pais = "'".$r['IP_pais']."'"; }
  489. if (strlen($hoste[count($hoste)-1]) == 2) { $el_pais = "'".strtoupper($hoste[count($hoste)-1])."'"; }
  490. if ((!$el_pais) AND (CLAVE_API_ipinfodb != '...')) {
  491. $res = file_get_contents('http://api.ipinfodb.com/v3/ip-city/?key='.CLAVE_API_ipinfodb.'&ip='.$la_IP[0].'.'.$la_IP[1].'.1.1');
  492. $res = strtoupper(explodear(';', $res, 3));
  493. if (strlen($res) != 2) { $res = '??'; }
  494. $el_pais = "'".$res."'";
  495. }
  496. $_SERVER['HTTP_X_FORWARDED_FOR'] = (filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)&&substr($_SERVER['HTTP_X_FORWARDED_FOR'], 0, 3)!='127'?$_SERVER['HTTP_X_FORWARDED_FOR']:'');
  497. if (($_SERVER['HTTP_X_FORWARDED_FOR'] != '') AND (substr(long2ip($IP), 0, 10) == '80.58.205.')) { $IP = ip2long($_SERVER['HTTP_X_FORWARDED_FOR']); }
  498. $i = get_browser(null, true);
  499. sql("INSERT INTO users_con (user_ID, time, IP, host, proxy, nav, login_ms, login_seg, nav_resolucion, ISP, tipo, nav_so, IP_pais, IP_rango, IP_rango3, dispositivo)
  500. VALUES ('".$user_ID."', '".date('Y-m-d H:i:s')."', '".$IP."', '".$host."', '".$_SERVER['HTTP_X_FORWARDED_FOR']."', '".$_SERVER['HTTP_USER_AGENT']." | ".$_SERVER['HTTP_ACCEPT_LANGUAGE']."".($extra_array[0]?" | ".$extra_array[0]." ".$extra_array[3]:"")."', '".round((microtime(true)-TIME_START)*1000)."', '".$extra_array[2]."', ".($extra_array[0]?"'".$extra_array[0]." ".$extra_array[3]."'":"NULL").", ".$ISP.", '".$tipo."', '".str_replace('Android Android', 'Android', $i['platform']." ".$i['parent'])."', ".$el_pais.", '".$la_IP[0].".".$la_IP[1]."', '".$la_IP[0].".".$la_IP[1].".".$la_IP[2]."', ".($_COOKIE['trz']?"'".$_COOKIE['trz']."'":"NULL").")");
  501. sql("UPDATE users SET host = '".$host."' WHERE ID = '".$user_ID."' LIMIT 1");
  502. return ($rejs==true?'<script type="text/javascript"> $(document).ready(function(){ $.post("'.vp_url('/accion.php?a=users_con', $_SESSION['pol']['pais']).'", { extra: screen.width + "x" + screen.height + "|" + screen.availWidth + "x" + screen.availHeight + "||" + screen.colorDepth + "|"}); }); </script>':true);
  503. }
  504. ?>